Skip to content

Instantly share code, notes, and snippets.

@txus
Created July 18, 2016 17:03
Show Gist options
  • Save txus/bed5ced790ccb1344511e938fb754aae to your computer and use it in GitHub Desktop.
Save txus/bed5ced790ccb1344511e938fb754aae to your computer and use it in GitHub Desktop.
Small Town
(ns small-town.app)
;; person
(def genders #{:male :female})
(defn make-person [age]
{:age age
:gender (rand-nth (vec genders))
:dead false})
(defn age [{:keys [age] :as person}]
(let [next-age (inc age)]
(cond-> person
(>= next-age 15)
(assoc :dead true)
true
(assoc :age next-age))))
(def male? (comp boolean #{:male} :gender))
(def female? (complement male?))
;; town
(defn make-town [{:keys [people] :as town}]
(assoc town :people (repeatedly people make-person)))
(defn render [{:keys [people food] :as town}]
(let [elem (.. js/document (createElement "DIV"))]
(aset elem "innerHTML"
(str
"<p>"
"People: " (pr-str people)
"<br/>"
"Food: " (pr-str food)
"</p>"))
elem))
(defn population-eats [{:keys [eating-rate food people] :as town}]
(update town :food (fn [f]
(- f (* (count (filter (comp not :dead) people)) eating-rate)))))
(defn population-ages [{:keys [people] :as town}]
(update town :people (fn [peeps]
(map age peeps))))
(defn gravedigger-works [{:keys [people] :as town}]
(update town :people (partial remove :dead)))
(defn turn [{:keys [food people eating-rate] :as town}]
(-> town
population-eats
population-ages
gravedigger-works))
(defn init []
(let [c (.. js/document (createElement "DIV"))
town (atom (make-town {:food 500000
:people 10
:eating-rate 12}))]
(js/setInterval (fn []
(let [new-town (swap! town turn)]
(.. js/document (getElementById "container") (appendChild (render new-town)))))
1000)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment