Conway's Game of Life Session 1 of 2
In this activity, we'll recreate the Game of Life, a famous simulation devised by mathematician John Conway. Along the way we'll learn about functions, events, algorithms, arrays, loops and if statements.
This lesson uses the Kid.js JavaScript framework. To get started with Kid.js, create an account on kidjs.app or import the framework into your own project.
How the Game Works
The Game of Life is played on a grid of squares, called cells. To start, we fill in a few of the cells. Then the game takes over, creating one generation after another by following four simple rules.
Part 1: Setup 15 Minutes
Before we write any code, open the "Settings" panel and turn on "Big Pixel" mode. This makes each pixel larger. It's not required, but it will make the game a lot easier to see.
Functions
We program a computer by giving it a series of commands, also known as functions. To run a command or function in JavaScript, type the name of the function followed by parentheses.
Many functions need parameters. For example, if you were to command someone to walk, you may also need to tell them how many steps or which direction. The parameters go inside of the parentheses.
Kid.js provides a putPixel() function which, you guessed it,
puts a pixel on the screen. The parameters are the x and y coordinates of where
to place the pixel.
There is also a getPixel() function that checks if there is a
pixel at a location. This will come in handy later.
Events
Events are "things" that happen while our app is running, like a mouse click, or key press. We can write code that runs when that event occurs.
The first step is to bundle up the code we want to run in our own custom function.
function dot() {
putPixel(5, 5)
}
Then connect the function to the "click" event.
function dot() {
putPixel(5, 5)
}
on('click', dot)
Now a dot appears when we click, but always in the same spot. Kid.js provides
two global variables, mouseX and mouseY, that contain
the current mouse coordinates. Let's use those instead.
And voilà, we've created a simple paint app! Click around to draw a few starting cells.
Part 2: The Next Generation 45 Minutes
For each generation, we'll look at every pixel on the screen and count its neighbors. Then, based on the rules of the game, we'll turn it on or off.
Algorithms
Let's take a moment to break down what we need to do, step-by-step. A set of step-by-step instructions like this is called an algorithm.
- Check each pixel one at a time.
- Count its neighbors.
- If the pixel is on and has fewer than two neighbors, turn it off.
- If the pixel is on and has more than three neighbors, turn it off.
- If the pixel is off and has exactly three neighbors, turn it on.
Seems simple enough, but there's one gotcha. Since we check the pixels one at a time, changing a pixel right away could change the neighbor count of pixels we haven't yet checked.
Instead, we'll keep two lists: one of pixels that will die and one of pixels that will be born. We won't change anything until we've checked every pixel.
- Check each pixel one at a time.
- Count its neighbors.
- If the pixel is on and has fewer than two neighbors, add it to the "dies" list.
- If the pixel is on and has more than three neighbors, add it to the "dies" list.
- If the pixel is off and has exactly three neighbors, add it to the "born" list.
- Turn off each pixel in the "dies" list.
- Turn on each pixel in the "born" list.
Now let's turn our algorithm into code. We'll put it all inside a function called
generation(), so we can run it again and again.
function generation() {
// Code goes here
}
Variables
Variables are used to keep track of things. Think of a variable as a box with a label you can put things in. There are many things we may need to keep track of in an app, such as high score or health, or how many neighbors a pixel has.
We create a variable using the word let, followed by its name.
We can the equals sign, also know as the assignment operator, to put something
into the box. For example:
let neighbors = 0
Arrays
Arrays are a type of variable used to store lists of things. Think of arrays as a box divided into sections, each storing a single item. Each section has a unique number, called an index, that we can use to reference it.
In JavaScript, we create an array using square brackets, and optionally including a number of initial items. For example, we could create a list of our favorite things.
let favs = ['pizza', 'rainbows', 'puppies']
We can access an individual item by providing the index, again using square brackets. Be aware that the first item is index 0, the second is index 1, and so on.
favs[0] // 'pizza'
Let's get back to our game.We'll create two arrays, one for pixels that die and one for pixels that are born.
function generation() {
let dies = []
let born = []
}
The For Loop
A for loop is used to repeat a block of code. It's broken into three parts. Code that runs before the loop starts; a condition to check if we should continue; and code that runs after each pass through the loop.
In the first part, we'll create a new variable x to keep track of the
horizontal position. We'll start it at 0.
For the second part, we check to see if x is less than the width of the
screen. If yes, then the loop continues.
For the third part, we add 1 to x. This moves us one pixel to the right.
function generation() {
let dies = []
let born = []
for (let x = 0; x < width; x = x + 1) {
// Do something
}
}
Nested Loops
Now here's where things can get a little tricky. That loop only moves us across the screen. To check every pixel, we'll put a second loop inside the first one. For each step to the right, the inner loop moves down the column, one pixel at a time.
function generation() {
let dies = []
let born = []
for (let x = 0; x < width; x = x + 1) {
for (let y = 0; y < height; y = y + 1) {
// Do something
}
}
}
Counting Neighbors
First, let's use getPixel() to check if the pixel is alive.
function generation() {
let dies = []
let born = []
for (let x = 0; x < width; x = x + 1) {
for (let y = 0; y < height; y = y + 1) {
let alive = getPixel(x, y)
}
}
}
Next, we'll count its neighbors. We create a neighbors variable
starting at 0, then check each of the eight pixels around it. Here's how we
check the pixel one to the left and one up.
if (getPixel(x - 1, y - 1)) neighbors = neighbors + 1
This is called an if statement. If there is a pixel there, we add one to
neighbors. If not, we skip it.
Follow the same pattern for the other seven neighbors, adding or subtracting
one from x or y.
function generation() {
let dies = []
let born = []
for (let x = 0; x < width; x = x + 1) {
for (let y = 0; y < height; y = y + 1) {
let alive = getPixel(x, y)
let neighbors = 0
if (getPixel(x - 1, y - 1)) neighbors = neighbors + 1
if (getPixel(x, y - 1)) neighbors = neighbors + 1
if (getPixel(x + 1, y - 1)) neighbors = neighbors + 1
if (getPixel(x - 1, y)) neighbors = neighbors + 1
if (getPixel(x + 1, y)) neighbors = neighbors + 1
if (getPixel(x - 1, y + 1)) neighbors = neighbors + 1
if (getPixel(x, y + 1)) neighbors = neighbors + 1
if (getPixel(x + 1, y + 1)) neighbors = neighbors + 1
}
}
}
Rules of the Game
Now for the rules. If the pixel is alive and has fewer than two neighbors,
add it to the "dies" list. In this if statement, the && means
"and", so both things must be true.
if (alive && neighbors < 2) {
dies.push([x, y])
}
push() adds an item to the end of an array. Here we're adding
the x and y of the pixel, grouped together in their own little array.
dies.push([x, y])
If the pixel is alive with more than three neighbors, it's also toast.
if (alive && neighbors > 3) {
dies.push([x, y])
}
If the pixel is empty and has exactly three neighbors, it comes to life!
The ! means "not", so !alive means "not alive".
In every other case, we leave the pixel as is.
if (!alive && neighbors == 3) {
born.push([x, y])
}
These three if statements go inside the inner loop, right after we count the neighbors.
Updating the Screen
Once we've checked every pixel, we'll use two more for loops to go through
our lists. We'll turn off each pixel in the dies list using clearPixel(),
and turn on each pixel in the born list using putPixel(). These
loops go after the nested loops, but still inside generation().
for (let i = 0; i < dies.length; i = i + 1) {
clearPixel(dies[i][0], dies[i][1])
}
for (let i = 0; i < born.length; i = i + 1) {
putPixel(born[i][0], born[i][1])
}
Finally, let's connect generation() to the space bar.
on('space', generation)
Draw a few cells, then press the space bar. Each press moves the game forward one generation. Try drawing three cells in a row and see what happens!