Conway's Game Of Life In PHP

12th April 2020

I was saddened to hear of the passing of the Mathematician John Horton Conway today so I decided to put together a post on his 'game of life' simulator.

This game of life, more commonly called Conway's game of life, was devised by John Conway in 1970 and is a way of modelling very simple cell population dynamics. The game takes place on a two dimensional board containing a grid of orthogonal cells. The game is technically a zero player game in that the initial setup of the game dictates the eventual evolution of the board.

The rules of the game (taken from wikipedia) are as follows.

  • Any live cell with fewer than two live neighbours dies, as if by underpopulation.
  • Any live cell with two or three live neighbours lives on to the next generation.
  • Any live cell with more than three live neighbours dies, as if by overpopulation.
  • Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.

For every 'tick' of the game board the rules are evaluated and each cell is kept alive, given life or killed. Through these simple rules a great deal of complexity can be generated. This is the simulation running on a 100 by 100 game board for 100 frames.

Conway's game of life

If you look up Conway's game of life you will see a large collection of examples and programs that can be used to generate the game. It is often used as a teaching aid in computer science both in terms of data science but also as a very simple introduction to artificial intelligence.

To create this in PHP we first need to represent the game board. This is essentially a two dimensional array so we can represent this as a property in a class called Life.

  1. class Life {
  2. public $grid = [];
  3. }

To actually create the grid we need to generate the multi-dimensional array. We can do this by generating lots of arrays that represent the y axis of the grid and then add them to an array that represents the x axis of the grid. Each cell will contain number 0 for dead and 1 for alive.

  1. public function createGrid(){
  2. for ($i = 1; $i <= 25; ++$i) {
  3. $height = [];
  4. for ($j = 1; $j <= 50; ++$j) {
  5. $height[$j] = 0;
  6. }
  7. $this->grid[$i] = $height;
  8. }
  9. }

When we run function our array contains a 25 by 50 grid of 'cells', all of which are dead. This isn't a great start, but this can be easily altered to create a random grid where each cell is randomly selected to be alive or dead. This random grid is a good way of starting out a game of life simulation.

  1. public function generateRandomGrid() {
  2. for ($i = 1; $i <= 25; ++$i) {
  3. $height = [];
  4. for ($j = 1; $j <= 50; ++$j) {
  5. $height[$j] = round(rand(0,1));
  6. }
  7. $this->grid[$i] = $height;
  8. }
  9. }

The next step is to create the 'tick' for each generation of the grid. All this does is loop through every cell in the grid and find out how many neighbours it has using the countAdjacentCells() method (which will be tackled later). With this count of neighbours we can then made a decision as to what to do with that cell. 

  1. public function runLife() {
  2. $newGrid = [];
  3.  
  4. foreach ($this->grid as $widthId => $width) {
  5. $newGrid[$widthId] = [];
  6. foreach ($width as $heightId => $height) {
  7. $count = $this->countAdjacentCells($widthId, $heightId);
  8.  
  9. if ($height == 1) {
  10. // The cell is alive.
  11. if ($count < 2 || $count > 3) {
  12. // Any live cell with less than two or more than three neighbours dies.
  13. $height = 0;
  14. }
  15. else {
  16. // Any live cell with exactly two or three neighbours lives.
  17. $height = 1;
  18. }
  19. }
  20. else {
  21. if ($count == 3) {
  22. // Any dead cell with three neighbours lives.
  23. $height = 1;
  24. }
  25. }
  26.  
  27. $newGrid[$widthId][$heightId] = $height;
  28. }
  29. }
  30. $this->grid = $newGrid;
  31. unset($newGrid);
  32. }

Working out the count of adjacent cells is perhaps the most tricky bit in this algorithm. When I first sat down to write this I started off with a bunch of if statements that looked at each of the 8 adjacent cells. I realised that I could compress this "if statement hell" into a simple loop that goes through the 8 adjacent squares surrounding the central cell and look to see if they contain a live cell. This method will count the number of cells found and return that count.

  1. public function countAdjacentCells($x, $y) {
  2. $coordinatesArray = [
  3. [-1, -1],[-1, 0],[-1, 1],
  4. [0, -1],[0, 1],
  5. [1, -1],[1, 0],[1, 1]
  6. ];
  7.  
  8. $count = 0;
  9.  
  10. foreach ($coordinatesArray as $coordinate) {
  11. if (isset($this->grid[$x + $coordinate[0]][$y + $coordinate[1]])
  12. && $this->grid[$x + $coordinate[0]][$y + $coordinate[1]] == 1) {
  13. $count++;
  14. }
  15. }
  16. return $count;
  17. }

Running the simulation without being able to see the output is pretty dull, so we need a way of doing this. The simplest way of doing this is by generating a string that represents the multi-dimensional array. This will just create a string and then loop through the multi-dimensional array, adding a "*" to represent a live cell and a "." to represent a dead cell. Each line is appended with a newline character so that the grid is correctly represented.

  1. function render(Life $life) {
  2. $output = '';
  3. foreach ($life->grid as $widthId => $width) {
  4. foreach ($width as $heightId => $height) {
  5. if ($height == 1) {
  6. $output .= '*';
  7. } else {
  8. $output .= '.';
  9. }
  10. }
  11. $output .= PHP_EOL;
  12. }
  13.  
  14. return $output;
  15. }

This is everything we need to run Conway's game of life. The final step here is to put all of this together and run the simulation.

The following code will create a Life object, fill it with random data and then run the simulation. This will clear the command line output on each tick so that it will appear to animate the simulation. This is a really quick way of printing the output of the simulation without trying to generate gif animations.

Also, the size of 25 by 50 cells may seem odd, but this will print out a square shape when printed out in the command line.

  1. <?php
  2.  
  3. $life = new Life();
  4. $life->generateRandomGrid();
  5.  
  6. while (true) {
  7. system('clear');
  8. echo render($life);
  9. $life->runLife();
  10. usleep(1000);
  11. }

Note that to stop this simulation you'll need to press ctrl + c, otherwise it will just continue forever.

This will produce the following output when first run, which will change on each run of the tick.

  1. *..****...***....*....**.....*..**..*..******.*.*.
  2. .*.**.**.**....****.**********.**.*.**.*.*******.*
  3. .***.*..*......*.***...****.*.*.*..*...**....*.*..
  4. **.......*.**..*..*.*.*..**.***..*.**..*.****....*
  5. **..**..***.**.*......*.**..*.*.*.......***...**.*
  6. *.**..*.*..*...*.********.*..**.****.*..*..**.***.
  7. .*.**.**.***..*..***....**...*.*...**.*....*.*.**.
  8. ...*.**.*.***..**.*..**..*..**..*.*..*.*.**..*.**.
  9. ..******.*.****...**..*..*.**...**.*...*.****.*..*
  10. *.***.*..**...**.*.****..****.***.*..**..***.*..**
  11. **.**.....*..***..**..*.*...***..*****.*****.****.
  12. *.*...*.**.*..*****.**...***...*........**.*.**.**
  13. ..*...***.**.*.*......*.*..**.****.***.*...*..***.
  14. *..*****.*.*.**.*.*****.*....***...**..*..*.****.*
  15. ...*.***....*...*.*.**.**.**....***.**...*.*..*.*.
  16. ..**..*....**........*.*****......**....***.*..*.*
  17. ..*****.**..*..**.******..*.*.**..**..**.****...**
  18. ***..**.*..**..*.*..**....*..**.***...*****.*.**.*
  19. ****..**.***..***..*.*...**.*..**..**.*.**.*.*****
  20. *...***.*...*.**..***..........*.*.*****..**.**.**
  21. ***.....*...*.....**..*...*.*.**.***.**..**.*..*.*
  22. ..**..*...*.*****.*.***..*..*.*.**.**.....*.**...*
  23. **.*****..****.***.******.*.*.**.*.******.**..*..*
  24. *.*.....****.*.....**..*.*..*.*....*..*.**.*.*.**.
  25. **.*.**.**....*...***.**.....****.*..*..*..**...*.

This basic output will run until stopped, but you might find that on such a small grid that the simulation will quickly reach a state in which everything is either dead or (more likely) into some stable state where nothing is moving.

  1. .....**...........................................
  2. .....**....**............................**.......
  3. ...........**..............*.......**....**.......
  4. ..........................*.*......**.............
  5. ..........................*.*.....................
  6. ...........................*......................
  7. ..................................................
  8. ..................................................
  9. .......**.........................................
  10. .......**..**.....................................
  11. ...........**...............................**....
  12. ............................................**....
  13. ..................................................
  14. ..................................................
  15. ..................................................
  16. ....................*.............................
  17. ...................*.*............................
  18. ...................*.*............................
  19. ....................*.............................
  20. ......................................**..........
  21. ..***................................*..*.........
  22. ......................................**..........
  23. ..................................................
  24. ..................................................
  25. ..................................................

Using random data in this way will mean that you will rarely encounter what is called a 'generator'. That is, a shape of cells that will produce other shapes that move away. I mentioned at the start that Conway's game of life can generate great complexity, and these generators is part of that.

This is a simple solution to Conway's game of life, but it produces the results pretty well using the limitations of PHP.

Add new comment

The content of this field is kept private and will not be shown publicly.