Below is a single-file, self-contained demo that shows
• how to cast rays in a little 2-D “grid world”,
• feed those ray-distances into a neural network,
• train the network with Deep-Q-Learning to reach a goal while avoiding walls.
It can be run headless (no graphics) and only needs NumPy and PyTorch.
pip install numpy torch
python raycast_rl.py # you’ll see the training print-outs
Feel free to expand/visualise with Pygame, add more obstacles, change reward shaping, etc.
# file: raycast_rl.py
# Python 3.8+ – minimal ML + ray-cast example
import random, math, collections, itertools, os, time
import numpy as np
import torch, torch.nn as nn, torch.optim as optim
# ---------- Hyper-params ----------
GRID_W, GRID_H = 12, 12 # board size
N_EPISODES = 600 # total training episodes
MAX_STEPS = 200 # safety cap inside one episode
MAX_RAY_RANGE = 10 # how far each ray can see
RAY_DIRS = [ # 8-way LIDAR
( 1, 0), (-1, 0), (0, 1), (0,-1),
( 1, 1), ( 1,-1), (-1, 1), (-1,-1)
]
LR = 1e-3 # learning rate
GAMMA = 0.98 # discount
EPS_START, EPS_END = 1.0, 0.05 # ε-greedy schedule
TARGET_SYNC = 200 # how often to copy online → target net
MEM_CAPACITY = 50_000
BATCH_SIZE = 256
HIDDEN = 64
# ---------- Environment ----------
class RaycastWorld:
EMPTY, WALL, AGENT, GOAL = 0, 1, 2, 3
def __init__(self, w=GRID_W, h=GRID_H):
self.w, self.h = w, h
self.grid = np.zeros((h, w), dtype=np.int8)
self._init_maze()
self.reset()
def _init_maze(self):
# Simple hard-coded maze; add or randomise as you wish
self.grid[:] = self.EMPTY
self.grid[[0,-1],:] = self.WALL
self.grid[:,[0,-1]] = self.WALL
# inner obstacle walls
for i in range(2, self.h-2):
self.grid[i, 4] = self.WALL
for i in range(3, self.h-3):
self.grid[i, 7] = self.WALL
def reset(self):
# agent starts top-left corner; goal bottom-right
self.agent = [1,1]
self.goal = [self.w-2, self.h-2]
return self._observation()
# -------------------------------- Raycasting
def _raycast(self, pos, dxy):
"""Return normalised distance [0,1] until wall or limit"""
x, y = pos
dx, dy = dxy
dist = 0
for _ in range(MAX_RAY_RANGE):
x += dx; y += dy; dist += 1
if x<0 or x>=self.w or y<0 or y>=self.h: break
if self.grid[y,x] == self.WALL: break
return dist / MAX_RAY_RANGE
def _observation(self):
rays = [self._raycast(self.agent, d) for d in RAY_DIRS]
# vector to goal, normalised
gx = (self.goal[0]-self.agent[0]) / self.w
gy = (self.goal[1]-self.agent[1]) / self.h
return np.array(rays + [gx,gy], dtype=np.float32)
# -------------------------------- RL interface
ACTIONS = [(1,0), (-1,0), (0,1), (0,-1)] # right, left, down, up
def step(self, action_idx):
dx, dy = self.ACTIONS[action_idx]
nx, ny = self.agent[0]+dx, self.agent[1]+dy
reward, done = ‑0.02, False
# wall hit?
if self.grid[ny, nx] == self.WALL:
reward = ‑0.25
else:
self.agent = [nx, ny]
# goal?
if self.agent == self.goal:
reward, done = +1.0, True
return self._observation(), reward, done, {}
# ---------- Replay buffer ----------
Transition = collections.namedtuple('T', ('s','a','r','s2','done'))
class Replay:
def __init__(self, cap=MEM_CAPACITY):
self.cap = cap; self.buf = collections.deque(maxlen=cap)
def push(self, *args): self.buf.append(Transition(*args))
def sample(self,bz): return random.sample(self.buf, bz)
def __len__(self): return len(self.buf)
# ---------- DQN ----------
class Net(nn.Module):
def __init__(self, in_dim, n_act):
super().__init__()
self.net = nn.Sequential(
nn.Linear(in_dim, HIDDEN), nn.ReLU(),
nn.Linear(HIDDEN, HIDDEN), nn.ReLU(),
nn.Linear(HIDDEN, n_act)
)
def forward(self,x): return self.net(x)
def select_action(state, steps_done, policy_net):
eps = EPS_END + (EPS_START-EPS_END)*math.exp(-1.5*steps_done/5000)
if random.random()<eps:
return random.randrange(len(RaycastWorld.ACTIONS))
with torch.no_grad():
q = policy_net(torch.from_numpy(state).unsqueeze(0))
return int(torch.argmax(q))
# ---------- Training loop ----------
def optimize(optimiser, policy, target, memory):
if len(memory)<BATCH_SIZE: return
batch = Transition(*zip(*memory.sample(BATCH_SIZE)))
s = torch.tensor(batch.s)
a = torch.tensor(batch.a).unsqueeze(1)
r = torch.tensor(batch.r).unsqueeze(1)
s2 = torch.tensor(batch.s2)
done= torch.tensor(batch.done).unsqueeze(1)
q = policy(s).gather(1,a)
with torch.no_grad():
q_next = target(s2).max(1,keepdim=True)[0]
q_target = r + GAMMA * q_next * (~done)
loss = nn.functional.smooth_l1_loss(q,q_target)
optimiser.zero_grad(); loss.backward(); optimiser.step()
def main():
env = RaycastWorld()
n_in = len(env._observation())
n_act = len(env.ACTIONS)
policy, target = Net(n_in,n_act), Net(n_in,n_act)
target.load_state_dict(policy.state_dict())
optim_ = optim.Adam(policy.parameters(), lr=LR)
memory = Replay()
steps = 0
for ep in range(1, N_EPISODES+1):
s = env.reset(); ep_reward = 0
for t in range(MAX_STEPS):
a = select_action(s, steps, policy); steps+=1
s2,r,done,_ = env.step(a)
memory.push(s,a,r,s2,done)
s = s2; ep_reward += r
optimize(optim_, policy, target, memory)
if steps % TARGET_SYNC == 0:
target.load_state_dict(policy.state_dict())
if done: break
print(f'Episode {ep:4d} ─ Reward {ep_reward:6.2f} Steps {t+1:3d}')
print("Training done!")
# quick demo run (greedy)
s = env.reset()
track=[]
for _ in range(60):
a = select_action(s, 1e9, policy) # epsilon≈0
s,_,done,_ = env.step(a)
track.append(tuple(env.agent))
if done: break
print("Greedy path:", track)
if __name__ == "__main__":
main()
What you just built 🚀
- Grid world with solid walls.
- 8 “LIDAR”-style raycasts that sense how far you can move before hitting an obstacle.
- Those distances, plus a vector to the goal, form the state fed into a tiny neural net.
- Deep-Q-Learning trains the agent to reach the goal.
- For simplicity there is no GUI, but you can import
pygame and draw the grid/agent each step.
Ideas for extensions
• Swap the Q-table network for an RNN and turn those rays into a “sonar sweep”.
• Randomise mazes and train a PPO or A2C agent instead.
• Move to 3-D: use the same raycasting principle with Panda3D or PyBullet and turn the ML part into an obstacle avoidance stack for a virtual drone.
Have fun hacking!