move obstacle checking down from command to drive

main
Daniel Barlow 2023-01-23 22:34:14 +00:00
parent 689fb894ad
commit 2dfc7ac5e4
1 changed files with 26 additions and 24 deletions

View File

@ -6,18 +6,28 @@
(< 180 x) (wrap-longitude (- x 360))
x))
(fn at-obstacle? [{: x : y : obstacles}]
(any obstacles
(fn [[ox oy]] (and (= ox x) (= oy y)))))
(fn try-to-drive [{: x : y : direction : stopped &as r} distance]
(let [distance
(if (. {:w true :e true} direction)
(/ distance (math.cos (/ (* math.pi y) 180)))
distance)]
(match direction
:n {:y (+ y distance)}
:s {:y (- y distance)}
:w {:x (wrap-longitude (- x distance))}
:e {:x (wrap-longitude (+ x distance))})))
(fn drive [{: x : y : direction : stopped &as r} distance]
(if stopped
r
(let [distance
(if (. {:w true :e true} direction)
(/ distance (math.cos (/ (* math.pi y) 180)))
distance)]
(match direction
:n {:y (+ y distance)}
:s {:y (- y distance)}
:w {:x (wrap-longitude (- x distance))}
:e {:x (wrap-longitude (+ x distance))}))))
(let [next-move (merge r (try-to-drive r distance))]
(if (at-obstacle? next-move)
(merge r {:stopped [next-move.x next-move.y]})
next-move))))
(fn turn-left [{: x : y : direction}]
(if (= y 90)
@ -43,22 +53,14 @@
}
(. direction))}))
(fn at-obstacle? [{: x : y : obstacles}]
(any obstacles
(fn [[ox oy]] (and (= ox x) (= oy y)))))
(fn command [rover string]
(let [next-move
(merge rover
(match string
:f (drive rover 1)
:b (drive rover -1)
:r (turn-right rover)
:l (turn-left rover)
_ (assert false (. "unrecognised command " string))))]
(if (at-obstacle? next-move)
(merge rover {:stopped [next-move.x next-move.y]})
next-move)))
(merge rover
(match string
:f (drive rover 1)
:b (drive rover -1)
:r (turn-right rover)
:l (turn-left rover)
_ (assert false (. "unrecognised command " string)))))
(fn fudge-for-pole [{: y &as r}]
(if (= y 90)