Created
June 3, 2024 02:03
-
-
Save saubuny/2b1db90f57976dfe26755f95ade32b00 to your computer and use it in GitHub Desktop.
Conway's game of life in Lua
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ROWS = 16 | |
COLS = 32 | |
--- @param b table | |
local function zeroBoard(b) | |
for i = 1, ROWS do | |
b[i] = {} | |
for j = 1, COLS do | |
-- 0 is truthy. this is annoying. | |
b[i][j] = false | |
end | |
end | |
end | |
--- @param b table | |
local function randomBoard(b) | |
for i = 1, ROWS do | |
b[i] = {} | |
for j = 1, COLS do | |
if math.random(0, 1) == 1 then | |
b[i][j] = true | |
else | |
b[i][j] = false | |
end | |
end | |
end | |
end | |
--- Thanks Tsoding, 1-based indexing made this harder | |
--- @param cx number | |
--- @param cy number | |
--- @param b table | |
--- @return number | |
local function count_nbors(cx, cy, b) | |
local nbors = 0 | |
for dx = -1, 1 do | |
for dy = -1, 1 do | |
if dx ~= 0 or dy ~= 0 then | |
local x = ((cx + dx) % ROWS) | |
local y = ((cy + dy) % COLS) | |
if x ~= 0 and y ~= 0 and b[x][y] then | |
nbors = nbors + 1 | |
end | |
end | |
end | |
end | |
return nbors | |
end | |
--- @param b table | |
local function print_board(b) | |
for x = 1, ROWS do | |
for y = 1, COLS do | |
io.write(b[x][y] and "#" or ".") | |
end | |
io.write("\n") | |
end | |
end | |
--- @param b table | |
--- @return table | |
local function next(b) | |
local nb = {} | |
zeroBoard(nb) | |
for x = 1, ROWS do | |
for y = 1, COLS do | |
local nbors = count_nbors(x, y, b) | |
nb[x][y] = b[x][y] and (nbors == 2 or nbors == 3) or nbors == 3 | |
end | |
end | |
return nb | |
end | |
local b = {} | |
randomBoard(b) | |
-- zeroBoard(b) | |
b[3][2] = true | |
b[3][3] = true | |
b[3][4] = true | |
b[2][4] = true | |
b[1][3] = true | |
b[7][6] = true | |
b[7][7] = true | |
b[7][8] = true | |
for _ = 1, math.huge do | |
os.execute("clear") | |
print_board(b) | |
b = next(b) | |
local r = io.read("*l") | |
if r == "end" then | |
break | |
elseif r == "reset" then | |
randomBoard(b) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment