Designing a maze environment
I'm thinking we should provide a complete code block as a single script for the user to run, ensuring there's no environment leakage. I’m considering designing a 6x6 grid with obstacles. I’ll use NumPy for the maze environment, setting up start and goal positions from the grid values. I'll define valid actions and compute positions accordingly, ensuring the system handles walls and out-of-bounds actions while possibly applying a penalty for invalid moves. This should offer a solid example!Refining maze environment rewards
I’m refining the movement logic to ensure the agent can't move into walls or out-of-bounds, applying a penalty when that happens. I'll set the completion criteria for reaching the goal or hitting a step limit. The reward system will be -1 per step and +10 for the goal, but I might consider +100 for stronger Q-learning. I’ll implement a training loop where actions are chosen based on exploration. Plus, I need to map the state tuple to integers for the Q-table, and I'll create a function to help with that.Implementing Q-learning updates
I’ve decided we can keep states that won’t be visited during training, and inside the training loop, I’ll convert the current state to an index. Once I take a step, I’ll get the next state, reward, and done status. I’ll update the Q-value accordingly and handle the case for 'done' where there’s no future state. At the end, I want to print the optimal policy path from start to goal and render the maze with the path marked. I need to ensure the code runs smoothly in Python 3 without bugs.Addressing potential pitfalls
I’ve identified some potential pitfalls for our maze implementation, starting with the need for an example grid. For instance, I could use a 6x6 grid like this:
maze = [
[2,0,1,0,0,0],
[0,0,1,0,1,0],
[0,0,0,0,1,0],
[1,1,0,1,1,0],
[0,0,0,0,0,0],
[0,1,1,1,1,3]
]
Also, I’ll make sure to define the environment as completed when the steps reach the maximum limit. I’ll combine everything into one script and keep the focus on coding without referring to "short answers" or “great questions.” Let's get started! ```python
"""
Q-learning agent that solves a simple grid maze.
- 0 = free cell
- 1 = wall
- 2 = start
- 3 = goal
"""
import numpy as np
import random
class MazeEnv:
def init(self, maze, max_steps=200):
self.maze = np.array(maze)
self.n_rows, self.n_cols = self.maze.shape
self.max_steps = max_steps
# Find start and goal
start_pos = np.argwhere(self.maze == 2)
goal_pos = np.argwhere(self.maze == 3)
if len(start_pos) == 0 or len(goal_pos) == 0:
raise ValueError("Maze must have one start (2) and one goal (3).")
self.start = tuple(start_pos[0])
self.goal = tuple(goal_pos[0])
# Actions: 0=up, 1=right, 2=down, 3=left
self.action_space = [0, 1, 2, 3]
self.n_actions = len(self.action_space)
self.n_states = self.n_rows * self.n_cols
self.reset()
def state_to_index(self, state):
"""Map (row, col) -> single integer index."""
r, c = state
return r * self.n_cols + c
def index_to_state(self, index):
"""Map index -> (row, col)."""
return divmod(index, self.n_cols)
def reset(self):
self.pos = self.start
self.steps = 0
return self.pos
def step(self, action):
"""
Take an action in the environment.
Returns:
next_state (row, col)
reward (float)
done (bool)
"""
self.steps += 1
r, c = self.pos
# Compute proposed next position
if action == 0: # up
nr, nc = r - 1, c
elif action == 1: # right
nr, nc = r, c + 1
elif action == 2: # down
nr, nc = r + 1, c
elif action == 3: # left
nr, nc = r, c - 1
else:
raise ValueError("Invalid action.")
# If out of bounds or into wall, stay in place
if not (0 <= nr < self.n_rows and 0 <= nc < self.n_cols) or self.maze[nr, nc] == 1:
nr, nc = r, c
self.pos = (nr, nc)
# Rewards
if self.pos == self.goal:
reward = 100.0
done = True
else:
reward = -1.0 # time penalty
done = False
# Prevent infinite loops
if self.steps >= self.max_steps:
done = True
return self.pos, reward, done
def render(self, path=None):
"""
Print the maze.
Optionally highlight a path: list of (row, col).
"""
display = self.maze.astype(object)
# Copy so we don't overwrite internal maze
display = np.array(display, dtype=object)
# Mark walls and free cells for readability
for r in range(self.n_rows):
for c in range(self.n_cols):
if display[r, c] == 0:
display[r, c] = ' '
elif display[r, c] == 1:
display[r, c] = '#'
elif display[r, c] == 2:
display[r, c] = 'S'
elif display[r, c] == 3:
display[r, c] = 'G'
if path is not None:
for (r, c) in path:
if (r, c) != self.start and (r, c) != self.goal and display[r, c] == ' ':
display[r, c] = '.'
for r in range(self.n_rows):
print(''.join(str(x) for x in display[r]))
Example maze (6x6)
maze = [
[2, 0, 1, 0, 0, 0],
[0, 0, 1, 0, 1, 0],
[0, 0, 0, 0, 1, 0],
[1, 1, 0, 1, 1, 0],
[0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 3],
]
env = MazeEnv(maze)
Q-learning parameters
alpha = 0.1 # learning rate
gamma = 0.99 # discount factor
epsilon = 1.0 # exploration rate
epsilon_min = 0.01
epsilon_decay = 0.995
num_episodes = 3000
Initialize Q-table
Q = np.zeros((env.n_states, env.n_actions))
def choose_action(state, epsilon):
"""Epsilon-greedy action selection."""
if random.random() < epsilon:
return random.choice(env.action_space)
else:
s_idx = env.state_to_index(state)
return int(np.argmax(Q[s_idx]))
Training loop
for episode in range(num_episodes):
state = env.reset()
done = False
while not done:
action = choose_action(state, epsilon)
next_state, reward, done = env.step(action)
s_idx = env.state_to_index(state)
ns_idx = env.state_to_index(next_state)
# Q-learning update
best_next = np.max(Q[ns_idx])
td_target = reward + gamma * best_next * (0 if done else 1)
td_error = td_target - Q[s_idx, action]
Q[s_idx, action] += alpha * td_error
state = next_state
# Decay exploration
if epsilon > epsilon_min:
epsilon *= epsilon_decay
# Optional: simple progress print
if (episode + 1) % 500 == 0:
print(f"Episode {episode + 1}/{num_episodes}, epsilon={epsilon:.3f}")
print("\nTraining finished.\n")
Test the learned policy (greedy)
def get_greedy_path(env, Q, max_steps=200):
state = env.reset()
path = [state]
for _ in range(max_steps):
s_idx = env.state_to_index(state)
action = int(np.argmax(Q[s_idx]))
next_state, reward, done = env.step(action)
path.append(next_state)
state = next_state
if done:
break
return path
path = get_greedy_path(env, Q)
print("Learned path:")
env.render(path=path)