I have looked into AI/Machine Learning breifly before, but this was the first time I made an AI that plays a game.
Because I made this project in Python instead of HTML and JavaScript like the other projects on my website, I can only show you what I did and recordings of it working. If you want to try it yourself, you can download the code on my GitHub page.
I first learned how to make games with python using pygame, following this tutorial.
After this, I made my own Snake game.
With this Snake game, I tried to use TensorFlow for the AI. After several attempts, I was unable to do so and so I looked into doing it another way.
I found this tutorial, which did work! This tutorial uses PyTorch instead of TensorFlow, which I found much easier to use.
Using what I learned from that tutorial, I added PyTorch to my Snake game, and an AI can now play my Snake game!
This AI uses Reinforcement Learning, it learns from the rewards it receives (positive rewards when picking up fruit, negative rewards when losing) when performing actions (moving around the board) to decide how to act in the future. It also uses Deep Q learning because a deep neural network is netword is used to make decisions (a deep neural network is one or more hidden layers between the sensor input and the calculated output).
It usually takes the snake around 80 games to become good. This could be because after 80 games, the snake never takes random moves (it initially moves randomly to learn more about the environment, called 'exploration vs exploitation').
Here is a graph of its results after 100 games (the blue line is each game's score, the orange line is the average score over time):
After around 100 games, the snake does not improve its score- the score varies between 10 and 60, averaging around 35.
Here is a graph of its results after 750 games:
Here it is playing after around 600 rounds:
Its highest score I have seen has been 75, after 128 games. Here is a screenshot of it and a GIF of the game:
You can see all of the recordings I took in the Media folder of the GitHub page.