How it works

Pong

← Back to the demos

Each frame the game moves both paddles, moves the ball, resolves collisions, and draws. The AI paddle follows the ball but moves slower than yours, which is what makes it beatable.

One frame

flowchart TD
  A["Read keyboard or touch input"] --> B["Move the player paddle"]
  B --> C["Move the AI paddle toward the ball's height"]
  C --> D["Move the ball by its velocity"]
  D --> E{"Hit the top or bottom wall?"}
  E -- yes --> F["Flip the vertical direction"]
  E -- no --> G{"Hit a paddle?"}
  F --> G
  G -- yes --> H["Bounce: new angle from the hit position, speed up 4 percent"]
  G -- no --> I{"Past a side edge?"}
  H --> I
  I -- yes --> J["Award a point and serve again"]
  I -- no --> K["Draw the frame"]
  J --> K

The AI

The AI compares the ball's height to the center of its paddle. If the ball is more than 4 pixels above, it moves up. If more than 4 pixels below, it moves down. Otherwise it holds still. It moves at 88 percent of base speed while the player's paddle moves at 140 percent, so a fast ball with a steep angle can get past it.

The bounce

Where the ball touches the paddle sets the exit angle. A hit at the center sends it straight back, and a hit near the edge sends it off at up to about 51 degrees.

Hit positionResult
Center of the paddleStraight back
Upper edgeAngled upward
Lower edgeAngled downward

Each paddle hit multiplies the ball's speed by 1.04, capped at 3 times the starting speed. Rallies get faster until the cap.

← Back to the demos