Sure! Let's create a simple yet engaging game in Python where two populations of players evolve over generations using a genetic algorithm. One population will have a mutation rate of 0.1, and the other will have a mutation rate of 0.05. We'll observe how different mutation rates affect the evolution and performance of the players.
Game Idea: Grid Explorer
Overview
In Grid Explorer, players (agents) navigate a 5x5 grid to collect as many targets as possible within a fixed number of moves. Each player has a predefined sequence of moves encoded in their genome. The genetic algorithm evolves these sequences over generations to maximize the number of targets collected.
Key Components
- Grid: A 5x5 grid where targets are randomly placed.
- Player: An agent with a genome representing a sequence of moves (up, down, left, right).
- Genome: A list of moves determining the player's actions.
- Fitness: The number of targets collected by the player.
- Genetic Algorithm: Evolves the population by selection, crossover, and mutation.
Let's delve into the implementation.
Implementation
We'll structure the code into the following parts:
- Constants and Configurations
- Player Class
- Genetic Algorithm Functions
- Game Environment
- Evolution Process
- Visualization and Comparison
1. Constants and Configurations
import random
import copy
# Grid dimensions
GRID_SIZE = 5
# Move options
MOVES = ['UP', 'DOWN', 'LEFT', 'RIGHT']
# Genome length (number of moves per player)
GENOME_LENGTH = 10
# Population size
POPULATION_SIZE = 50
# Number of generations
GENERATIONS = 30
# Mutation rates
MUTATION_RATE_HIGH = 0.1
MUTATION_RATE_LOW = 0.05
# Number of targets on the grid
NUM_TARGETS = 3
# Number of moves per game
MOVES_PER_GAME = GENOME_LENGTH
2. Player Class
class Player:
def __init__(self, genome=None):
if genome:
self.genome = genome
else:
self.genome = [random.choice(MOVES) for _ in range(GENOME_LENGTH)]
self.fitness = 0
def mutate(self, mutation_rate):
new_genome = []
for move in self.genome:
if random.random() < mutation_rate:
new_move = random.choice(MOVES)
new_genome.append(new_move)
else:
new_genome.append(move)
self.genome = new_genome
def crossover(self, partner):
pivot = random.randint(1, GENOME_LENGTH - 1)
child_genome = self.genome[:pivot] + partner.genome[pivot:]
return Player(child_genome)
3. Genetic Algorithm Functions
def create_initial_population():
return [Player() for _ in range(POPULATION_SIZE)]
def evaluate_fitness(player, grid, targets):
x, y = 0, 0 # Starting position at top-left corner
collected = 0
collected_targets = set()
for move in player.genome[:MOVES_PER_GAME]:
if move == 'UP' and y > 0:
y -= 1
elif move == 'DOWN' and y < GRID_SIZE - 1:
y += 1
elif move == 'LEFT' and x > 0:
x -= 1
elif move == 'RIGHT' and x < GRID_SIZE - 1:
x += 1
if (x, y) in targets and (x, y) not in collected_targets:
collected += 1
collected_targets.add((x, y))
player.fitness = collected
def selection(population):
sorted_population = sorted(population, key=lambda p: p.fitness, reverse=True)
# Select top 20% as parents
retain_length = int(len(sorted_population) * 0.2)
parents = sorted_population[:retain_length]
return parents
def crossover(parents):
children = []
while len(children) < POPULATION_SIZE:
parent1, parent2 = random.sample(parents, 2)
child = parent1.crossover(parent2)
children.append(child)
return children
def mutate(children, mutation_rate):
for child in children:
child.mutate(mutation_rate)
return children
def generate_new_population(parents, mutation_rate):
children = crossover(parents)
mutated_children = mutate(children, mutation_rate)
return mutated_children
4. Game Environment
def generate_targets():
targets = set()
while len(targets) < NUM_TARGETS:
x = random.randint(0, GRID_SIZE - 1)
y = random.randint(0, GRID_SIZE - 1)
targets.add((x, y))
return list(targets)
def run_game(population):
targets = generate_targets()
for player in population:
evaluate_fitness(player, GRID_SIZE, targets)
5. Evolution Process
def evolve_population(initial_population, mutation_rate):
population = initial_population
best_fitness_per_generation = []
for generation in range(GENERATIONS):
run_game(population)
parents = selection(population)
best_fitness = parents[0].fitness if parents else 0
best_fitness_per_generation.append(best_fitness)
population = generate_new_population(parents, mutation_rate)
return best_fitness_per_generation
6. Visualization and Comparison
import matplotlib.pyplot as plt
def main():
# Initialize two populations
population_high = create_initial_population()
population_low = copy.deepcopy(population_high)
# Evolve populations with different mutation rates
fitness_high = evolve_population(population_high, MUTATION_RATE_HIGH)
fitness_low = evolve_population(population_low, MUTATION_RATE_LOW)
# Plotting the results
generations = list(range(1, GENERATIONS + 1))
plt.plot(generations, fitness_high, label=f'Mutation Rate {MUTATION_RATE_HIGH}')
plt.plot(generations, fitness_low, label=f'Mutation Rate {MUTATION_RATE_LOW}')
plt.xlabel('Generation')
plt.ylabel('Best Fitness')
plt.title('Evolution of Players with Different Mutation Rates')
plt.legend()
plt.grid(True)
plt.show()
if __name__ == "__main__":
main()
Explanation
-
Player Class: Each player has a genome representing a sequence of moves. The mutate method randomly changes moves based on the mutation rate. The crossover method combines genomes from two parents to produce a child.
-
Genetic Algorithm Functions:
- create_initial_population: Generates the initial population of players with random genomes.
- evaluate_fitness: Simulates the game for each player and assigns a fitness score based on the number of targets collected.
- selection: Selects the top 20% of players as parents for the next generation.
- crossover: Produces children by combining genomes from selected parents.
- mutate: Applies mutations to the children based on the mutation rate.
- generate_new_population: Creates a new generation by selecting parents, performing crossover, and applying mutations.
-
Game Environment:
- generate_targets: Randomly places targets on the grid.
- run_game: Runs the game for the entire population, evaluating each player's fitness.
-
Evolution Process:
- evolve_population: Evolves the population over a specified number of generations, recording the best fitness in each generation.
-
Visualization:
- Plots the best fitness over generations for both mutation rates to compare their effects.
Running the Game
Ensure you have matplotlib installed. You can install it using:
pip install matplotlib
Run the script:
python grid_explorer.py
You should see a plot showing how the best fitness evolves over generations for both mutation rates. Typically, a higher mutation rate (0.1) introduces more diversity, which can help escape local optima but may also lead to instability. A lower mutation rate (0.05) maintains better traits but might converge slower.
Observations
By comparing the two mutation rates:
-
Mutation Rate 0.1:
- Higher diversity in the population.
- Potentially faster exploration of the solution space.
- Risk of disrupting good solutions due to frequent mutations.
-
Mutation Rate 0.05:
- Less diversity, which might lead to slower evolution.
- More stable inheritance of beneficial traits.
- Lower risk of disrupting good solutions.
Depending on the complexity of the problem, one mutation rate might outperform the other. In our simple Grid Explorer game, you might observe that both mutation rates converge towards similar fitness levels, but the paths they take differ.
Feel free to experiment by changing parameters like POPULATION_SIZE, GENOME_LENGTH, GENERATIONS, and NUM_TARGETS to see how they affect the evolution process.