Skip to content

Instantly share code, notes, and snippets.

@wvdlaan
Last active January 13, 2016 20:18
Show Gist options
  • Save wvdlaan/9f47b50ea7bede4570ff to your computer and use it in GitHub Desktop.
Save wvdlaan/9f47b50ea7bede4570ff to your computer and use it in GitHub Desktop.
Game of life dojo
(ns gol.core
(:require
[reagent.core :as reagent]
[sablono.core :as sab :include-macros true])
(:require-macros
[devcards.core :as dc :refer [defcard deftest defcard-rg]]))
(enable-console-print!)
(defn neighbours
[[x y]]
(for [dx [-1 0 1]
dy [-1 0 1]
:when (not= 0 dx dy)]
[(+ x dx) (+ y dy)]))
(defn cell-alive?
[cells pos]
(let [alive? (cells pos)
c (->> (neighbours pos)
(filter cells)
count)]
(println pos c)
(if alive?
(<= 2 c 3)
(= c 3))))
(defn next-cells
[cells]
(let [cells-to-check (into #{} (mapcat neighbours cells))]
(into #{} (filter (partial cell-alive? cells) cells-to-check))))
(defcard first-card
(neighbours [0 0]))
(defcard two
(cell-alive? #{[0 0] [1 1] [1 0]} [1 0]))
(defcard next-cells-card
(take 6 (iterate next-cells #{[1 1] [1 2] [1 3]})))
(defn render-grid
[cells rows cols]
[:table
[:tbody
(for [row (range rows)]
^{:key row} [:tr (for [col (range cols)]
^{:key col} [:td {:style {:background (if (cells [row col]) "black" "white")}} "_"])])]])
(defcard-rg ui-test
(let [state (reagent/atom #{[1 1] [1 2] [1 3]})]
(render-grid @state 10 10)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment