I would like to kindly ask others to review my code. I'd like suggestions, criticisms, and discussions on what is good and what could be done better.
const canvas = document.querySelector('.gameOfLife');
const ctx = canvas.getContext('2d');
// create an array
const canvasWidth = 100;
const canvasHeight = 100;
canvas.width = 3 * canvasWidth;
canvas.height = 3 * canvasHeight;
let gameBoard = createBoard(canvasWidth, canvasHeight);
let gameBoard2 = createBoard(canvasWidth, canvasHeight);
let gameBoard3 = createBoard(canvasWidth, canvasHeight);
function createBoard(width, height) {
let board = new Array(0);
for (let i = 0; i < width; i++) {
board [i] = [];
for (let j = 0; j < height; j++){
board[i][j] = 0;
}
}
return board;
}
function randomNumber(max) {
return Math.floor(Math.random() * max);
}
function randomPos() {
const x = randomNumber(canvasWidth);
const y = randomNumber(canvasHeight);
return [x, y];
}
function randomBoard(arr) {
for (let i = 0; i <= 0.2 * canvasHeight * canvasWidth; i++) {
const [x, y] = randomPos();
arr[x][y] = 1;
}
}
function drawBoard(arr) {
ctx.clearRect(0, 0, canvas.width, canvas.height)
for (let i = 0; i < canvasWidth; i++) {
for (let j = 0; j < canvasHeight; j++){
if (arr[i][j] === 1) {
ctx.fillStyle = "#012345";
ctx.fillRect(i*3, j*3, 3, 3);
}
}
}
}
// calculate new cycle
function checkSurrounding(x, y) {
let sum = 0;
startX = x-1 < 0 ? x : x-1;
stopX = x+1 >= canvasWidth ? x : x+1;
startY = y-1 < 0 ? y : y-1;
stopY = y+1 >= canvasHeight ? y : y+1;
for (let i = startX ; i <= stopX; i++) {
for (let j = startY ; j <= stopY; j++) {
if (i !== x || j !== y) {
sum += gameBoard[i][j];
}
}
}
return sum;
}
function deadOrAlive(x, y) {
const surround = checkSurrounding(x, y);
if (gameBoard[x][y] === 1 && (surround === 2 || surround === 3)) return 1;
else if (gameBoard[x][y] === 0 && surround === 3) return 1;
else return 0;
}
function nextGene() {
let newBoard = createBoard(canvasWidth, canvasHeight);
for (let i = 0; i < canvasWidth; i++) {
for (let j = 0; j < canvasHeight; j++) {
newBoard[i][j] = deadOrAlive(i, j);
}
}
gameBoard = newBoard;
drawBoard(newBoard);
}
randomBoard(gameBoard);
drawBoard(gameBoard);
setInterval(nextGene, 150);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Game of Life - Canvas</title>
</head>
<body>
<canvas class="gameOfLife" width="400" height="400"></canvas>
<script type="text/javascript" src="scripts.js"></script>
</body>
<style>
body {
background-color: #ffc600;
}
.gameOfLife{
margin: 15px auto;
background-color: #ff6c00;
display: block;
}
</style>
</html>