Creating a game and making a genetic algorithm to play it

Recently I’ve been using the Phaser JavaScript game framework to create a game with a friend. I thought that it would be interesting to use what I’ve learned to create a basic game that a genetic algorithm can play.

I ended up with a simple game where the player has to jump over rocks floating on lava streams using the space bar. I made the graphics myself so they are, to put it lightly, rather lacking.

You can try playing the game in your browser here, and the code is all on GitHub here.

The next step was to add a genetic algorithm. I modified the game by removing the code that let the user play and adding some methods to get data about the position of rocks and whether there is grass at a particular y coordinate.

The genetic algorithm evolves weights for a logistic regression classifier that decides whether the player should jump forward or not. I made a LogisticRegressionClassifier class as well as an Agent class that represents a single player and a GeneticAlgorithm class that manages the population of agents and carries out selection, crossover, mutation and elitism.

You can try running the genetic algorithm in your browser here and you can see the code on GitHub here.

The genetic algorithm does actually seem to learn! For example on generation 1 below it was pretty hopeless with the highest score being 7.

The agents are opaque – if they appear solid it means that there are multiple agents on top of each other (quite confusing to look at).

However, by generation 39 it has learned and some of the agents are able to get scores over 30, which is where the lava streams stop on the modified version of the game.

The lava gets faster as they go further

I wrote a more detailed walk-through of the code for creating the game on the Micropi blog here, and a walk-through of the genetic algorithm code here.

Leave a comment

Design a site like this with WordPress.com
Get started