Skip to content

Instantly share code, notes, and snippets.

@marzvrover
Created March 20, 2020 06:31
Show Gist options
  • Save marzvrover/aa0271472b69c86cb89fb77787101a5f to your computer and use it in GitHub Desktop.
Save marzvrover/aa0271472b69c86cb89fb77787101a5f to your computer and use it in GitHub Desktop.
I decided to throw together Conway's Game of Life in Lua for a TikTok for no reason.
WIDTH=100
HEIGHT=50
PERCENT_START=66
CELL='0'
LIFECYCLES=25
TIME_DELAY='.246'
gameboard = {}
for i=0,HEIGHT
do
gameboard[i] = {}
for j=0,WIDTH
do
gameboard[i][j] = false
end
end
percent_total = math.floor((WIDTH * HEIGHT) * (PERCENT_START / 100))
percent_counter = 0
math.randomseed(os.time())
while (percent_counter <= percent_total)
do
local x = math.random(0, HEIGHT)
local y = math.random(0, WIDTH)
if (gameboard[x][y] == false)
then
gameboard[x][y] = true
percent_counter = percent_counter + 1
end
end
function copy2d(arr0, arr1)
for i=0,#arr0
do
arr1[i] = {}
for j=0,#arr0[i]
do
arr1[i][j] = arr0[i][j]
end
end
end
function processLife(gb0)
gb = {}
copy2d(gb0, gb)
for i=0,#gb
do
for j=0,#gb[i]
do
local neighbors = 0
if ((i > 0) and (gb[i-1][j] ~= false))
then
neighbors = neighbors + 1
end
if ((j > 0) and (gb[i][j-1] ~= false))
then
neighbors = neighbors + 1
end
if ((i < #gb) and (gb[i+1][j] ~= false))
then
neighbors = neighbors + 1
end
if ((j < #gb[0]) and (gb[i][j+1] ~= false))
then
neighbors = neighbors + 1
end
-- kill or birth
if (neighbors < 2)
then
gb0[i][j] = false
elseif (neighbors == 3)
then
gb0[i][j] = true
elseif (neighbors > 3)
then
gb0[i][j] = false
end
end
end
end
function printBoard(gb)
io.write("\027[H\027[2J")
for i=0,#gb
do
for j=0,#gb[i]
do
if (gb[i][j] == false)
then
io.write(" ")
else
io.write(CELL)
end
end
io.write('\n')
end
end
printBoard(gameboard)
for c=0,LIFECYCLES
do
processLife(gameboard)
printBoard(gameboard)
os.execute('sleep ' .. TIME_DELAY)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment