Skip to content

Instantly share code, notes, and snippets.

@seeflanigan
Created December 14, 2012 00:56
Show Gist options
  • Save seeflanigan/4281571 to your computer and use it in GitHub Desktop.
Save seeflanigan/4281571 to your computer and use it in GitHub Desktop.
Conway's Game of Life in Clojure (with Venkat at CodeRetreat, Uncubed, 2012/01/21)
(ns game
(:use clojure.test))
(defn vitality [cell-state live-neighbors]
(or (= live-neighbors 3) (and cell-state (= live-neighbors 2))))
(defn count-live-neighbors [grid position]
(let [row (first position)
column (last position)]
(def neighbors
(list
(list (- row 1) (- column 1)) (list (- row 1) column) (list (- row 1) (+ column 1))
(list row (- column 1)) (list row (+ column 1))
(list (+ row 1) (- column 1)) (list (+ row 1) column) (list (+ row 1) (+ column 1))))
(count (filter #(get grid %) neighbors))))
(defn tick [grid]
(defn new-state-for-cell [result-grid map-entry]
(assoc result-grid (key map-entry) (vitality (get grid (key map-entry)) (count-live-neighbors grid (key map-entry)))))
(reduce new-state-for-cell (hash-map) grid))
(def test-canary
(is true))
(def test-dead-cell-w-3-live-neighbors-alive
(is (vitality false 3)))
(def test-dead-cell-w-1-live-neighbors-alive
(is (not (vitality false 1))))
(def test-dead-cell-w-5-live-neighbors-alive
(is (not (vitality false 5))))
(def test-live-cell-w-2-live-neighbors-alive
(is (vitality true 2)))
(def test-live-cell-w-3-live-neighbors-alive
(is (vitality true 3)))
(def test-live-cell-w-1-live-neighbors-dead
(is (not (vitality true 1))))
(def test-live-cell-w-5-live-neighbors-dead
(is (not (vitality true 5))))
(def test-zero-live-neighbors
(let [grid (hash-map
'(0 0) false '(0 1) false '(0 2) false
'(1 0) false '(1 1) false '(1 2) false
'(2 0) false '(2 1) false '(2 2) false
)
position '(1 1)]
(is (= 0 (count-live-neighbors grid position)))))
(def test-two-live-neighbors
(let [grid (hash-map
'(0 0) false '(0 1) false '(0 2) false
'(1 0) true '(1 1) true '(1 2) true
'(2 0) false '(2 1) false '(2 2) false
)
position '(1 1)]
(is (= 2 (count-live-neighbors grid position)))))
(def test-two-live-neighbors-for-corner-cell
(let [grid (hash-map
'(0 0) false '(0 1) true '(0 2) false
'(1 0) true '(1 1) false '(1 2) true
'(2 0) false '(2 1) false '(2 2) false
)
position '(0 0)]
(is (= 2 (count-live-neighbors grid position)))))
(def test-tick
(let [grid (hash-map
'(0 0) false '(0 1) false '(0 2) false
'(1 0) true '(1 1) true '(1 2) true
'(2 0) false '(2 1) false '(2 2) false
)
position '(0 0)
result-grid (hash-map
'(0 0) false '(0 1) true '(0 2) false
'(1 0) false '(1 1) true '(1 2) false
'(2 0) false '(2 1) true '(2 2) false
)]
(is (= result-grid (tick grid)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment