Creating a Python program that combines machine learning and natural selection in Pygame is a fascinating project! Typically, this involves simulating a population of agents that learn or evolve over time to improve their performance on a task.
Below is a simple example of such a system:
We simulate a population of "creatures" that try to move toward a target.
Each creature has a simple "brain" represented by a neural network (using NumPy).
Creatures "live" for a fixed number of frames.
At the end of each generation, the best performers are selected, and their "brains" are combined and mutated to create the next generation.
The process repeats, showing natural selection and learning over generations.
Requirements
Python 3.x
Pygame (pip install pygame)
NumPy (pip install numpy)
Code
python
import pygame
import numpy as np
import random
# Pygame setup
WIDTH, HEIGHT = 800, 600
FPS = 60
# Neural network parameters
INPUT_SIZE = 4 # x, y, target_x, target_y (normalized)
HIDDEN_SIZE = 6
OUTPUT_SIZE = 2 # dx, dy movement
# Evolution parameters
POPULATION_SIZE = 50
LIFESPAN = 200 # frames per generation
MUTATION_RATE = 0.1
SELECTION_RATIO = 0.2 # top 20% selected
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("ML + Natural Selection Demo")
clock = pygame.time.Clock()
# Target position
target_pos = np.array([WIDTH // 2, HEIGHT // 8])
def sigmoid(x):
return 1 / (1 + np.exp(-x))
class NeuralNetwork:
def __init__(self, input_size, hidden_size, output_size):
# Initialize weights randomly
self.w1 = np.random.randn(hidden_size, input_size)
self.b1 = np.random.randn(hidden_size, 1)
self.w2 = np.random.randn(output_size, hidden_size)
self.b2 = np.random.randn(output_size, 1)
def forward(self, x):
# x shape: (input_size, 1)
z1 = np.dot(self.w1, x) + self.b1
a1 = sigmoid(z1)
z2 = np.dot(self.w2, a1) + self.b2
a2 = np.tanh(z2) # output between -1 and 1 for movement
return a2
def copy(self):
nn = NeuralNetwork(INPUT_SIZE, HIDDEN_SIZE, OUTPUT_SIZE)
nn.w1 = np.copy(self.w1)
nn.b1 = np.copy(self.b1)
nn.w2 = np.copy(self.w2)
nn.b2 = np.copy(self.b2)
return nn
def mutate(self):
def mutate_matrix(m):
mutation_mask = np.random.rand(*m.shape) < MUTATION_RATE
random_values = np.random.randn(*m.shape) * 0.5
m += mutation_mask * random_values
mutate_matrix(self.w1)
mutate_matrix(self.b1)
mutate_matrix(self.w2)
mutate_matrix(self.b2)
@staticmethod
def crossover(parent1, parent2):
child = NeuralNetwork(INPUT_SIZE, HIDDEN_SIZE, OUTPUT_SIZE)
def crossover_matrix(m1, m2):
mask = np.random.rand(*m1.shape) > 0.5
return np.where(mask, m1, m2)
child.w1 = crossover_matrix(parent1.w1, parent2.w1)
child.b1 = crossover_matrix(parent1.b1, parent2.b1)
child.w2 = crossover_matrix(parent1.w2, parent2.w2)
child.b2 = crossover_matrix(parent1.b2, parent2.b2)
return child
class Creature:
RADIUS = 5
def __init__(self):
self.pos = np.array([random.uniform(0, WIDTH), random.uniform(HEIGHT//2, HEIGHT)])
self.brain = NeuralNetwork(INPUT_SIZE, HIDDEN_SIZE, OUTPUT_SIZE)
self.fitness = 0
self.alive = True
def update(self):
if not self.alive:
return
# Normalize inputs between 0 and 1
input_vector = np.array([
self.pos[0] / WIDTH,
self.pos[1] / HEIGHT,
target_pos[0] / WIDTH,
target_pos[1] / HEIGHT
]).reshape(INPUT_SIZE, 1)
output = self.brain.forward(input_vector)
move = output.flatten() * 5 # scale movement speed
self.pos += move
self.pos = np.clip(self.pos, [0, 0], [WIDTH, HEIGHT])
# Update fitness: inverse distance to target
dist = np.linalg.norm(self.pos - target_pos)
self.fitness = 1 / (dist + 1) # +1 to avoid div by zero
# Optional: kill if too far or out of bounds (already clipped)
# Here we keep all alive for lifespan
def draw(self, surface):
color = (0, 255, 0) if self.alive else (100, 100, 100)
pygame.draw.circle(surface, color, self.pos.astype(int), self.RADIUS)
def evolve_population(population):
# Sort by fitness descending
population.sort(key=lambda c: c.fitness, reverse=True)
survivors = population[:int(POPULATION_SIZE * SELECTION_RATIO)]
# Print best fitness for debug
print(f"Best fitness: {survivors[0].fitness:.4f}")
new_population = []
# Keep the best creature unchanged (elitism)
elite = survivors[0]
elite_copy = Creature()
elite_copy.brain = elite.brain.copy()
new_population.append(elite_copy)
# Generate new creatures by crossover and mutation
while len(new_population) < POPULATION_SIZE:
parent1, parent2 = random.sample(survivors, 2)
child = Creature()
child.brain = NeuralNetwork.crossover(parent1.brain, parent2.brain)
child.brain.mutate()
new_population.append(child)
return new_population
def main():
population = [Creature() for _ in range(POPULATION_SIZE)]
generation = 1
frame_count = 0
running = True
while running:
clock.tick(FPS)
frame_count += 1
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((30, 30, 30))
pygame.draw.circle(screen, (255, 0, 0), target_pos.astype(int), 10)
# Update and draw creatures
for creature in population:
creature.update()
creature.draw(screen)
pygame.display.flip()
if frame_count >= LIFESPAN:
# Evolve population
population = evolve_population(population)
frame_count = 0
generation += 1
pygame.display.set_caption(f"Generation: {generation}")
pygame.quit()
if __name__ == "__main__":
main()
How it works:
Each creature tries to move toward the red target circle.
Their neural network takes their position and the target position as input and outputs a movement vector.
After LIFESPAN frames, creatures are evaluated by how close they got to the target.
The top 20% are selected to breed the next generation.
New creatures are created by crossover and mutation of the parents' neural networks.
Over generations, creatures should learn to move more efficiently toward the target.
Possible extensions:
Add obstacles and more complex environments.
Use more sophisticated neural networks or reinforcement learning.
Visualize fitness graphs.
Add more sensors (e.g., distance to obstacles).
Implement different mutation strategies.
If you want me to help you extend or customize this example, just ask!