Skip to content

Flappy Bird AI - Genetic Algorithm Evolution ๐Ÿงฌ๐Ÿฆ

License

antilneeraj/GeneticAlgorithm

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

17 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

Flappy Bird AI - Genetic Algorithm Evolution ๐Ÿงฌ๐Ÿฆ

Stars Follow License Python Pygame

โญ Star this repository if you find it interesting! โญ

๐Ÿš€ Quick Start โ€ข ๐Ÿ“– Documentation โ€ข ๐Ÿงฌ How It Works โ€ข ๐Ÿ“Š Results

Watch AI birds evolve from random chaos to expert Flappy Bird gameplay using neural networks and genetic algorithms!


๐ŸŽฏ What is this?

This project implements an AI that learns to play Flappy Bird using:

  • ๐Ÿง  Neural Networks for decision making
  • ๐Ÿงฌ Genetic Algorithm for evolution
  • ๐ŸŽฎ Pygame for game simulation
  • ๐Ÿ“Š Real-time visualization of learning progress

No training data needed! The AI learns purely through trial and error, just like biological evolution.

Note: Add your gameplay GIFs/videos here to showcase the evolution!

๐Ÿš€ Quick Start

Prerequisites

  • Python 3.8+
  • pip package manager

Installation

# Clone the repository
git clone https://github.com/antilneeraj/geneticalgorithm.git
cd geneticalgorithm

# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt

Usage

# Watch AI learn to play (recommended)
python main.py --mode ai_training --population 50

# Play yourself
python main.py --mode human

# Watch trained AI play
python main.py --mode ai_play

# Run diagnostics
python diagnostic_ai_debug.py

๐ŸŽฎ Game Controls

Key Action
SPACE Jump (Human mode) / Start game
R Restart game
P Pause/Unpause
D Toggle debug info
ESC Quit game

๐Ÿงฌ How It Works

1. Neural Network Brain

Each bird has a neural network with:

  • Input: Bird position, velocity, pipe distance, gap location
  • Hidden Layers: 6 โ†’ 4 neurons with tanh activation
  • Output: Jump decision (sigmoid activation)

2. Genetic Algorithm Evolution

Generation 1: 50 random birds โ†’ Most die quickly
    โ†“
Fitness Evaluation: Survival time + Score + Bonuses
    โ†“
Selection: Keep top 5 performers (elitism)
    โ†“
Reproduction: Crossover + Mutation
    โ†“
Generation 2: Improved birds โ†’ Better performance
    โ†“
Repeat for 100+ generations...
    โ†“
Result: Expert-level AI players!

3. Fitness Function

fitness = survival_time * 1.0 + score * 100 + bonuses
  • Survival bonus: +1 point per frame alive
  • Pipe bonus: +100 points per pipe passed
  • Death penalty: -50 points for crashing

๐Ÿ“Š Training Results

Performance Evolution

Generation Best Score Avg Survival Best AI Behavior
1-5 0 30-80 frames Random chaos
10-20 1-2 200-400 frames Basic navigation
30-50 3-8 500-800 frames Smart pipe avoidance
50+ 10+ 1000+ frames Expert gameplay

Key Metrics

  • Population Size: 50 birds per generation
  • Training Time: ~2-5 minutes per generation
  • Convergence: Expert level in ~50 generations
  • Success Rate: 95%+ birds learn to score points

๐Ÿ—๏ธ Project Structure

geneticalgorithm/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ game/               # Game engine and components
โ”‚   โ”‚   โ”œโ”€โ”€ bird.py        # Bird class with AI integration
โ”‚   โ”‚   โ”œโ”€โ”€ pipe.py        # Pipe generation and collision
โ”‚   โ”‚   โ”œโ”€โ”€ game_engine.py # Main game loop and AI training
โ”‚   โ”‚   โ””โ”€โ”€ renderer.py    # Graphics and UI rendering
โ”‚   โ”œโ”€โ”€ ai/                # AI and machine learning components
โ”‚   โ”‚   โ”œโ”€โ”€ neural_network.py    # Neural network implementation
โ”‚   โ”‚   โ”œโ”€โ”€ genetic_algorithm.py # Evolution logic
โ”‚   โ”‚   โ””โ”€โ”€ fitness.py           # Fitness evaluation
โ”‚   โ””โ”€โ”€ utils/             # Utilities and configuration
โ”‚       โ”œโ”€โ”€ constants.py   # Game and AI parameters
โ”‚       โ””โ”€โ”€ asset_loader.py # Resource management
โ”œโ”€โ”€ assets/                # Game sprites, sounds, fonts
โ”œโ”€โ”€ data/                 # Training data and saved models
โ”œโ”€โ”€ main.py              # Entry point
โ”œโ”€โ”€ requirements.txt     # Dependencies
โ””โ”€โ”€ README.md           # This file

๐Ÿ› ๏ธ Configuration

Customize training parameters in src/utils/constants.py:

# Genetic Algorithm Settings
POPULATION_SIZE = 50        # Number of birds per generation
GENERATIONS = 100           # Maximum generations
MUTATION_RATE = 0.1         # Probability of mutation
CROSSOVER_RATE = 0.8        # Probability of crossover
ELITE_COUNT = 5             # Top performers to preserve

# Neural Network Architecture  
NN_INPUT_NODES = 4          # Game state inputs
NN_HIDDEN_NODES = [6, 4]    # Hidden layer sizes
NN_OUTPUT_NODES = 1         # Jump decision output

# Fitness Parameters
FITNESS_BONUS_PIPE = 100    # Points per pipe passed
FITNESS_BONUS_DISTANCE = 1  # Points per frame survived
FITNESS_PENALTY_DEATH = -50 # Penalty for dying

๐Ÿงช Running Tests

# Test neural network diversity
python diagnostic_ai_debug.py

# Validate AI components
python validate_ai_constants.py

# Run performance benchmarks
python benchmarks.py

๐Ÿ“ˆ Features

  • โœ… Real-time AI training visualization
  • โœ… Multiple game modes (Human, AI Training, AI Play)
  • โœ… Configurable parameters for experimentation
  • โœ… Performance analytics and statistics
  • โœ… Save/load trained models
  • โœ… Debug mode with detailed metrics
  • โœ… Professional logging system
  • โœ… Cross-platform compatibility

๐Ÿค Contributing

Contributions are welcome! Here's how you can help:

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Commit changes: git commit -m 'Add amazing feature'
  4. Push to branch: git push origin feature/amazing-feature
  5. Open a Pull Request

Development Setup

# Install development dependencies
pip install -r requirements-dev.txt

# Run tests
python -m pytest tests/

# Format code
python -m black src/
python -m isort src/

๐Ÿ“š Learning Resources

๐Ÿ› Troubleshooting

Common Issues & Solutions

Issue: Birds not learning / identical behavior

# Run diagnostics to check neural network diversity
python diagnostic_ai_debug.py

Issue: Game crashes on startup

# Check pygame installation
pip install --upgrade pygame

Issue: Poor AI performance

# Try adjusting parameters in constants.py
MUTATION_RATE = 0.15  # Increase for more diversity
POPULATION_SIZE = 100 # Larger population

Issue: Slow training

# Reduce population size for faster iterations
POPULATION_SIZE = 20

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ™ Acknowledgments

  • Pygame Community for the excellent game development framework
  • NEAT Algorithm inspiration for neural network evolution
  • Flappy Bird original game concept by Dong Nguyen
  • AI Research Community for genetic algorithm innovations

๐Ÿ“ž Contact & Support


โญ Don't forget to star this repository if you found it useful! โญ

Stars Follow

Made with โค๏ธ and lots of โ˜• by Neeraj Antil

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •  

Languages