Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Attach to monitor on the right
- local monitor = peripheral.wrap("right")
- if not monitor then
- error("Monitor not found on the right side.")
- end
- -- Setup monitor
- monitor.setTextScale(0.5) -- Smaller text = more space
- term.redirect(monitor)
- monitor.clear()
- -- Configuration
- local width, height = monitor.getSize()
- local delay = 0.2
- local alive = "O"
- local dead = " "
- -- Create grid
- local function createGrid()
- local grid = {}
- for y = 1, height do
- grid[y] = {}
- for x = 1, width do
- grid[y][x] = math.random() < 0.2 and 1 or 0
- end
- end
- return grid
- end
- -- Count live neighbors
- local function countNeighbors(grid, 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
- -- Update the grid
- local function updateGrid(grid)
- local newGrid = {}
- for y = 1, height do
- newGrid[y] = {}
- for x = 1, width do
- local neighbors = countNeighbors(grid, x, y)
- local cell = grid[y][x]
- if cell == 1 then
- newGrid[y][x] = (neighbors == 2 or neighbors == 3) and 1 or 0
- else
- newGrid[y][x] = (neighbors == 3) and 1 or 0
- end
- end
- end
- return newGrid
- end
- -- Check if all cells are dead
- local function isAllDead(grid)
- for y = 1, height do
- for x = 1, width do
- if grid[y][x] == 1 then
- return false
- end
- end
- end
- return true
- end
- -- Draw the grid
- local function drawGrid(grid)
- monitor.setCursorPos(1,1)
- for y = 1, height do
- for x = 1, width do
- monitor.write(grid[y][x] == 1 and alive or dead)
- end
- end
- end
- -- Main loop
- while true do
- local grid = createGrid()
- while true do
- drawGrid(grid)
- sleep(delay)
- grid = updateGrid(grid)
- if isAllDead(grid) then
- monitor.clear()
- monitor.setCursorPos(1, 1)
- monitor.write("All cells died. Restarting...")
- sleep(1)
- monitor.clear()
- break
- end
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement