Skip to content

Instantly share code, notes, and snippets.

@jcytong
Created June 3, 2021 02:44
Show Gist options
  • Save jcytong/714533d4ea845744ebad6e107deadbc7 to your computer and use it in GitHub Desktop.
Save jcytong/714533d4ea845744ebad6e107deadbc7 to your computer and use it in GitHub Desktop.
Clojure TO—Clojure Beginners Chat
(ns demo.ui
(:require
[reagent.dom :as rdom]
[reagent.core :as r]))
(update [true false] 0 not)
(defn future-cell-state [cell neighbours]
(let [num-alive (count (filter true? neighbours))]
(cond (and cell (<= 2 num-alive 3))
true
(and (not cell) (= num-alive 3))
true
:else
false
)))
(defn get-neighbours [i grid]
(map (fn [j] (get grid (mod j 100) false))
[(- i 11) (- i 10) (- i 9)
(- i 1) (+ i 1)
(+ i 9) (+ i 10) (+ i 11)]))
(defn game-of-life [cells]
(vec (map-indexed
(fn [i cell]
(future-cell-state cell (get-neighbours i cells)))
cells)))
(defonce state (r/atom (vec (repeatedly 100
(fn [] (rand-nth [true false]))))))
(defonce interval (js/setInterval (fn [] (swap! state game-of-life)) 100))
(defn app-view []
[:div
{:style {:width "250px"
:display "flex"
:flex-wrap "wrap"}}
(map-indexed (fn [i foo] [:div {:key i
:style {:width "25px"
:height "25px"
:border "1px solid black"
:box-sizing "border-box"
:background (if foo "black" "white")}
:on-click (fn [] (swap! state update i not))}])
@state)
])
(defn render! []
(rdom/render
[app-view]
(js/document.getElementById "app")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment