Advertisement
Guest User

Untitled

a guest
Sep 2nd, 2018
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ;; GRID
  2. (defn create-tile [position content]
  3.   {:position position :content content})
  4.  
  5. (defn create-grid [[size-x size-y]]
  6.   (mapv
  7.     (fn [x] (mapv (fn [y] (create-tile [x y] nil)) (range size-y)))
  8.     (range size-x)))
  9.  
  10. (defn position-in-grid? [grid [pos-x pos-y]]
  11.   (and
  12.     (>= pos-x 0)
  13.     (>= pos-y 0)
  14.     (< pos-x (count grid))
  15.     (< pos-y (count (grid pos-x)))))
  16.  
  17. (defn validate-position [grid position]
  18.   (if (not (position-in-grid? grid position))
  19.     (throw (AssertionError. (str "Invalid position " position)))))
  20.  
  21. (defn place-content [grid position content]
  22.   (validate-position grid position)
  23.   (assoc-in grid position (create-tile position content)))
  24.  
  25.  
  26. ;; ROBOT
  27. (def directions
  28.   [[0 1] [1 0] [0 -1] [-1 0]])
  29.  
  30. (defn create-robot [position direction]
  31.   {:position position :direction direction})
  32.  
  33. (defn move-robot [{:keys [position direction] :as robot}]
  34.   (let [new-pos (vec (map + position direction))]
  35.     (assoc robot :position new-pos)))
  36.  
  37.  
  38. ;; STATE
  39. (defn create-game-state [grid robots]
  40.   {:grid grid :robots robots})
  41.  
  42. (defn place-robot-in-state [state {position :position :as robot}]
  43.   (-> state
  44.     (assoc-in [:grid (first position) (second position)] (create-tile position :robot))
  45.     (assoc-in [:robots] (conj (:robots state) robot))))
  46.  
  47. (defn remove-robot-from-state [state {position :position :as robot}]
  48.   (let [robot-index (.indexOf (:robots state) robot)
  49.         robots (:robots state)
  50.         new-robots-list (concat (subvec robots 0 robot-index) (subvec robots (inc robot-index)))]
  51.     (-> state
  52.       (assoc-in [:grid (first position) (second position)] (create-tile position nil))
  53.       (assoc-in [:robots] (vec new-robots-list)))))
  54.  
  55. (defn move-robot-in-state [state {old-pos :position :as robot}]
  56.   (let [new-robot (move-robot robot) new-pos (:position new-robot)]
  57.     (validate-position (:grid state) new-pos)
  58.     (-> state
  59.       (remove-robot-from-state robot)
  60.       (place-robot-in-state (move-robot robot)))))
  61.  
  62.  
  63. ;; GAME-LOOP
  64. (as-> (create-game-state (create-grid [2 2]) []) state
  65.   (do (println state "\n") state)
  66.   (place-robot-in-state state (create-robot [0 0] (first directions)))
  67.   (do (println state "\n") state)
  68.   ;; (remove-robot-from-state state (first (:robots state)))
  69.   ;; (do (println state "\n") state)
  70.   (move-robot-in-state state (first (:robots state)))
  71.   (do (println state "\n") state)
  72. )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement