Created
July 29, 2020 22:52
-
-
Save xxMrPHDxx/8757bdb85bbf4c263c7090c12389222b to your computer and use it in GitHub Desktop.
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 canvas = document.querySelector('canvas#screen'); | |
canvas.width = innerWidth; | |
canvas.height = innerHeight; | |
const ctx = canvas.getContext('2d'); | |
const RED = 0, GREEN = 1; | |
const COLORS = ['red', 'green']; | |
// const COLORS = ['white', 'black']; | |
class Cell { | |
constructor(row, col, value=RED){ | |
this.row = row; | |
this.col = col; | |
this.value = value; | |
} | |
} | |
function to_cell(row, col, value){ return new Cell(row, col, value); } | |
function is_green(cell){ return cell.value == GREEN; } | |
const iters = 10; | |
let niter = 0; | |
const SIZE = 10; | |
// let grid = Array(3).fill().map((_,row)=>Array(3).fill().map((_,col)=>new Cell(row, col))); | |
// const grid = [ | |
// [1,0,0,1].map((val, col)=>to_cell(0, col, val)), | |
// [1,1,1,1].map((val, col)=>to_cell(1, col, val)), | |
// [0,1,0,0].map((val, col)=>to_cell(2, col, val)), | |
// [1,0,1,0].map((val, col)=>to_cell(3, col, val)) | |
// ]; | |
let grid = Array(60).fill().map((_,row)=>Array(60).fill().map((_,col)=>{ | |
return new Cell( | |
row, col, | |
(row >= 20 && row < 40 && col >= 20 && col < 40) ? | |
(Math.random() >= 0.5 ? RED : GREEN) : RED | |
); | |
})); | |
for(let i=0; i<3; i++) grid[1][i].value = GREEN; | |
const loop = setInterval(()=>{ | |
for(let i=0; i<grid.length; i++){ | |
for(let j=0; j<grid[i].length; j++){ | |
const cell = grid[i][j]; | |
const x = j*SIZE, y = i*SIZE; | |
ctx.fillStyle = COLORS[cell.value]; | |
ctx.fillRect(x, y, SIZE, SIZE); | |
} | |
} | |
for(let i=0; i<grid.length; i++){ | |
for(let j=0; j<grid[i].length; j++){ | |
const cell = grid[i][j]; | |
const neighbors = [].concat.apply([], grid).filter(cell=>{ | |
const {row, col} = cell; | |
if(row == i && col == j) return false; | |
return row >= i-1 && row <= i+1 && col >= j-1 && col <= j+1; | |
}); | |
if(cell.value == RED && | |
[3,6].includes(neighbors.filter(is_green).length)) | |
cell.value = GREEN; | |
if(cell.value == GREEN && | |
![2,3,6].includes(neighbors.filter(is_green).length)) | |
cell.value = RED; | |
} | |
} | |
if(false) | |
if(niter >= iters){ clearInterval(loop); return; } | |
niter++; | |
console.clear(); | |
console.log(`Number of iterations: ${niter}`); | |
}, 1000); | |
// }, 300); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment