Rules of the Game:
The universe of the Game of Life is an infinite two-dimensional orthogonal grid of square cells, each of which is in one of two possible states, alive or dead. Every cell interacts with its eight neighbors, which are the cells that are horizontally, vertically, or diagonally adjacent. At each step in time, the following transitions occur:- Any live cell with fewer than two live neighbors dies as if caused by under-population.
- Any live cell with two or three live neighbors lives on to the next generation.
- Any live cell with more than three live neighbors dies, as if by overcrowding.
- Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
We start by creating a HTML boiler plate with an empty canvas in the the body tag.
after the html we add a script tag and initialize the canvas and some global variables along with some utility fucntions.:
Next, we creat a Class which is representative of a cell in the universe of the game.
We define a draw member function to draw a grid of a cell. We will also define a fill member function which will add a fill to the grid to signify a live cell. Other member variables would be the position and dimensions of the cell.
we will define a method to draw the universe:
we will define a pure function to apply the rules of the game and a method to calculate the next generation.
You will notice in the pure function there is a line
lifeCount = lifeCount > 0 ? lifeCount - 1 : 0;
we reduce the count because the calculation is inclusive of the current cell.to close the development on the game we'll add some event handlers to make the game a little interactive:
and then you will have the final result: https://keith3895.github.io/conways-game-of-life/index.html
the code is on github: https://github.com/Keith3895/conways-game-of-life/blob/master/
Comments
Post a Comment