Conway's Game of Life Session 2 of 2
Part 3: Autoplay 10 Minutes
I don't know about you, but my thumb is getting a bit sore from pressing the space bar over and over. Let's have the game play itself, moving forward one generation every second. We'll still use the space bar, but just to kick things off.
We'll use JavaScript's setInterval() function. It runs a function
again and again, with a pause in between. The parameters are (in order) the
function to run and the length of the pause. The pause is measured in milliseconds,
so 1000 is one second.
function start() {
setInterval(generation, 1000)
}
Then update the space bar event to run start() instead of
generation().
on('space', start)
Now draw your cells, press the space bar, and sit back and watch them go!
Part 4: Reset 10 Minutes
It would be nice to be able to easily start the game over? In order to do this, we need to first stop our interval from running, then clear the screen.
We can store the interval from setInterval() in a variable that we can
then pass to the clearInterval() function to stop it.
function start() {
let interval = setInterval(generation, 1000)
}
Scope
But there's a catch. Variables only exist within the block they are defined in. If
we want to use interval elsewhere, say in a restart() function,
we need to declare it outside of the start() function. It's okay if we don't
use it right away.
let interval
function start() {
interval = setInterval(generation, 1000)
}
Multiple Intervals
Pressing the space bar multiple times will kick off multiple intervals, causing
the game to behave a bit wonky. To solve this, check if the interval
variable is set, and clear that interval before starting a new one.
let interval
function start() {
if (interval) {
clearInterval(interval)
}
interval = setInterval(generation, 1000)
}
Restart Function
Our restart function will clear the interval, then clear the screen.
function restart() {
clearInterval(interval)
clear()
}
Let's wire it up to the R key.
function restart() {
clearInterval(interval)
clear()
}
on('r', restart)
Putting It All Together
Let's put it all together. We have dot() to draw our starting cells,
generation() to apply the rules, and start() to kick things
off, and restart() to start the game over.
Patterns to Try 40 Minutes
Patterns in Conway's Game of Life can be classified into different types. Still life patterns are stable from one generation to the next. Oscillating patterns repeat after a certain number of generations. Space ships move across the screen. And Methuselah patterns start simple and take a long time to stabilize or scatter.
Here are a few to try out.
Taking It Further
- See what other cool patterns you can come up with.
- Speed things up or slow them down by changing the 1000 in
setInterval(). - Fill the screen with random cells using the
random()function. - Use the "mousemove" event so you can click and drag to draw.
- Click on a cell that's already alive to erase it.
- Add a key that pauses the game.