Skip to content

Instantly share code, notes, and snippets.

@abachman
Last active November 15, 2017 03:01
Show Gist options
  • Save abachman/99352000ec235f2a7d01399474507268 to your computer and use it in GitHub Desktop.
Save abachman/99352000ec235f2a7d01399474507268 to your computer and use it in GitHub Desktop.
-- conway's game of life
-- by adam b
world = {}
pw = "a"
nw = "b"
function _init()
for y = 1,128 do
add(world, {})
for x = 1,128 do
add(world[y], {a=0,b=0})
end
end
-- r pentamino
local o = 60
world[1+o][2+o].a = 1
world[1+o][3+o].a = 1
world[2+o][1+o].a = 1
world[2+o][2+o].a = 1
world[3+o][2+o].a = 1
-- or just randomize
set_world()
cls()
end
-- randomize world
function set_world()
for y = 1,128 do
for x = 1,128 do
world[y][x][pw] = flr(rnd(2))
end
end
end
function check_world()
for y = 1,128 do
for x = 1,128 do
nabes = count_neighbors(x, y)
if world[y][x][pw] == 0 then
if nabes == 3 then
world[y][x][nw] = 1
else
world[y][x][nw] = 0
end
else
if nabes == 2 or nabes == 3 then
world[y][x][nw] = 1
else
world[y][x][nw] = 0
end
end
end
end
end
-- neighbors around the cell
offsets = {
{-1,-1},{0,-1},{1,-1},
{-1, 0}, {1, 0},
{-1, 1},{0, 1},{1, 1}
}
function count_neighbors(x, y)
local sum = 0
for n, offs in pairs(offsets) do
nx = x + offs[1]
if nx == 0 then nx = 128
elseif nx == 129 then nx = 1
end
ny = y + offs[2]
if ny == 0 then ny = 128
elseif ny == 129 then ny = 1
end
sum += world[ny][nx][pw]
end
return sum
end
function _update()
check_world()
local tw = pw
pw = nw
nw = tw
end
function _draw()
for y = 1,128 do
for x = 1,128 do
if world[y][x][pw] == 1 then
pset(x, y, 2)
else
pset(x, y, 0)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment