Created
December 5, 2011 11:46
-
-
Save bguthrie/1433336 to your computer and use it in GitHub Desktop.
An implementation of Conway's Game of Life in Clojure.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns gol-clj.spec.core | |
(:use [gol-clj.core]) | |
(:use [speclj.core])) | |
(describe "Game state after a single step" | |
(it "is empty given an empty set of points" | |
(should= #{} (gol-step #{}))) | |
(it "is empty given only a single point" | |
(should= #{} (gol-step #{[0 0]}))) | |
(it "works with a stable 4x4 configuration" | |
(should= | |
#{[0 0] [0 1] [1 0] [1 1]} | |
(gol-step | |
#{[0 0] [0 1] [1 0] [1 1]}))) | |
(it "turns a dead cell live as needed" | |
(should= | |
#{[0 0] [0 1] [1 0] [1 1]} | |
(gol-step | |
#{[0 0] [0 1] [1 0]}))) | |
(it "runs one of those flipper things" | |
(should= | |
#{[0 0] [-1 0] [1 0]} | |
(gol-step | |
#{[0 0] [0 -1] [0 1]}))) | |
) | |
(run-specs) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns gol-clj.core | |
(:use [clojure.set])) | |
(defn possible-neighbours-of [point] | |
(let [x (first point) y (last point)] | |
#{[(dec x) y] | |
[(inc x) y] | |
[(dec x) (dec y)] | |
[x (dec y)] | |
[(inc x) (dec y)] | |
[(dec x) (inc y)] | |
[x (inc y)] | |
[(inc x) (inc y)] | |
})) | |
(defn live-neighbours-of [existing-points point] | |
(intersection existing-points (possible-neighbours-of point))) | |
(def overpopulated 3) | |
(def underpopulated 2) | |
(def growth-factor 3) | |
(defn should-live? [existing-points point] | |
(let [neighbours-count (count (live-neighbours-of existing-points point))] | |
(if (contains? existing-points point) | |
(>= overpopulated neighbours-count underpopulated) | |
(= neighbours-count growth-factor)))) | |
(defn all-possible-points [existing-points] | |
(reduce | |
(fn [points point] | |
(union points (possible-neighbours-of point))) | |
#{} existing-points)) | |
(defn gol-step [existing-points] | |
(set | |
(filter | |
(partial should-live? existing-points) | |
(all-possible-points existing-points)))) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defproject gol-clj "1.0.0-SNAPSHOT" | |
:description "FIXME: write description" | |
:dependencies [[org.clojure/clojure "1.2.0"]] | |
:dev-dependencies [[speclj "1.2.0"]] | |
:test-path "spec/") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment