Skip to content
Phil Hagelberg edited this page Apr 23, 2023 · 2 revisions

This uses the TIC-80 platform to implement Conway's Game of Life, a famous cellular automata.

Left click to set a cell; right click to advance a frame.

See it running.

;; author: technomancy
;; script: fennel
;; input: mouse

(local size 2)
(local cells [])

(for [y 0 (/ 136 size)]
  (tset cells y [])
  (for [x 0 (/ 240 size)]
    (tset (. cells y) x false)))

(fn put [x y c] (tset (. cells y) x c))
(fn get [x y] (= 4 (pix (* x size) (* y size))))

(local neighborhood [[-1 -1] [-1 0] [-1 1] [0 -1] [0 1] [1 -1] [1 0] [1 1]])

(fn near [x y count i]
  (match (. neighborhood i)
    [dx dy] (near x y (+ count (if (get (+ x dx) (+ y dy)) 1 0)) (+ i 1))
    _ count))

(fn update []
  (for [y 0 (/ 136 size)]
    (for [x 0 (/ 240 size)]
      (let [n (near x y 0 1)
            last (get x y)]
        (put x y (or (= n 3) (and last (= n 2))))))))

(var pause true)

(fn _G.TIC []
  (when (not pause) (update))
  (match (mouse)
    (mx my true) (put (// mx size) (// my size) true)
    (_ _ _ _ true) (set pause (not pause)))
  (for [y 0 (/ 136 size)]
    (for [x 0 (/ 240 size)]
      (rect (* x size) (* y size) size size
            (if (. (. cells y) x) 4 0)))))

;; <PALETTE>
;; 000:4c3434000000000000000000ced2ba
;; </PALETTE>
Clone this wiki locally