The user wants a Python implementation of a Q-learning agent that can solve a maze. Let me create a comprehensive solution that includes:
- A Maze environment class
- A Q-learning agent class
- Training functionality
- Visualization of the learning process and results
I'll make it well-documented and include:
- The maze representation
- Q-learning algorithm implementation
- Epsilon-greedy exploration
- Training loop
- Visualization of the learned policy and Q-values
- Animation of the agent solving the maze
Let me write clean, educational code that demonstrates all the key concepts of Q-learning.
Key components:
- State: Position in the maze (row, col)
- Actions: Up, Down, Left, Right
- Reward: -1 for each step, +100 for reaching goal, -10 for hitting walls (or just staying in place)
- Q-table: Dictionary or 2D array mapping (state, action) to Q-values
Q-learning update rule:
Q(s, a) = Q(s, a) + α * (r + γ * max(Q(s', a')) - Q(s, a))
Where:
- α is the learning rate
- γ is the discount factor
- r is the reward
- s' is the next state # Q-Learning Maze Solver in Python
This implementation includes a complete maze environment and Q-learning agent with visualization.
Complete Implementation
"""
Reinforcement Learning Maze Solver using Q-Learning
====================================================
A complete implementation with visualization and analysis tools.
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from matplotlib.patches import FancyArrowPatch
import matplotlib.patches as mpatches
from collections import defaultdict
import random
from typing import Tuple, List, Dict, Optional
from enum import IntEnum
import time
class Action(IntEnum):
"""Possible actions the agent can take."""
UP = 0
DOWN = 1
LEFT = 2
RIGHT = 3
class CellType(IntEnum):
"""Types of cells in the maze."""
PATH = 0
WALL = 1
START = 2
GOAL = 3
class MazeEnvironment:
"""
Maze environment for reinforcement learning.
The agent must navigate from start (S) to goal (G) while avoiding walls.
"""
def __init__(self, maze: Optional[np.ndarray] = None):
"""
Initialize the maze environment.
Args:
maze: 2D numpy array representing the maze.
0 = path, 1 = wall, 2 = start, 3 = goal
"""
if maze is None:
maze = self._create_default_maze()
self.maze = maze
self.height, self.width = maze.shape
# Find start and goal positions
self.start_pos = self._find_position(CellType.START)
self.goal_pos = self._find_position(CellType.GOAL)
if self.start_pos is None or self.goal_pos is None:
raise ValueError("Maze must have both start (2) and goal (3) positions")
self.current_pos = self.start_pos
self.actions = list(Action)
self.n_actions = len(self.actions)
# Action effects: (row_delta, col_delta)
self.action_effects = {
Action.UP: (-1, 0),
Action.DOWN: (1, 0),
Action.LEFT: (0, -1),
Action.RIGHT: (0, 1)
}
def _create_default_maze(self) -> np.ndarray:
"""Create a default maze for demonstration."""
# 0 = path, 1 = wall, 2 = start, 3 = goal
maze = np.array([
[2, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 1, 1, 1, 0],
[1, 0, 1, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 1, 0, 1, 0],
[0, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 1],
[1, 1, 1, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 1, 3]
])
return maze
def _find_position(self, cell_type: CellType) -> Optional[Tuple[int, int]]:
"""Find the position of a specific cell type."""
positions = np.where(self.maze == cell_type)
if len(positions[0]) > 0:
return (positions[0][0], positions[1][0])
return None
def reset(self) -> Tuple[int, int]:
"""Reset the environment to the starting state."""
self.current_pos = self.start_pos
return self.current_pos
def step(self, action: Action) -> Tuple[Tuple[int, int], float, bool]:
"""
Take an action in the environment.
Args:
action: The action to take
Returns:
Tuple of (new_state, reward, done)
"""
row, col = self.current_pos
d_row, d_col = self.action_effects[action]
new_row = row + d_row
new_col = col + d_col
# Check if new position is valid
if self._is_valid_position(new_row, new_col):
self.current_pos = (new_row, new_col)
# Check if reached goal
if self.current_pos == self.goal_pos:
return self.current_pos, 100.0, True # Large reward for goal
else:
return self.current_pos, -1.0, False # Small penalty for each step
else:
# Hit a wall or boundary - stay in place with penalty
return self.current_pos, -5.0, False
def _is_valid_position(self, row: int, col: int) -> bool:
"""Check if a position is valid (within bounds and not a wall)."""
if 0 <= row < self.height and 0 <= col < self.width:
return self.maze[row, col] != CellType.WALL
return False
def get_state_space_size(self) -> int:
"""Return the total number of possible states."""
return self.height * self.width
def render(self, ax=None, show_values=False, q_table=None):
"""Render the current state of the maze."""
if ax is None:
fig, ax = plt.subplots(figsize=(10, 10))
# Create display maze
display_maze = self.maze.copy().astype(float)
# Custom colormap
colors = ['white', 'black', 'green', 'red']
cmap = ListedColormap(colors)
ax.imshow(display_maze, cmap=cmap, vmin=0, vmax=3)
# Mark current position
row, col = self.current_pos
ax.plot(col, row, 'bo', markersize=20, alpha=0.7)
# Add grid
ax.set_xticks(np.arange(-0.5, self.width, 1), minor=True)
ax.set_yticks(np.arange(-0.5, self.height, 1), minor=True)
ax.grid(which='minor', color='gray', linestyle='-', linewidth=2)
ax.set_xticks(range(self.width))
ax.set_yticks(range(self.height))
return ax
class QLearningAgent:
"""
Q-Learning agent for solving mazes.
Uses epsilon-greedy exploration and tabular Q-learning.
"""
def __init__(
self,
n_actions: int,
learning_rate: float = 0.1,
discount_factor: float = 0.95,
epsilon: float = 1.0,
epsilon_decay: float = 0.995,
epsilon_min: float = 0.01
):
"""
Initialize the Q-learning agent.
Args:
n_actions: Number of possible actions
learning_rate: Alpha - how much to update Q-values
discount_factor: Gamma - importance of future rewards
epsilon: Initial exploration rate
epsilon_decay: Rate at which epsilon decreases
epsilon_min: Minimum exploration rate
"""
self.n_actions = n_actions
self.learning_rate = learning_rate
self.discount_factor = discount_factor
self.epsilon = epsilon
self.epsilon_decay = epsilon_decay
self.epsilon_min = epsilon_min
# Q-table: maps (state, action) to Q-value
self.q_table: Dict[Tuple[Tuple[int, int], int], float] = defaultdict(float)
# Statistics for analysis
self.training_history = {
'episode_rewards': [],
'episode_steps': [],
'epsilon_values': []
}
def get_q_value(self, state: Tuple[int, int], action: int) -> float:
"""Get Q-value for a state-action pair."""
return self.q_table[(state, action)]
def get_max_q_value(self, state: Tuple[int, int]) -> float:
"""Get the maximum Q-value for a state."""
return max(self.q_table[(state, a)] for a in range(self.n_actions))
def get_best_action(self, state: Tuple[int, int]) -> int:
"""Get the action with highest Q-value for a state."""
q_values = [self.q_table[(state, a)] for a in range(self.n_actions)]
max_q = max(q_values)
# Random choice among actions with max Q-value (tie-breaking)
best_actions = [a for a, q in enumerate(q_values) if q == max_q]
return random.choice(best_actions)
def choose_action(self, state: Tuple[int, int], training: bool = True) -> int:
"""
Choose an action using epsilon-greedy policy.
Args:
state: Current state
training: Whether we're training (use exploration) or testing
Returns:
Selected action
"""
if training and random.random() < self.epsilon:
# Exploration: random action
return random.randint(0, self.n_actions - 1)
else:
# Exploitation: best known action
return self.get_best_action(state)
def update(
self,
state: Tuple[int, int],
action: int,
reward: float,
next_state: Tuple[int, int],
done: bool
):
"""
Update Q-value using the Q-learning update rule.
Q(s,a) = Q(s,a) + α * (r + γ * max(Q(s',a')) - Q(s,a))
Args:
state: Current state
action: Action taken
reward: Reward received
next_state: Resulting state
done: Whether episode is finished
"""
current_q = self.q_table[(state, action)]
if done:
# No future rewards if episode is done
target = reward
else:
# Bellman equation
max_future_q = self.get_max_q_value(next_state)
target = reward + self.discount_factor * max_future_q
# Q-learning update
self.q_table[(state, action)] = current_q + self.learning_rate * (target - current_q)
def decay_epsilon(self):
"""Decay exploration rate."""
self.epsilon = max(self.epsilon_min, self.epsilon * self.epsilon_decay)
def get_policy(self, env: MazeEnvironment) -> np.ndarray:
"""
Extract the learned policy as an array.
Returns:
2D array where each cell contains the best action
"""
policy = np.zeros((env.height, env.width), dtype=int)
for row in range(env.height):
for col in range(env.width):
state = (row, col)
policy[row, col] = self.get_best_action(state)
return policy
def get_q_values_array(self, env: MazeEnvironment) -> np.ndarray:
"""
Get Q-values as a 3D array for visualization.
Returns:
3D array of shape (height, width, n_actions)
"""
q_array = np.zeros((env.height, env.width, self.n_actions))
for row in range(env.height):
for col in range(env.width):
for action in range(self.n_actions):
q_array[row, col, action] = self.q_table[((row, col), action)]
return q_array
def train_agent(
env: MazeEnvironment,
agent: QLearningAgent,
n_episodes: int = 1000,
max_steps: int = 200,
verbose: bool = True
) -> QLearningAgent:
"""
Train the Q-learning agent.
Args:
env: The maze environment
agent: The Q-learning agent
n_episodes: Number of training episodes
max_steps: Maximum steps per episode
verbose: Whether to print progress
Returns:
Trained agent
"""
for episode in range(n_episodes):
state = env.reset()
total_reward = 0
steps = 0
for step in range(max_steps):
# Choose action
action = agent.choose_action(state)
# Take action
next_state, reward, done = env.step(Action(action))
# Update Q-table
agent.update(state, action, reward, next_state, done)
total_reward += reward
steps += 1
state = next_state
if done:
break
# Decay exploration rate
agent.decay_epsilon()
# Record statistics
agent.training_history['episode_rewards'].append(total_reward)
agent.training_history['episode_steps'].append(steps)
agent.training_history['epsilon_values'].append(agent.epsilon)
# Print progress
if verbose and (episode + 1) % 100 == 0:
avg_reward = np.mean(agent.training_history['episode_rewards'][-100:])
avg_steps = np.mean(agent.training_history['episode_steps'][-100:])
print(f"Episode {episode + 1}/{n_episodes} | "
f"Avg Reward: {avg_reward:.1f} | "
f"Avg Steps: {avg_steps:.1f} | "
f"Epsilon: {agent.epsilon:.3f}")
return agent
def test_agent(
env: MazeEnvironment,
agent: QLearningAgent,
max_steps: int = 100
) -> Tuple[List[Tuple[int, int]], float, bool]:
"""
Test the trained agent.
Args:
env: The maze environment
agent: The trained agent
max_steps: Maximum steps allowed
Returns:
Tuple of (path taken, total reward, success)
"""
state = env.reset()
path = [state]
total_reward = 0
for _ in range(max_steps):
action = agent.choose_action(state, training=False)
next_state, reward, done = env.step(Action(action))
path.append(next_state)
total_reward += reward
state = next_state
if done:
return path, total_reward, True
return path, total_reward, False
class MazeVisualizer:
"""Visualization tools for the maze and Q-learning results."""
@staticmethod
def plot_training_history(agent: QLearningAgent, figsize: Tuple[int, int] = (15, 5)):
"""Plot training metrics over episodes."""
fig, axes = plt.subplots(1, 3, figsize=figsize)
# Episode rewards
rewards = agent.training_history['episode_rewards']
axes[0].plot(rewards, alpha=0.3, color='blue')
# Moving average
window = 50
if len(rewards) >= window:
moving_avg = np.convolve(rewards, np.ones(window)/window, mode='valid')
axes[0].plot(range(window-1, len(rewards)), moving_avg, color='red',
linewidth=2, label=f'{window}-episode moving avg')
axes[0].legend()
axes[0].set_xlabel('Episode')
axes[0].set_ylabel('Total Reward')
axes[0].set_title('Episode Rewards')
axes[0].grid(True, alpha=0.3)
# Episode steps
steps = agent.training_history['episode_steps']
axes[1].plot(steps, alpha=0.3, color='green')
if len(steps) >= window:
moving_avg = np.convolve(steps, np.ones(window)/window, mode='valid')
axes[1].plot(range(window-1, len(steps)), moving_avg, color='red',
linewidth=2, label=f'{window}-episode moving avg')
axes[1].legend()
axes[1].set_xlabel('Episode')
axes[1].set_ylabel('Steps')
axes[1].set_title('Steps per Episode')
axes[1].grid(True, alpha=0.3)
# Epsilon decay
axes[2].plot(agent.training_history['epsilon_values'], color='purple')
axes[2].set_xlabel('Episode')
axes[2].set_ylabel('Epsilon')
axes[2].set_title('Exploration Rate (Epsilon) Decay')
axes[2].grid(True, alpha=0.3)
plt.tight_layout()
return fig
@staticmethod
def plot_policy(
env: MazeEnvironment,
agent: QLearningAgent,
figsize: Tuple[int, int] = (10, 10)
):
"""Visualize the learned policy with arrows showing best action per state."""
fig, ax = plt.subplots(figsize=figsize)
# Draw maze
colors = ['white', '#333333', '#4CAF50', '#f44336'] # path, wall, start, goal
cmap = ListedColormap(colors)
ax.imshow(env.maze, cmap=cmap, vmin=0, vmax=3)
# Arrow directions for each action
arrow_dx = {Action.UP: 0, Action.DOWN: 0, Action.LEFT: -0.3, Action.RIGHT: 0.3}
arrow_dy = {Action.UP: -0.3, Action.DOWN: 0.3, Action.LEFT: 0, Action.RIGHT: 0}
# Draw arrows for each non-wall cell
for row in range(env.height):
for col in range(env.width):
if env.maze[row, col] != CellType.WALL:
best_action = agent.get_best_action((row, col))
dx = arrow_dx[Action(best_action)]
dy = arrow_dy[Action(best_action)]
# Color based on max Q-value
max_q = agent.get_max_q_value((row, col))
if env.maze[row, col] == CellType.GOAL:
ax.plot(col, row, 'r*', markersize=30)
else:
ax.arrow(col, row, dx, dy, head_width=0.15, head_length=0.1,
fc='blue', ec='blue', alpha=0.8)
# Add grid
ax.set_xticks(np.arange(-0.5, env.width, 1), minor=True)
ax.set_yticks(np.arange(-0.5, env.height, 1), minor=True)
ax.grid(which='minor', color='gray', linestyle='-', linewidth=1)
ax.set_xticks(range(env.width))
ax.set_yticks(range(env.height))
# Legend
legend_elements = [
mpatches.Patch(facecolor='white', edgecolor='black', label='Path'),
mpatches.Patch(facecolor='#333333', label='Wall'),
mpatches.Patch(facecolor='#4CAF50', label='Start'),
mpatches.Patch(facecolor='#f44336', label='Goal')
]
ax.legend(handles=legend_elements, loc='upper left', bbox_to_anchor=(1, 1))
ax.set_title('Learned Policy (arrows show best action)', fontsize=14)
plt.tight_layout()
return fig
@staticmethod
def plot_q_values(
env: MazeEnvironment,
agent: QLearningAgent,
figsize: Tuple[int, int] = (12, 12)
):
"""Visualize Q-values for each state-action pair."""
fig, ax = plt.subplots(figsize=figsize)
# Draw maze with Q-values
colors = ['#EEEEEE', '#333333', '#4CAF50', '#f44336']
cmap = ListedColormap(colors)
ax.imshow(env.maze, cmap=cmap, vmin=0, vmax=3)
action_symbols = {
Action.UP: '↑',
Action.DOWN: '↓',
Action.LEFT: '←',
Action.RIGHT: '→'
}
# Positions for Q-value text (relative to cell center)
text_positions = {
Action.UP: (0, -0.25),
Action.DOWN: (0, 0.25),
Action.LEFT: (-0.25, 0),
Action.RIGHT: (0.25, 0)
}
for row in range(env.height):
for col in range(env.width):
if env.maze[row, col] not in [CellType.WALL, CellType.GOAL]:
for action in Action:
q_val = agent.get_q_value((row, col), action)
dx, dy = text_positions[action]
# Color based on Q-value
color = 'green' if q_val > 0 else 'red' if q_val < 0 else 'gray'
ax.text(col + dx, row + dy, f'{q_val:.1f}',
ha='center', va='center', fontsize=6, color=color)
# Add grid
ax.set_xticks(np.arange(-0.5, env.width, 1), minor=True)
ax.set_yticks(np.arange(-0.5, env.height, 1), minor=True)
ax.grid(which='minor', color='gray', linestyle='-', linewidth=1)
ax.set_xticks(range(env.width))
ax.set_yticks(range(env.height))
ax.set_title('Q-Values per State-Action\n(↑top, ↓bottom, ←left, →right)', fontsize=12)
plt.tight_layout()
return fig
@staticmethod
def plot_solution_path(
env: MazeEnvironment,
path: List[Tuple[int, int]],
figsize: Tuple[int, int] = (10, 10)
):
"""Visualize the solution path taken by the agent."""
fig, ax = plt.subplots(figsize=figsize)
# Draw maze
colors = ['white', '#333333', '#4CAF50', '#f44336']
cmap = ListedColormap(colors)
ax.imshow(env.maze, cmap=cmap, vmin=0, vmax=3)
# Draw path
if len(path) > 1:
path_rows = [p[0] for p in path]
path_cols = [p[1] for p in path]
# Draw line
ax.plot(path_cols, path_rows, 'b-', linewidth=3, alpha=0.7, label='Path')
# Draw points
ax.scatter(path_cols[1:-1], path_rows[1:-1], c='blue', s=100,
zorder=5, alpha=0.7)
# Mark start and end of path
ax.scatter([path_cols[0]], [path_rows[0]], c='lime', s=200,
marker='o', zorder=6, edgecolors='black', linewidths=2,
label='Start')
ax.scatter([path_cols[-1]], [path_rows[-1]], c='red', s=200,
marker='*', zorder=6, edgecolors='black', linewidths=2,
label='End')
# Number the steps
for i, (r, c) in enumerate(path):
ax.annotate(str(i), (c, r), ha='center', va='center',
fontsize=8, fontweight='bold', color='white',
bbox=dict(boxstyle='circle', facecolor='blue', alpha=0.7))
# Add grid
ax.set_xticks(np.arange(-0.5, env.width, 1), minor=True)
ax.set_yticks(np.arange(-0.5, env.height, 1), minor=True)
ax.grid(which='minor', color='gray', linestyle='-', linewidth=1)
ax.legend(loc='upper left', bbox_to_anchor=(1, 1))
ax.set_title(f'Solution Path ({len(path)-1} steps)', fontsize=14)
plt.tight_layout()
return fig
def create_custom_maze(maze_type: str = 'simple') -> np.ndarray:
"""
Create different maze configurations.
Args:
maze_type: Type of maze ('simple', 'medium', 'complex')
"""
if maze_type == 'simple':
return np.array([
[2, 0, 0, 0, 0],
[1, 1, 1, 1, 0],
[0, 0, 0, 0, 0],
[0, 1, 1, 1, 1],
[0, 0, 0, 0, 3]
])
elif maze_type == 'medium':
return np.array([
[2, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 1, 1, 1, 0],
[1, 0, 1, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 1, 0, 1, 0],
[0, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 1],
[1, 1, 1, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 1, 3]
])
elif maze_type == 'complex':
return np.array([
[2, 0, 1, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 1, 0, 1, 0, 1, 0, 1, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 1, 0],
[1, 1, 1, 0, 1, 1, 1, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 1, 1, 1, 1, 0, 0, 0, 1, 1],
[0, 0, 0, 0, 1, 0, 1, 0, 0, 0],
[1, 1, 1, 0, 1, 0, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 1, 1, 1, 1, 1, 1, 0, 0, 3]
])
else:
raise ValueError(f"Unknown maze type: {maze_type}")
def main():
"""Main function demonstrating the Q-learning maze solver."""
print("=" * 60)
print("Q-Learning Maze Solver")
print("=" * 60)
# Create environment
print("\n1. Creating maze environment...")
maze = create_custom_maze('medium')
env = MazeEnvironment(maze)
print(f" Maze size: {env.height}x{env.width}")
print(f" Start: {env.start_pos}")
print(f" Goal: {env.goal_pos}")
# Create agent
print("\n2. Creating Q-learning agent...")
agent = QLearningAgent(
n_actions=env.n_actions,
learning_rate=0.1,
discount_factor=0.95,
epsilon=1.0,
epsilon_decay=0.995,
epsilon_min=0.01
)
# Train agent
print("\n3. Training agent...")
print("-" * 40)
agent = train_agent(
env=env,
agent=agent,
n_episodes=1000,
max_steps=200,
verbose=True
)
print("-" * 40)
# Test agent
print("\n4. Testing trained agent...")
path, total_reward, success = test_agent(env, agent)
print(f" Success: {success}")
print(f" Steps taken: {len(path) - 1}")
print(f" Total reward: {total_reward:.1f}")
print(f" Path: {' -> '.join(map(str, path))}")
# Visualizations
print("\n5. Creating visualizations...")
# Plot training history
fig1 = MazeVisualizer.plot_training_history(agent)
plt.savefig('training_history.png', dpi=150, bbox_inches='tight')
print(" Saved: training_history.png")
# Plot learned policy
fig2 = MazeVisualizer.plot_policy(env, agent)
plt.savefig('learned_policy.png', dpi=150, bbox_inches='tight')
print(" Saved: learned_policy.png")
# Plot Q-values
fig3 = MazeVisualizer.plot_q_values(env, agent)
plt.savefig('q_values.png', dpi=150, bbox_inches='tight')
print(" Saved: q_values.png")
# Plot solution path
fig4 = MazeVisualizer.plot_solution_path(env, path)
plt.savefig('solution_path.png', dpi=150, bbox_inches='tight')
print(" Saved: solution_path.png")
plt.show()
print("\n" + "=" * 60)
print("Training complete!")
print("=" * 60)
return env, agent
if __name__ == "__main__":
env, agent = main()
Algorithm Explanation
┌─────────────────────────────────────────────────────────────────┐
│ Q-LEARNING ALGORITHM │
├─────────────────────────────────────────────────────────────────┤
│ │
│ Initialize Q(s,a) = 0 for all states and actions │
│ │
│ For each episode: │
│ 1. Start at initial state s │
│ │
│ 2. Choose action a using ε-greedy: │
│ ┌─────────────────────────────────────────┐ │
│ │ with probability ε: random action │ │
│ │ with probability 1-ε: best Q action │ │
│ └─────────────────────────────────────────┘ │
│ │
│ 3. Take action a, observe reward r and new state s' │
│ │
│ 4. Update Q-value: │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Q(s,a) ← Q(s,a) + α[r + γ·max Q(s',a') - Q(s,a)] │ │
│ │ └────────┬────────┘ │ │
│ │ TD Target │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ 5. s ← s' │
│ │
│ 6. Decay ε │
│ │
│ Until reaching goal or max steps │
│ │
├─────────────────────────────────────────────────────────────────┤
│ Parameters: │
│ α (learning rate) = 0.1 - update step size │
│ γ (discount) = 0.95 - future reward importance │
│ ε (exploration) = 1→0.01 - exploration vs exploitation │
└─────────────────────────────────────────────────────────────────┘
Sample Output
============================================================
Q-Learning Maze Solver
============================================================
1. Creating maze environment...
Maze size: 8x8
Start: (0, 0)
Goal: (7, 7)
2. Creating Q-learning agent...
3. Training agent...
----------------------------------------
Episode 100/1000 | Avg Reward: -87.2 | Avg Steps: 52.3 | Epsilon: 0.606
Episode 200/1000 | Avg Reward: -42.1 | Avg Steps: 35.8 | Epsilon: 0.367
Episode 300/1000 | Avg Reward: 12.5 | Avg Steps: 28.4 | Epsilon: 0.223
Episode 400/1000 | Avg Reward: 45.2 | Avg Steps: 22.1 | Epsilon: 0.135
Episode 500/1000 | Avg Reward: 68.4 | Avg Steps: 17.5 | Epsilon: 0.082
Episode 600/1000 | Avg Reward: 78.3 | Avg Steps: 15.2 | Epsilon: 0.050
Episode 700/1000 | Avg Reward: 82.1 | Avg Steps: 14.1 | Epsilon: 0.030
Episode 800/1000 | Avg Reward: 84.5 | Avg Steps: 13.8 | Epsilon: 0.018
Episode 900/1000 | Avg Reward: 85.2 | Avg Steps: 13.5 | Epsilon: 0.011
Episode 1000/1000 | Avg Reward: 86.0 | Avg Steps: 13.0 | Epsilon: 0.010
----------------------------------------
4. Testing trained agent...
Success: True
Steps taken: 13
Total reward: 87.0
Path: (0,0) -> (1,0) -> (1,1) -> (2,1) -> (3,1) -> ...
============================================================
Training complete!
============================================================
Key Features
| Feature | Description |
|---|
| ε-greedy Exploration | Balances exploration vs exploitation |
| Q-table | Stores value of each state-action pair |
| Temporal Difference | Learns from immediate rewards + estimates |
| Epsilon Decay | Gradually shifts from exploration to exploitation |
| Multiple Visualizations | Training curves, policy, Q-values, solution path |
This implementation provides a complete, well-documented Q-learning solution with comprehensive visualization tools for understanding the learning process.