Okay, let's create a Python program using Pygame that simulates agents evolving through natural selection, using a simple neural network as their "brain."
The scenario: Agents (circles) move around the screen trying to find and "eat" food items (smaller circles). Agents that eat more food are considered fitter and are more likely to pass on their neural network (with slight mutations) to the next generation.
Concepts Demonstrated:
- Machine Learning (Neural Network): Each agent will have a small feedforward neural network that takes sensory inputs (like the position of the closest food) and outputs movement decisions (like desired velocity).
- Natural Selection:
- Variation: Agents start with slightly different random neural networks. When reproducing, mutations introduce further variation.
- Inheritance: Agents pass on their neural network structure and weights/biases to their offspring.
- Selection: Agents with higher fitness (more food eaten) are chosen as parents for the next generation.
- Time: The simulation runs over generations, allowing traits (NN weights) that lead to higher fitness to become more common.
Requirements:
- Python 3.x
- Pygame (
pip install pygame)
- NumPy (
pip install numpy) - Used for the neural network calculations.
Code Structure:
- Constants: Define parameters like screen size, population size, food count, generation duration, mutation rate, etc.
- NeuralNetwork Class: Handles the structure, forward pass, cloning, and mutation of an agent's brain. Uses NumPy.
- Agent Class: Represents a single agent. Holds its position, velocity, color, fitness, and a
NeuralNetwork instance. Includes methods for movement, thinking (using the NN), eating food, and drawing.
- Food Class: Represents a food item. Holds its position and includes a draw method.
- PopulationManager Class: Manages the collection of agents and food. Runs the simulation for a generation, calculates fitness, performs selection and reproduction, and creates the next generation.
- Main Game Loop: Initializes Pygame, creates a
PopulationManager, and runs the generation loop.
import pygame
import random
import math
import numpy as np
# --- Constants ---
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
BG_COLOR = (20, 20, 20) # Dark grey
POPULATION_SIZE = 50
FOOD_COUNT = 30
GENERATION_DURATION_FRAMES = 600 # How many frames a generation lasts
AGENT_RADIUS = 10
AGENT_COLOR = (100, 150, 255) # Blueish
AGENT_SPEED = 2.0
AGENT_TURN_SPEED = 0.1 # How much velocity can change per frame
FOOD_RADIUS = 5
FOOD_COLOR = (0, 255, 0) # Green
# NEURAL NETWORK PARAMETERS
INPUT_NODES = 5 # dx, dy to closest food, agent vx, agent vy, bias
HIDDEN_NODES = 4
OUTPUT_NODES = 2 # Desired vx, desired vy
MUTATION_RATE = 0.1 # Probability a weight/bias will be mutated
MUTATION_STRENGTH = 0.2 # How much a weight/bias changes when mutated
SELECTION_PERCENTAGE = 0.2 # Top 20% of agents selected for reproduction (plus some cloning)
# --- Neural Network Class ---
class NeuralNetwork:
def __init__(self, input_nodes, hidden_nodes, output_nodes):
self.input_nodes = input_nodes
self.hidden_nodes = hidden_nodes
self.output_nodes = output_nodes
# Initialize weights and biases randomly
# Input -> Hidden weights
self.weights_ih = np.random.uniform(-1, 1, (self.hidden_nodes, self.input_nodes))
# Hidden -> Output weights
self.weights_ho = np.random.uniform(-1, 1, (self.output_nodes, self.hidden_nodes))
# Biases for hidden and output layers
self.bias_h = np.random.uniform(-1, 1, (self.hidden_nodes, 1))
self.bias_o = np.random.uniform(-1, 1, (self.output_nodes, 1))
# Activation function (tanh is good for outputs around 0)
def activation(self, x):
return np.tanh(x)
# Feedforward pass through the network
def feedforward(self, inputs_array):
# Ensure inputs are a column vector
inputs = np.array(inputs_array).reshape(-1, 1)
# Input -> Hidden
hidden = np.dot(self.weights_ih, inputs)
hidden += self.bias_h
# Activation
hidden = self.activation(hidden)
# Hidden -> Output
output = np.dot(self.weights_ho, hidden)
output += self.bias_o
# Activation (using tanh here too, could use linear for velocity)
output = self.activation(output)
# Return output as a simple list/array
return output.flatten()
# Create a copy of the network
def clone(self):
clone = NeuralNetwork(self.input_nodes, self.hidden_nodes, self.output_nodes)
clone.weights_ih = self.weights_ih.copy()
clone.weights_ho = self.weights_ho.copy()
clone.bias_h = self.bias_h.copy()
clone.bias_o = self.bias_o.copy()
return clone
# Mutate weights and biases
def mutate(self, mutation_rate, mutation_strength):
def mutate_matrix(matrix):
for i in range(matrix.shape[0]):
for j in range(matrix.shape[1]):
if random.random() < mutation_rate:
# Add Gaussian noise
matrix[i][j] += np.random.normal(0, mutation_strength)
# Optional: Clamp values
# matrix[i][j] = max(-1, min(1, matrix[i][j]))
return matrix
self.weights_ih = mutate_matrix(self.weights_ih)
self.weights_ho = mutate_matrix(self.weights_ho)
self.bias_h = mutate_matrix(self.bias_h)
self.bias_o = mutate_matrix(self.bias_o)
# --- Agent Class ---
class Agent(pygame.sprite.Sprite):
def __init__(self, x, y, nn=None):
super().__init__()
self.image = pygame.Surface([AGENT_RADIUS * 2, AGENT_RADIUS * 2], pygame.SRCALPHA)
pygame.draw.circle(self.image, AGENT_COLOR, (AGENT_RADIUS, AGENT_RADIUS), AGENT_RADIUS)
self.rect = self.image.get_rect(center=(x, y))
self.pos = pygame.math.Vector2(x, y)
self.vel = pygame.math.Vector2(random.uniform(-1, 1), random.uniform(-1, 1)).normalize() * AGENT_SPEED
# Neural network - create new one or use provided
if nn is None:
self.nn = NeuralNetwork(INPUT_NODES, HIDDEN_NODES, OUTPUT_NODES)
else:
self.nn = nn
self.fitness = 0
self.time_alive = 0
def update(self, food_list):
self.time_alive += 1
self.think(food_list)
self.move()
self.check_food_collision(food_list)
def think(self, food_list):
# Find the closest food item
closest_food = None
min_dist_sq = float('inf')
if not food_list:
# If no food, maybe wander or stop
# For simplicity, let's output small random velocities
output = np.random.uniform(-0.1, 0.1, 2)
else:
for food in food_list:
dist_sq = (self.pos.x - food.pos.x)**2 + (self.pos.y - food.pos.y)**2
if dist_sq < min_dist_sq:
min_dist_sq = dist_sq
closest_food = food
# Calculate relative position of closest food
dx = closest_food.pos.x - self.pos.x
dy = closest_food.pos.y - self.pos.y
# Normalize dx, dy to be roughly between -1 and 1 based on screen size
# This helps the NN inputs stay within a reasonable range
dx_normalized = dx / (SCREEN_WIDTH / 2)
dy_normalized = dy / (SCREEN_HEIGHT / 2)
# Create NN inputs: [normalized dx, normalized dy, current vx, current vy, bias]
# Normalizing current velocity might also be good, but let's use raw for now
inputs = [dx_normalized, dy_normalized, self.vel.x / AGENT_SPEED, self.vel.y / AGENT_SPEED, 1.0]
# Feed inputs to the neural network
output = self.nn.feedforward(inputs)
# output is [desired_vx_scaled, desired_vy_scaled], values between -1 and 1
# Interpret output: update velocity
# Scale the desired velocity by max speed
target_vx = output[0] * AGENT_SPEED
target_vy = output[1] * AGENT_SPEED
# Create a vector for the desired velocity
target_vel = pygame.math.Vector2(target_vx, target_vy)
# Smoothly transition velocity towards target velocity
# Limit the change in velocity per frame (simulates inertia/turn speed)
change_in_vel = target_vel - self.vel
if change_in_vel.length() > AGENT_TURN_SPEED:
change_in_vel.normalize_ip()
change_in_vel *= AGENT_TURN_SPEED
self.vel += change_in_vel
# Optional: Cap the final speed
if self.vel.length() > AGENT_SPEED:
self.vel.normalize_ip()
self.vel *= AGENT_SPEED
def move(self):
self.pos += self.vel
# Wrap around screen edges
if self.pos.x < 0: self.pos.x += SCREEN_WIDTH
if self.pos.x > SCREEN_WIDTH: self.pos.x -= SCREEN_WIDTH
if self.pos.y < 0: self.pos.y += SCREEN_HEIGHT
if self.pos.y > SCREEN_HEIGHT: self.pos.y -= SCREEN_HEIGHT
self.rect.center = (int(self.pos.x), int(self.pos.y))
def check_food_collision(self, food_list):
# Check collision with food items
# Use a list comprehension to build a list of food items that were eaten
eaten_food = [food for food in food_list if pygame.sprite.collide_circle(self, food)]
for food in eaten_food:
self.fitness += 1 # Increase fitness for eating food
# Remove the eaten food item from the list
food_list.remove(food)
# Add a new food item somewhere else
food_list.append(Food(random.randint(0, SCREEN_WIDTH), random.randint(0, SCREEN_HEIGHT)))
# --- Food Class ---
class Food(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = pygame.Surface([FOOD_RADIUS * 2, FOOD_RADIUS * 2], pygame.SRCALPHA)
pygame.draw.circle(self.image, FOOD_COLOR, (FOOD_RADIUS, FOOD_RADIUS), FOOD_RADIUS)
self.rect = self.image.get_rect(center=(x, y))
self.pos = pygame.math.Vector2(x, y)
# --- Population Manager ---
class PopulationManager:
def __init__(self, screen):
self.screen = screen
self.agents = pygame.sprite.Group()
self.food_items = [] # Use a list for easier add/remove by Agent
self.generation = 0
self.frame_count = 0
self.best_fitness_prev_gen = 0 # Track best fitness from the last finished gen
self.create_initial_population()
self.create_food()
def create_initial_population(self):
self.agents.empty() # Clear any existing agents
for _ in range(POPULATION_SIZE):
x = random.randint(0, SCREEN_WIDTH)
y = random.randint(0, SCREEN_HEIGHT)
self.agents.add(Agent(x, y))
def create_food(self):
self.food_items = [] # Clear existing food
for _ in range(FOOD_COUNT):
x = random.randint(0, SCREEN_WIDTH)
y = random.randint(0, SCREEN_HEIGHT)
self.food_items.append(Food(x, y))
def run_generation(self):
self.frame_count = 0
self.generation += 1
print(f"--- Starting Generation {self.generation} ---")
# Reset agents' fitness and time_alive for the new generation
for agent in self.agents:
agent.fitness = 0
agent.time_alive = 0
# Recreate food for the new generation
self.create_food()
def evolve(self):
print(f"--- Ending Generation {self.generation} ---")
# 1. Calculate fitness (already done by agents eating food)
# 2. Sort agents by fitness (descending)
sorted_agents = sorted(self.agents, key=lambda agent: agent.fitness, reverse=True)
# Record best fitness for display
self.best_fitness_prev_gen = sorted_agents[0].fitness if sorted_agents else 0
print(f"Best fitness in Generation {self.generation}: {self.best_fitness_prev_gen}")
# 3. Select top performers for reproduction
selection_size = max(1, int(POPULATION_SIZE * SELECTION_PERCENTAGE))
selected_agents = sorted_agents[:selection_size]
# 4. Create the next generation
next_generation = pygame.sprite.Group()
# Add the top performers directly (elitism - optional but good practice)
# They are added as new agents with cloned NNs so their state is reset
for agent in selected_agents:
new_agent = Agent(random.randint(0, SCREEN_WIDTH), random.randint(0, SCREEN_HEIGHT), agent.nn.clone())
next_generation.add(new_agent)
# Fill the rest of the population by reproducing (cloning and mutating)
while len(next_generation) < POPULATION_SIZE:
# Choose a random parent from the selected pool
parent = random.choice(selected_agents)
# Create a child by cloning the parent's network
child_nn = parent.nn.clone()
# Mutate the child's network
child_nn.mutate(MUTATION_RATE, MUTATION_STRENGTH)
# Create a new agent with the mutated network
new_agent = Agent(random.randint(0, SCREEN_WIDTH), random.randint(0, SCREEN_HEIGHT), child_nn)
next_generation.add(new_agent)
# Replace the old population with the new one
self.agents = next_generation
# Start the next generation
self.run_generation()
def update(self):
self.frame_count += 1
# Update agents (agents update themselves and interact with food)
# Need to pass the mutable food_items list to the agent's update method
# Pygame sprite group update() takes arbitrary arguments passed to each sprite's update method
self.agents.update(self.food_items)
# Check if generation duration is reached
if self.frame_count >= GENERATION_DURATION_FRAMES:
self.evolve() # Trigger evolution and start a new generation
def draw(self):
self.screen.fill(BG_COLOR)
# Draw food items
for food in self.food_items:
self.screen.blit(food.image, food.rect)
# Draw agents
self.agents.draw(self.screen)
# Display generation info
font = pygame.font.Font(None, 36)
text_gen = font.render(f"Generation: {self.generation}", True, (255, 255, 255))
text_fitness = font.render(f"Best Fitness (Prev Gen): {self.best_fitness_prev_gen}", True, (255, 255, 255))
self.screen.blit(text_gen, (10, 10))
self.screen.blit(text_fitness, (10, 40))
# --- Main Game Function ---
def main():
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("ML & Natural Selection Simulation")
clock = pygame.time.Clock()
population_manager = PopulationManager(screen)
population_manager.run_generation() # Start the first generation
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Update
population_manager.update()
# Draw
population_manager.draw()
# Refresh display
pygame.display.flip()
# Cap frame rate
clock.tick(60) # Max 60 FPS
pygame.quit()
if __name__ == "__main__":
main()
Explanation:
-
NeuralNetwork:
- A simple feedforward network with one hidden layer.
- Uses NumPy for matrix operations (
np.dot).
__init__: Initializes weights and biases randomly.
activation: Uses the tanh function, which squashes values between -1 and 1.
feedforward: Takes inputs, performs matrix multiplications and adds biases through the layers, applying the activation function.
clone: Creates an exact copy of the network (essential for inheritance).
mutate: Iterates through weights and biases, adding small random noise with a certain probability (MUTATION_RATE). This introduces variation.
-
Agent:
- A Pygame
Sprite representing a circle.
- Holds its position (
pos), velocity (vel), and NeuralNetwork instance (nn).
fitness: Score based on food eaten in the current generation.
think: This is where the ML happens. It finds the closest food, calculates its relative position (dx, dy), prepares the input vector (including current velocity and a bias), feeds it to the agent's nn, and updates the agent's velocity based on the network's output. The output velocity is scaled and smoothly transitioned to prevent jerky movements.
move: Updates position based on velocity and handles wrapping around screen edges.
check_food_collision: Detects collision with food, increments fitness, removes the eaten food, and adds a new one randomly.
update: Called by the PopulationManager each frame to run the agent's logic (think, move, check_food_collision).
-
Food:
- A simple Pygame
Sprite for the food items.
-
PopulationManager:
- Manages the
agents (a Pygame Group) and food_items (a Python list).
create_initial_population: Creates the first generation of agents with random NNs.
How to Run:
- Save the code as a Python file (e.g.,
evolution_sim.py).
- Make sure you have Pygame and NumPy installed (
pip install pygame numpy).
- Run the file from your terminal:
python evolution_sim.py
You should see blue agents moving around, trying to find and eat green food items. As generations pass, you'll likely observe the agents getting better at finding food because the neural networks that lead to higher food consumption are being preferentially selected and reproduced. The "Best Fitness (Prev Gen)" counter on the screen should generally trend upwards over time.
You can experiment with the constants at the top (population size, mutation rates, generation duration, etc.) to see how they affect the evolution process.