Skip to content

Instantly share code, notes, and snippets.

@zehnpaard
Last active June 27, 2016 09:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zehnpaard/e594a79ef5c4edff8651a066a966f0c2 to your computer and use it in GitHub Desktop.
Save zehnpaard/e594a79ef5c4edff8651a066a966f0c2 to your computer and use it in GitHub Desktop.
Game of Life with Clojure and Quil
(ns game-of-life
(:require [quil.core :as q] [quil.middleware :as m]))
;Core logic
(defn next-round
"Take as input a set of vectors representing coords of currently living cells
and return a set of vectors representing coords of living cells in the next stage"
[live-cells]
(letfn [(surrounding [[cell-x cell-y]]
(for [x [-1 0 1]
y [-1 0 1] :when (not (= 0 x y))]
[(+ cell-x x) (+ cell-y y)]))
(living-count [cells]
(count
(clojure.set/intersection
live-cells (set cells))))
(dead-to-life? [dead-cell]
(= 3 (living-count (surrounding dead-cell))))
(remain-alive? [live-cell]
(< 1 (living-count (surrounding live-cell)) 4))]
(let [surrounds (->> live-cells
(map surrounding)
(apply concat)
distinct)
new-alive (->> surrounds
(remove live-cells)
(filter dead-to-life?))
remains (filter remain-alive? live-cells)]
(clojure.set/union (set new-alive) (set remains)))))
;Define setup variables
(def start-state ;Example initial state values
#{[1 1] [0 0] [1 0] [0 1] [3 3] [2 2] [2 3]})
(def screen-size [500 500])
(def screen-center (map #(/ % 2) screen-size))
(def square-size 10)
;Custom function using Quil
(defn draw-live-cells
"Take a set of vectors representing coords and
draw squares according to those coords"
[live-cells]
(doseq [[i j] live-cells]
(apply q/rect
(map #(* % square-size) [i j 1 1]))))
;Quil core functions
(defn setup []
(q/frame-rate 10)
start-state)
(defn update [state]
(next-round state))
(defn draw [state]
(q/background 255)
(q/fill 255 0 0)
(apply q/translate screen-center)
(draw-live-cells state))
(q/defsketch game-of-life
:size screen-size
:setup setup
:update update
:draw draw
:middleware [m/fun-mode])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment