Skip to content

Instantly share code, notes, and snippets.

@float64co
Created August 31, 2026 20:48
Show Gist options
  • Select an option

  • Save float64co/d00b8a51b756934c36d96cdae0444680 to your computer and use it in GitHub Desktop.

Select an option

Save float64co/d00b8a51b756934c36d96cdae0444680 to your computer and use it in GitHub Desktop.
peril
#!/usr/bin/env python3
"""
A tiny wireframe FPS built on top of leet.py's flight-mode 3D engine.
leet.py's space-flight mode already has everything a first-person shooter
needs under the hood: an orthonormal (forward, up, right) camera basis
(derive_basis), a perspective-divide projector, near-plane clipping
(clip_near), and a curses line rasterizer. This file imports that vector
math straight from leet.py and points it at a walking camera instead of a
ship: fixed eye height, yaw+pitch look, a generated wall maze instead of
open space, and enemies that close in and melee/fireball you.
Controls:
W/A/S/D - move / strafe
Left/Right - turn
Up/Down - look up/down
Space - fire
Q / Esc - quit (also: any key to continue past title/death/win)
"""
import curses
import math
import random
from dataclasses import dataclass, field
from leet import (
v_add, v_sub, v_scale, v_dot, v_len, v_norm,
derive_basis, clip_near, local_to_world, clamp,
)
# --------------------------------------------------------------------------
# Constants
# --------------------------------------------------------------------------
CELL = 64.0 # world size of one maze cell
WALL_H = 48.0 # wall height
EYE_H = 26.0 # camera height off the floor
PLAYER_RADIUS = 10.0
ENEMY_RADIUS = 10.0
MAZE_COLS, MAZE_ROWS = 11, 9
LOOP_CHANCE = 0.14 # chance an interior wall between two cells is knocked
# down after maze generation, to add loops/shortcuts
TICK_MS = 70
MOVE_SPEED = 5.0
TURN_SPEED = 0.09 # radians per keypress (relies on terminal autorepeat,
# same trick leet.py's flight controls use)
PITCH_LIMIT = math.radians(60)
PROJ_SCALE_X = 50.0
PROJ_SCALE_Y = 25.0
NEAR_PLANE = 2.0
VIEW_RANGE = 850.0
PLAYER_MAX_HEALTH = 100
GUN_RANGE = 480.0
GUN_CONE = math.radians(12) # same cone leet.py uses for its laser
GUN_DAMAGE = 14
GUN_COOLDOWN = 4
GUN_MUZZLE_OFFSET = (0.0, -6.0, 10.0) # (right, up, forward), ship-local-
# style offset so a miss doesn't
# collapse to a point under the
# crosshair (see leet.py's note on
# LASER_MUZZLE_OFFSET)
FX_TICKS = 5
ENEMY_COUNT = 8
ENEMY_HEALTH = 34
ENEMY_SPEED = 2.1
ENEMY_DETECT_RANGE = 480.0
ENEMY_MELEE_RANGE = 28.0
ENEMY_MELEE_DAMAGE = 7
ENEMY_MELEE_COOLDOWN = 14
ENEMY_FIREBALL_RANGE = 380.0
ENEMY_FIREBALL_COOLDOWN = 45
FIREBALL_SPEED = 7.0
FIREBALL_LIFE = 90
FIREBALL_DAMAGE = 11
FIREBALL_HIT_RADIUS = 16.0
CP_WALL, CP_FLOOR, CP_ENEMY, CP_HUD, CP_DANGER, CP_FIRE = 1, 2, 3, 4, 5, 6
# --------------------------------------------------------------------------
# Maze generation (recursive backtracker on a cols x rows cell grid, walls
# doubled so the result is directly a character grid: '#' wall, '.' floor)
# --------------------------------------------------------------------------
def generate_maze(cols, rows, rng):
w, h = 2 * cols + 1, 2 * rows + 1
grid = [['#'] * w for _ in range(h)]
visited = [[False] * cols for _ in range(rows)]
stack = [(0, 0)]
visited[0][0] = True
grid[1][1] = '.'
while stack:
cx, cy = stack[-1]
dirs = [(0, -1), (0, 1), (-1, 0), (1, 0)]
rng.shuffle(dirs)
carved = False
for dx, dy in dirs:
nx, ny = cx + dx, cy + dy
if 0 <= nx < cols and 0 <= ny < rows and not visited[ny][nx]:
visited[ny][nx] = True
grid[2 * cy + 1 + dy][2 * cx + 1 + dx] = '.'
grid[2 * ny + 1][2 * nx + 1] = '.'
stack.append((nx, ny))
carved = True
break
if not carved:
stack.pop()
return [''.join(row) for row in grid]
def add_loops(grid, rng, prob):
h, w = len(grid), len(grid[0])
rows = [list(r) for r in grid]
for r in range(1, h - 1):
for c in range(1, w - 1):
if rows[r][c] != '#':
continue
if r % 2 == 1 and c % 2 == 0:
if rows[r][c - 1] == '.' and rows[r][c + 1] == '.' and rng.random() < prob:
rows[r][c] = '.'
elif r % 2 == 0 and c % 2 == 1:
if rows[r - 1][c] == '.' and rows[r + 1][c] == '.' and rng.random() < prob:
rows[r][c] = '.'
return [''.join(row) for row in rows]
def build_wall_faces(grid):
"""One rectangle (4 world verts) per wall face that borders open space -
interior wall/wall boundaries are never drawn, which is what keeps this
readable as a wireframe corridor instead of a block of clutter."""
h, w = len(grid), len(grid[0])
faces = []
for r in range(h):
for c in range(w):
if grid[r][c] != '#':
continue
x0, x1 = c * CELL, (c + 1) * CELL
z0, z1 = r * CELL, (r + 1) * CELL
if r - 1 < 0 or grid[r - 1][c] != '#':
faces.append(((x0, 0, z0), (x1, 0, z0), (x1, WALL_H, z0), (x0, WALL_H, z0)))
if r + 1 >= h or grid[r + 1][c] != '#':
faces.append(((x0, 0, z1), (x1, 0, z1), (x1, WALL_H, z1), (x0, WALL_H, z1)))
if c - 1 < 0 or grid[r][c - 1] != '#':
faces.append(((x0, 0, z0), (x0, 0, z1), (x0, WALL_H, z1), (x0, WALL_H, z0)))
if c + 1 >= w or grid[r][c + 1] != '#':
faces.append(((x1, 0, z0), (x1, 0, z1), (x1, WALL_H, z1), (x1, WALL_H, z0)))
return faces
def build_floor_points(grid):
pts = set()
for r, row in enumerate(grid):
for c, ch in enumerate(row):
if ch == '.':
pts.add((c * CELL, 0.0, r * CELL))
pts.add(((c + 1) * CELL, 0.0, r * CELL))
pts.add((c * CELL, 0.0, (r + 1) * CELL))
pts.add(((c + 1) * CELL, 0.0, (r + 1) * CELL))
return list(pts)
def is_wall(grid, x, z):
col, row = int(x // CELL), int(z // CELL)
if row < 0 or row >= len(grid) or col < 0 or col >= len(grid[0]):
return True
return grid[row][col] == '#'
def blocked(grid, x, z, r):
return any(is_wall(grid, x + ox, z + oz) for ox in (-r, r) for oz in (-r, r))
def wall_blocks(grid, p0, p1):
"""Sample the segment between two (x, z) points for wall crossings -
used both for enemy line-of-sight and hitscan occlusion."""
dist = math.hypot(p1[0] - p0[0], p1[1] - p0[1])
steps = max(1, int(dist / 8.0))
for i in range(1, steps):
t = i / steps
x = p0[0] + (p1[0] - p0[0]) * t
z = p0[1] + (p1[1] - p0[1]) * t
if is_wall(grid, x, z):
return True
return False
def floor_cells(grid):
return [(r, c) for r, row in enumerate(grid) for c, ch in enumerate(row) if ch == '.']
# --------------------------------------------------------------------------
# Enemy wireframe model (a flat billboard sprite: local x=right, y=up, and
# it is always drawn facing the camera - see draw_enemies)
# --------------------------------------------------------------------------
IMP_MODEL = dict(
verts=[(0, 48), (-6, 40), (6, 40), # 0,1,2 head
(0, 34), (-12, 34), (12, 34), # 3,4,5 neck/shoulders
(-16, 14), (16, 14), # 6,7 hands
(0, 18), (-8, 18), (8, 18), # 8,9,10 hip center/sides
(-8, 0), (8, 0)], # 11,12 feet
edges=[(0, 1), (0, 2), (1, 2),
(3, 8),
(4, 5),
(4, 6), (5, 7),
(9, 10),
(9, 11), (10, 12),
(3, 4), (3, 5),
(8, 9), (8, 10)],
)
@dataclass
class Enemy:
x: float
z: float
health: float = ENEMY_HEALTH
alive: bool = True
aware: bool = False
melee_cd: int = 0
fire_cd: int = field(default_factory=lambda: random.randint(0, ENEMY_FIREBALL_COOLDOWN))
hit_flash: int = 0
@dataclass
class Fireball:
x: float
y: float
z: float
dx: float
dy: float
dz: float
life: int = FIREBALL_LIFE
def spawn_enemies(grid, rng, n, avoid_rc):
cells = [rc for rc in floor_cells(grid)
if abs(rc[0] - avoid_rc[0]) + abs(rc[1] - avoid_rc[1]) > 4]
rng.shuffle(cells)
enemies = []
for r, c in cells[:n]:
enemies.append(Enemy(x=(c + 0.5) * CELL, z=(r + 0.5) * CELL))
return enemies
# --------------------------------------------------------------------------
# Game
# --------------------------------------------------------------------------
class Game:
def __init__(self, stdscr):
self.stdscr = stdscr
self.state = "title"
self._new_run()
def _new_run(self):
rng = random.Random()
grid = generate_maze(MAZE_COLS, MAZE_ROWS, rng)
self.grid = add_loops(grid, rng, LOOP_CHANCE)
self.wall_faces = build_wall_faces(self.grid)
self.floor_points = build_floor_points(self.grid)
self.px, self.pz = 1.5 * CELL, 1.5 * CELL
self.py = EYE_H
self.yaw = math.radians(45)
self.pitch = 0.0
self.health = PLAYER_MAX_HEALTH
self.kills = 0
self.gun_cooldown = 0
self.fx_lines = [] # [ (x1,y1,z1,x2,y2,z2), ttl ]
self.enemies = spawn_enemies(self.grid, rng, ENEMY_COUNT, (1, 1))
self.fireballs = []
self.msg, self.msg_ttl = "", 0
self.clock = 0
def _set_msg(self, text, ttl=24):
self.msg, self.msg_ttl = text, ttl
# ------------------------------------------------------------- camera
def _look_basis(self):
fwd = (math.sin(self.yaw) * math.cos(self.pitch),
math.sin(self.pitch),
math.cos(self.yaw) * math.cos(self.pitch))
return derive_basis(fwd)
def _ground_basis(self):
fwd = (math.sin(self.yaw), 0.0, math.cos(self.yaw))
return derive_basis(fwd)
# --------------------------------------------------------------- loop
def tick_once(self):
self.draw()
key = self.stdscr.getch()
if key != -1:
self._handle_key(key)
if self.state == "playing":
self._update()
self.clock += 1
def _handle_key(self, key):
if self.state == "playing":
self._key_playing(key)
elif self.state == "title":
if key in (ord('q'), ord('Q'), 27):
self.state = "quit"
else:
self.state = "playing"
else: # dead / win
if key in (ord('q'), ord('Q'), 27):
self.state = "quit"
else:
self._new_run()
self.state = "playing"
def _key_playing(self, key):
if key in (ord('q'), ord('Q'), 27):
self.state = "quit"
elif key == curses.KEY_LEFT:
self.yaw = (self.yaw - TURN_SPEED) % (2 * math.pi)
elif key == curses.KEY_RIGHT:
self.yaw = (self.yaw + TURN_SPEED) % (2 * math.pi)
elif key == curses.KEY_UP:
self.pitch = clamp(self.pitch + TURN_SPEED, -PITCH_LIMIT, PITCH_LIMIT)
elif key == curses.KEY_DOWN:
self.pitch = clamp(self.pitch - TURN_SPEED, -PITCH_LIMIT, PITCH_LIMIT)
elif key in (ord('w'), ord('W')):
self._try_move(1, 0)
elif key in (ord('s'), ord('S')):
self._try_move(-1, 0)
elif key in (ord('a'), ord('A')):
self._try_move(0, -1)
elif key in (ord('d'), ord('D')):
self._try_move(0, 1)
elif key == ord(' '):
self._fire()
def _try_move(self, fwd_amt, strafe_amt):
fwd, up, right = self._ground_basis()
nx = self.px + (fwd[0] * fwd_amt + right[0] * strafe_amt) * MOVE_SPEED
nz = self.pz + (fwd[2] * fwd_amt + right[2] * strafe_amt) * MOVE_SPEED
if not blocked(self.grid, nx, self.pz, PLAYER_RADIUS):
self.px = nx
if not blocked(self.grid, self.px, nz, PLAYER_RADIUS):
self.pz = nz
def _fire(self):
if self.gun_cooldown > 0:
return
self.gun_cooldown = GUN_COOLDOWN
fwd, up, right = self._look_basis()
ppos = (self.px, self.py, self.pz)
muzzle = local_to_world(ppos, right, up, fwd, GUN_MUZZLE_OFFSET)
best, best_d = None, GUN_RANGE
for e in self.enemies:
if not e.alive:
continue
target = (e.x, EYE_H, e.z)
rel = v_sub(target, ppos)
d = v_len(rel)
if d > GUN_RANGE or d < 1e-6:
continue
if v_dot(v_scale(rel, 1.0 / d), fwd) < math.cos(GUN_CONE):
continue
if wall_blocks(self.grid, (self.px, self.pz), (e.x, e.z)):
continue
if d < best_d:
best_d, best = d, e
if best is None:
far = v_add(muzzle, v_scale(fwd, GUN_RANGE))
self.fx_lines.append([muzzle[0], muzzle[1], muzzle[2], far[0], far[1], far[2], FX_TICKS])
return
self.fx_lines.append([muzzle[0], muzzle[1], muzzle[2],
best.x, EYE_H, best.z, FX_TICKS])
best.health -= GUN_DAMAGE
best.hit_flash = 3
if best.health <= 0 and best.alive:
best.alive = False
self.kills += 1
remaining = sum(1 for e in self.enemies if e.alive)
self._set_msg(f"Kill! {remaining} left.")
if remaining == 0:
self.state = "win"
# ------------------------------------------------------------- update
def _update(self):
if self.gun_cooldown > 0:
self.gun_cooldown -= 1
if self.msg_ttl > 0:
self.msg_ttl -= 1
for e in self.enemies:
if not e.alive:
continue
if e.melee_cd > 0:
e.melee_cd -= 1
if e.fire_cd > 0:
e.fire_cd -= 1
if e.hit_flash > 0:
e.hit_flash -= 1
dx, dz = self.px - e.x, self.pz - e.z
dist = math.hypot(dx, dz)
if not e.aware and dist < ENEMY_DETECT_RANGE and \
not wall_blocks(self.grid, (e.x, e.z), (self.px, self.pz)):
e.aware = True
if not e.aware:
continue
if dist > ENEMY_MELEE_RANGE:
if dist > 1e-6:
nx, nz = dx / dist, dz / dist
sx, sz = e.x + nx * ENEMY_SPEED, e.z + nz * ENEMY_SPEED
if not blocked(self.grid, sx, e.z, ENEMY_RADIUS):
e.x = sx
if not blocked(self.grid, e.x, sz, ENEMY_RADIUS):
e.z = sz
if (e.fire_cd <= 0 and dist < ENEMY_FIREBALL_RANGE and
not wall_blocks(self.grid, (e.x, e.z), (self.px, self.pz))):
e.fire_cd = ENEMY_FIREBALL_COOLDOWN
d = v_norm((dx, EYE_H - EYE_H, dz))
self.fireballs.append(Fireball(e.x, EYE_H, e.z, d[0], 0.0, d[2]))
elif e.melee_cd <= 0:
e.melee_cd = ENEMY_MELEE_COOLDOWN
self.health -= ENEMY_MELEE_DAMAGE
self._set_msg("Clawed!")
if self.health <= 0:
self.state = "dead"
for f in list(self.fireballs):
f.x += f.dx * FIREBALL_SPEED
f.y += f.dy * FIREBALL_SPEED
f.z += f.dz * FIREBALL_SPEED
f.life -= 1
if f.life <= 0 or is_wall(self.grid, f.x, f.z):
self.fireballs.remove(f)
continue
if math.dist((f.x, f.y, f.z), (self.px, self.py, self.pz)) < FIREBALL_HIT_RADIUS:
self.fireballs.remove(f)
self.health -= FIREBALL_DAMAGE
self._set_msg("Fireball hit!")
if self.health <= 0:
self.state = "dead"
self.fx_lines = [f for f in self.fx_lines if f[6] > 0]
for f in self.fx_lines:
f[6] -= 1
# --------------------------------------------------------------- draw
def _safe_addstr(self, y, x, text, attr=0):
max_y, max_x = self.stdscr.getmaxyx()
if y < 0 or y >= max_y or x >= max_x or x < 0:
return
text = text[:max(0, max_x - x - 1)]
if not text:
return
try:
self.stdscr.addstr(y, x, text, attr)
except curses.error:
pass
def _safe_addch(self, y, x, ch, attr=0):
max_y, max_x = self.stdscr.getmaxyx()
if 0 <= y < max_y and 0 <= x < max_x - 1:
try:
self.stdscr.addch(y, x, ch, attr)
except curses.error:
pass
def draw(self):
self.stdscr.erase()
max_y, max_x = self.stdscr.getmaxyx()
if max_y < 20 or max_x < 60:
self._safe_addstr(0, 0, f"Terminal too small ({max_x}x{max_y}). Need at least 60x20.")
self.stdscr.refresh()
return
if self.state == "title":
self._draw_title(max_x, max_y)
elif self.state == "dead":
self._draw_playing(max_x, max_y)
self._draw_banner(max_x, max_y, "YOU DIED", CP_DANGER)
elif self.state == "win":
self._draw_playing(max_x, max_y)
self._draw_banner(max_x, max_y, "ALL ENEMIES DESTROYED", CP_HUD)
else:
self._draw_playing(max_x, max_y)
self.stdscr.refresh()
def _draw_title(self, max_x, max_y):
lines = [
"W I R E F R A M E D O O M",
"",
"A wireframe FPS built on leet.py's flight-mode 3D engine.",
"",
"W/A/S/D move Left/Right turn Up/Down look Space fire",
"Q / Esc quit",
"",
"Press any key to drop into the maze.",
]
y0 = max(1, max_y // 2 - len(lines) // 2)
for i, line in enumerate(lines):
x0 = max(0, (max_x - len(line)) // 2)
self._safe_addstr(y0 + i, x0, line, curses.color_pair(CP_HUD) | curses.A_BOLD)
def _draw_banner(self, max_x, max_y, text, pair):
y0 = max_y // 2
x0 = max(0, (max_x - len(text) - 4) // 2)
self._safe_addstr(y0, x0, f" {text} ", curses.color_pair(pair) | curses.A_REVERSE | curses.A_BOLD)
sub = "Press any key to try again, Q to quit."
self._safe_addstr(y0 + 2, max(0, (max_x - len(sub)) // 2), sub, curses.color_pair(CP_HUD))
def _draw_playing(self, max_x, max_y):
top_h, bot_h = 1, 3
view_w, view_h = max_x, max_y - top_h - bot_h
cx, cy = view_w // 2, top_h + view_h // 2
fwd, up, right = self._look_basis()
flat_fwd, flat_up, flat_right = self._ground_basis()
ppos = (self.px, self.py, self.pz)
def to_view(wp):
rel = v_sub(wp, ppos)
return (v_dot(rel, right), v_dot(rel, up), v_dot(rel, fwd))
def project(lp):
sx = lp[0] / lp[2] * PROJ_SCALE_X
sy = -lp[1] / lp[2] * PROJ_SCALE_Y
return cx + int(round(sx)), cy + int(round(sy))
def draw_point(wp, ch, attr):
lp = to_view(wp)
if lp[2] < NEAR_PLANE or lp[2] > VIEW_RANGE:
return
gx, gy = project(lp)
if 0 <= gx < view_w and top_h <= gy < top_h + view_h:
self._safe_addch(gy, gx, ch, attr)
def draw_edge(p0w, p1w, attr, ch=None):
clipped = clip_near(to_view(p0w), to_view(p1w), NEAR_PLANE)
if not clipped:
return
ax, ay = project(clipped[0])
bx, by = project(clipped[1])
dx, dy = bx - ax, by - ay
steps = max(abs(dx), abs(dy), 1)
if steps > 4000:
return
if ch is None:
if abs(dx) > abs(dy) * 2:
c = '-'
elif abs(dy) > abs(dx) * 2:
c = '|'
elif (dx > 0) == (dy > 0):
c = '\\'
else:
c = '/'
else:
c = ch
for i in range(steps + 1):
t = i / steps
gx = int(round(ax + dx * t))
gy = int(round(ay + dy * t))
if 0 <= gx < view_w and top_h <= gy < top_h + view_h:
self._safe_addch(gy, gx, c, attr)
for p in self.floor_points:
draw_point(p, '.', curses.A_DIM | curses.color_pair(CP_FLOOR))
for v0, v1, v2, v3 in self.wall_faces:
if math.dist((self.px, self.pz), ((v0[0] + v2[0]) / 2, (v0[2] + v2[2]) / 2)) > VIEW_RANGE:
continue
attr = curses.color_pair(CP_WALL)
draw_edge(v0, v1, attr)
draw_edge(v1, v2, attr)
draw_edge(v2, v3, attr)
draw_edge(v3, v0, attr)
for f in self.fireballs:
attr = curses.color_pair(CP_FIRE) | curses.A_BOLD
tail = (f.x - f.dx * 14, f.y - f.dy * 14, f.z - f.dz * 14)
draw_edge(tail, (f.x, f.y, f.z), attr)
draw_point((f.x, f.y, f.z), '*', attr)
for e in self.enemies:
if not e.alive:
continue
if math.dist((self.px, self.pz), (e.x, e.z)) >= VIEW_RANGE:
continue
attr = curses.color_pair(CP_ENEMY) | (curses.A_BOLD if e.hit_flash else 0)
if e.hit_flash:
attr |= curses.A_REVERSE
def world_vert(local, e=e):
lx, ly = local
return (e.x + flat_right[0] * lx, ly, e.z + flat_right[2] * lx)
for i0, i1 in IMP_MODEL["edges"]:
draw_edge(world_vert(IMP_MODEL["verts"][i0]), world_vert(IMP_MODEL["verts"][i1]), attr)
for fx in self.fx_lines:
x1, y1, z1, x2, y2, z2, ttl = fx
attr = curses.color_pair(CP_HUD) | (curses.A_BOLD if ttl > FX_TICKS // 2 else 0)
draw_edge((x1, y1, z1), (x2, y2, z2), attr)
self._safe_addch(cy, cx, '+', curses.color_pair(CP_HUD) | curses.A_BOLD)
alive = sum(1 for e in self.enemies if e.alive)
top = f"WIREFRAME DOOM HP:{max(0, int(self.health))}/{PLAYER_MAX_HEALTH} Enemies:{alive}/{len(self.enemies)} Kills:{self.kills}"
self._safe_addstr(0, 0, top, curses.color_pair(CP_HUD))
hint = "W/A/S/D:move Left/Right:turn Up/Down:look Space:fire Q:quit"
self._safe_addstr(top_h + view_h, 0, hint[:max_x], curses.color_pair(CP_HUD))
if self.msg_ttl > 0:
self._safe_addstr(top_h + view_h + 1, 0, self.msg[:max_x], curses.color_pair(CP_DANGER))
# --------------------------------------------------------------------------
# Entry point
# --------------------------------------------------------------------------
def main(stdscr):
curses.curs_set(0)
stdscr.keypad(True)
stdscr.timeout(TICK_MS)
curses.start_color()
curses.use_default_colors()
curses.init_pair(CP_WALL, curses.COLOR_CYAN, -1)
curses.init_pair(CP_FLOOR, curses.COLOR_WHITE, -1)
curses.init_pair(CP_ENEMY, curses.COLOR_RED, -1)
curses.init_pair(CP_HUD, curses.COLOR_GREEN, -1)
curses.init_pair(CP_DANGER, curses.COLOR_RED, -1)
curses.init_pair(CP_FIRE, curses.COLOR_YELLOW, -1)
game = Game(stdscr)
while game.state != "quit":
game.tick_once()
if __name__ == "__main__":
curses.wrapper(main)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment