write a neural network that competes with the player who will find the fastest way out of the maze. First, we write one code in which the trained neural network finds a way out and saves the model. and then another code for the competition itself. these are pytorch and pygame. there will be a train.py and competition.py.
Assistant
Certainly! Below are two Python scripts, train.py and competition.py, which together create a maze-solving agent using PyTorch and Pygame.
train.py: This script sets up a simple maze environment, defines a Deep Q-Network (DQN) agent, trains the agent to navigate the maze, and saves the trained model.
competition.py: This script loads the trained model and allows both the AI agent and a human player to compete in finding the fastest way out of the maze. Pygame is used to visualize the competition.
Prerequisites
Before running the scripts, ensure you have the necessary libraries installed. You can install them using pip:
bash
pip install pygame torch numpy
train.py
This script defines the maze environment, the DQN agent, and handles the training process.
python
# train.py
import pygame
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import random
from collections import deque
import os
# Define constants
SCREEN_SIZE = 500
GRID_SIZE = 10
BLOCK_SIZE = SCREEN_SIZE // GRID_SIZE
FPS = 60
# Define actions
ACTION_UP = 0
ACTION_DOWN = 1
ACTION_LEFT = 2
ACTION_RIGHT = 3
ACTION_SPACE = 4
# Define the maze (0: free, 1: wall)
MAZE = [
[0,0,0,0,0,0,0,0,0,0],
[0,1,1,1,0,1,1,1,1,0],
[0,1,0,1,0,1,0,0,1,0],
[0,1,0,0,0,0,0,1,1,0],
[0,1,1,1,1,1,0,1,0,0],
[0,0,0,0,0,1,0,1,0,0],
[0,1,1,1,0,1,0,1,0,0],
[0,1,0,1,0,0,0,1,0,0],
[0,1,0,1,1,1,1,1,1,0],
[0,0,0,0,0,0,0,0,0,0],
]
# Define start and goal positions
START_POS = (1, 1)
GOAL_POS = (8, 8)
class MazeEnv:
def __init__(self):
pygame.init()
self.screen = pygame.display.set_mode((SCREEN_SIZE, SCREEN_SIZE))
pygame.display.set_caption("Maze Environment")
self.clock = pygame.time.Clock()
self.reset()
def reset(self):
self.agent_pos = START_POS
self.steps = 0
return self.agent_pos
def step(self, action):
x, y = self.agent_pos
if action == ACTION_UP:
new_pos = (x, y - 1)
elif action == ACTION_DOWN:
new_pos = (x, y + 1)
elif action == ACTION_LEFT:
new_pos = (x - 1, y)
elif action == ACTION_RIGHT:
new_pos = (x + 1, y)
else:
new_pos = self.agent_pos
# Check boundaries and walls
if (0 <= new_pos[0] < GRID_SIZE and 0 <= new_pos[1] < GRID_SIZE and
MAZE[new_pos[1]][new_pos[0]] == 0):
self.agent_pos = new_pos
reward = -0.1 # Small penalty for each move
done = False
if self.agent_pos == GOAL_POS:
reward = 10
done = True
else:
reward = -1 # Penalty for hitting wall
done = False
self.steps += 1
if self.steps > 100:
done = True
return self.agent_pos, reward, done
def render(self, agent_path=[]):
self.screen.fill((255, 255, 255))
for y in range(GRID_SIZE):
for x in range(GRID_SIZE):
rect = pygame.Rect(x*BLOCK_SIZE, y*BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE)
if MAZE[y][x] == 1:
pygame.draw.rect(self.screen, (0, 0, 0), rect)
else:
pygame.draw.rect(self.screen, (200, 200, 200), rect, 1)
# Draw the path
for pos in agent_path:
rect = pygame.Rect(pos[0]*BLOCK_SIZE, pos[1]*BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE)
pygame.draw.rect(self.screen, (0, 255, 0), rect)
# Draw start and goal
pygame.draw.rect(self.screen, (0, 255, 0), pygame.Rect(START_POS[0]*BLOCK_SIZE, START_POS[1]*BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE))
pygame.draw.rect(self.screen, (255, 0, 0), pygame.Rect(GOAL_POS[0]*BLOCK_SIZE, GOAL_POS[1]*BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE))
# Draw agent
pygame.draw.circle(self.screen, (0, 0, 255), (self.agent_pos[0]*BLOCK_SIZE + BLOCK_SIZE//2, self.agent_pos[1]*BLOCK_SIZE + BLOCK_SIZE//2), BLOCK_SIZE//3)
pygame.display.flip()
self.clock.tick(FPS)
def close(self):
pygame.quit()
class DQN(nn.Module):
def __init__(self, inputs, outputs):
super(DQN, self).__init__()
self.fc1 = nn.Linear(inputs, 128)
self.fc2 = nn.Linear(128, 128)
self.out = nn.Linear(128, outputs)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
return self.out(x)
class ReplayMemory:
def __init__(self, capacity):
self.memory = deque(maxlen=capacity)
def push(self, transition):
self.memory.append(transition)
def sample(self, batch_size):
return random.sample(self.memory, batch_size)
def __len__(self):
return len(self.memory)
def state_to_tensor(state):
# One-hot encode the position in the grid
x, y = state
tensor = torch.zeros(GRID_SIZE * GRID_SIZE, dtype=torch.float32)
index = y * GRID_SIZE + x
tensor[index] = 1.0
return tensor
def train():
env = MazeEnv()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
policy_net = DQN(GRID_SIZE * GRID_SIZE, ACTION_SPACE).to(device)
target_net = DQN(GRID_SIZE * GRID_SIZE, ACTION_SPACE).to(device)
target_net.load_state_dict(policy_net.state_dict())
target_net.eval()
optimizer = optim.Adam(policy_net.parameters(), lr=1e-3)
memory = ReplayMemory(10000)
batch_size = 64
gamma = 0.99
epsilon_start = 1.0
epsilon_end = 0.05
epsilon_decay = 500
target_update = 10
num_episodes = 500
steps_done = 0
for episode in range(num_episodes):
state = env.reset()
total_reward = 0
agent_path = [state]
done = False
while not done:
# Epsilon-greedy action selection
epsilon = epsilon_end + (epsilon_start - epsilon_end) * \
np.exp(-1. * steps_done / epsilon_decay)
if random.random() < epsilon:
action = random.randrange(ACTION_SPACE)
else:
with torch.no_grad():
state_tensor = state_to_tensor(state).unsqueeze(0).to(device)
q_values = policy_net(state_tensor)
action = q_values.max(1)[1].item()
steps_done += 1
next_state, reward, done = env.step(action)
total_reward += reward
memory.push((state, action, reward, next_state, done))
state = next_state
agent_path.append(state)
if len(memory) >= batch_size:
transitions = memory.sample(batch_size)
batch = list(zip(*transitions))
states, actions, rewards, next_states, dones = batch
state_batch = torch.stack([state_to_tensor(s) for s in states]).to(device)
action_batch = torch.tensor(actions, dtype=torch.long).unsqueeze(1).to(device)
reward_batch = torch.tensor(rewards, dtype=torch.float32).to(device)
next_state_batch = torch.stack([state_to_tensor(s) for s in next_states]).to(device)
done_batch = torch.tensor(dones, dtype=torch.float32).to(device)
# Compute Q(s,a)
q_values = policy_net(state_batch).gather(1, action_batch).squeeze()
# Compute V(s') for next states
next_q_values = target_net(next_state_batch).max(1)[0]
expected_q_values = reward_batch + gamma * next_q_values * (1 - done_batch)
# Compute loss
loss = nn.MSELoss()(q_values, expected_q_values)
# Optimize the model
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Update the target network
if episode % target_update == 0:
target_net.load_state_dict(policy_net.state_dict())
print(f"Episode {episode+1}/{num_episodes}, Total Reward: {total_reward}")
# Save the model
if not os.path.exists("models"):
os.makedirs("models")
torch.save(policy_net.state_dict(), "models/dqn_maze.pth")
env.close()
if __name__ == "__main__":
train()
Explanation of train.py:
Environment Setup: A simple maze is defined using a 2D list where 0 represents free space and 1 represents walls. The MazeEnv class manages the agent's interactions within this environment.
Deep Q-Network (DQN): A neural network is defined using PyTorch, which takes the agent's current position (one-hot encoded) as input and outputs Q-values for all possible actions.
Replay Memory: A buffer to store and sample experience tuples (state, action, reward, next_state, done) for training stability.
Training Loop: For a specified number of episodes, the agent interacts with the environment, collects experiences, and learns to maximize rewards using the DQN and experience replay. The target network is periodically updated to stabilize learning.
Model Saving: After training, the model is saved to models/dqn_maze.pth.
competition.py
This script allows a human player and the trained AI agent to compete in solving the maze. The first to reach the goal wins.
python
Explanation of competition.py:
Environment Setup: The same MazeEnv class is used to manage the maze. Both the AI agent and the human player start at the START_POS and aim to reach the GOAL_POS.
AI Agent: The trained DQN model from train.py is loaded. At each step, the AI selects the best action based on the current state.
Human Player: The human can navigate the maze using arrow keys:
Up: pygame.K_UP
Down: pygame.K_DOWN
Left: pygame.K_LEFT
Right: pygame.K_RIGHT
Competition Logic: Both the AI and the human move step-by-step. If either reaches the goal, their time and steps are recorded. The competition ends when both have reached the goal, and the script declares the winner based on who reached the goal faster.
Visualization: Pygame is used to visualize the maze, the AI agent (blue circle), and the human player (orange circle).
Running the Scripts
Train the AI Agent:
First, run the train.py script to train the AI agent. This might take some time depending on your machine.
bash
python train.py
The trained model will be saved in the models directory as dqn_maze.pth.
Start the Competition:
After training, run the competition.py script to start the competition between the AI and the human player.
bash
python competition.py
Use the arrow keys to move the human player.
The AI will automatically navigate the maze.
The first to reach the goal will have their performance recorded.
Notes and Possible Enhancements
Maze Complexity: The current maze is predefined and simple. For more complex mazes, you might want to implement maze generation algorithms.
State Representation: Currently, the state is represented as a one-hot encoded vector of the agent's position. Enhancements could include adding more information, such as the positions of walls relative to the agent.
Performance Improvements: Implementing more sophisticated reinforcement learning techniques (like Double DQN, Dueling Networks, etc.) can improve the agent's performance.
Visualization: Enhancing the Pygame visualization to show paths taken, steps remaining, or real-time updates can make the competition more engaging.
Multiple Mazes: Training and competing across multiple maze configurations can make the AI more robust.
Handling Simultaneous Actions: In the current setup, the AI and human take turns to move. Enhancing it to handle simultaneous actions could make the competition more realistic.
Feel free to modify and extend these scripts to better suit your requirements or to explore more advanced features!