Created
September 3, 2020 14:54
-
-
Save N8python/ff20edd59cff3e33231889f35171d9fa to your computer and use it in GitHub Desktop.
Terrain generation using p5js and cellular automata.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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