Let’s program the Game Of Life

gol1

Ok, this is the first “coding post” of the blog and it is not in Python! You red my first post and thought that this blog was going to be about Python, and then, a programming post using JavaScript. Well… here you will see a lot of things in a lot of languages.

Note: You can grab lots of game of life algorithms in different languages for free from Rosetta Code.

In this post we will start with the game of life coding by doing the logic in javascript, so, next time we can start programming the html part with canvas.

 

So, lets get started: first lets create our gameOfLife.js file, the logic of the game:

For a good start, our 2 dimensional array will be 10×10 positions:

For now, all the positions will take a 0 or 1 in a random way:

Until we have some good way to see it, lets put the output in the console, so I was thinking in a simple function like this:

So, if we send the array there we should see our initial state.

And now let’s run this (for showing purpose I will run it with node, but any way to run your js is good):

gol1

Now, we have to change it in cycles so, we will enter in a new for and look for our 4 rules:

  1. Any live cell with fewer than two live neighbours dies, as if caused by under-population.
  2. Any live cell with two or three live neighbours lives on to the next generation.
  3. Any live cell with more than three live neighbours dies, as if by over-population.
  4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.

To do so, we need a function to count the neighbours of a cell:

 

And, once you have the status you need a function to determine the status of the cell given the rules:

All these values will be put in a second auxiliar array (If I put them in the actual array the values of a cell will be calculated using the modified values, so, lets create a new function with an array that will receive the new values:

And at least, the loop with steps to make it work (for the example I will hardcode it to 5):

This is all for this post, in the next one, we will add the web part and star quitting all the hardcoding.

If you want the latest code of this project, you can clone it from github

Leave a Reply

Your email address will not be published. Required fields are marked *