-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
73 lines (67 loc) · 2.09 KB
/
script.js
File metadata and controls
73 lines (67 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
let board = [];
const directions = [
[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]
];
const speed = 100;
const pixelNumber = 100;
const canvasSize = 1000;
const pixelSize = canvasSize/pixelNumber;
function createBoard() {
for(let i = 0; i < pixelNumber; i++) {
let arr = [];
for(let j = 0; j < pixelNumber; j++) {
arr.push((Math.floor(Math.random() * 2)))
}
board.push(arr);
}
}
function draw() {
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
for(let i = 0; i < board.length; i++) {
for(let j = 0; j < board[i].length; j++) {
if(board[i][j] == 0) {
ctx.clearRect(i*pixelSize, j*pixelSize, pixelSize, pixelSize);
} else {
ctx.fillRect(i*pixelSize, j*pixelSize, pixelSize, pixelSize);
}
}
}
ctx.stroke();
}
function simulation() {
setInterval(() => {
const newBoard = board.map(arr => [...arr]);
for(let i = 0; i < board.length; i++) {
for(let j = 0; j < board[i].length; j++) {
let neighbours = 0;
for(const direction of directions) {
const x = i + direction[0];
const y = j + direction[1];
if(x >= 0 && x < board.length && y >= 0 && y < board[i].length) {
neighbours += board[x][y];
}
}
if (board[i][j] == 1 && (neighbours < 2 || neighbours > 3)) {
newBoard[i][j] = 0;
} else if (board[i][j] == 0 && neighbours == 3) {
newBoard[i][j] = 1;
}
}
}
board = newBoard;
draw();
}, speed)
}
function setup() {
const canvas = document.getElementById("canvas");
canvas.height = canvasSize;
canvas.width = canvasSize;
createBoard();
simulation();
}
window.addEventListener('load', function () {
setup();
})