summary refs log tree commit diff
path: root/lib/cells.fnl
blob: 3a43010a4c9629f75a73ffd50c600b0add4063fe (plain)
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
(local cell (require :lib.cell))

(local neighbors [{:x -1 :y -1}
                  {:x -1 :y 0}
                  {:x -1 :y 1}
                  {:x 0 :y -1}
                  {:x 0 :y 1}
                  {:x 1 :y -1}
                  {:x 1 :y 0}
                  {:x 1 :y 1}])

(fn neighbors> [f threshold]
  (var x 0)
  ;; nnn this could be faster maybe
  (for [k 1 8]
    (when (> (cell.aliveness (f (. neighbors k))) threshold)
      (set x (+ x 1))))
  x)

(local life
  {cell.init
   (fn [self]
     (setmetatable {} self))
   cell.birth
   (fn [self get]
     (if (= (neighbors> get 0) 3)
         self
         nil))
   cell.update
   (fn [self get]
     (let [n (neighbors> get 0)]
       (if (or (= n 3)
               (= n 2))
         self
         nil)))
   cell.aliveness
   #1
   cell.color
   #[0.4 0.4 0.7]
   })

(local brain
  {cell.init
   (fn [self]
     (setmetatable {:stage 0} self))
   cell.birth
   (fn [self get]
     (if (= (neighbors> get 0.8) 2)
         (do
           (setmetatable {:stage 0} (getmetatable self)))
         nil))
   cell.update
   (fn [self get]
     (if (= self.stage 0)
         (setmetatable {:stage 1} (getmetatable self))
         nil))
   cell.aliveness
   #(- 1 (* 0.5 $.stage))
   cell.color
   #(if (= $.stage 0)
        [0.7 0.4 0.3]
        (= $.stage 1)
        [0.2 0.2 0.3])
   })

(local boom
  {cell.init
   (fn [self]
     (setmetatable {:life 1} self))
   cell.birth
   (fn [self get]
     (if (and (> self.life 0.08)
              (> (neighbors> get (* (if (> self.life 0.9) 0.3 0.1) (math.random 7))) 0))
         (do
           (setmetatable {:life (* self.life 0.8)} (getmetatable self)))
         nil))
   cell.update
   (fn [self get]
     (if (> self.life 0.3)
         (setmetatable {:life (* self.life (+ 0.5 (* (math.random 5) 0.1)))} (getmetatable self))
         nil))
   cell.aliveness
   #$.life
   cell.color
   #[(+ 0.4 (* 0.6 $.life))
     (math.max 0 (- 0.8 (* 0.9 (- 1 $.life))))
     (+ 0.1 )]})

{: life : brain : boom}