Create a gist now

Instantly share code, notes, and snippets.

anonymous /overload.clj
Created Nov 4, 2012

What would you like to do?
Day of Code
(def size 3)
(def empty-board (vec (repeat size (vec (repeat size {:color :none :num 0})))))
(defn get-winner
[filtered-board (filter #(not (= :none %)) (flatten board))]
(if (and (seq filtered-board)
(every? #(= (:color (first filtered-board)) (:color %)) filtered-board))
(:color (first filtered-board))
(defn adjacent-cells [x y]
(filter (fn [[x y]] (and (not (neg? y)) (not (neg? x)) (< x size) (< y size)))
(list [(dec x) y] [(inc x) y] [x (dec y)] [x (inc y)])))
(defn spill [x y board]
(defn place-piece [color board x y]
(let [board (update-in board [x y :num]
#(if (= (+ 1 %) (overload-limit board x y)) 0 (inc %)))]
(if (= 0 (get-in board [x y :num]))
(spill x y board)
(defn overload-limit
[board x y]
(and (or (= x 0) (= x (- size 1)))
(or (= y 0) (= y (- size 1)))) 2
(or (or (= x 0) (= x (- size 1)))
(or (= y 0) (= y (- size 1)))) 3
:else 4))
;; tests
(def black-board (vec (repeat size (vec (repeat size {:color :black :num 1})))))
(def white-board (vec (repeat size (vec (repeat size {:color :white :num 1})))))
(def mixed-board (assoc-in white-board [1 1 :color] :black))
(describe "empty board"
(it "has no winner"
(should= :none (get-winner empty-board))))
(describe "board with black pieces"
(it "has winner - black"
(should= :black (get-winner black-board))))
(describe "board with white pieces"
(it "has winner - white"
(should= :white (get-winner white-board))))
(describe "board with mixed pieces"
(it "has no winner"
(should= :none (get-winner mixed-board))))
(describe "placing piece in empty square"
(it "has board with piece in square"
(should= 1 (get-in (place-piece :white empty-board 0 0) [0 0 :num]))))
(describe "placing piece in corner square with one"
(it "leaves empty square"
(should= 0 (get-in (place-piece :white (update-in empty-board [0 0 :num] inc) 0 0) [0 0 :num]))))
(describe "placing piece in edge square with two"
(it "leaves empty square"
(should= 0 (get-in (place-piece :white (assoc-in empty-board [0 1 :num] 2) 0 1) [0 1 :num]))))
(describe "adjacent squares function"
(it "returns adjacent squares"
(should= (list [1 0] [0 1]) (adjacent-cells 0 0))))
(describe "placing piece in centre square with three"
(it "leaves empty square"
(should= 0 (get-in (place-piece :white (assoc-in empty-board [1 1 :num] 3) 1 1) [1 1 :num]))))
(describe "corner"
(it "has overload limit of two"
(should= 2 (overload-limit empty-board 0 0))))
(describe "edge"
(it "has overload limit of three"
(should= 3 (overload-limit empty-board 0 1))))
(describe "middle"
(it "has overload limit of four"
(should= 4 (overload-limit empty-board 1 1))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment