I'm now focusing on breaking down the user's objective. The primary goal is creating a Q-learning agent for a maze. I've begun to dissect the core elements required for this project, such as the maze environment and the Q-learning algorithm implementation. Next, I plan to consider the agent's actions and the reward system.
Structuring the Solution
The core environment setup is taking shape. I'm solidifying the maze representation as a 2D NumPy array. Defining the actions, state spaces, and rewards is the focus now, especially how to penalize the agent and reward the goal. The state transition dynamics are also being carefully considered.
Mapping the Code Architecture
The focus is now on mapping out the code structure. I'm visualizing the Maze class, ensuring it manages environment interactions. The agent's step function needs careful design to return state, reward, and a "done" flag. I'm leaning toward defining a separate function for the Q-learning update. The core loop will iterate through episodes and actions.
Codifying the Algorithm
I'm now starting the actual code, beginning with the MazeEnvironment class. I'll define its __init__, reset, and step functions and incorporate reward structures. I'll initially keep the maze simple and work on the Q-learning algorithm in parallel, defining the Q-table, action selection (epsilon-greedy), and update rule. I'll test each segment as it's built.
Refining the Rewards
I'm now revisiting the reward structure. Thinking it through, simpler rewards often lead to faster and more reliable learning. I'll experiment with penalizing each step, rewarding the goal, and preventing penalties for wall collisions; perhaps I will just disallow the action entirely. I will likely focus on a simple step cost and a high reward for reaching the end.
Reflecting on the Design
I'm now contemplating the user's specific context, which is to create copy-and-paste Python code. This simplifies the approach, as I can avoid external library dependencies and provide a self-contained, immediately runnable solution. It emphasizes clear code structure and commenting.
Here is a complete, standalone Python solution. Since we want to keep dependencies minimal, I have created a custom environment class (similar to how OpenAI Gym works) rather than relying on external game libraries.
This code defines the maze, implements the Q-Learning algorithm, trains the agent, and visualizes the final path.
The Python Code
python
import numpy as np
import random
import time
import os
class MazeEnvironment:
def __init__(self):
# 0 = Path, 1 = Wall, 2 = Goal, 3 = Start
self.maze = np.array([
[3, 0, 0, 0, 1],
[1, 1, 0, 1, 1],
[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 1, 2]
])
self.start_pos = np.argwhere(self.maze == 3)[0]
self.goal_pos = np.argwhere(self.maze == 2)[0]
self.current_pos = self.start_pos
self.rows, self.cols = self.maze.shape
# Actions: 0: Up, 1: Down, 2: Left, 3: Right
self.action_space = [0, 1, 2, 3]
def reset(self):
self.current_pos = self.start_pos.copy()
return tuple(self.current_pos)
def step(self, action):
# Calculate new position based on action
row, col = self.current_pos
new_row, new_col = row, col
if action == 0: # Up
new_row -= 1
elif action == 1: # Down
new_row += 1
elif action == 2: # Left
new_col -= 1
elif action == 3: # Right
new_col += 1
# Check Bounds and Walls
if (0 <= new_row < self.rows and
0 <= new_col < self.cols and
self.maze[new_row, new_col] != 1):
self.current_pos = np.array([new_row, new_col])
else:
# Hit a wall or out of bounds: stay in place
pass
# Check Goals and Rewards
current_state = tuple(self.current_pos)
if np.array_equal(self.current_pos, self.goal_pos):
reward = 10.0 # Big reward for winning
done = True
else:
reward = -0.1 # Small penalty for each step to encourage shortest path
done = False
return current_state, reward, done
# --- Q-Learning Parameters ---
alpha = 0.1 # Learning Rate
gamma = 0.9 # Discount Factor
epsilon = 1.0 # Exploration Rate (start with high exploration)
epsilon_decay = 0.995
epsilon_min = 0.01
episodes = 1000
# Initialize Environment
env = MazeEnvironment()
# Initialize Q-Table: (Row, Col, Actions)
q_table = np.zeros((env.rows, env.cols, len(env.action_space)))
# --- Training Loop ---
print("Training agent...")
for episode in range(episodes):
state = env.reset()
done = False
while not done:
# 1. Choose Action (Epsilon-Greedy)
if random.uniform(0, 1) < epsilon:
action = random.choice(env.action_space) # Explore
else:
action = np.argmax(q_table[state]) # Exploit
# 2. Take Action
next_state, reward, done = env.step(action)
# 3. Update Q-Value (Bellman Equation)
# Q(s,a) = Q(s,a) + alpha * [R + gamma * max(Q(s',a')) - Q(s,a)]
current_q = q_table[state + (action,)]
max_future_q = np.max(q_table[next_state])
new_q = current_q + alpha * (reward + gamma * max_future_q - current_q)
q_table[state + (action,)] = new_q
state = next_state
# Decay Epsilon (Reduce exploration over time)
if epsilon > epsilon_min:
epsilon *= epsilon_decay
print("Training completed.\n")
# --- Visualize the Solution ---
def print_maze_path(env, path):
visual_maze = env.maze.astype(str)
visual_maze[visual_maze == '0'] = ' '
visual_maze[visual_maze == '1'] = '█' # Wall
visual_maze[visual_maze == '2'] = 'G' # Goal
visual_maze[visual_maze == '3'] = 'S' # Start
for step in path:
if visual_maze[step] not in ['S', 'G']:
visual_maze[step] = '·' # Path taken
print("--- Solved Maze Path ---")
for row in visual_maze:
print(' '.join(row))
print("------------------------")
# Run the best path
state = env.reset()
done = False
path = []
steps = 0
while not done and steps < 20:
path.append(state)
action = np.argmax(q_table[state]) # Strictly exploit (choose best action)
state, reward, done = env.step(action)
steps += 1
path.append(state) # Add final goal state
print_maze_path(env, path)
print(f"Steps taken: {steps}")
How this works
Environment (MazeEnvironment):
It creates a 5x5 grid.
step function: This is the physics engine. It takes an action (0–3), checks if the move hits a wall or goes off the edge. If valid, it updates the position.
Rewards:
+10: Finding the goal.
-0.1: Taking a step. This penalty is crucial; it forces the agent to find the shortest path. If there were no penalty, the agent might wander in circles forever even if it eventually found the goal.
The Q-Table:
Think of this as a "Cheat Sheet." It is a 3D array of size (Rows, Cols, 4 Actions).
q_table[0, 0, 1] stores the value of being at coordinates (0,0) and moving "Down".
Training (The Loop):
Epsilon-Greedy: At the start (epsilon=1.0), the agent acts randomly to explore the map. As training progresses, epsilon decreases, and the agent starts relying on what it has learned (the Q-Table).
Update Rule:
Basically: "The value of this action is what I thought it was, plus a correction based on the reward I just got and the best potential future reward."
Q
new
=
Qold+
α⋅
(Reward+
γ⋅
max(Qnext)−
Qold)
Visualization:
After training, we turn off randomness (epsilon isn't used). The agent looks at the Q-Table, picks the action with the highest number for its current cell, and moves there. We print the grid using · to show the path taken.