This project implements a genetic algorithm to find an optimal or near-optimal solution for a Connect 4 game state. The algorithm simulates the evolution of game boards over several generations, selecting the fittest boards, performing crossover, and applying mutations to generate new populations. The goal is to find a board state that maximizes a specified fitness function.
genetic_game.py
: The main script that runs the genetic algorithm and displays the game state using Pyglet.connect_4.py
: Contains the core genetic algorithm functions.connect_4_utils.py
: Utility functions for generating random game states and printing the board.genetic_game_utils.py
: Pyglet utilities for drawing the Connect 4 grid and managing the display.README.md
: This readme file.
- Python 3.6 or higher
- Pyglet
- Clone the repository:
git clone https://github.com/Bilal-Ahmad102/Genetic-Algorithm
- Navigate to the project directory:
cd Genetic-Algorithm
- Install the required dependencies:
pip install pyglet
- Execute the main script:
python genetic_game.py
- The Pyglet window will open, displaying the evolution of the game states. The best fitness and generation number will be displayed on the screen.
initialize_population(size)
: Generates an initial population of random game boards.
fitness(board, player='x')
: Evaluates the fitness of a game board based on the number of desired positions for the player and the opponent.
select_parents(population, fitnesses)
: Selects parents for the next generation using roulette wheel selection.
crossover(parent1, parent2)
: Performs crossover between two parent boards to generate two child boards.
mutate(board)
: Randomly mutates a single position on the board.
draw_grid(state)
: Draws the Connect 4 grid with the current game state on the Pyglet window.
- The generation number and best fitness are displayed at the top of the Pyglet window.
population_size
: Number of boards in the population.generations
: Number of generations to run the genetic algorithm.crossover_prob
: Probability of performing crossover.mutation_prob
: Probability of performing mutation.
- Pyglet: For providing the library to create the graphical interface.
For any inquiries or suggestions, please contact [[email protected]].