From 2dfc7ac5e451d7226f7537c36f8ee5ae0db8c093 Mon Sep 17 00:00:00 2001 From: Daniel Barlow Date: Mon, 23 Jan 2023 22:34:14 +0000 Subject: [PATCH] move obstacle checking down from command to drive --- rover.fnl | 50 ++++++++++++++++++++++++++------------------------ 1 file changed, 26 insertions(+), 24 deletions(-) diff --git a/rover.fnl b/rover.fnl index b743ee6..f1a7d4d 100644 --- a/rover.fnl +++ b/rover.fnl @@ -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)