From 900003177f0060499bbfce84e8bf94922dd129c9 Mon Sep 17 00:00:00 2001 From: JC Date: Sun, 30 Jul 2023 21:08:09 -0500 Subject: [PATCH] Add B3/S23 rules These are the B3/S23 rules as displayed on wikipedia, except for the edge squares due to array indexing. --- source/main.lua | 83 ++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 65 insertions(+), 18 deletions(-) diff --git a/source/main.lua b/source/main.lua index cc8aee4..0b94cc8 100644 --- a/source/main.lua +++ b/source/main.lua @@ -4,29 +4,63 @@ local gfx = playdate.graphics local WIDTH = 12 local HEIGHT = 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) @@ -46,6 +80,19 @@ 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 -- 2.20.1