move obstacle checking down from command to drive

This commit is contained in:
Daniel Barlow 2023-01-23 22:34:14 +00:00
parent 689fb894ad
commit 2dfc7ac5e4

View File

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