Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Lua Language for ComputerCraft
- -- Conway's Game of Life (Tweaked Version)
- -- CONFIGURATION
- local width, height = 20, 10 -- Size of the grid
- local survival = {2,3} -- Cells survive with this many neighbors
- local birth = {3} -- Dead cells become alive with this many neighbors
- local delay = 0.5 -- Delay between generations
- -- Initialize empty grid
- local grid = {}
- for y=1,height do
- grid[y] = {}
- for x=1,width do
- grid[y][x] = math.random(0,1) -- Randomly start alive or dead
- end
- end
- -- Count alive neighbors of a cell
- local function countNeighbors(x, y)
- local count = 0
- for dy=-1,1 do
- for dx=-1,1 do
- if not (dx == 0 and dy == 0) then
- local nx, ny = x+dx, y+dy
- if nx >= 1 and nx <= width and ny >=1 and ny <= height then
- count = count + grid[ny][nx]
- end
- end
- end
- end
- return count
- end
- -- Compute next generation
- local function nextGeneration()
- local newGrid = {}
- for y=1,height do
- newGrid[y] = {}
- for x=1,width do
- local alive = grid[y][x]
- local neighbors = countNeighbors(x, y)
- if alive == 1 then
- newGrid[y][x] = 0
- for _, v in ipairs(survival) do
- if neighbors == v then
- newGrid[y][x] = 1
- break
- end
- end
- else
- newGrid[y][x] = 0
- for _, v in ipairs(birth) do
- if neighbors == v then
- newGrid[y][x] = 1
- break
- end
- end
- end
- end
- end
- grid = newGrid
- end
- -- Render the grid on terminal
- local function render()
- term.clear()
- term.setCursorPos(1,1)
- for y=1,height do
- for x=1,width do
- if grid[y][x] == 1 then
- term.write("█")
- else
- term.write(" ")
- end
- end
- term.write("
- ")
- end
- end
- -- Main loop
- while true do
- render()
- nextGeneration()
- sleep(delay)
- end
- Features of This Tweaked Version
Advertisement
Add Comment
Please, Sign In to add comment