PranavIndependent software & experiments GitHub
Back to rabbit holes
Systems / Engineering notes

Building Space Duel: 2D physics and game loops in Pygame

Revisiting a two-dimensional arcade shooter: delta-time tick loops, bounding-box collision detection, weapon cooldowns, and frame governance.

By Pranav4 min read
On this page

Space-Duel is a two-player arcade space game built with Pygame. No physics engine, no asset pipeline, no scene graph. Two ships, some bullets, and a game loop that runs until someone dies.

It was one of the earlier Python projects I actually finished — which is maybe the main reason I remember it. Games are good at producing visible feedback and clear failure. If the frame rate drops, you feel it. If collision detection is wrong, you see it. That immediate loop makes bugs easier to notice than in a lot of web work.

The game loop is the entire architecture

Pygame doesn't have an event system in the browser or server sense. It has a loop you write yourself.

python
clock = pygame.time.Clock()
FPS = 60

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    update_ships()
    update_bullets()
    check_collisions()

    screen.fill(BLACK)
    draw_everything(screen)
    pygame.display.flip()

    clock.tick(FPS)

clock.tick(60) blocks the loop long enough to hold sixty frames per second. Without it, the loop runs as fast as the CPU allows — ships cross the screen in a fraction of a second, physics calculations depend on the host machine's speed, and two players on different hardware play different games.

The structure is strictly sequential: read inputs, update state, draw. Nothing happens between frames that hasn't been explicitly scheduled.

Movement with momentum

A simple arcade game moves a ship in the direction a key is pressed. That works, but it feels weightless. Spaceships have inertia — they should keep moving when you stop pressing.

The solution is a velocity vector that thrust adds to rather than replaces:

text
Thrust key held
  -> acceleration = (cos(angle) * force, -sin(angle) * force)
  -> velocity += acceleration
  -> velocity *= 0.985  (slight drag)
  -> position += velocity

The 0.985 multiplier is not physically accurate. Pure vacuum would be 1.0 — ships would drift forever and quickly become impossible to control in a small arena. A little artificial drag keeps the game playable without making movement feel like a grid.

When a ship reaches the edge of the screen, it wraps to the opposite side rather than bouncing. The arena is a torus. Ships fly off the top and come back from the bottom, momentum intact.

The collision problem with rotated sprites

Pygame has a built-in collision check: rect.colliderect(other_rect). A Rect is an axis-aligned bounding box — four sides, all parallel to the screen edges.

That works fine until a ship rotates 45 degrees. The bounding box grows to fit the tilted sprite, and the empty corners of that box start registering as hits. A bullet that clearly misses the hull of a rotated ship can still trigger a collision because it clipped the corner of an invisible rectangle.

text
Actual sprite shape:         Bounding box that gets checked:
       /\                         +-----------+
      /  \                        |    /\     |
     /    \                       |   /  \    |
    /______\                      |  /____\   |
                                  +-----------+

The fix doesn't require polygon triangulation. Ships are roughly circular, so a radial distance check is close enough:

python
def check_radial_collision(ship, bullet):
    cx = ship.x + ship.width / 2
    cy = ship.y + ship.height / 2
    dx = cx - bullet.x
    dy = cy - bullet.y
    radius = (ship.width / 2) * 0.75
    return (dx * dx + dy * dy) <= (radius * radius)

The * 0.75 shrinks the effective radius so it stays inside the visible hull rather than covering the wingtips. Squaring both sides avoids math.sqrt, which is worth avoiding in anything that runs every frame.

Cooldowns and bullet cleanup

If you let bullets spawn every frame the spacebar is held, two things go wrong quickly. The screen fills with projectiles, and the entity list grows indefinitely because bullets keep going after they leave the screen.

Cooldowns are frame counters, not time-based sleeps:

python
class Weapon:
    def __init__(self, cooldown=12, max_bullets=6):
        self.cooldown = cooldown
        self.timer = 0
        self.bullets = []

    def update(self):
        if self.timer > 0:
            self.timer -= 1
        self.bullets = [b for b in self.bullets if b.alive]

    def fire(self, x, y, angle):
        if self.timer == 0 and len(self.bullets) < self.max_bullets:
            self.bullets.append(Bullet(x, y, angle))
            self.timer = self.cooldown

Twelve frames at 60 FPS is a 200ms delay between shots. That's tunable. Using a frame counter keeps the cooldown synchronized with the physics clock — time.sleep() would drift.

The list comprehension at the end of update removes dead bullets. It runs every frame, so the list never accumulates garbage.

Audio lag

One thing that surprised me was the sound delay. I added an explosion effect and it was noticeably late — the visible flash happened, then half a second later the sound played.

The default Pygame mixer buffer is 4096 samples. At 44,100 Hz, that's about 93ms of latency before any audio gets through. Enough to feel wrong.

Initializing the mixer with a smaller buffer before pygame.init() fixes it:

python
pygame.mixer.pre_init(frequency=44100, size=-16, channels=2, buffer=512)
pygame.init()

512 samples is about 11ms. Effects feel immediate.

Browse Space-Duel on GitHub.

Thanks for reading. Download Markdown
Keep following the thread