Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Game of Life Demo #7

Merged
merged 3 commits into from
Apr 19, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions demos/game_of_life.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
-- Game of Life Demo by Paul Adam
-- https://github.com/pauladam94

local fenster = require('fenster')
jonasgeiler marked this conversation as resolved.
Show resolved Hide resolved

local window_width = 200
local window_height = 200
local window_scale = 4
local window = fenster.open(
window_width,
window_height,
'Game of Life Demo - Press ESC to exit',
window_scale
)

local neighbours = { { -1, -1 }, { -1, 0 }, { 0, -1 }, { -1, 1 }, { 1, -1 }, { 1, 0 }, { 0, 1 }, { 1, 1 } }

local function count_alive_neighbours(x, y, world)
local count = 0
for _, neighbour in pairs(neighbours) do
local dx = x + neighbour[1]
local dy = y + neighbour[2]
if dx >= 1 and dx <= window_width and dy <= window_height and dy >= 1 then
if world[dx][dy] then
count = count + 1
end
end
end
return count
end

local function copy(obj)
if type(obj) ~= 'table' then return obj end
local res = {}
for k, v in pairs(obj) do res[copy(k)] = copy(v) end
return res
end

local world = {}
for x = 1, window_width do
world[x] = {}
for y = 1, window_height do
world[x][y] = false
if x % 2 == 0 then
world[x][y] = true
end
end
end

while window:loop() and not window.keys[27] do
local previous_world = copy(world)
for x = 1, window_width do
for y = 1, window_height do
if previous_world[x][y] then
window:set(x - 1, y - 1, 0xffffff)
else
window:set(x - 1, y - 1, 0x000000)
end
local count = count_alive_neighbours(x, y, previous_world)
world[x][y] = (count == 3) or (previous_world[x][y] and count == 2)
end
end
end
Loading