import numpy as np
# Define the maze: 0 = open path, 1 = wall
maze = np.array([
[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 1, 0, 1, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 0]
])
start = (0, 0)
goal = (4, 4)
actions = [(-1, 0), (0, 1), (1, 0), (0, -1)] # up, right, down, left
def get_next_state(state, action_idx, maze):
"""Get the next state after taking an action, stay in place if invalid."""
r, c = state
dr, dc = actions[action_idx]
nr, nc = r + dr, c + dc
if 0 <= nr < maze.shape[0] and 0 <= nc < maze.shape[1] and maze[nr, nc] == 0:
return (nr, nc)
return state
def get_reward(state, goal):
"""Reward function: +100 at goal, -1 otherwise."""
if state == goal:
return 100
return -1
def print_maze(maze, path=None):
"""Print the maze, optionally highlighting the path."""
rows, cols = maze.shape
symbols = [[' ' for _ in range(cols)] for _ in range(rows)]
# Set walls, start, goal, and open spaces
for i in range(rows):
for j in range(cols):
if maze[i, j] == 1:
symbols[i][j] = '#'
elif (i, j) == start:
symbols[i][j] = 'S'
elif (i, j) == goal:
symbols[i][j] = 'G'
else:
symbols[i][j] = '.'
# Highlight path if provided (skip start and goal)
if path:
for pos in path[1:-1]:
r, c = pos
symbols[r][c] = '*'
# Print the maze
for row in symbols:
print(' '.join(row))
print()
# Q-Learning parameters
rows, cols = maze.shape
Q = np.zeros((rows, cols, 4)) # Q-table: state (r,c) -> action -> Q-value
alpha = 0.1 # Learning rate
gamma = 0.99 # Discount factor
epsilon = 1.0 # Initial exploration rate
min_epsilon = 0.01
epsilon_decay = 0.999
episodes = 5000
print("Initial maze:")
print_maze(maze)
print("Training the Q-learning agent...")
for episode in range(episodes):
state = start
while state != goal:
# Epsilon-greedy action selection
if np.random.random() < epsilon:
action = np.random.randint(4)
else:
action = np.argmax(Q[state[0], state[1], :])
# Take action
new_state = get_next_state(state, action, maze)
reward = get_reward(new_state, goal)
# Q-update
current_q = Q[state[0], state[1], action]
next_max_q = np.max(Q[new_state[0], new_state[1], :])
new_q = current_q + alpha * (reward + gamma * next_max_q - current_q)
Q[state[0], state[1], action] = new_q
state = new_state
# Decay epsilon
epsilon = max(min_epsilon, epsilon * epsilon_decay)
print("Training complete!")
# Extract the optimal path using the learned policy
print("Best path found:")
state = start
path = [state]
while state != goal:
action = np.argmax(Q[state[0], state[1], :])
state = get_next_state(state, action, maze)
path.append(state)
print_maze(maze, path)
print(f"Path length: {len(path) - 1} steps")
This code implements a Q-learning agent that learns to solve the maze.
Maze: A 5x5 grid with walls (#), start (S), goal (G), open paths (.), and solved path (*).
Training: Runs for 5000 episodes with epsilon-greedy exploration (decaying from 1.0 to 0.01).
Output: Prints the initial maze, trains the agent, then shows the optimal path and its length.
Run the code to see the agent solve the maze! The Q-table converges to find the shortest path efficiently. You can adjust parameters, maze size, or rewards for experimentation.