Skip to content

Instantly share code, notes, and snippets.

@mmzsource
Last active June 28, 2021 19:32
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmzsource/655b9dcfe56eed8a045022837186ed84 to your computer and use it in GitHub Desktop.
Save mmzsource/655b9dcfe56eed8a045022837186ed84 to your computer and use it in GitHub Desktop.
;; This script prints runs game of life on a randomly chosen GOL object
;;
;; This commandline script has 1 dependency:
;; Babashka installed: https://github.com/babashka/babashka#installation (and bb on PATH)
;;
;; Run like this: bb bb-gol.clj
;; Thanks to Christophe Grand for the brilliant GOL implementation
;; of the neighbours and step function!
;; http://clj-me.cgrand.net/2011/08/19/conways-game-of-life/
(defn neighbours [[x y]]
(for [dx [-1 0 1] dy (if (zero? dx) [-1 1] [-1 0 1])]
[(+ dx x) (+ dy y)]))
(defn step [cells]
(set (for [[loc n] (frequencies (mapcat neighbours cells))
:when (or (= n 3) (and (= n 2) (cells loc)))]
loc)))
(defn stringify-board [w h cells]
(vec (for [x (range w)]
(vec (for [y (range h)]
(if (contains? cells [y x]) "▒" " "))))))
(def blinker {:width 5
:height 5
:cells #{[2 1] [2 2] [2 3]}})
(def pulsar {:width 15
:height 15
:cells #{[3 1] [4 1] [5 1] [9 1] [10 1] [11 1]
[1 3] [6 3] [8 3] [13 3]
[1 4] [6 4] [8 4] [13 4]
[1 5] [6 5] [8 5] [13 5]
[3 6] [4 6] [5 6] [9 6] [10 6] [11 6]
[3 8] [4 8] [5 8] [9 8] [10 8] [11 8]
[1 9] [6 9] [8 9] [13 9]
[1 10] [6 10] [8 10] [13 10]
[1 11] [6 11] [8 11] [13 11]
[3 13] [4 13] [5 13] [9 13] [10 13] [11 13]}})
(def glider {:width 20
:height 20
:cells #{[2 1] [3 2] [1 3] [2 3] [3 3]}})
(def spaceship {:width 20
:height 20
:cells #{[15 1] [18 1] [14 2] [14 3] [18 3] [14 4] [15 4] [16 4] [17 4]}})
(let [board (rand-nth [blinker pulsar glider spaceship])
width (:width board)
height (:height board)
start-cells (:cells board)]
(loop [cells start-cells]
(Thread/sleep 250)
(println "\033[H\033[2J") ; equals 'clear' command in shell -> see: https://github.com/babashka/book/issues/6
(let [next-gen (step cells)
board (stringify-board width height next-gen)]
(run! #(println (reduce str %)) board)
(recur next-gen))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment