Git Product home page Git Product logo

ssusnic / machine-learning-flappy-bird Goto Github PK

View Code? Open in Web Editor NEW
1.8K 89.0 403.0 485 KB

Machine Learning for Flappy Bird using Neural Network and Genetic Algorithm

Home Page: http://www.askforgametask.com/tutorial/machine-learning-algorithm-flappy-bird

License: MIT License

JavaScript 94.09% HTML 5.91%
machine-learning flappy-bird genetic-algorithm machine-learning-algorithm artificial-intelligence neuroevolution ai-tutorial ai artificial-evolution game-programming

machine-learning-flappy-bird's Introduction

Machine Learning for Flappy Bird using Neural Network and Genetic Algorithm

Here is the source code for a HTML5 project that implements a machine learning algorithm in the Flappy Bird video game using neural networks and a genetic algorithm. The program teaches a little bird how to flap optimally in order to fly safely through barriers as long as possible.

The complete tutorial with much more details and demo you can find here:
http://www.askforgametask.com/tutorial/machine-learning-algorithm-flappy-bird

Here you can also watch a short video with a simple presentation of the algorithm:
https://www.youtube.com/watch?v=aeWmdojEJf0

All code is written in HTML5 using Phaser framework and Synaptic Neural Network library for neural network implementation.

Flappy Bird Screenshot

Neural Network Architecture

To play the game, each unit (bird) has its own neural network consisted of the next 3 layers:

  1. an input layer with 2 neurons presenting what a bird sees:

    1) horizontal distance between the bird and the closest gap
    2) height difference between the bird and the closest gap
    
  2. a hidden layer with 6 neurons

  3. an output layer with 1 neuron used to provide an action as follows:

    if output > 0.5 then flap else do nothing
    

Flappy Bird Neural Network

There is used Synaptic Neural Network library to implement entire artificial neural network instead of making a new one from the scratch.

The Main Concept of Machine Learning

The main concept of machine learning implemented in this program is based on the neuro-evolution form. It uses evolutionary algorithms such as a genetic algorithm to train artificial neural networks. Here are the main steps:

  1. create a new population of 10 units (birds) with a random neural network

  2. let all units play the game simultaneously by using their own neural networks

  3. for each unit calculate its fitness function to measure its quality as:

    fitness = total travelled distance - distance to the closest gap
    

    Flappy Bird Fitness

  4. when all units are killed, evaluate the current population to the next one using genetic algorithm operators (selection, crossover and mutation) as follows:

    1. sort the units of the current population in decreasing order by their fitness ranking
    2. select the top 4 units and mark them as the winners of the current population
    3. the 4 winners are directly passed on to the next population
    4. to fill the rest of the next population, create 6 offsprings as follows:
        - 1 offspring is made by a crossover of two best winners
        - 3 offsprings are made by a crossover of two random winners
        - 2 offsprings are direct copy of two random winners
    5. to add some variations, apply random mutations on each offspring.
    
  5. go back to the step 2

Implementation

Requirements

Since the program is written in HTML5 using Phaser framework and Synaptic Neural Network library you need these files:

  • phaser.min.js
  • synaptic.min.js

gameplay.js

The entire game logic is implemented in gameplay.js file. It consists of the following classes:

  • App.Main, the main routine with the following essential functions:

    • preload() to preload all assets
    • create() to create all objects and initialize a new genetic algorithm object
    • update() to run the main loop in which the Flappy Bird game is played by using AI neural networks and the population is evolved by using genetic algorithm
    • drawStatus() to display information of all units
  • TreeGroup Class, extended Phaser Group class to represent a moving barrier. This group contains a top and a bottom Tree sprite.

  • Tree Class, extended Phaser Sprite class to represent a Tree sprite.

  • Bird Class, extended Phaser Sprite class to represent a Bird sprite.

  • Text Class, extended Phaser BitmapText class used for drawing text.

genetic.js

The genetic algorithm is implemented in genetic.js file which consists of the following class:

  • GeneticAlgorithm Class, the main class to handle all genetic algorithm operations. It needs two parameters: max_units to set a total number of units in population and top_units to set a number of top units (winners) used for evolving population. Here are its essential functions:

    • reset() to reset genetic algorithm parameters
    • createPopulation() to create a new population
    • activateBrain() to activate the AI neural network of an unit and get its output action according to the inputs
    • evolvePopulation() to evolve the population by using genetic operators (selection, crossover and mutations)
    • selection() to select the best units from the current population
    • crossOver() to perform a single point crossover between two parents
    • mutation() to perform random mutations on an offspring

machine-learning-flappy-bird's People

Contributors

ssusnic avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

machine-learning-flappy-bird's Issues

saving training progress in a file

I tried to save the trained network to a file, but when I export the network from the file, it is not trained

Due to the getting training data from the Internet, I want to save the intermediate population to a file in case of a disconnection

(Node.js)
Saving:

    var pop = [];
    for (var i = 0; i < GA.Population.length; i++) {//  GA = new GeneticAlgorithm(max_units, winners_count)
        pop.push(GA.Population[i].toJSON());
    }
    fs.writeFileSync('./population.json', JSON.stringify(pop));
    console.log("saved");

`
I do saving after each training

Exporting:

if (fs.existsSync('./population.json')){
    var d = fs.readFileSync('./population.json', 'utf8');
    var pop = JSON.parse(d);
    for (var i = 0; i < pop.length; i++) {
        var unit = synaptic.Network.fromJSON(pop[i]);
        unit.index = i;
        unit.fitness = 0;
        unit.score = 0;
        unit.isWinner = false;
        GA.Population[i] = unit;
        console.log('unit has been read');
    }
}
Score(GA)

Exporting is been doing when I start a new training session
But all of exported networks are not trained and gives bad results on activating even if they were trained on a immutable data. I activate exported network on that data and get a very bad result, but at the previous session the result is good

what could it be?

Thanks!

P.S. Sorry for my English, I'm a foreigner
P.P.S. I know, that the problem mainly in synaptic unit, but perhaps somebody could help here

Add speed control

Please add a speed control to speed up the process (like 2x, 4x 8x, 16x) to let the birds fly faster. I'm more interested in GEN 100 than in watching GEN 3 failing ;)

What exactly is 'bias' in the context of the program?

I have no idea what bias is in the genetic.js. Is it a keyword?

crossOver : function(parentA, parentB) {
		var cutPoint = this.random(0, parentA.neurons.length-1);
		for (var i = cutPoint; i < parentA.neurons.length; i++){
			//what is the bias part. what does it mean
			var biasFromParentA = parentA.neurons[i]['bias'];
			parentA.neurons[i]['bias'] = parentB.neurons[i]['bias'];
			parentB.neurons[i]['bias'] = biasFromParentA;
		}

		return this.random(0, 1) == 1 ? parentA : parentB;
	},

Similarly, is connections a keyword? What is this achieveing?

mutation : function (offspring){
		for (var i = 0; i < offspring.neurons.length; i++){
			offspring.neurons[i]['bias'] = this.mutate(offspring.neurons[i]['bias']);
		}
		
		//is connections a keyword?
		for (var i = 0; i < offspring.connections.length; i++){
			offspring.connections[i]['weight'] = this.mutate(offspring.connections[i]['weight']);
		}
		
		return offspring;
	},

Also, the function 'activate' is not referenced anywhere. I am not sure if that is a keyword because intellisense didn't pick it up. Could somebody tell me how the activate function working?


activateBrain: function(bird, target){
			var horizontalDistance = this.normalize(target.x,700) *this.SCALE_FACTOR;
			var verticalDistance = this.normalize(bird.y - target.y,800) * this.SCALE_FACTOR;	
			var inputs = [horizontalDistance,verticalDistance];
			//not sure what activate is
			var outputs = this.Population[bird.index].activate(inputs);
			if(outputs[0] > 0.5) bird.flap();
	},

Would appreciate if somebody could help me understand these 3 things. Thank you so much.

a step-by-step guide

Hi, it is a nice work to learning machine learning and I like it very much. I am new to HTML and JS, can you give a step-by-step guide to install, train and play this game?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.