-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcgol.clj
More file actions
executable file
·43 lines (35 loc) · 1.12 KB
/
cgol.clj
File metadata and controls
executable file
·43 lines (35 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#!/usr/bin/env clojure
(def width 50)
(def height 30)
(def density 0.2)
(defn init-grid []
(vec (for [_ (range height)]
(vec (for [_ (range width)]
(< (rand) density))))))
(defn count-neighbors [grid x y]
(reduce + (for [dx [-1 0 1]
dy [-1 0 1]
:when (not (and (= dx 0) (= dy 0)))]
(let [nx (mod (+ x dx) width)
ny (mod (+ y dy) height)]
(if (get-in grid [ny nx]) 1 0)))))
(defn next-generation [grid]
(vec (for [y (range height)]
(vec (for [x (range width)]
(let [alive (get-in grid [y x])
neighbors (count-neighbors grid x y)]
(or (and alive (or (= neighbors 2) (= neighbors 3)))
(and (not alive) (= neighbors 3)))))))))
(defn print-grid [grid]
;; Clear screen
(println "\033[H\033[2J")
(doseq [row grid]
(println (apply str (map #(if % "█" " ") row)))))
(defn game-loop [grid]
(loop [g grid]
(print-grid g)
(Thread/sleep 100)
(recur (next-generation g))))
(defn -main []
(game-loop (init-grid)))
(-main)