DEV Community

Cover image for Improving Pong! Calibrating the game AI across aspect ratios using Monte Carlo Simulations
Rodrigo Fuentealba Cartes
Rodrigo Fuentealba Cartes

Posted on Edited on AI-assisted

Improving Pong! Calibrating the game AI across aspect ratios using Monte Carlo Simulations

Designing a faithful Pong clone for modern devices looks deceptively simple on paper: two paddles, a ball, four boundaries, and basic reflection math. Yet the moment your game has to adapt fluidly across widely different screen geometries—such as 16:10, 16:9, and ultra-wide 2.22:1 mobile displays—a subtle physics and game-feel problem emerges.

If you scale ball speed proportionally to screen width, add multiplicative acceleration on every hit, and keep paddle movement grounded so touch controls feel deliberate rather than twitchy, how do you guarantee that a match feels equally fair and engaging on every device?

Instead of playtesting hundreds of rounds manually on every screen ratio, you can model the entire problem mathematically and solve it in seconds with a Monte Carlo simulation.

Why Aspect Ratios Break Naive Scaling

Suppose we set the vertical height of the playing field to H = 1.0, making the width equal to the screen's aspect ratio r = W / H (so r = 1.60 for 16:10, r = 1.78 for 16:9, and r = 2.22 for 2.22:1).

If you scale the ball's speed directly with the screen width (speed = base_speed * r), the horizontal crossing time between paddles stays the same for any given launch angle:

t_x = r / (base_speed * r * cos(angle)) = 1 / (base_speed * cos(angle))
Enter fullscreen mode Exit fullscreen mode

However, the vertical speed component grows with r while the vertical distance between the top and bottom walls stays fixed at 1.0:

v_y = base_speed * r * sin(angle)
Enter fullscreen mode Exit fullscreen mode

As a consequence, on a 2.22:1 screen compared to a 16:10 screen, the ball crosses the arena in the exact same amount of time—but bounces off the top and bottom walls nearly 39% more often. More wall bounces mean sharper trajectory reads per second and higher vertical travel demands on the paddle.

When you combine this geometric distortion with two additional mechanics—multiplicative ball acceleration per hit and direct touch control with a capped paddle speed—simple formulas are no longer enough to predict how full rallies behave.

Framing Pong as a Monte Carlo Experiment

A Monte Carlo simulation replaces manual trial-and-error with thousands of randomized, headless rallies. Rather than rendering frames at 60 FPS, we compute exact wall reflections analytically and evaluate whether a modeled player can reach the ball on each crossing.

1. Random Inputs (What Varies Each Rally)

  • Initial serve angle: Picked randomly within a range from -max_angle to +max_angle.

  • Touch positioning noise: On mobile devices, dragging a finger introduces human imprecision, modeled as small random offset error around the true interception point.

  • Return angle deflection: Determined by where the ball strikes the paddle face (center hits return flatter; edge hits create steeper angles), plus a small random jitter.

2. Fixed Rules (Your Game Physics)

  • Multiplicative speed escalation: After k successful hits, ball speed is:
speed(k) = base_speed * (r ^ alpha) * ((1 + g) ^ k)
Enter fullscreen mode Exit fullscreen mode

where g is the percentage gain per hit (for example, 0.04 for +4% per hit) and alpha controls how strongly base speed scales with screen width.

  • Capped paddle velocity: To preserve the classic, tactical feel of Pong on touchscreens without jittery teleportation, the paddle moves toward the target up to a maximum vertical speed (paddle_max_speed) during the crossing time t_x.

3. Output Metrics (What We Measure)

By running 10,000 simulated rallies per aspect ratio, we get clear distributions for:

  • Mean and median (P50) rally length in hits.

  • 90th percentile (P90) rally length, capturing how long intense exchanges last before speed overwhelms the paddle.

  • First-hit miss rate, ensuring the initial serve is never unfairly punishing on wider screens.

Headless Python Implementation

The following self-contained Python script runs 10,000 rallies per aspect ratio using only the standard library:

import math
import random
import statistics
from dataclasses import dataclass


@dataclass
class PongSimConfig:
    aspect_ratios: tuple[tuple[str, float], ...] = (
        ("16:10", 16 / 10),
        ("16:9", 16 / 9),
        ("2.22:1", 2.22),
    )
    n_rallies: int = 10_000
    max_hits: int = 500

    # Ball parameters (normalized to court height H = 1.0)
    base_speed: float = 0.65        # Initial speed in H/s
    width_scale_exp: float = 1.0    # 1.0 = linear width scaling; <1.0 dampens ultrawide
    accel_pct: float = 0.04         # +4% multiplicative speed increase per hit
    max_angle_deg: float = 55.0     # Maximum deflection angle from horizontal
    paddle_margin: float = 0.04     # Horizontal paddle inset as a fraction of width

    # Touch paddle parameters
    paddle_half_h: float = 0.09     # Half-height of paddle (total height = 0.18 H)
    paddle_max_speed: float = 1.15  # Maximum vertical paddle speed in H/s
    touch_error_std: float = 0.035  # Touch drag imprecision (std dev in H)
    seed: int = 42


def simulate_rally(cfg: PongSimConfig, ratio: float, rng: random.Random) -> tuple[int, float]:
    width = ratio
    height = 1.0
    span_x = width * (1.0 - 2.0 * cfg.paddle_margin)

    y = 0.5 * height
    paddle_y = 0.5 * height
    max_rad = math.radians(cfg.max_angle_deg)

    dir_x = 1.0 if rng.random() < 0.5 else -1.0
    angle = rng.uniform(-max_rad, max_rad)

    hits = 0
    elapsed = 0.0

    while hits < cfg.max_hits:
        speed = cfg.base_speed * (ratio ** cfg.width_scale_exp) * ((1.0 + cfg.accel_pct) ** hits)
        vx = dir_x * speed * math.cos(angle)
        vy = speed * math.sin(angle)

        t_cross = span_x / max(abs(vx), 1e-6)
        elapsed += t_cross

        # Exact vertical reflection across top (y = 1.0) and bottom (y = 0.0) boundaries
        raw_y = y + vy * t_cross
        period = 2.0 * height
        mod_y = raw_y % period
        target_y = mod_y if mod_y <= height else (period - mod_y)

        # Direct touch tracking with Gaussian finger error and capped speed
        perceived_y = target_y + rng.gauss(0.0, cfg.touch_error_std)
        perceived_y = max(cfg.paddle_half_h, min(height - cfg.paddle_half_h, perceived_y))

        max_step = cfg.paddle_max_speed * t_cross
        delta_y = perceived_y - paddle_y
        if abs(delta_y) > max_step:
            paddle_y += math.copysign(max_step, delta_y)
        else:
            paddle_y = perceived_y

        # Check paddle interception
        offset = target_y - paddle_y
        if abs(offset) <= cfg.paddle_half_h:
            hits += 1
            y = target_y
            dir_x *= -1.0
            norm_offset = offset / cfg.paddle_half_h
            angle = max(-max_rad, min(max_rad, norm_offset * max_rad + rng.uniform(-0.08, 0.08)))
        else:
            break

    return hits, elapsed


def run_simulation(cfg: PongSimConfig) -> None:
    rng = random.Random(cfg.seed)
    print(f"Monte Carlo Pong Benchmark | N={cfg.n_rallies} | accel=+{cfg.accel_pct*100:.1f}%/hit\n")
    print(f"{'Ratio':<8} | {'Mean Hits':>9} | {'P50 Hits':>8} | {'P90 Hits':>8} | {'Avg Time':>9} | {'1st-Hit Miss':>12}")
    print("-" * 68)

    for label, ratio in cfg.aspect_ratios:
        results = [simulate_rally(cfg, ratio, rng) for _ in range(cfg.n_rallies)]
        hits = sorted(r[0] for r in results)
        times = [r[1] for r in results]
        p90 = hits[int(0.90 * len(hits))]
        miss_rate = 100.0 * sum(1 for h in hits if h == 0) / len(hits)

        print(
            f"{label:<8} | {statistics.mean(hits):>9.2f} | {statistics.median(hits):>8.1f} | "
            f"{p90:>8d} | {statistics.mean(times):>8.2f}s | {miss_rate:>11.1f}%"
        )


if __name__ == "__main__":
    run_simulation(PongSimConfig())
Enter fullscreen mode Exit fullscreen mode

Turning Simulation Results into Game Balance

Once the benchmark runs, tuning the game shifts from guesswork to data-driven calibration:

  1. Equalizing Difficulty Across Screens: If 2.22:1 shows noticeably lower P50 and P90 hit counts than 16:10 due to extra vertical bounces, lowering width_scale_exp (alpha) from 1.0 to roughly 0.75–0.85 compensates for the extra vertical frequency while keeping ultra-wide gameplay fast and responsive.

  2. Finding the Sweet Spot for Multiplicative Acceleration: Adjusting accel_pct (g) lets you control the exact pacing curve. If P90 rallies exceed 30 hits, points drag on; if P50 drops below 3 hits, rallies end before tension builds.

  3. Separating Physics Limits from Input Error: Setting touch_error_std = 0 reveals the pure speed limit—the exact hit count where ball speed outpaces paddle_max_speed on steep angles—allowing you to tune paddle height and touch responsiveness independently.

By distilling your game loop into a fast analytical step function, Monte Carlo methods give indie and mobile developers a rigorous way to verify game feel across every screen ratio before shipping a single build.


How does it feel?

Majestic. After spending several hours working on this (instead of going with random trial and error values) the game feels really good on both phones and my tablet. Take this with a grain of salt though, as I'm not very good at playing videogames, but time will tell.


Can I play the game?

Not yet. I'm actually preparing it to be downloaded from the Google Play Store and Steam, but drop me a line if you are interested in it! And if you are interested in any other data science projects you want to discuss, I'm all eyes to read you too!


AI disclosure

I used some AI assistance for writing this article in English because it's not my native language. The whole idea was conceived in Spanish, translated into English and reviewed by AI with my approval.


About the Author

Hi! I'm Rodrigo Fuentealba Cartes, an entrepreneur, Bachelor of Engineering Sciences and Computer and Informatics Engineer. For more than two decades I've combined data analysis with software engineering to take projects from idea to production. Now I offer my services through a small company named Sea Dragon.

I'm also a chess player, musician, motorcyclist, amateur radio operator (license CA5NFS), and a low performance athlete.

You can find me around the web:

Top comments (0)