DEV Community

loading...

Flappy Bird in Go with an AI from scratch

fr3fou profile image fr3fou!! 🎀 ・2 min read

🐥 A Neural Network + Genetic Algorithm which plays Flappy Bird

A genetic algorithm with a neural network (fr3fou/gone) built on top of fr3fou/flappy-go which plays flappy bird.

Here's a video on how it plays

Credits

This project was greatly inspired by Daniel Shiffman and his series on Neuroevolution:

How it works

The core game is reused and built on top of using composition

type Game struct {
    *flappy.Game
    // extra fields only used from the AI
}
type Bird struct {
    *flappy.Bird
    // extra fields only used from the AI
}

AI Architecture

500 birds in total are put in the game with the following architecutre of their brain

var BrainLayers = []gone.Layer{
    {
        Nodes:     5,
        Activator: gone.Sigmoid(),
    },
    {
        Nodes:     8,
        Activator: gone.Sigmoid(),
    },
    {
        Nodes:     2,
        Activator: gone.Sigmoid(), // ideally should be softmax
    },
}

There are 5 inputs, 4 of them described in the following image and the last 1 is the velocity of the bird

vars

The 2 outputs determine whether the bird should jump or not

if output[0] > output[1] {
    bird.Jump()
}

Their score is determined by how well they perform (how long they survive)

At the end of each generation, the best performing birds are to mate.

Using the crossoverOdds and mutationRate arguments to ai.New() it is determined what % of the new population should be created using ONLY mutation or crossover AND mutation.

After a new population has been created, the process gets repeated.

How it was built

I started working on my Neural Network library from scratch back in March of 2020. One month later I wanted to explore Genetic Algorithms and NEAT, I decided that I should make my own Flappy Clone using Go and Raylib. After 1 week of working on the game, I got working on the actual Genetic Algorithm. Overall It took me 2 weeks to finish this project (excluding the 4 or 5 weeks working on the neural network library)

Discussion (0)

pic
Editor guide