🎡 Fair Game, Episode 3

The trick behind every old first-person game: one ray for each column of the screen, a short walk across the grid, and a strip that is tall when the wall is near. Flat colours for now.

Video: Fair Game, Episode 3 (Fair Game video)
Prefer to watch? This short video runs this page's main commands on a real Ubuntu 24.04 desktop, with on-screen captions and a synthetic voiceover (an AI voice trained on the author's own recording). Click to play, or watch it on YouTube.
Episode 3 ends with this: the window shows the inside of the fairground in first person. The sky at the top, the ground at the bottom, and walls in perspective: the corridor runs away from you towards the ticket gate, with the walls getting shorter and darker the further they are. You walk with the arrow keys and turn with left and right. Tab shows the map from above in the corner.

You will need: your project from episode 2, or the starter files below.
You will make: a cast function that finds where a ray hits a wall, and a render_walls function that draws a strip for each ray.
You will learn: the digital differential analyser (DDA), a grid walk that is the heart of every raycaster, the camera plane, why you use the perpendicular distance, and how a distance becomes a height.
Starter files: fair-game-ep02.zip is where this episode begins, fair-game-ep03.zip is where it ends.

The code of each step was run headless on Python 3.12 with pygame 2.5, and what it does is described below.

The idea

Imagine standing in the map and looking along your angle. The screen is 1280 pixels wide. For each of 320 vertical slices of the screen (each 4 pixels wide) we send one ray out of Pip's eyes, spread across his field of view, from the far left of the view to the far right. Each ray travels across the map until it enters a wall tile. If we know how far it travelled we know how big that wall looks:

  near wall  ->  a tall strip
  far wall   ->  a short strip

Draw one strip for each ray, side by side, and the strips make a picture of the walls in perspective. Nothing is 3D: it is a flat map, a number for each ray and a rectangle for each number. The method was used by the first games of this kind, on computers a thousand times slower than yours.

Two things need explaining: how a ray finds its wall quickly, and how the rays are spread over the screen.

Walking a ray across the grid

A ray from (px, py) in the direction (dx, dy) crosses vertical grid lines (x = 1, 2, 3 ...) and horizontal ones (y = 1, 2, 3 ...). A wall can only be entered by crossing a line, so we do not need to test every point along the ray. We need only to visit the lines it crosses, in order, and ask each time: is the tile I have just entered a wall?

Two numbers per direction drive the walk:

  ddx = 1 / |dx|    how far along the ray you go to move one tile in x
  ddy = 1 / |dy|    the same for y

and two running totals, side_x and side_y: how far along the ray we are when it will cross the next vertical line, and the next horizontal one. At each step, the smaller of the two is the next line the ray reaches. We take that step: add ddx or ddy to the total and move one tile in that direction. Then we test the tile. When we find a wall, the total of the side we did NOT just add to is the distance at which the ray entered the tile. We keep going until we hit one, which is why the map has a thick fence all round: a ray always finds a wall in the end.

That is the DDA. It takes at most a few dozen steps for even a long corridor, so 320 of them every frame is easy.

The camera plane

How are the rays spread over the screen? Pip has a direction vector (dx, dy) of length 1 pointing the way he looks. Next to it is the camera plane: a vector at right angles to it, of length 0.66. The screen is a flat window in front of Pip's eyes, and the plane is half its width. The ray for column 0 goes through the left edge of the window, and the ray for the last column goes through the right:

  ray = direction + plane * camera        camera goes from -1 (left) to +1 (right)

The 0.66 gives a field of view of about 67 degrees, which looks natural. A bigger number is a wider view and more distortion at the edges (that is FOV in the constants). Why a plane and not just a fan of angles? Because the window is flat. Angles would be bent, and walls at the edges would look curved like in a fisheye lens.

The same flat window gives us the right distance. If you measured the length of each ray you would get small numbers in the middle and big numbers at the edges for the same flat wall, so the wall would bend. What we want is the distance from the plane of the window, the perpendicular distance, and the DDA delivers exactly that: side_x - ddx and side_y - ddy are measured along the ray direction scaled the way this ray is, which works out to the perpendicular distance. A flat wall in front of you makes a flat line of strips, and there is no correction step to write.

Step 1: walls in 3D

Make these changes to game.py:

Add this after line 38 of your file (SOLID = "F#SNWcd"   # tiles we cannot walk through)

WALLS = "F#SNW"   # tiles a ray stops at (the stands are pictures, not walls)

- - -

Add this after line 40 of your file (SPEED, TURN, RADIUS = 3.0, 2.4, 0.25)

FOV = 0.66
RAYS = 320
COLW = WIDTH // RAYS

- - -

Add this after line 84 of your file (self.try_move(math.cos(self.angle) * walk * SPEED * dt, math.sin(self.angle) * walk * SPEED * dt))

def cast(px, py, dx, dy):
    """Walk a ray across the grid one tile edge at a time until it hits a wall.
    Returns (distance, side, wall character, how far along the wall it hit, 0 to 1)."""
    mx, my = int(px), int(py)
    ddx = abs(1 / dx) if dx else 1e30   # distance the ray travels to cross one tile in x, and in y
    ddy = abs(1 / dy) if dy else 1e30
    step_x, side_x = (-1, (px - mx) * ddx) if dx < 0 else (1, (mx + 1 - px) * ddx)
    step_y, side_y = (-1, (py - my) * ddy) if dy < 0 else (1, (my + 1 - py) * ddy)
    while True:
        if side_x < side_y:
            side_x += ddx
            mx += step_x
            side = 0
        else:
            side_y += ddy
            my += step_y
            side = 1
        if MAP[my][mx] in WALLS:
            break
    dist = side_x - ddx if side == 0 else side_y - ddy
    hit = (py + dist * dy) if side == 0 else (px + dist * dx)
    return max(dist, 0.05), side, MAP[my][mx], hit - math.floor(hit)


def render_walls(screen, player):
    """One vertical strip per ray: the nearer the wall, the taller the strip. Flat colours for now."""
    screen.fill((30, 24, 70), (0, 0, WIDTH, HEIGHT // 2))
    screen.fill((200, 160, 110), (0, HEIGHT // 2, WIDTH, HEIGHT // 2))
    dx, dy = math.cos(player.angle), math.sin(player.angle)
    plane_x, plane_y = -dy * FOV, dx * FOV   # the camera plane: sideways across the view
    for col in range(RAYS):
        camera = 2 * col / RAYS - 1
        dist, side, ch, hit = cast(player.x, player.y, dx + plane_x * camera, dy + plane_y * camera)
        height = int(HEIGHT / dist)
        shade = max(0.25, min(1.0, 1.6 / (1 + dist * 0.25))) * (0.75 if side else 1.0)
        color = tuple(int(c * shade) for c in WALL_COLORS[ch])
        screen.fill(color, (col * COLW, (HEIGHT - height) // 2, COLW, height))


def draw_panel(screen, rect):
    panel = pygame.Surface(rect[2:], pygame.SRCALPHA)
    pygame.draw.rect(panel, (20, 20, 40, 170), panel.get_rect(), border_radius=14)
    screen.blit(panel, rect[:2])

- - -

Add this after line 90 of your file (player = Player())

    show_map = False

- - -

Add this after line 98 of your file (running = False)

            elif event.type == pygame.KEYDOWN and event.key == pygame.K_TAB:
                show_map = not show_map

- - -

Replace lines 100-103

        screen.fill((20, 30, 25))
        draw_map(screen, 36)
        pygame.draw.circle(screen, (255, 255, 255), (int(player.x * 36), int(player.y * 36)), 8)
        pygame.draw.line(screen, (255, 255, 255), (player.x * 36, player.y * 36), (player.x * 36 + math.cos(player.angle) * 30, player.y * 36 + math.sin(player.angle) * 30), 3)

with

        render_walls(screen, player)
        if show_map:
            draw_panel(screen, (10, 10, MAP_W * 10 + 20, MAP_H * 10 + 20))
            draw_map(screen, 10, 20, 20)
            pygame.draw.circle(screen, (255, 255, 255), (20 + int(player.x * 10), 20 + int(player.y * 10)), 4)

What is new:

WALLS                       the characters a ray stops at. The stands are not in it: they are going to be pictures standing on the ground (episode 5), so a ray goes through their tile. You still cannot walk into them, because SOLID has them
FOV                         0.66, the length of the camera plane
RAYS, COLW                  320 rays, each drawing a strip 4 pixels wide (1280 / 320)
cast(px, py, dx, dy)        the DDA. It returns four things: the distance, which side of the tile was hit (0 for a wall that faces left or right, 1 for up or down), the map character of the wall, and how far along that wall the ray hit, between 0 and 1. We use the last two in the next episode
the loop in cast            side_x < side_y picks the nearer line; step_x and step_y are -1 or +1 depending on which way the ray goes
render_walls                paints the sky and the ground as two big rectangles, then makes the strips. plane_x, plane_y is the camera plane: the direction turned a quarter turn, times FOV
camera = 2 * col / RAYS - 1 the spread from -1 to +1
height = int(HEIGHT / dist) a wall one tile away fills the screen (720 pixels), two tiles away it fills half, and so on. HEIGHT / distance is all the perspective there is
shade                       1.6 / (1 + dist * 0.25) makes far walls darker, clamped between 0.25 and 1. Walls that face up or down get 0.75 of that, so you can see a corner
screen.fill(color, rect)    a one-line rectangle: a 4-pixel-wide strip centred on the middle of the screen
show_map, Tab               a flag toggled by the Tab key. When on, a small copy of the map and a white dot for Pip are drawn on top of the 3D view, with the same draw_map as episode 1, at 10 pixels a tile instead of 36. It is a handy view while you are lost in the alleys

Run it:

(.venv) $ python game.py

The window shows the sky, a ground and, straight ahead, a long corridor of teal walls going to a dark gold square far away: the ticket gate. The walls get darker as they get further away. Walk to a corner and the side wall is darker than the front wall. Press Tab: the map appears in the corner with a white dot where you are. (Checked: it ran for 120 frames with the up key held and closed normally, exit status 0.)
Fair Game episode 3 running
Episode 3 running (a screenshot of the finished step).

Things to try

Three changes before episode 4:

1  Change RAYS to 160. COLW becomes 8 and the picture is chunkier but it runs faster. What about 640? COLW is 2, and it is smoother but slower.
2  Change FOV to 1.2 and then to 0.3. One looks like a fish-eye camera and the other like binoculars.
3  Change the shade line so there is no distance darkening at all. Why is the picture much harder to read?

Check your work

If something is different:

ZeroDivisionError                         a ray with dx or dy exactly 0 divides by zero: check the (1 / dx) if dx else 1e30 lines
KeyError: 'c'                             WALLS does not exclude the stands: a ray stopped at a stand and found no colour for it
the walls bend at the edges               the distance is measured along the ray instead of the perpendicular distance: use side_x - ddx and side_y - ddy as written
everything is one dark colour             the shade has gone below zero, or the distance is huge: check the clamp
the picture is mirrored                   plane_x, plane_y has the wrong sign: left and right swap

Not run in the lab: a window bigger than 1280 x 720 (the numbers are constants, but some of the drawing assumes the 4-pixel strips) and a raycaster in a language other than Python.