DEV Community

Cover image for Building Conway's Game of Life in Javascript
Simon Pfeiffer for Codesphere Inc.

Posted on • Edited on

14 6

Building Conway's Game of Life in Javascript

Conway's Game of Life has amazed Computer Scientists and Mathematicians for over half a century now. For those who don't know, the Game of Life is a zero-player game that follows four simple rules and can end in chaotic, beautiful, and mind-blowing outcomes. This simple game can even be used to simulate a Turing machine (you can essentially program using the game).

Today, I'm going to be showing you how you can make this game yourself with only 100 lines of Javascript.

You can get a feel for the game here: https://playgameoflife.com/


What is Conway's Game of Life?

Conway's Game of Life starts with a 2d grid, and each cell in the grid being either alive or dead. The grid will then evolve after each iteration based on the following rules:

  1. Any living cell with less than 2 live neighbors dies
  2. Any living cell with 2 or 3 live neighbors continues to be alive
  3. Any dead cell with three live neighbors becomes a live cell
  4. Any live cell with more than 3 live neighbors dies

Following these rules, each cell counts the number of live cells adjacent to it and determines its upcoming status.


Tech We'll Be Using

To create our Game of Life Simulator, we are going to be using Javascript in conjunction with the following tools:

P5.js

P5.js is an easy-to-use javascript graphics library. It is going to make displaying our cells extremely easy. You can check it out here:

https://p5js.org/

Codesphere

Codesphere is a no-config cloud provider that will allow us to deploy our app seamlessly. We're going to use it to host our Game of Life simulator. You can learn more here:

https://codesphere.com

The Code

<script
src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.1.9/p5.min.js"
integrity="sha512-WIklPM6qPCIp6d3fSSr90j+1unQHUOoWDS4sdTiR8gxUTnyZ8S2Mr8e10sKKJ/bhJgpAa/qG068RDkg6fIlNFA=="
crossorigin="anonymous"
></script>
<script>
let boxWid = 20; // Width of each cell
let tableArr = []; //2D array of grid. 1 - Alive, 0 - Dead
let fps = 30; // 30 fps at start, 2 fps when game is active
gridLn = 30; // Grid is size gridLn x gridLn
let state = 0; // 0 = Setup, 1 = Active
let startBtn;
// Populate the table with 0s
for (let r = 0; r < gridLn; r++) {
let rowArr = [];
for (let c = 0; c < gridLn; c++) {
rowArr.push(0);
}
tableArr.push(rowArr);
}
function mousePressed() {
let row = (mouseX - (mouseX % boxWid)) / boxWid; // Grab nearest row above click
let col = (mouseY - (mouseY % boxWid)) / boxWid; // Grab nearest col left of click
if (row <= gridLn && col <= gridLn) { // Valid row, col
tableArr[row][col] = -1 * tableArr[row][col] + 1; // Invert the cell
draw(); // Redraw table
}
}
function startGame() {
if (state == 0) { // If game hasn't yet started
fps = 2;
frameRate(fps);
state = 1;
}
}
function setup() { // Runs on start
frameRate(fps);
createCanvas(1500, 1500);
button = createButton("Start Game");
button.position(gridLn * boxWid + 20, 50);
button.mousePressed(startGame);
}
function checkNeighbors(row, col) {
// Return number of live neighbors
let count = 0;
for (let i = -1; i < 2; i++) { //This checks the row above and row below
if (col + i >= 0 && col + i < gridLn - 1) { // Check for valid column
if (row > 0 && tableArr[row - 1][col + i] == 1) {
count++;
}
if (row < gridLn - 1 && tableArr[row + 1][col + i] == 1) {
count++;
}
}
}
if (col - 1 >= 0 && tableArr[row][col - 1] == 1) { // Check left cell
count++;
}
if (col + 1 < gridLn - 1 && tableArr[row][col + 1] == 1) { // Check right cell
count++;
}
return count;
}
function draw() {
tableArr.forEach((rowArr, row) => {
rowArr.forEach((colVal, col) => {
fill(colVal == 1 ? "black" : "transparent"); // Black if live, transparent if dead
rect(row * boxWid, col * boxWid, boxWid, boxWid);
});
});
if (state == 1) {
// Apply rules
let newTable = []; // Upcoming grid
tableArr.forEach((rowArr, row) => {
let newRow = [];
rowArr.forEach((colVal, col) => {
let cellVal = colVal;
let nCount = checkNeighbors(row, col);
if (cellVal == 1 && nCount < 2) { // If live and <2 live neighbors
cellVal = 0;
} else if (cellVal == 1 && nCount > 3) { // If live and >3 live neighbors
cellVal = 0;
} else if (cellVal == 0 && nCount == 3) { // If dead and 3 live neighbors
cellVal = 1;
}
newRow.push(cellVal);
});
newTable.push(newRow);
});
tableArr = newTable; // Update the grid
}
}
</script>
view raw conway.html hosted with ❤ by GitHub

Cool Starting Grids

And there we go! We've created Conway's Game of Life with some pretty rudimentary javascript! Here are some cool creations you can create:

Alt Text

Alt Text

Alt Text

These are just the tip of the iceberg! By adjusting the grid length and survival rules there is literally an infinite number of patterns you can generate.


Hope you enjoyed it!

Happy coding from your good friends at Codesphere, the next-generation cloud provider.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay