local WIDTH <const> = 12
local HEIGHT <const> = 7
-local cells = {}
-for i=1, WIDTH do
- cells[i] = {}
- for j=1, HEIGHT do
- r = pd.geometry.rect.new(32 * (i-1), 32 * (j-1), 32, 32)
- cells[i][j] = { cell = r, live = false }
- end
+-- Convenience function for iterating over 8 neighbors
+function neighbors(g1, x, y)
+ if (x - 1) > 0 and x < WIDTH and (y - 1) > 0 and y < HEIGHT then
+ return ipairs({
+ g1[x-1][y-1],
+ g1[x-1][y],
+ g1[x-1][y+1],
+ g1[x][y-1],
+ g1[x][y+1],
+ g1[x+1][y-1],
+ g1[x+1][y],
+ g1[x+1][y+1]})
+ else
+ -- TODO corners
+ return ipairs({
+ { live = false },
+ { live = false },
+ { live = false },
+ { live = false },
+ { live = false },
+ { live = false },
+ { live = false },
+ { live = false },
+ { live = false },
+ })
+ end
end
-local x = 1
-local y = 1
-
-local running = false
-
-function generation(cells)
- local tab = {}
- for i,row in ipairs(cells) do
- tab[i] = {}
+function generation(g1)
+ local g2 = {}
+ for i,row in ipairs(g1) do
+ g2[i] = {}
for j,cell in ipairs(row) do
- tab[i][j] = { cell = cell.cell, live = not cell.live }
+ liveNeighbors = 0
+ for r,neighbor in neighbors(g1, i, j) do
+ if neighbor.live then
+ liveNeighbors = liveNeighbors + 1
+ end
+ end
+
+ -- All other live cells die in the next generation. Similarly, all other dead cells stay dead.
+ live = false
+ if cell.live then
+ -- Any live cell with two or three live neighbours survives.
+ if liveNeighbors == 2 or liveNeighbors == 3 then
+ live = true
+ end
+ elseif not cell.live then
+ -- Any dead cell with three live neighbours becomes a live cell.
+ if liveNeighbors == 3 then
+ live = true
+ end
+ end
+ g2[i][j] = { cell = cell.cell, live = live }
end
end
- return tab
+ return g2
end
function draw(cells)
end
end
+local cells = {}
+for i=1, WIDTH do
+ cells[i] = {}
+ for j=1, HEIGHT do
+ r = pd.geometry.rect.new(32 * (i-1), 32 * (j-1), 32, 32)
+ cells[i][j] = { cell = r, live = false }
+ end
+end
+
+local x = 1
+local y = 1
+
+local running = false
function playdate.update()
if playdate.buttonJustPressed("b") then
running = not running