Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Dynamic neighbor-influenced Game of Life
- math.randomseed(os.time())
- local width, height = 20, 10
- local aliveChar = "O"
- local deadChar = "o"
- local maxRandomInfluence = 0.3 -- max extra random chance
- -- Initialize grid randomly
- local grid = {}
- for y = 1, height do
- grid[y] = {}
- for x = 1, width do
- grid[y][x] = math.random() > 0.5 and 1 or 0
- end
- end
- -- Count alive neighbors
- 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
- -- Update grid
- local function updateGrid()
- local newGrid = {}
- for y = 1, height do
- newGrid[y] = {}
- for x = 1, width do
- local neighbors = countNeighbors(x, y)
- local current = grid[y][x]
- -- Base probability influenced by neighbors
- local neighborInfluence = neighbors / 8 -- 0 to 1
- local randomChance = math.random()
- -- Decision influenced by neighbors
- local nextState
- if randomChance < neighborInfluence then
- nextState = 1 -- more neighbors -> more likely alive
- elseif randomChance < neighborInfluence + maxRandomInfluence then
- nextState = 1 - current -- small chance to flip randomly
- else
- nextState = 0 -- otherwise dead
- end
- newGrid[y][x] = nextState
- end
- end
- grid = newGrid
- end
- -- Draw grid
- local function drawGrid()
- term.clear()
- term.setCursorPos(1,1)
- for y = 1, height do
- local line = ""
- for x = 1, width do
- line = line .. (grid[y][x] == 1 and aliveChar or deadChar)
- end
- print(line)
- end
- end
- -- Main loop
- while true do
- drawGrid()
- updateGrid()
- sleep(0.2)
- end
Advertisement
Add Comment
Please, Sign In to add comment