Skip to content

Instantly share code, notes, and snippets.

@N8python
Created September 3, 2020 14:54
Show Gist options
  • Save N8python/ff20edd59cff3e33231889f35171d9fa to your computer and use it in GitHub Desktop.
Save N8python/ff20edd59cff3e33231889f35171d9fa to your computer and use it in GitHub Desktop.
Terrain generation using p5js and cellular automata.
const SQUARE_SIZE = 5;
let storage = [];
function setup() {
createCanvas(600, 600);
for (let x = 0; x < width / SQUARE_SIZE; x++) {
storage[x] = [];
for (let y = 0; y < height / SQUARE_SIZE; y++) {
storage[x].push((Math.random() > 0.5) ? "red" : "blue")
}
}
}
function draw() {
background(150);
for (let x = 0; x < width / SQUARE_SIZE; x++) {
for (let y = 0; y < height / SQUARE_SIZE; y++) {
noStroke();
fill(storage[x][y])
drawSquare(x, y);
const neighbors = [
storage[x + 1] && storage[x + 1][y],
storage[x + 1] && storage[x + 1][y - 1],
storage[x] && storage[x][y - 1],
storage[x - 1] && storage[x - 1][y - 1],
storage[x - 1] && storage[x - 1][y],
storage[x - 1] && storage[x - 1][y + 1],
storage[x] && storage[x][y + 1],
storage[x + 1] && storage[x + 1][y + 1]
]
const reds = neighbors.filter(x => x === "red").length;
const blues = neighbors.filter(x => x === "blue").length;
if (reds > blues) {
storage[x][y] = "red";
}
if (blues > reds) {
storage[x][y] = "blue";
}
}
}
}
function drawSquare(x, y) {
rect(x * SQUARE_SIZE, y * SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment