Skip to content

Instantly share code, notes, and snippets.

@Fitzse
Created July 7, 2012 22:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fitzse/3068458 to your computer and use it in GitHub Desktop.
Save Fitzse/3068458 to your computer and use it in GitHub Desktop.
Beginning of Conway's Game of Life in Clojure
(ns GameOfLife.core)
(defn next-state [neighbours state]
(cond
(= :dying state) :dead
(and (= :alive state)
(or (= 2 neighbours)
(= 3 neighbours))) :alive
:else :dying))
(defn is-within-one? [a b]
(<= (Math/abs (- a b)) 1))
(defn is-in-range? [coord cell]
(and (is-within-one? (:x coord) (:x cell))
(is-within-one? (:y coord) (:y cell))
(is-within-one? (:z coord) (:z cell))))
(defn is-neighbour? [othercell cell]
(let [other_coords (:coords othercell) cell_coords (:coords cell)]
(and (is-in-range? other_coords cell_coords)
(not (= other_coords cell_coords)))))
(defn living-neighbours [cell world]
(filter #(and (is-neighbour? % cell) (= (:state %) :alive)) world))
(defn evolve [world]
(filter #(not (= (:state %) :dead))
(map #(assoc % :state (next-state (count (living-neighbours % world)) (:state %))) world)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment