Here’s a self-contained example of a little 2D “car” that uses raycasts as its sensor and a Deep Q-Network (DQN) to learn to navigate toward a goal while avoiding walls. Over time you’ll see the episode-reward improve as the network trains.
Requirements
pip install pygame torch numpy
# file: raycast_dqn.py
import pygame, sys, math, random
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from collections import deque, namedtuple
# --- Hyper-params ---
SCREEN_W, SCREEN_H = 600, 400
FPS = 60
MAX_EPISODES = 500
MAX_STEPS = 300
LR = 1e-3
GAMMA = 0.99
EPS_START, EPS_END, EPS_DECAY = 1.0, 0.01, 0.995
BATCH_SIZE = 64
MEMORY_SIZE = 10000
# --- Simple replay buffer ---
Transition = namedtuple('Transition',
('state','action','reward','next_state','done'))
class ReplayBuffer:
def __init__(self, capacity):
self.buf = deque(maxlen=capacity)
def push(self, *args):
self.buf.append(Transition(*args))
def sample(self, batch_size):
return random.sample(self.buf, batch_size)
def __len__(self):
return len(self.buf)
# --- DQN network ---
class DQN(nn.Module):
def __init__(self, n_inputs, n_actions):
super().__init__()
self.net = nn.Sequential(
nn.Linear(n_inputs, 128),
nn.ReLU(),
nn.Linear(128, 64),
nn.ReLU(),
nn.Linear(64, n_actions)
)
def forward(self, x):
return self.net(x)
# --- The 2D Environment ---
class Env2D:
def __init__(self):
pygame.init()
self.screen = pygame.display.set_mode((SCREEN_W, SCREEN_H))
self.clock = pygame.time.Clock()
# Walls: list of pygame.Rect
self.walls = [
pygame.Rect(50,50,500,10),
pygame.Rect(50,340,500,10),
pygame.Rect(50,50,10,300),
pygame.Rect(540,50,10,300),
# add inner obstacles:
pygame.Rect(200,150,200,10),
pygame.Rect(200,250,200,10)
]
# ray angles in degrees relative to heading
self.ray_angles = [-60, -30, 0, 30, 60]
self.max_ray_dist = 150
def reset(self):
# Car state: (x,y,theta)
self.x, self.y = 100.0, 200.0
self.theta = 0.0
self.goal = (500, 200)
return self._get_obs()
def step(self, action):
# action: 0=left,1=straight,2=right
if action == 0: self.theta -= 10 * math.pi/180
elif action == 2: self.theta += 10 * math.pi/180
# move forward
speed = 2.0
self.x += speed * math.cos(self.theta)
self.y += speed * math.sin(self.theta)
# check collisions
car_rect = pygame.Rect(self.x-5, self.y-5,10,10)
done = False
reward = -0.01 # time penalty
if car_rect.collidelist(self.walls) != -1:
reward = -1.0
done = True
# check goal
if math.hypot(self.x-self.goal[0], self.y-self.goal[1]) < 10:
reward = +1.0
done = True
obs = self._get_obs()
return obs, reward, done
def _get_obs(self):
# Raycast distances
dists = []
for a in self.ray_angles:
ray_ang = self.theta + math.radians(a)
dist = self._cast_ray(ray_ang)
dists.append(dist / self.max_ray_dist) # normalize
# angle to goal
ang_to_goal = math.atan2(self.goal[1]-self.y, self.goal[0]-self.x)
diff = (ang_to_goal - self.theta + math.pi) % (2*math.pi) - math.pi
obs = np.array(dists + [diff/math.pi], dtype=np.float32)
return obs
def _cast_ray(self, ang):
# step along the ray until hit wall or max distance
x0,y0 = self.x, self.y
for d in range(self.max_ray_dist):
xi = x0 + d*math.cos(ang)
yi = y0 + d*math.sin(ang)
if xi<0 or xi>SCREEN_W or yi<0 or yi>SCREEN_H:
return d
for w in self.walls:
if w.collidepoint(xi, yi):
return d
return self.max_ray_dist
def render(self):
self.screen.fill((30,30,30))
# draw walls
for w in self.walls:
pygame.draw.rect(self.screen, (200,200,200), w)
# draw goal
pygame.draw.circle(self.screen, (0,255,0), (int(self.goal[0]),int(self.goal[1])), 8)
# draw car
px,py = int(self.x), int(self.y)
pygame.draw.circle(self.screen, (255,0,0), (px,py), 5)
# draw rays
for a in self.ray_angles:
ang = self.theta + math.radians(a)
d = self._cast_ray(ang)
ex = px + d*math.cos(ang)
ey = py + d*math.sin(ang)
pygame.draw.line(self.screen, (100,200,255), (px,py),(ex,ey),1)
pygame.display.flip()
self.clock.tick(FPS)
# --- Training Loop ---
def train():
env = Env2D()
n_states = len(env.ray_angles) + 1
n_actions = 3
net = DQN(n_states, n_actions)
tgt_net = DQN(n_states, n_actions)
tgt_net.load_state_dict(net.state_dict())
optimizer = optim.Adam(net.parameters(), lr=LR)
memory = ReplayBuffer(MEMORY_SIZE)
epsilon = EPS_START
for ep in range(1, MAX_EPISODES+1):
state = env.reset()
total_r = 0.0
for t in range(MAX_STEPS):
# handle quit
for evt in pygame.event.get():
if evt.type == pygame.QUIT:
pygame.quit()
sys.exit()
# select action
if random.random() < epsilon:
action = random.randrange(n_actions)
else:
with torch.no_grad():
qv = net(torch.from_numpy(state))
action = int(qv.argmax().item())
next_s, rew, done = env.step(action)
total_r += rew
memory.push(state, action, rew, next_s, done)
state = next_s
# train
if len(memory) >= BATCH_SIZE:
batch = Transition(*zip(*memory.sample(BATCH_SIZE)))
s_batch = torch.tensor(batch.state)
a_batch = torch.tensor(batch.action).unsqueeze(1)
r_batch = torch.tensor(batch.reward)
ns_batch = torch.tensor(batch.next_state)
done_batch= torch.tensor(batch.done, dtype=torch.bool)
# Q(s,a)
q_values = net(s_batch).gather(1, a_batch).squeeze()
# max_a' Q_target(s',a')
with torch.no_grad():
q_next = tgt_net(ns_batch).max(1)[0]
q_next[done_batch] = 0.0
q_target = r_batch + GAMMA * q_next
loss = nn.MSELoss()(q_values, q_target)
optimizer.zero_grad()
loss.backward()
optimizer.step()
env.render()
if done:
break
# update target net
if ep % 10 == 0:
tgt_net.load_state_dict(net.state_dict())
epsilon = max(EPS_END, epsilon * EPS_DECAY)
print(f"Episode {ep:3d} | Reward: {total_r:6.2f} | Eps: {epsilon:.3f}")
pygame.quit()
if __name__ == '__main__':
train()
How it works
-
Env2D
- A rectangular arena with walls.
- The “car” has position
(x,y) and orientation theta.
- 5 rays (–60°, –30°, 0°, +30°, +60°) measure distance to nearest wall.
- Also measures relative angle to the goal.
-
DQN Agent
- A small MLP maps the 6-dim observation → 3 Q-values (turn left / straight / turn right).
- Replay buffer + ε-greedy, target network updated every 10 episodes.
-
Training loop
- Runs up to 500 episodes of max 300 steps.
- Renders in real-time with Pygame so you can watch the car explore and gradually learn to steer toward the green goal.
Run it and watch the episode reward printed each episode. Over time you’ll see the rewards climb as the agent learns from its raycast “vision” and improves its policy. Good luck experimenting! 🚗💨