Last active
December 12, 2015 07:49
-
-
Save ponzao/4739356 to your computer and use it in GitHub Desktop.
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 core | |
(:use quil.core)) | |
(defn tick | |
[state] | |
(let [neighbors (fn [x y] | |
(for [xinc (range -1 (inc 1)) | |
yinc (range -1 (inc 1)) :when (not (= 0 xinc yinc))] | |
[(+ x xinc) (+ y yinc)])) | |
map-matrix (fn [f matrix] | |
(map-indexed (fn [x row] | |
(map-indexed (fn [y cell] (f x y cell)) row)) | |
matrix))] | |
(mapv vec | |
(map-matrix (fn [x y cell] | |
(let [n (count (remove nil? | |
(map #(get-in state %) | |
(neighbors x y))))] | |
(cond (= n 3) :cell | |
(and (= cell :cell) (= n 2)) :cell | |
:else nil))) | |
state)))) | |
(def current-state | |
(atom (mapv (partial mapv #(when (= % \#) :cell)) | |
[" # " | |
" # # " | |
" # ## " | |
" ## " | |
" " | |
" ### ### " | |
" ### ########## " | |
" ##### ### ########## " | |
" ##### ########## " | |
" ##### ########## " | |
" ##### ########## " | |
" "]))) | |
(defn adjust | |
[n] | |
(int (Math/floor (/ n 20.0)))) | |
(defn mouse-handler | |
[] | |
(try | |
(swap! current-state assoc-in [(adjust (mouse-y)) (adjust (mouse-x))] :cell) | |
(catch IndexOutOfBoundsException e | |
(println e)))) | |
(defn draw | |
[] | |
(stroke 10) | |
(stroke-weight 1) | |
(let [width 20] | |
(doall (map-indexed | |
(fn [row cols] | |
(doall (map-indexed | |
(fn [col cell] | |
(if cell | |
(fill 255) | |
(fill 0)) | |
(rect (* 20 col) (* 20 row) width width)) | |
cols))) | |
@current-state)))) | |
(def thread (Thread. | |
#(while true | |
(swap! current-state tick) | |
(Thread/sleep 1000)))) | |
(.start thread) | |
(defn setup | |
[] | |
(smooth) | |
;(frame-rate 1) | |
(background 200)) | |
(defsketch game-of-life | |
:title "Game of Life" | |
:setup setup | |
:draw draw | |
:size [640 240] | |
:mouse-dragged mouse-handler | |
:mouse-pressed mouse-handler) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment