The Concept
Cellular Automata (often inspired by Conway's Game of Life) works by applying local rules to every tile based on its neighbors. For caves, we usually start with random noise and then "smooth" it over several iterations.
Rule: If a tile has more than 4 wall neighbors, it becomes a wall. Otherwise, it becomes a floor.
Iteration: 0
Core Logic
// Counting neighbors
let count = 0;
for(let i = -1; i <= 1; i++) {
for(let j = -1; j <= 1; j++) {
if(grid[x+i][y+j] === WALL) count++;
}
}
// Smoothing rule
newGrid[x][y] = (count > 4) ? WALL : FLOOR;