code / btui

Lines2.4K C1.3K Python559 Markdown219 make156 Lua131
(89 lines)
2 local btui = require("btui")
4 local W, H
6 local screen = {}
7 local function draw(bt, cells)
8 for y = 1,H do
9 for x = 1,W do
10 local alive = cells[x][y]
11 local key = tostring(x)..","..tostring(y)
12 if screen[key] ~= alive then
13 bt:move((x-1)*2, y-1)
14 bt:withbg(alive, alive, alive, function()
15 bt:write(" ")
16 end)
17 screen[key] = alive
18 end
19 end
20 end
21 end
23 local function get(cells, x, y)
24 x = ((x-1)%W) + 1
25 y = ((y-1)%H) + 1
26 return cells[x][y]
27 end
29 local function count_neighbors(cells, x, y)
30 local n = 0
31 for dx=-1,1 do
32 for dy=-1,1 do
33 if dx ~= 0 or dy ~= 0 then
34 n = n + get(cells, x+dx, y+dy)
35 end
36 end
37 end
38 return n
39 end
41 local function update(cells)
42 local new = {}
43 for x = 1,W do
44 new[x] = {}
45 for y = 1,H do
46 local n = count_neighbors(cells, x, y)
47 if (get(cells, x, y) == 0 and n == 3) or (get(cells, x, y) == 1 and (n == 2 or n == 3)) then
48 new[x][y] = 1
49 else
50 new[x][y] = 0
51 end
52 end
53 end
54 return new
55 end
57 btui(function(bt)
58 W = bt:width()
59 H = bt:height()
61 local cells = {}
62 for x = 1,W do
63 cells[x] = {}
64 for y = 1,H do
65 cells[x][y] = 0
66 end
67 end
69 local key = nil
70 local paused = false
71 while key ~= "q" and key ~= "Ctrl-c" do
72 draw(bt, cells)
73 if not paused then
74 cells = update(cells)
75 end
77 local mouse_x, mouse_y
78 key, mouse_x, mouse_y = bt:getkey(1)
79 if mouse_x and mouse_y then
80 cells[math.floor(mouse_x/2)][mouse_y] = 1
81 paused = true
82 else
83 paused = false
84 end
85 end
86 if key == "Ctrl-c" then
87 error("Interrupt received!")
88 end
89 end)