Skip to content

Instantly share code, notes, and snippets.

@djanatyn
Created June 20, 2013 15:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save djanatyn/5823689 to your computer and use it in GitHub Desktop.
Save djanatyn/5823689 to your computer and use it in GitHub Desktop.
ants with threads <3
(ns ants.core
(:import java.util.Date))
(defn graveyard [ant]
(str "RIP " (:name ant) " the ant - " (.. (Date.) (toString))))
(defn random-name [length]
(apply str (repeatedly length #(char (+ 97 (rand-int 25))))))
(def running?
"is the simulation currently running?"
(atom false))
(defn random-ant [metabolism]
(agent {:dead? false :name (random-name 5) :health 100 :metabolism metabolism}))
(defn random-colony [num-ants]
(take num-ants (repeatedly #(random-ant (rand-int 100)))))
(def ant-colony
"different ants have different threads!"
[(agent {:dead? false :health 100 :metabolism 1000 :name (random-name 5)})
(agent {:dead? false :health 100 :metabolism 100 :name (random-name 5)})
(agent {:dead? false :health 100 :metabolism 2000 :name (random-name 5)})])
(defn tick [ant]
(if (and @running? (= (:dead? ant) false))
(do (Thread/sleep (:metabolism ant))
(send *agent* tick)
(if (= (:health ant) 0) {:dead? true :tombstone (graveyard ant)}
(assoc ant :health (- (:health ant) 1))))
ant))
(defn start [colony]
(reset! running? true)
(map #(send % tick) colony))
(defn status-report [colony]
(let [dead (filter #(= (:dead? (deref %)) true) colony)
living (remove (set dead) colony)]
(println "LIVING")
(doseq [ant living]
(println (:name (deref ant)) "the ant has" (:health (deref ant)) "health."))
(println "DEAD")
(doseq [ant dead]
(println (:tombstone (deref ant))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment