You can do this by looping over all cells and check how many neighbours are alive per cell. If you want to learn more about drawing graphics on the HTML5 canvas, check out this tutorial.įor every step in the evolution of this Game of Life, all cells need to check their neighbours to see if their area is under- or overpopulated. It has a small delay build in before requesting the next frame, to make the evolution of the game easier to follow. In this example the loops starts by checking the surroundings of each cell, it then draws all cells to the canvas. }, 100) // The delay will make the game easier to follow Window.requestAnimationFrame(() => this.gameLoop()) You can create a new grid of cells with a nested for loop: That's 3000 cells in total! The grid has the right measurements to completely fill the canvas element since each cell is 10x10 pixels and the canvas is 750x400. You're going to build a grid of 75x40 items. Once you have your cell framework ready, you can start to create a lot of cells. (idX * Cell.width, idY * Cell.height, Cell.width, Cell.height) Draw a square, let the state determine the color
Store the position of this cell in the grid You can choose to draw a square or go for another shape, like the circles used in this tutorial. Start by creating a new Cell class and implement a draw() method. A cell has about 50% chance to start alive, but you can easily tweak that percentage to create different starting situations. When a new cell is created, its state of being is determined randomly. Each state will be drawn with a different color. It doesn't have to be smart, it's just a square on a grid that can be either alive or dead. Let's start by creating the framework for a single cell. Define the appearance and behaviour of a single cell Here's an example of a Gosper glider gun:įor this tutorial you're not going to use paper, but going to create The Game of Life with JavaScript on the HTML5 canvas and generate starting positions and new generations through code. Real fanatics are even looking for so called guns and spaceships (or gliders), patterns that will emit cells or look like a moving object. You can play this game on paper and think of initial starting states that will result in interesting shapes or even moving objects. Cells with less than 2 neighbours will die of underpopulation, cells with 4 or more neighbours will die of overpopulation.A living cell will stay alive if 2 or 3 neighbours are living.A dead cell will come alive if exactly 3 neighbours are living.Each cell has 8 neighbours (except for the ones at the edge of the canvas). Every cell observes its surrounding neighbours to check whether its living area is underpopulated, overpopulated or suitable to live in.