Skip to content

Instantly share code, notes, and snippets.

@manuerumx
Created March 6, 2019 14:39
Show Gist options
  • Save manuerumx/4141ff969d7d70614c27d3c5352a01cc to your computer and use it in GitHub Desktop.
Save manuerumx/4141ff969d7d70614c27d3c5352a01cc to your computer and use it in GitHub Desktop.
Game of Life (Canvas + JS)
const sWidth = 800;
const sHeight = 400;
const resolution = 2;
let scenario = null;
let context = null;
let grid = null;
let cols = 0;
let rows = 0;
let iteration = 0;
let interval = null;
const GameOfLife = {
setup: function () {
cols = sWidth / resolution;
rows = sHeight / resolution;
grid = GameOfLife.buildState(cols, rows);
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
grid[i][j] = (Math.random() > 0.5) ? 1 : 0;
}
}
},
loadScenario: function () {
scenario = document.getElementById('scenario');
context = scenario.getContext('2d');
this.setup();
interval = setInterval(this.drawScenario, 100);
},
buildState: function (cols, rows) {
let arr = new Array(cols);
for (let i = 0; i < arr.length; i++) {
arr[i] = new Array(rows);
}
return arr;
},
drawScenario: function () {
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
let x = resolution * i;
let y = resolution * j;
if (grid[i][j] === 1) {
context.fillStyle = "#000000";
} else {
context.fillStyle = "#FFFFFF";
}
context.fillRect(x, y, resolution, resolution);
}
}
GameOfLife.updateState();
if (iteration <= 200) {
let it = document.getElementById('iteration');
it.innerHTML = 'Iteration: ' + iteration;
iteration++;
} else {
clearInterval(interval);
}
},
updateState: function () {
let next = GameOfLife.buildState(cols, rows);
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
let state = grid[i][j];
let neighbors = GameOfLife.countNeighbors(grid, i, j);
if (state == 0 && neighbors == 3) {
next[i][j] = 1;
} else if (state == 1 && (neighbors < 2 || neighbors > 3)) {
next[i][j] = 0;
} else {
next[i][j] = state;
}
}
}
grid = next;
},
countNeighbors: function (grid, x, y) {
let sum = 0;
for (let i = -1; i < 2; i++) {
for (let j = -1; j < 2; j++) {
let col = (x + i + cols) % cols;
let row = (y + j + rows) % rows;
sum += grid[col][row];
}
}
sum -= grid[x][y];
return sum;
}
};
<html>
<head>
<title>Game of life</title>
<meta charset="UTF-8">
<style>
#scenario {
width: 800px;
height: 400px;
}
</style>
<script src="game.js"></script>
</head>
<body>
<h4>Game of life</h4>
<canvas id="scenario"></canvas>
<h5><span id="iteration">0</span> of 200</h5>
<script type="text/javascript">
GameOfLife.loadScenario();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment