xxxxxxxxxx
111
//WEEK 11 - CELLULAR AUTOMATA RIPPLES ISLANDS
//RULESET:
// 1) Each cell state is the average update of its neighbor and previous state
// 2) Two grids: Current holds current wave height; Previous holds wave from past time
// 3) Use Wave equation and add a damping factor to reduce wave energy
//Wave Equation: current[i][j] = 2 * previous[i][j] + damping(avg. neighbor - previous[i][j])
//The equation calculates the cell 'height' and determines its color based on this!
//START
let cols, rows;
let resolution = 10; //Cell size
let current, previous, islands;
let damping = 1; // Wave damping speed
function setup() {
createCanvas(600, 600);
cols = width / resolution;
rows = height / resolution;
// Initialize grids
current = make2DArray(cols, rows);
previous = make2DArray(cols, rows);
islands = make2DArray(cols, rows);
// Generate random islands
generateIslands();
}
function draw() {
background(0);
frameRate(12);
// Draw CURRENT wave state & Islands
// Iterate over the cells
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
let x = i * resolution;
let y = j * resolution;
//Check if cell is islands
if (islands[i][j] == 1) {
fill(0);
} else {
let value = current[i][j];
fill(127 + value * 127); //This colors the wave based on height value
}
rect(x, y, resolution, resolution);
}
}
// Compute the next wave state
let next = make2DArray(cols, rows);
for (let i = 1; i < cols - 1; i++) {
for (let j = 1; j < rows - 1; j++) {
if (islands[i][j] == 1) {
//DO NOTHING IF IT IS ISLANDS!
next[i][j] = 0;
} else {
// Add the wave equation!
next[i][j] =
(2 * current[i][j] - previous[i][j]) +
damping *
((current[i - 1][j] +
current[i + 1][j] +
current[i][j - 1] +
current[i][j + 1]) /
4 -
current[i][j]);
}
}
}
// Update grids
previous = current;
current = next;
// MOUSE PRESS INTERACTION
if (mouseIsPressed) {
let x = floor(mouseX / resolution);
let y = floor(mouseY / resolution);
if (x > 0 && x < cols && y > 0 && y < rows && islands[x][y] == 0) {
current[x][y] = 1;
}
}
}
//FUNCTION TO MAKE 2D ARRAYS
function make2DArray(cols, rows) {
let arr = new Array(cols);
for (let i = 0; i < cols; i++) {
arr[i] = new Array(rows).fill(0);
}
return arr;
}
//FUNCTION TO GENERATE ISLANDS
function generateIslands() {
// Randomly generate islands of varying sizes
for (let n = 0; n < 17; n++) { // Generate n number of islands
let startX = floor(random(cols));
let startY = floor(random(rows));
let size = floor(random(1, 10)); // Island size up to 5x5
for (let i = startX; i < startX + size && i < cols; i++) {
for (let j = startY; j < startY + size && j < rows; j++) {
islands[i][j] = 1; //Turn cell into 1 if it is an Island
}
}
}
}