Conway’s game of life

Python project.

Conway’s game of life, simple rules lead to incredible things.

GitHub link: https://github.com/Apiquet/Game_of_life_Conway

The Game of Life is a cellular automation. Its evolution is determined by some rules of life or death:

  1. Loneliness: Less than 2 neighbors -> Death
  2. Overcrowding: More than 3 neighbors -> Death
  3. Reproduction: 3 neighbors -> Birth
  4. Stasis: 2 neighbors -> No changes

Illustration from http://battleship.ru/virus/conway.html:

conway1.png

The following video explains the concept and its incredible possibilities:

Conway’s Game of Life Explanation

I choose Python and the library Pygame.

First step: Installing Python and Pygame:

Second step: implementation:

  1. Import Pygame in the first lines,
  2. Display a window thanks to Pygame,
  3. Fill this window with alive and dead cells (different colors in function of the state),
  4. Code the logic to calculate the number of neighbors for each cell to know the next state of each ones.
  5. (Optional) Implement events to improve your game: Pause option, reset game, increase or decrease the speed, start with a famous structure, etc).

Only the logic part will be explained here but the code can be found on my Github profile

https://github.com/Apiquet/Game_of_life_Conway

The code implements the possibility to start with some famous structure like glider gun, different size of glider and an exponential structure evolution:

 

  1. How to initialize the board:
    return [[randint(0,1) for x in range(Nbr_Cell_x)] for y in range(Nbr_Cell_y)]

    allows you to initialize a random board thanks to the random library: from random import randint. It returns a random int between 0 and 1, 0 means death, 1 alive.

  2. How to find the number of neighbors:
    There are many possibilities, the easiest is the following with many if statements:
def find_cell_neighbors(board, x, y):
    neighbors = 0
    if board[y][x+1]:
        neighbors+=1
    if board[y+1][x+1]:
        neighbors+=1
    if board[y-1][x+1]:
        neighbors+=1 
    if board[y][x-1]:
        neighbors+=1
    if board[y+1][x-1]:
        neighbors+=1 
    if board[y-1][x-1]:
        neighbors+=1 
    if board[y+1][x]:
        neighbors+=1 
    if board[y-1][x]:
        neighbors+=1 
    return neighbors

But there are more “efficient” code that can be found online (example: https://github.com/scienceetonnante/GameOfLife/blob/master/GameOfLife_utils.py)
The goal is to find the number of neighbors of each cell to determine its evolution. Under 2 neighbors it dies, more than 3, it dies, 3 it lives, for 2 there is no change.


I hope you will enjoy creating your own Conway’s game of life, you can find my own game at the following link:

https://github.com/Apiquet/Game_of_life_Conway