Skip to content

Instantly share code, notes, and snippets.

@cgrand
Created November 26, 2012 18:19
Show Gist options
  • Save cgrand/4149750 to your computer and use it in GitHub Desktop.
Save cgrand/4149750 to your computer and use it in GitHub Desktop.
(ns life.core
(:require [quil.core :as q]))
(defn neighbours [[x y]]
(for [dx [-1 0 1]
dy [-1 0 1]
:when (not= 0 dx dy)]
[(+ dx x) (+ dy y)]))
(defn step [cells]
(let [f (frequencies
(mapcat neighbours cells))]
(set
(for [[cell n] f
:when (or (= 3 n)
(and (= 2 n)
(cells cell)))]
cell))))
(defn stepper [neighbours survive? birth?]
(fn [cells]
(let [f (frequencies
(mapcat neighbours cells))]
(set
(for [[cell n] f
:when (if (cells cell)
(survive? n)
(birth? n))]
cell)))))
(def step (stepper neighbours
#(or (= % 2) (= % 3))
#(= % 3)))
(def step (stepper neighbours #{2 3} #{3}))
(defn hex-neighbours [[x y]]
(for [dy [-1 0 1]
dx (cond
(zero? dy) [-1 1]
(odd? y) [0 1]
:else [-1 0])]
[(+ dx x) (+ dy y)]))
(def hex-step (stepper hex-neighbours #{2} #{3}))
;;; visualisation
(def cells
(atom
(set
(repeatedly
80
(juxt #(rand-int 15) #(rand-int 15))))))
(defn setup []
(q/smooth)
(q/frame-rate 30)
(q/stroke-weight 0)
(q/background 0 0 255))
(defn draw []
(q/background 0 0 255)
(q/fill 255 255 0)
(doseq [[x y] @cells]
(q/ellipse (+ (* 30 x) (if (odd? y) 15 0)) (* 30 y) 24 24)))
(q/defsketch life
:title "life is good"
:setup setup
:draw draw
:size [400 400])
(def thread (future
(while true
(Thread/sleep 500)
(swap! cells step))))
(def thread2 (future
(while true
(Thread/sleep 100)
(swap! cells step))))
#_(def hex-thread (future
(while true
(Thread/sleep 500)
(swap! cells hex-step))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment