Creating a maze-solving competition between a neural network and a human player involves two main components:
- Training the Neural Network: We'll use Deep Q-Learning with PyTorch to train an agent to navigate the maze.
- Competition Interface: We'll use Pygame to create a visual maze where the trained agent and a human player can compete to find the exit.
Below are the detailed steps and code implementations for both components.
1. Training the Neural Network to Solve the Maze
Overview
We'll implement a Deep Q-Network (DQN) agent that learns to navigate through a maze. The maze will be represented as a grid where the agent can move up, down, left, or right. The goal is to reach the exit as quickly as possible.
Dependencies
Ensure you have the following libraries installed:
pip install numpy pygame torch
Maze Environment
First, let's define the maze environment using Pygame. This environment will interact with the DQN agent.
# maze_env.py
import pygame
import numpy as np
class MazeEnv:
def __init__(self, maze, start, end, cell_size=40):
pygame.init()
self.maze = maze
self.start = start
self.end = end
self.cell_size = cell_size
self.width = len(maze[0]) * cell_size
self.height = len(maze) * cell_size
self.screen = pygame.display.set_mode((self.width, self.height))
pygame.display.set_caption("Maze Environment")
self.reset()
def reset(self):
self.agent_pos = self.start
self.done = False
return self.agent_pos
def step(self, action):
if self.done:
return self.agent_pos, 0, self.done
x, y = self.agent_pos
if action == 0: # Up
new_pos = (x, y - 1)
elif action == 1: # Down
new_pos = (x, y + 1)
elif action == 2: # Left
new_pos = (x - 1, y)
elif action == 3: # Right
new_pos = (x + 1, y)
else:
new_pos = self.agent_pos
if self.is_valid(new_pos):
self.agent_pos = new_pos
reward = -1 # Step penalty
if self.agent_pos == self.end:
reward = 100
self.done = True
return self.agent_pos, reward, self.done
def is_valid(self, pos):
x, y = pos
if 0 <= x < len(self.maze[0]) and 0 <= y < len(self.maze):
return self.maze[y][x] == 0
return False
def render(self):
self.screen.fill((255, 255, 255))
for y in range(len(self.maze)):
for x in range(len(self.maze[0])):
color = (0, 0, 0) if self.maze[y][x] == 1 else (255, 255, 255)
pygame.draw.rect(self.screen, color, (x*self.cell_size, y*self.cell_size, self.cell_size, self.cell_size))
# Draw the end
pygame.draw.rect(self.screen, (0, 255, 0), (self.end[0]*self.cell_size, self.end[1]*self.cell_size, self.cell_size, self.cell_size))
# Draw the agent
pygame.draw.circle(self.screen, (255, 0, 0), (self.agent_pos[0]*self.cell_size + self.cell_size//2, self.agent_pos[1]*self.cell_size + self.cell_size//2), self.cell_size//3)
pygame.display.flip()
def get_state(self):
""" Returns a flattened maze with agent position """
state = np.copy(self.maze)
state[self.agent_pos[1]][self.agent_pos[0]] = 2 # Agent marked as '2'
return state.flatten()
def close(self):
pygame.quit()
Deep Q-Network Implementation
Now, let's implement the DQN agent using PyTorch.
# dqn_agent.py
import torch
import torch.nn as nn
import torch.optim as optim
import random
import numpy as np
from collections import deque
class DQN(nn.Module):
def __init__(self, input_size, hidden_size, num_actions):
super(DQN, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_size)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(hidden_size, num_actions)
def forward(self, x):
x = self.relu(self.fc1(x))
x = self.fc2(x)
return x
class Agent:
def __init__(self, state_size, action_size, hidden_size=128, lr=0.001, gamma=0.99, epsilon_start=1.0, epsilon_end=0.01, epsilon_decay=0.995, memory_size=10000, batch_size=64):
self.state_size = state_size
self.action_size = action_size
self.memory = deque(maxlen=memory_size)
self.batch_size = batch_size
self.gamma = gamma
self.epsilon = epsilon_start
self.epsilon_min = epsilon_end
self.epsilon_decay = epsilon_decay
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.policy_net = DQN(state_size, hidden_size, action_size).to(self.device)
self.target_net = DQN(state_size, hidden_size, action_size).to(self.device)
self.target_net.load_state_dict(self.policy_net.state_dict())
self.target_net.eval()
self.optimizer = optim.Adam(self.policy_net.parameters(), lr=lr)
self.loss_fn = nn.MSELoss()
self.steps_done = 0
def select_action(self, state):
if random.random() < self.epsilon:
return random.randrange(self.action_size)
state = torch.FloatTensor(state).unsqueeze(0).to(self.device)
with torch.no_grad():
q_values = self.policy_net(state)
return q_values.argmax().item()
def store_transition(self, state, action, reward, next_state, done):
self.memory.append( (state, action, reward, next_state, done) )
def train_step(self):
if len(self.memory) < self.batch_size:
return
batch = random.sample(self.memory, self.batch_size)
states, actions, rewards, next_states, dones = zip(*batch)
states = torch.FloatTensor(np.array(states)).to(self.device)
actions = torch.LongTensor(actions).unsqueeze(1).to(self.device)
rewards = torch.FloatTensor(rewards).unsqueeze(1).to(self.device)
next_states = torch.FloatTensor(np.array(next_states)).to(self.device)
dones = torch.FloatTensor(dones).unsqueeze(1).to(self.device)
current_q = self.policy_net(states).gather(1, actions)
with torch.no_grad():
max_next_q = self.target_net(next_states).max(1)[0].unsqueeze(1)
target_q = rewards + (self.gamma * max_next_q * (1 - dones))
loss = self.loss_fn(current_q, target_q)
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
# Update epsilon
if self.epsilon > self.epsilon_min:
self.epsilon *= self.epsilon_decay
def update_target_network(self):
self.target_net.load_state_dict(self.policy_net.state_dict())
def save_model(self, path):
torch.save(self.policy_net.state_dict(), path)
def load_model(self, path):
self.policy_net.load_state_dict(torch.load(path, map_location=self.device))
self.target_net.load_state_dict(self.policy_net.state_dict())
Training the Agent
Now, let's create the training loop where the agent learns to solve the maze.
# train.py
import numpy as np
import pygame
from maze_env import MazeEnv
from dqn_agent import Agent
import torch
def main():
# Define the maze as a 2D grid (0: free path, 1: wall)
maze = [
[0, 1, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 1, 0],
[1, 1, 1, 1, 1, 0, 1, 0],
[0, 0, 0, 0, 1, 0, 0, 0],
[0, 1, 1, 0, 1, 1, 1, 1],
[0, 0, 1, 0, 0, 0, 0, 0],
]
start = (0, 0)
end = (7, 6)
env = MazeEnv(maze, start, end)
state_size = len(maze) * len(maze[0])
action_size = 4 # up, down, left, right
agent = Agent(state_size, action_size)
num_episodes = 1000
target_update = 10
for episode in range(num_episodes):
state = env.reset()
state = np.array(env.get_state()) / 2 # Normalize
total_reward = 0
done = False
step = 0
while not done:
# env.render() # Uncomment to visualize training
action = agent.select_action(state)
next_pos, reward, done = env.step(action)
next_state = np.array(env.get_state()) / 2
agent.store_transition(state, action, reward, next_state, done)
agent.train_step()
state = next_state
total_reward += reward
step += 1
if step > 1000:
break # Prevent infinite loops
if episode % target_update == 0:
agent.update_target_network()
if episode % 100 == 0:
print(f"Episode {episode}, Total Reward: {total_reward}, Epsilon: {agent.epsilon:.2f}")
agent.save_model("dqn_maze_model.pth")
env.close()
if __name__ == "__main__":
main()
Explanation
- Maze Representation: The maze is a 2D list where
0 represents a free path and 1 represents walls.
- Environment Interaction: The
MazeEnv class handles the agent's movement and interaction with the maze.
- DQN Agent: The
Agent class implements the DQN with experience replay and a target network for stability.
- Training Loop: In
train.py, the agent interacts with the environment, stores experiences, and learns from them.
Running the Training
Run the training script to train the agent:
python train.py
This will train the agent and save the trained model as dqn_maze_model.pth.
2. Competition: Neural Network vs. Human Player
Overview
We'll create a Pygame interface where both the trained DQN agent and a human player can navigate the maze simultaneously. We'll track the time each takes to reach the exit.
Competition Script
# competition.py
import pygame
import numpy as np
from maze_env import MazeEnv
from dqn_agent import Agent
import torch
import sys
import time
def main():
# Define the maze
maze = [
[0, 1, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 1, 0],
[1, 1, 1, 1, 1, 0, 1, 0],
[0, 0, 0, 0, 1, 0, 0, 0],
[0, 1, 1, 0, 1, 1, 1, 1],
[0, 0, 1, 0, 0, 0, 0, 0],
]
start = (0, 0)
end = (7, 6)
cell_size = 60
env = MazeEnv(maze, start, end, cell_size=cell_size)
# Initialize DQN Agent
state_size = len(maze) * len(maze[0])
action_size = 4
agent = Agent(state_size, action_size)
agent.load_model("dqn_maze_model.pth")
agent.epsilon = 0.0 # Disable exploration
# Initialize human position
human_pos = list(start)
agent_pos = list(start)
clock = pygame.time.Clock()
font = pygame.font.SysFont(None, 36)
start_time = time.time()
human_finished = False
agent_finished = False
human_time = None
agent_time = None
running = True
while running:
clock.tick(10) # 10 FPS
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
break
keys = pygame.key.get_pressed()
if not human_finished:
if keys[pygame.K_LEFT]:
new_pos = (human_pos[0] - 1, human_pos[1])
if env.is_valid(new_pos):
human_pos = list(new_pos)
if keys[pygame.K_RIGHT]:
new_pos = (human_pos[0] + 1, human_pos[1])
if env.is_valid(new_pos):
human_pos = list(new_pos)
if keys[pygame.K_UP]:
new_pos = (human_pos[0], human_pos[1] - 1)
if env.is_valid(new_pos):
human_pos = list(new_pos)
if keys[pygame.K_DOWN]:
new_pos = (human_pos[0], human_pos[1] + 1)
if env.is_valid(new_pos):
human_pos = list(new_pos)
if tuple(human_pos) == end:
human_finished = True
human_time = time.time() - start_time
print(f"Human finished in {human_time:.2f} seconds!")
if not agent_finished:
# Agent selects action
state = np.copy(env.maze)
state[agent_pos[1]][agent_pos[0]] = 2 # Mark agent's position
state = state.flatten() / 2
with torch.no_grad():
state_tensor = torch.FloatTensor(state).unsqueeze(0).to(agent.device)
q_values = agent.policy_net(state_tensor)
action = q_values.argmax().item()
# Take action
if action == 0: # Up
new_pos = (agent_pos[0], agent_pos[1] - 1)
elif action == 1: # Down
new_pos = (agent_pos[0], agent_pos[1] + 1)
elif action == 2: # Left
new_pos = (agent_pos[0] - 1, agent_pos[1])
elif action == 3: # Right
new_pos = (agent_pos[0] + 1, agent_pos[1])
else:
new_pos = tuple(agent_pos)
if env.is_valid(new_pos):
agent_pos = list(new_pos)
if tuple(agent_pos) == end:
agent_finished = True
agent_time = time.time() - start_time
print(f"Agent finished in {agent_time:.2f} seconds!")
# Render
env.screen.fill((255, 255, 255))
for y in range(len(maze)):
for x in range(len(maze[0])):
color = (0, 0, 0) if maze[y][x] == 1 else (255, 255, 255)
pygame.draw.rect(env.screen, color, (x*cell_size, y*cell_size, cell_size, cell_size))
# Draw the end
pygame.draw.rect(env.screen, (0, 255, 0), (end[0]*cell_size, end[1]*cell_size, cell_size, cell_size))
# Draw the agent
pygame.draw.circle(env.screen, (255, 0, 0), (agent_pos[0]*cell_size + cell_size//2, agent_pos[1]*cell_size + cell_size//2), cell_size//3)
# Draw the human
pygame.draw.circle(env.screen, (0, 0, 255), (human_pos[0]*cell_size + cell_size//2, human_pos[1]*cell_size + cell_size//2), cell_size//3)
# Display times
if human_finished:
text = font.render(f"Human Time: {human_time:.2f}s", True, (0, 0, 255))
env.screen.blit(text, (10, env.height - 40))
if agent_finished:
text = font.render(f"Agent Time: {agent_time:.2f}s", True, (255, 0, 0))
env.screen.blit(text, (250, env.height - 40))
pygame.display.flip()
# Check for competition end
if human_finished and agent_finished:
running = False
# Final Results
if human_time and agent_time:
if agent_time < human_time:
print("Agent wins!")
elif agent_time > human_time:
print("Human wins!")
else:
print("It's a tie!")
env.close()
pygame.quit()
sys.exit()
if __name__ == "__main__":
main()
Explanation
- Loading the Trained Model: The script loads the previously trained DQN model.
- Human Controls: The human player can use arrow keys to navigate the maze.
- Agent Controls: The trained agent automatically selects the best action based on the current state.
- Rendering: Both the human and agent positions are drawn on the maze. Their completion times are displayed once they reach the exit.
- Competition Outcome: After both the human and agent finish, the script prints who won based on the time taken.
Running the Competition
Run the competition script:
python competition.py
Control the human player using the arrow keys:
- Left Arrow: Move left
- Right Arrow: Move right
- Up Arrow: Move up
- Down Arrow: Move down
The agent will automatically navigate towards the exit. The competition concludes when both have reached the end, displaying who won.
Notes and Improvements
- Maze Complexity: The current maze is relatively simple. For more challenging mazes, consider implementing maze generation algorithms.
- Agent Optimization: The DQN implementation can be further optimized with techniques like Double DQN, prioritized experience replay, etc.
- Visualization During Training: Uncomment
env.render() in the training loop to visualize the agent’s progress, but note that it will slow down training.
- Multiple Episodes and Averaging: Implement averaging of multiple episodes to evaluate the agent's performance more robustly.
- Handling Stuck Scenarios: Introduce mechanisms to handle scenarios where the agent or human gets stuck in loops.
By following the above steps, you can create a neural network that learns to solve a maze and set up a competition between the trained agent and a human player using PyTorch and Pygame.