Creating a neural network that learns to navigate a maze and then competes against another player involves several steps. Below, I'll provide two separate Python scripts using PyTorch and Pygame:
- Training Script: This script will define the maze environment, implement a reinforcement learning agent (using Deep Q-Learning), train the neural network to find the exit, and save the trained model.
- Competition Script: This script will load the saved model and allow the trained agent to compete in navigating the maze, potentially against another agent.
Prerequisites
Before diving into the code, ensure you have the following libraries installed:
pip install pygame
pip install torch
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import random
import numpy as np
from collections import deque
1. Training Script: Training the Neural Network to Navigate the Maze
This script sets up the maze environment, defines the neural network, implements the Deep Q-Learning algorithm, trains the agent, and saves the trained model.
# maze_training.py
import pygame
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import random
import numpy as np
from collections import deque
# Initialize Pygame
pygame.init()
# Define Maze Parameters
WIDTH, HEIGHT = 600, 600
ROWS, COLS = 10, 10
CELL_SIZE = WIDTH // COLS
# Define Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# Define Actions
ACTION_UP = 0
ACTION_DOWN = 1
ACTION_LEFT = 2
ACTION_RIGHT = 3
ACTIONS = [ACTION_UP, ACTION_DOWN, ACTION_LEFT, ACTION_RIGHT]
# Define the Maze Layout (1 - Wall, 0 - Path)
# Simple 10x10 maze example
MAZE = [
[1,1,1,1,1,1,1,1,1,1],
[1,0,0,0,1,0,0,0,0,1],
[1,0,1,0,1,0,1,1,0,1],
[1,0,1,0,0,0,0,1,0,1],
[1,0,1,1,1,1,0,1,0,1],
[1,0,0,0,0,1,0,1,0,1],
[1,1,1,1,0,1,0,1,0,1],
[1,0,0,1,0,0,0,1,0,1],
[1,0,0,0,0,1,0,0,0,1],
[1,1,1,1,1,1,1,1,1,1],
]
# Define Start and End Positions
START_POS = (1,1)
END_POS = (8,8)
class MazeEnv:
def __init__(self):
self.reset()
def reset(self):
self.agent_pos = list(START_POS)
return self.get_state()
def get_state(self):
# State can be the agent's position and the maze layout
# For simplicity, we'll return the flattened maze with agent position marked
state = np.array(MAZE).flatten()
agent_index = self.agent_pos[0] * COLS + self.agent_pos[1]
state[agent_index] = 2 # Mark agent's position with '2'
return state.astype(np.float32)
def step(self, action):
x, y = self.agent_pos
if action == ACTION_UP:
new_x, new_y = x - 1, y
elif action == ACTION_DOWN:
new_x, new_y = x + 1, y
elif action == ACTION_LEFT:
new_x, new_y = x, y - 1
elif action == ACTION_RIGHT:
new_x, new_y = x, y + 1
else:
new_x, new_y = x, y
# Check for valid move
if MAZE[new_x][new_y] == 0:
self.agent_pos = [new_x, new_y]
done = False
reward = -0.1 # Small negative reward for each step
if tuple(self.agent_pos) == END_POS:
done = True
reward = 10 # Reward for reaching the goal
return self.get_state(), reward, done
class DQN(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(DQN, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_size)
self.fc2 = nn.Linear(hidden_size, hidden_size)
self.out = nn.Linear(hidden_size, output_size)
def forward(self, x):
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.out(x)
return x
class Agent:
def __init__(self, state_size, action_size):
self.memory = deque(maxlen=10000)
self.gamma = 0.99 # Discount factor
self.epsilon = 1.0 # Exploration rate
self.epsilon_min = 0.01
self.epsilon_decay = 0.995
self.learning_rate = 0.001
self.batch_size = 64
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.model = DQN(state_size, 128, action_size).to(self.device)
self.optimizer = optim.Adam(self.model.parameters(), lr=self.learning_rate)
def remember(self, state, action, reward, next_state, done):
self.memory.append( (state, action, reward, next_state, done) )
def act(self, state):
if random.random() < self.epsilon:
return random.choice(ACTIONS)
state = torch.FloatTensor(state).unsqueeze(0).to(self.device)
with torch.no_grad():
q_values = self.model(state)
return torch.argmax(q_values[0]).item()
def replay(self):
if len(self.memory) < self.batch_size:
return
minibatch = random.sample(self.memory, self.batch_size)
states = torch.FloatTensor([m[0] for m in minibatch]).to(self.device)
actions = torch.LongTensor([m[1] for m in minibatch]).unsqueeze(1).to(self.device)
rewards = torch.FloatTensor([m[2] for m in minibatch]).unsqueeze(1).to(self.device)
next_states = torch.FloatTensor([m[3] for m in minibatch]).to(self.device)
dones = torch.FloatTensor([float(m[4]) for m in minibatch]).unsqueeze(1).to(self.device)
# Compute current Q values
current_q = self.model(states).gather(1, actions)
# Compute next Q values
next_q = self.model(next_states).max(1)[0].unsqueeze(1)
target_q = rewards + self.gamma * next_q * (1 - dones)
# Compute loss
loss = F.mse_loss(current_q, target_q)
# Optimize the model
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
# Decay epsilon
if self.epsilon > self.epsilon_min:
self.epsilon *= self.epsilon_decay
def train():
env = MazeEnv()
state_size = ROWS * COLS
action_size = len(ACTIONS)
agent = Agent(state_size, action_size)
episodes = 500
for e in range(episodes):
state = env.reset()
done = False
step = 0
while not done:
action = agent.act(state)
next_state, reward, done = env.step(action)
agent.remember(state, action, reward, next_state, done)
state = next_state
step +=1
agent.replay()
if done:
print(f"Episode {e+1}/{episodes} - Steps: {step} - Epsilon: {agent.epsilon:.2}")
break
# Save the trained model
torch.save(agent.model.state_dict(), "maze_dqn.pth")
print("Training completed and model saved as maze_dqn.pth")
if __name__ == "__main__":
train()
Explanation:
-
Maze Representation:
- The maze is a 10x10 grid where
1 represents walls and 0 represents paths.
START_POS and END_POS define the starting and exit positions of the agent.
-
Environment (MazeEnv Class):
reset(): Resets the agent's position to the start.
get_state(): Provides the current state of the environment. The state is a flattened version of the maze with the agent's current position marked as 2.
step(action): Executes the action, updates the agent's position if the move is valid, assigns rewards, and checks if the goal is reached.
-
Neural Network (DQN Class):
- A simple feedforward neural network with two hidden layers using ReLU activation.
- Takes the flattened maze as input and outputs Q-values for each possible action.
-
Agent (Agent Class):
- Implements the Deep Q-Learning algorithm.
- Uses an epsilon-greedy policy for action selection to balance exploration and exploitation.
- Stores experiences in replay memory and samples mini-batches for training.
-
Training Loop (train Function):
- Runs through a specified number of episodes.
- In each episode, the agent interacts with the environment, collects experiences, and learns from them.
- After training, the model is saved to
maze_dqn.pth.
2. Competition Script: Competing to Navigate the Maze Faster
This script loads the trained model and allows the agent to navigate the maze. For competition purposes, you can run multiple agents and compare their performance. Below is a simple example where the trained agent competes against a random agent.
# maze_competition.py
import pygame
import torch
import torch.nn as nn
import torch.nn.functional as F
import random
import numpy as np
from collections import deque
import time
# Initialize Pygame
pygame.init()
# Define Maze Parameters
WIDTH, HEIGHT = 600, 600
ROWS, COLS = 10, 10
CELL_SIZE = WIDTH // COLS
# Define Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
# Define Actions
ACTION_UP = 0
ACTION_DOWN = 1
ACTION_LEFT = 2
ACTION_RIGHT = 3
ACTIONS = [ACTION_UP, ACTION_DOWN, ACTION_LEFT, ACTION_RIGHT]
# Define the Maze Layout (1 - Wall, 0 - Path)
MAZE = [
[1,1,1,1,1,1,1,1,1,1],
[1,0,0,0,1,0,0,0,0,1],
[1,0,1,0,1,0,1,1,0,1],
[1,0,1,0,0,0,0,1,0,1],
[1,0,1,1,1,1,0,1,0,1],
[1,0,0,0,0,1,0,1,0,1],
[1,1,1,1,0,1,0,1,0,1],
[1,0,0,1,0,0,0,1,0,1],
[1,0,0,0,0,1,0,0,0,1],
[1,1,1,1,1,1,1,1,1,1],
]
# Define Start and End Positions
START_POS = (1,1)
END_POS = (8,8)
class MazeEnv:
def __init__(self):
self.reset()
def reset(self):
self.agent_pos = list(START_POS)
return self.get_state()
def get_state(self):
state = np.array(MAZE).flatten()
agent_index = self.agent_pos[0] * COLS + self.agent_pos[1]
state[agent_index] = 2 # Mark agent's position with '2'
return state.astype(np.float32)
def step(self, action):
x, y = self.agent_pos
if action == ACTION_UP:
new_x, new_y = x - 1, y
elif action == ACTION_DOWN:
new_x, new_y = x + 1, y
elif action == ACTION_LEFT:
new_x, new_y = x, y - 1
elif action == ACTION_RIGHT:
new_x, new_y = x, y + 1
else:
new_x, new_y = x, y
if MAZE[new_x][new_y] == 0:
self.agent_pos = [new_x, new_y]
done = False
if tuple(self.agent_pos) == END_POS:
done = True
return self.get_state(), done
class DQN(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(DQN, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_size)
self.fc2 = nn.Linear(hidden_size, hidden_size)
self.out = nn.Linear(hidden_size, output_size)
def forward(self, x):
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.out(x)
return x
class PlayerAgent:
def __init__(self, model_path, state_size, action_size):
self.model = DQN(state_size, 128, action_size)
self.model.load_state_dict(torch.load(model_path))
self.model.eval()
self.state_size = state_size
self.action_size = action_size
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.model.to(self.device)
def act(self, state):
state = torch.FloatTensor(state).unsqueeze(0).to(self.device)
with torch.no_grad():
q_values = self.model(state)
return torch.argmax(q_values[0]).item()
class RandomAgent:
def __init__(self, action_size):
self.action_size = action_size
def act(self, state):
return random.choice(ACTIONS)
def draw_maze(screen):
for i in range(ROWS):
for j in range(COLS):
rect = pygame.Rect(j*CELL_SIZE, i*CELL_SIZE, CELL_SIZE, CELL_SIZE)
if MAZE[i][j] == 1:
pygame.draw.rect(screen, BLACK, rect)
elif MAZE[i][j] == 0:
pygame.draw.rect(screen, WHITE, rect)
# Draw Start and End
start_rect = pygame.Rect(START_POS[1]*CELL_SIZE, START_POS[0]*CELL_SIZE, CELL_SIZE, CELL_SIZE)
end_rect = pygame.Rect(END_POS[1]*CELL_SIZE, END_POS[0]*CELL_SIZE, CELL_SIZE, CELL_SIZE)
pygame.draw.rect(screen, GREEN, start_rect)
pygame.draw.rect(screen, RED, end_rect)
def draw_agent(screen, pos, color):
agent_rect = pygame.Rect(pos[1]*CELL_SIZE + CELL_SIZE//4, pos[0]*CELL_SIZE + CELL_SIZE//4, CELL_SIZE//2, CELL_SIZE//2)
pygame.draw.rect(screen, color, agent_rect)
def competition():
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Maze Competition")
clock = pygame.time.Clock()
env = MazeEnv()
state_size = ROWS * COLS
action_size = len(ACTIONS)
# Initialize Agents
trained_agent = PlayerAgent("maze_dqn.pth", state_size, action_size)
random_agent = RandomAgent(action_size)
# Reset Environment
state = env.reset()
trained_pos = list(START_POS)
random_pos = list(START_POS)
done_trained = False
done_random = False
steps_trained = 0
steps_random = 0
running = True
while running:
clock.tick(10) # Control the speed
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if not done_trained:
action_trained = trained_agent.act(state)
next_state, done_trained = env.step(action_trained)
trained_pos = [idx for idx, val in enumerate(next_state) if val == 2]
# Convert back to (x,y)
flat_index = next_state.tolist().index(2)
trained_pos = [flat_index // COLS, flat_index % COLS]
state = next_state
steps_trained +=1
if done_trained:
print(f"Trained Agent reached the goal in {steps_trained} steps.")
if not done_random:
action_random = random_agent.act(state)
next_state_random, done_random = env.step(action_random)
# Find random agent's position
flat_index_random = next_state_random.tolist().index(2)
random_pos = [flat_index_random // COLS, flat_index_random % COLS]
steps_random +=1
if done_random:
print(f"Random Agent reached the goal in {steps_random} steps.")
# Draw
screen.fill(WHITE)
draw_maze(screen)
if not done_trained:
draw_agent(screen, trained_pos, BLUE)
if not done_random:
draw_agent(screen, random_pos, YELLOW)
pygame.display.flip()
if done_trained and done_random:
running = False
pygame.quit()
if __name__ == "__main__":
competition()
Explanation:
-
Environment and Maze Representation:
- The
MazeEnv and maze definition are identical to the training script.
- The environment does not provide rewards here; it simply updates the agent's position.
-
Neural Network (DQN Class):
- Must match the architecture used during training for compatibility.
- Loads the trained weights from
maze_dqn.pth.
-
Agents:
PlayerAgent: Uses the trained neural network to decide actions.
RandomAgent: Chooses random actions.
-
Visualization:
- Uses Pygame to draw the maze, the start and end positions, and the agents.
- The trained agent is represented by a blue square, and the random agent by a yellow square.
-
Competition Logic:
- Both agents attempt to navigate the maze simultaneously.
- The competition ends when both agents reach the goal.
- The number of steps each agent takes to reach the goal is printed.
Running the Scripts
-
Train the Agent:
Run the training script to train the neural network and save the model.
python maze_training.py
This will start the training process. After completion, a maze_dqn.pth file will be saved containing the trained model.
-
Run the Competition:
After training, run the competition script to see how the trained agent performs against a random agent.
python maze_competition.py
A Pygame window will open visualizing the maze and the agents. Upon completion, the number of steps each agent took to reach the goal will be printed in the console.
Improving the Competition
To extend this into a more robust competition platform, consider the following enhancements:
- Multiple Trained Agents: Load multiple trained models and have them compete against each other.
- Graphical Enhancements: Improve the visualization with better graphics, agent animations, and real-time statistics.
- Leaderboards: Implement a system to track and display agent performances over multiple runs.
- Interactive Controls: Allow users to control agents manually or adjust competition parameters on the fly.
Conclusion
This setup provides a foundational framework for training a neural network to navigate a maze and then pitting it against another agent in a competition. Depending on your requirements, you can further expand and customize the environment, agents, and competition mechanics to suit more complex scenarios or different types of mazes.