Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Dynamic Cellular Simulation with Fade + Dead-Zone Regeneration
- math.randomseed(os.time())
- local termW, termH = term.getSize()
- local width, height = termW, termH
- local aliveChar = "O"
- local deadChar = "o"
- local steps = 8
- local fadeSpeed = 0.1
- local randomFlipChance = 0.02
- -- How many dead cells trigger regeneration
- local deadThreshold = 50
- -- How many random blobs to spawn when dead area is too big
- local blobsToSpawn = 5
- -- Blob size radius
- local blobRadius = 2
- local grid = {}
- for y = 1, height do
- grid[y] = {}
- for x = 1, width do
- grid[y][x] = math.random()
- end
- end
- local function countAliveNeighbors(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
- if grid[ny][nx] > 0.5 then
- count = count + 1
- end
- end
- end
- end
- end
- return count
- end
- local function intensityToChar(intensity)
- local step = math.floor(intensity * steps)
- if step < 1 then
- return deadChar
- else
- return aliveChar
- end
- end
- local function spawnBlobs()
- for i = 1, blobsToSpawn do
- local bx = math.random(3, width-3)
- local by = math.random(3, height-3)
- for dy = -blobRadius, blobRadius do
- for dx = -blobRadius, blobRadius do
- local nx, ny = bx + dx, by + dy
- if nx >= 1 and nx <= width and ny >= 1 and ny <= height then
- -- increase intensity toward alive
- grid[ny][nx] = math.min(1, grid[ny][nx] + math.random() * 0.5 + 0.5)
- end
- end
- end
- end
- end
- local function updateGrid()
- local deadCount = 0
- local newGrid = {}
- for y = 1, height do
- newGrid[y] = {}
- for x = 1, width do
- local current = grid[y][x]
- local neighbors = countAliveNeighbors(x, y)
- -- neighbor influence
- local target
- local nInfluence = neighbors / 8
- if math.random() < nInfluence then
- target = 1
- elseif math.random() < randomFlipChance then
- target = 1 - current
- else
- target = 0
- end
- if current < target then
- current = math.min(current + fadeSpeed, target)
- elseif current > target then
- current = math.max(current - fadeSpeed, target)
- end
- newGrid[y][x] = current
- if current < 0.2 then
- deadCount = deadCount + 1
- end
- end
- end
- grid = newGrid
- -- If too many dead, spawn random living blobs
- if deadCount > deadThreshold then
- spawnBlobs()
- end
- end
- local function drawGrid()
- term.clear()
- term.setCursorPos(1,1)
- for y = 1, height do
- local line = ""
- for x = 1, width do
- line = line .. intensityToChar(grid[y][x])
- end
- print(line)
- end
- end
- while true do
- drawGrid()
- updateGrid()
- sleep(0.15)
- end
Advertisement
Add Comment
Please, Sign In to add comment