xxxxxxxxxx
192
/*
1.Create an 2d array of dead/alive cells, all random
2.have a copy of that array to modify*
3.do a simulation step through every cell
3.1 count cell neighbours
3.2 deside to kill or tho make it born
4.change the real map values to the new one
*this is because if you change the cell [1][0] adn then the cell [2][0] the state of their neighbour has change
https://gamedevelopment.tutsplus.com/tutorials/generate-random-cave-levels-using-cellular-automata--gamedev-9664
*/
let squareSize = 10;
let map = [];
let mapSize = 70;
let mapvalue = [];
let mapvalueTmp = [];
let deathLimit = 3;
let bornLimit = 4;
let iterenation= 2;
function setup() {
createCanvas(750, 750);
noStroke();
frameRate(1);
for (i = 0; i < mapSize; i++) {
map[i] = [];
mapvalue[i] = [];
mapvalueTmp[i] = [];
}
for (x = 0; x < mapSize; x++) {
for (y = 0; y < mapSize; y++) {
let r = random() < 0.4;
//1.random map
map[x][y] = new Cell(x, y, r);
//2.copy of the map
mapvalue[x][y] = r;
}
}
//3.do smoth step
for(i=0;i<iterenation;i++){
doStep();
}
}
function draw() {
background(220);
for (x = 0; x < mapSize; x++) {
for (y = 0; y < mapSize; y++) {
map[x][y].display();
}
}
}
//functions
function doStep() {
mapvalueTmp = mapvalue;
for (x = 0; x < mapSize; x++) {
for (y = 0; y < mapSize; y++) {
//3.1 counbts neighbours
let n = cellNeighbours(x, y);
//3.2 deside to kill o to born
if (mapvalue[x][y]) { //if the cell is alive
if (n < deathLimit) {
mapvalueTmp[x][y] = false;
} else {
mapvalueTmp[x][y] = true;
}
} else { //if not
if (n > bornLimit) {
mapvalueTmp[x][y] = true;
} else {
mapvalueTmp[x][y] = false;
}
}
}
}
//4. applay effects
for (x = 0; x < mapSize; x++) {
for (y = 0; y < mapSize; y++) {
mapvalue[x][y] = mapvalueTmp[x][y];
}
}
for (x = 0; x < mapSize; x++) {
for (y = 0; y < mapSize; y++) {
map[x][y].alive = mapvalue[x][y]
}
}
}
function cellNeighbours(x, y) {
let n = 0;
if (x != mapSize - 1) {
if (mapvalue[x + 1][y]) {
n++;
}
}
if (x != 0) {
if (mapvalue[x - 1][y]) {
n++;
}
}
if(x!=0&&y!=0){
if(mapvalue[x-1][y-1]){
n++;
}
}
if(x!=mapSize-1&&y!=mapSize-1){
if(mapvalue[x+1][y+1]){
n++;
}
}
if(x!=0&&y!=mapSize-1){
if(mapvalue[x-1][y+1]){
n++;
}
}
if(x!=mapSize-1&&y!=0){
if(mapvalue[x+1][y-1]){
n++;
}
}
if (y != 0) {
if (mapvalue[x][y - 1]) {
n++;
}
}
if (y != mapSize - 1) {
if (mapvalue[x][y + 1]) {
n++;
}
}
return n;
}
// class
class Cell {
constructor(x, y, state) {
this.pos = createVector(x, y);
this.alive = state;
}
display() {
if (this.alive) {
fill(255);
} else {
fill(0);
}
rect(this.pos.x * squareSize * 1 + squareSize, this.pos.y * squareSize * 1 + squareSize, squareSize, squareSize);
}
}