May 24, 2015

Tetris in clojurescript and re-frame Part 7 - Collision Detection

Is Move Allowed?

In the last chapter we already used the is-move-allowed? function. There are four functions at all taking care of it.

The first one just checks the boundaries and if none tetriminio is defined at that position:

(defn is-moving-part-allowed? [x y grid]
  (and (<= 0 x) (< x 10) (<= 0 y) (< y 20) (= 0 (get-in grid [x y]))))

The second one makes use of the function definitions. If a x or y key exists in the map if will apply the function to the old x or y value. If not, it just returns the old one. This is how we update the four blocks:

(defn move-x-y [x y rec]
  (let [x' (if (get rec :x) ((get rec :x) x) x)
        y' (if (get rec :y) ((get rec :y) y) y)]
    {:x x' :y y'}))
(defn realize-move [x y t grid] (assoc-in grid [x y] t))

This draws one tetriminio in the grid according to the tetriminio definition:
(defn draw-tet [{:keys [x y t o] :as cur-tet} tet-recipe d grid]
  (let [new-position (map #(move-x-y x y %) (get-in tet-recipe [t o]))]
      (reduce (fn [a b] (realize-move (:x b) (:y b) (* t d) a)) grid new-position)))

is-move-allowed? basically only calls the functions defined above for every single block and returns true orfalse:
(defn is-move-allowed? [{:keys [x y t o]} cur-active grid tet-recipe]
  (let [new-position (map #(move-x-y x y %) (get-in tet-recipe [t o]))
        removed-grid (draw-tet cur-active tet-recipe 0 grid)]
    (h/not-in? (map #(is-moving-part-allowed? (:x %) (:y %) removed-grid) new-position) false)))
Tags: tetris clojuresrcipt