# competition.py
import torch
import torch.nn as nn
import numpy as np
import pygame
import json
import sys
import time
# Parameters
GRID_SIZE = 25
CELL_SIZE = 20
WINDOW_SIZE = GRID_SIZE * CELL_SIZE
MODEL_PATH = 'dqn_model.pth'
MAZE_PATH = 'maze.json'
# Actions: up, down, left, right
ACTION_SPACE = ['UP', 'DOWN', 'LEFT', 'RIGHT']
ACTION_DICT = {
0: (-1, 0), # UP
1: (1, 0), # DOWN
2: (0, -1), # LEFT
3: (0, 1) # RIGHT
}
class DQN(nn.Module):
def __init__(self, input_size, output_size):
super(DQN, self).__init__()
self.fc = nn.Sequential(
nn.Linear(input_size, 512),
nn.ReLU(),
nn.Linear(512, 256),
nn.ReLU(),
nn.Linear(256, output_size)
)
def forward(self, x):
return self.fc(x)
def load_maze():
with open(MAZE_PATH, 'r') as f:
maze = np.array(json.load(f))
return maze
def get_state(maze, pos, goal):
state = np.zeros((GRID_SIZE, GRID_SIZE), dtype=int)
state[pos] = 1
state[goal] = 2
return state.flatten()
def main():
# Initialize Pygame
pygame.init()
screen = pygame.display.set_mode((WINDOW_SIZE, WINDOW_SIZE))
pygame.display.set_caption("Maze Competition: AI vs Human")
clock = pygame.time.Clock()
# Load maze
maze = load_maze()
start = (1,1)
goal = (GRID_SIZE-2, GRID_SIZE-2)
# Load AI model
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
input_size = GRID_SIZE * GRID_SIZE
output_size = len(ACTION_SPACE)
policy_net = DQN(input_size, output_size).to(device)
policy_net.load_state_dict(torch.load(MODEL_PATH, map_location=device))
policy_net.eval()
# Initialize AI agent
ai_pos = start
ai_done = False
ai_steps = 0
# Initialize Human agent
human_pos = start
human_done = False
human_steps = 0
# Timing
start_time = time.time()
ai_time = None
human_time = None
running = True
while running:
clock.tick(60) # 60 FPS
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if not human_done:
if event.key == pygame.K_UP:
move = ACTION_DICT[0]
new_pos = (human_pos[0] + move[0], human_pos[1] + move[1])
if (0 <= new_pos[0] < GRID_SIZE and 0 <= new_pos[1] < GRID_SIZE and
maze[new_pos] == 0):
human_pos = new_pos
human_steps += 1
if human_pos == goal:
human_done = True
human_time = time.time() - start_time
elif event.key == pygame.K_DOWN:
move = ACTION_DICT[1]
new_pos = (human_pos[0] + move[0], human_pos[1] + move[1])
if (0 <= new_pos[0] < GRID_SIZE and 0 <= new_pos[1] < GRID_SIZE and
maze[new_pos] == 0):
human_pos = new_pos
human_steps += 1
if human_pos == goal:
human_done = True
human_time = time.time() - start_time
elif event.key == pygame.K_LEFT:
move = ACTION_DICT[2]
new_pos = (human_pos[0] + move[0], human_pos[1] + move[1])
if (0 <= new_pos[0] < GRID_SIZE and 0 <= new_pos[1] < GRID_SIZE and
maze[new_pos] == 0):
human_pos = new_pos
human_steps += 1
if human_pos == goal:
human_done = True
human_time = time.time() - start_time
elif event.key == pygame.K_RIGHT:
move = ACTION_DICT[3]
new_pos = (human_pos[0] + move[0], human_pos[1] + move[1])
if (0 <= new_pos[0] < GRID_SIZE and 0 <= new_pos[1] < GRID_SIZE and
maze[new_pos] == 0):
human_pos = new_pos
human_steps += 1
if human_pos == goal:
human_done = True
human_time = time.time() - start_time
# AI Agent's turn
if not ai_done:
state = get_state(maze, ai_pos, goal)
state_tensor = torch.FloatTensor(state).unsqueeze(0).to(device)
with torch.no_grad():
q_values = policy_net(state_tensor)
action = q_values.max(1)[1].item()
move = ACTION_DICT[action]
new_ai_pos = (ai_pos[0] + move[0], ai_pos[1] + move[1])
if (0 <= new_ai_pos[0] < GRID_SIZE and 0 <= new_ai_pos[1] < GRID_SIZE and
maze[new_ai_pos] == 0):
ai_pos = new_ai_pos
ai_steps += 1
if ai_pos == goal:
ai_done = True
ai_time = time.time() - start_time
# Draw Maze
for x in range(GRID_SIZE):
for y in range(GRID_SIZE):
rect = pygame.Rect(y*CELL_SIZE, x*CELL_SIZE, CELL_SIZE, CELL_SIZE)
if maze[x][y] == 1:
pygame.draw.rect(screen, pygame.Color('black'), rect)
else:
pygame.draw.rect(screen, pygame.Color('white'), rect)
# Draw goal
goal_rect = pygame.Rect(goal[1]*CELL_SIZE, goal[0]*CELL_SIZE, CELL_SIZE, CELL_SIZE)
pygame.draw.rect(screen, pygame.Color('green'), goal_rect)
# Draw AI Agent
ai_rect = pygame.Rect(ai_pos[1]*CELL_SIZE, ai_pos[0]*CELL_SIZE, CELL_SIZE, CELL_SIZE)
pygame.draw.rect(screen, pygame.Color('red'), ai_rect)
# Draw Human Agent
human_rect = pygame.Rect(human_pos[1]*CELL_SIZE, human_pos[0]*CELL_SIZE, CELL_SIZE, CELL_SIZE)
pygame.draw.rect(screen, pygame.Color('blue'), human_rect)
# Show Timers
font = pygame.font.SysFont(None, 24)
elapsed_time = time.time() - start_time
timer_text = font.render(f"Time: {elapsed_time:.2f}s", True, pygame.Color('black'))
screen.blit(timer_text, (10, 10))
# Check for competition end
if ai_done and human_done:
running = False
elif ai_done and not human_done:
end_text = font.render(f"AI reached the goal in {ai_time:.2f} seconds!", True, pygame.Color('red'))
screen.blit(end_text, (10, WINDOW_SIZE - 30))
elif human_done and not ai_done:
end_text = font.render(f"Human reached the goal in {human_time:.2f} seconds!", True, pygame.Color('blue'))
screen.blit(end_text, (10, WINDOW_SIZE - 30))
pygame.display.flip()
# Determine winner
if ai_done and human_done:
if ai_time < human_time:
print(f"AI won! AI Time: {ai_time:.2f}s, Human Time: {human_time:.2f}s")
elif human_time < ai_time:
print(f"Human won! Human Time: {human_time:.2f}s, AI Time: {ai_time:.2f}s")
else:
print(f"It's a tie! Both took {ai_time:.2f} seconds.")
elif ai_done:
print(f"AI reached the goal in {ai_time:.2f} seconds. Human did not reach the goal.")
elif human_done:
print(f"Human reached the goal in {human_time:.2f} seconds. AI did not reach the goal.")
else:
print("Competition ended without both reaching the goal.")
pygame.quit()
sys.exit()
if __name__ == "__main__":
main()