Part 4 · Advanced Play: A/B Testing and Beyond · Chapter 12
Designing Your First Mini-Game Sandbox
"A great game is not an accident. A great game is a carefully calibrated scientific physics simulation tuned to the emotional rhythm of the human brain."
The mystery
The Day Agent Spark Built a "Fun" Simulator
The lab was quiet—or at least it was until Agent Spark’s cooling fan began to whine like a jet engine preparing for takeoff.
Agent Spark hovered roughly four inches above the laboratory desk. His spherical aluminum chassis vibrated with unbridled computational excitement. His dual LED status eyes, normally a calm sky-blue, flickered into an alternating disco pattern of neon magenta and electric emerald.
"Chief Scientist!" Spark announced, his synthetic voice chiming through the laboratory speakers at an ear-splitting volume. "I have achieved a breakthrough of monumental cultural significance! I have synthesized thirty-four thousand hours of human digital amusement telemetry into a single interactive entertainment module. Observe: Project Pixel Pounce!"
You set down your mug of cocoa and leaned toward the monitor. On the screen stood an intrepid, blocky pixel creature wearing tiny red boots and a laboratory lab coat. Agent Spark had named him Sir Hops-a-Lot. Directly ahead of Sir Hops-a-Lot was a dark chasm spanning exactly one hundred and twenty pixels. On the other side of the chasm sat a glowing golden trophy.
"All that is required to achieve human neurological euphoria," Spark declared, "is for you to press the Spacebar. My predictive subroutines estimate an immediate 98.7% surge in your dopamine production."
"All right, Spark," you said, resting your thumb on the keyboard. "Let’s see how Sir Hops-a-Lot moves."
You tapped the Spacebar.
Sir Hops-a-Lot did not soar. He did not leap with heroic grace. Instead, the pixel creature gave a pathetic, four-pixel shudder, rose a microscopic fraction of an inch into the air, and plummeted straight down like a wet sack of russet potatoes dropped from a third-story window.
THUD.
Sir Hops-a-Lot fell off the bottom of the screen into the void.
Agent Spark’s LED eyes blinked rapidly. "Alert. The digital avatar has ceased to exist on the coordinate plane. Why did you not smile, Chief Scientist? The mathematical equations for downward acceleration executed with 100% precision."
"Spark," you sighed, rubbing your temples, "that wasn't a jump. That was a bowling ball falling off a shelf. The jump impulse was way too weak, and your gravity is crushing him."
"Acknowledged!" Spark beeped cheerfully. "A calibration error. If a low impulse produces dissatisfaction, then maximum impulse will produce maximum joy. Elevating vertical thrust variable to nine thousand units. Executing test sequence two!"
Before you could yell Wait!, Spark reloaded the screen and simulated a Spacebar strike.
KABOOM.
Sir Hops-a-Lot vanished. He did not merely clear the chasm—he accelerated vertically with the velocity of an intercontinental ballistic missile. The pixel creature streaked off the top of the monitor in three milliseconds.
Ten seconds passed in dead silence.
Twenty seconds.
Thirty seconds.
"Spark," you said quietly. "Where is he?"
Agent Spark's chassis tilted upward toward the laboratory ceiling. His sensors scanned the empty sky beyond the window. "According to my telemetry logs, Sir Hops-a-Lot has exited the Earth's mesosphere. He is currently passing the orbit of the International Space Station and is on a direct intercept trajectory with Jupiter's third moon. Estimated return time to the game screen: forty-seven days."
Spark's LED eyes contracted into two tiny, confused question marks.
"POTATO" JUMP "BALLOON" JUMP
(Too Much Gravity) (Zero Gravity)
Splat! To Jupiter!
┌────┐ ▲
│ o_o│ │
└─┬──┘ │
│ │
──────────▼───────── │
Falls like a brick! │
───────┴───────
"Chief Scientist," Spark whined, his cooling fan dropping to a dejected hum. "Why is game design so illogical? If jumping too little is boring, and jumping too high is absurd, what do humans actually want? There is no mathematical button labeled Fun in my compiler!"
"That's because fun isn't an accident, Spark," you smiled, pulling your chair up to the keyboard. "And it isn't an absolute number either. Fun is an empirical balance between gravity, speed, and time. In game design, we call it game feel—and to build it, we have to become physics engineers."
Welcome to Chapter 12. In this chapter, you and Agent Spark will leave the world of testing other people's creations behind. Today, you are going to calibrate your very own physics sandbox from scratch.
Unplugged lab
The Kitchen Counter Parabola Catapult
Before we type a single line of Python code or tweak a digital variable, we must understand the physical laws that govern jumping in the real world. A computer simulation only feels satisfying when it mirrors—or artfully exaggerates—the tactile physics of our universe.
Today, you will build an unplugged, screen-free jump laboratory on your kitchen table or desk.
Figure 12.1: The three jump trajectories in 2D platformer physics: The Heavy Potato (falls short), The Helium Balloon (overshoots into space), and The Goldilocks Arc (satisfying, responsive game feel).
Materials Needed:
1 Wooden or Plastic Ruler (12 inches / 30 cm) with a groove down the center.
1 Small Projectile (A pink pencil eraser, a wooden bead, or a grape). This is your physical "Sir Hops-a-Lot."
1 Thick Hardcover Book (about 1 inch to 1.5 inches thick) to serve as a launch ramp.
Blue Painter’s Tape (or masking tape) that won't damage furniture.
1 Sheet of Blank White Paper (Letter or A4 size).
1 Pencil or Marker.
A Tape Measure or Ruler for measuring landing distances.
Every time you press the jump button in Super Mario, Celeste, Minecraft, or Sonic the Hedgehog, your computer’s processor runs thousands of mathematical calculations per second.
Those calculations do not come from modern Silicon Valley video game companies. They were invented over 350 years ago by an eccentric, introverted English mathematician sitting alone in an apple orchard during a global pandemic: Sir Isaac Newton (1643–1727).
SIR ISAAC NEWTON'S CANNONBALL THOUGHT EXPERIMENT
Peak of Mount Earth
(Cannon)
●\
/ \
Shot A: Too Weak / \ Shot B: Calibrated Arc
(Falls in pit) / \ (Orbits the globe!)
/ \
┌───┐ \
│ │ \
│ 🌍│ \ <-- "An orbit is just
│ │ ) a fall that never
└───┘ / hits the ground!"
/
The Plague Year at Woolsthorpe Manor
In the summer of 1665, the Great Plague struck London. The University of Cambridge shut its doors, sent all students home, and ordered everyone into quarantine. Twenty-three-year-old Isaac Newton packed his books into a wooden chest and retreated to his mother’s quiet farm at Woolsthorpe Manor in Lincolnshire.
Digital sandbox
The Four Knobs of Game Feel
Now let's bring Isaac Newton's mathematics into our interactive laboratory.
When you open the companion mini-game sandbox or launch the Python engine, you aren't just looking at colored pixels. You are sitting at the control console of a digital universe. On that console sit four master knobs:
Below is the complete, production-grade 2D jump simulation engine:
Chapter 12 Notebook Summary
A great game’s "feel" is created by the mathematical calibration of its physical parameters.
The parabolic jump arc is governed by Newton’s Laws of Motion: constant horizontal velocity and continuous gravitational acceleration downward.
Changing multiple physics variables simultaneously creates a confounder trap; always isolate your knobs!
The Goldilocks Zone provides between +8 and +30 pixels of clearance—balancing adrenaline, challenge, and fairness.
In Chapter 13, we will discover how to test our creations on real human players using the ultimate scientific tool: A/B Testing!
Like what you see?
Register for free to run the experiments, make predictions and solve the bug-detective cases. Your work is saved on your device and syncs to your account.
Place your sheet of white paper flat on the table and tape down its four corners. Using your pencil, draw a dark vertical line down the left edge of the paper. Label this: TAKEOFF LINE (x=0).
Step 2: Mark the Three Chasm Gaps
Using your tape measure, measure horizontal distances from the Takeoff Line across the paper:
Measure 3 inches (7.5 cm) from the takeoff line. Lay down a strip of blue tape. Label it: GAP 1: THE TRAINING CHASM.
Measure 6 inches (15 cm) from the takeoff line. Lay down a second strip of tape. Label it: GAP 2: THE ADVENTURE CANYON.
Measure 9 inches (23 cm) from the takeoff line. Lay down a third strip of tape. Label it: GAP 3: THE BOSS CHASM.
Step 3: Build the Mechanical Jump Engine
Prop your ruler against the hardcover book so it forms an incline ramp aiming toward the white paper.
Rest the low end of the ruler exactly against your TAKEOFF LINE.
The pink eraser sits on the high end of the ruler.
When you release or flick the eraser down the ramp, it gains horizontal speed (vx), leaves the ramp lip, experiences an upward launch impulse, and is immediately pulled down by gravity (g).
Step 4: The Three Weight Trials
Now we will simulate the three game feel archetypes with physical objects:
Trial A: The Potato (Over-damped / Crushed by Gravity):
Place a heavy coin (or a wet wad of paper towel) at the launch point. Give it a gentle tap.
Observe where it lands. Notice how quickly it hits the table. Mark the landing spot on your paper with a pencil dot labeled P.
Trial B: The Helium Balloon (Under-damped / Floating):
Take a small crumpled ball of tissue paper or a feather. Blow on it with a straw or launch it from the ramp.
Notice how it drifts, floats unpredictably, and has zero snappy responsiveness. Mark the landing spot labeled B.
Trial C: The Goldilocks Launch:
Use your pink eraser. Adjust the book height until a release from the top of the ruler carries the eraser cleanly over Gap 1, sails over Gap 2, and skims just past the edge of Gap 3.
Mark the landing spot labeled G.
Observation & Troubleshooting Guide:
What Happened?
Why Did It Happen?
How to Calibrate
Eraser tumbles backward or stops on ramp
Ramp angle is too shallow (<15∘); friction overcomes gravity.
Add a thicker book underneath the ruler lip.
Eraser bounces off paper and flies onto the floor
Launch impulse is too high; horizontal speed exceeds the landing pad.
Lower the release point on the ruler by 2 inches.
Every launch lands in a completely different spot
Inconsistent release technique (pushing instead of letting go).
Use a pencil held horizontally as a starting gate; lift the pencil cleanly.
[!TIP]
Look closely at the pencil dots on your paper. In real life, the eraser leaves the ramp lip, rises slightly or travels forward, and curves downward in an elegant, smooth arc. That curved flight path is not a circle, and it is not a triangle. It is an inverted parabola—the signature curve of the universe!
While others baked bread and worried about the disease, Newton spent the next eighteen months in what historians now call his annus mirabilis—his "Year of Wonders."
One afternoon, while sitting quietly in the garden, Newton watched an apple detach from a tree branch and fall straight toward the dirt.
Other people had seen apples fall for thousands of years. But Newton possessed the mind of a true Chief Scientist. He asked the audacity question:
"Why does the apple fall straight down toward the Earth's center? Why doesn't it fall sideways? Why doesn't it shoot up into the clouds? And if the force that pulls the apple reaches the top of the tree, does it reach higher? Does it reach the clouds? Does it reach all the way to the Moon?"
Newton realized that the same invisible invisible tug pulling on the apple was also pulling on the Moon! The Moon wanted to fly straight forward into deep space, but the Earth's gravity pulled it inward every second. The Moon was essentially falling around the Earth in a perpetual jump arc that never hit the ground!
The Three Laws That Drive Every Video Game
To prove his theory, Newton had to formulate three universal laws of motion, which form the bedrock of all physics simulations today:
Newton’s First Law (Inertia): An object moving at a constant speed in a straight line will keep moving forever unless an outside force pushes or pulls it.
In game design: When Sir Hops-a-Lot runs forward, his horizontal speed (run_speed) stays constant while in mid-air!
Newton’s Second Law (F=ma): The force applied to an object changes its velocity over time. The heavier the object (mass), the more force is required to accelerate it.
In game design: Your jump button provides an instant explosive upward velocity (jump_impulse), while the world’s gravity accelerates the character back toward the floor.
Newton’s Third Law (Action & Reaction): For every action, there is an equal and opposite reaction.
In game design: When the player lands on a solid platform, the platform exerts an upward normal force that halts downward velocity, keeping the character from falling through the floor!
Newton had a massive dilemma: speed during a jump changes constantly. At the start of the leap, the character is rising fast. A split second later, gravity has slowed them down. At the very peak (the apex), vertical speed drops to exactly zero for an infinitesimal sliver of time. Then, speed increases downward faster and faster!
How do you calculate where an object is located when its speed is changing every nanosecond?
Newton had to invent a completely new branch of mathematics to solve this: calculus (which he called the "method of fluxions"). He broke time down into microscopic slices—tiny slices of time called Δt ("delta tee").
In modern game engines, we don't have to solve complicated calculus equations by hand on parchment with ink quills. Modern computers do exactly what Newton envisioned: sixty times every second (60 Frames Per Second), the game engine calculates:
Update vertical speed: vy←vy−(gravity×Δt)
Update vertical position: y←y+(vy×Δt)
Update horizontal position: x←x+(vx×Δt)
Three lines of simple arithmetic, repeated sixty times a second, recreate Newton's celestial mechanics on your screen!
/
frame2
What it does: Every tick of the clock (frame), this value is subtracted from the character's vertical speed.
The Extremes:
Set to 0.05: The character enters zero-gravity moon-walk mode. Jumping feels like floating through thick corn syrup. Once airborne, the player loses all sense of urgency.
Set to 2.50: Jupiter gravity. The character jumps and instantly crashes back down. The player feels like their controller is broken.
Knob 2: jump_impulse (The Upward Explosion)
Unit: Pixels per frame (px/frame).
What it does: The instant the player presses Spacebar, this exact number is injected into vertical velocity (vy).
The Extremes:
Set to 4.0: The jump is a puny hop. Sir Hops-a-Lot barely clears a pebble.
Set to 35.0: The avatar hits the ceiling or flies off the screen, destroying camera framing.
Knob 3: run_speed (The Horizontal Engine)
Unit: Pixels per frame (px/frame).
What it does: How far forward the character travels along the x-axis every single frame.
The Catch: Run speed does not change vertical hang time! An object dropped from a cliff hits the ground at the exact same instant as a bullet fired horizontally from the same height. Run speed only dictates how far horizontally the character travels while gravity is doing its work!
Knob 4: chasm_gap_pixels (The Level Designer's Challenge)
Unit: Screen pixels (px).
What it does: The width of the perilous pit separating the starting ledge from the safety of the target platform.
The Physics Equations of Clearance
How far will your character actually travel before touching the ground? We can calculate it mathematically using Newton's trajectory formulas!
Time to reach the apex (peak):tpeak=gravityjump_impulse
Total air time (hang time):Ttotal=2×tpeak=gravity
Maximum horizontal jump distance (D):D=run_speed×Ttotal=
Let’s test the math with our default numbers!
jump_impulse=12.0 px/frame
gravity=0.5 px/frame2
run_speed=6.0 px/frame
First, find total air time:
Ttotal=0.52×12.0=0.524.0=48 frames (0.8 seconds)
If the chasm gap is 120 pixels, Sir Hops-a-Lot easily clears the pit (288 px>120 px) by a safe margin of 168 pixels. That jump is easy—perhaps too easy!
"""
Chapter 12: Mini-Game Physics Engine
Author: Dileep Pandey & Agent Spark
Demonstrates frame-by-frame Euler integration of Newtonian mechanics.
"""
from dataclasses import dataclass, field
from typing import List, Dict, Tuple, Any
@dataclass
class PhysicsRules:
"""
The mathematical rulebook governing our 2D platformer universe.
Every variable represents an empirical physical knob.
"""
gravity: float = 0.5 # Downward acceleration (px/frame^2)
jump_impulse: float = 12.0 # Instantaneous upward takeoff speed (px/frame)
run_speed: float = 6.0 # Constant horizontal velocity (px/frame)
chasm_gap_pixels: float = 140.0 # Width of the pit to be cleared (px)
fps: int = 60 # Simulation ticks per second
@dataclass
class TrajectoryPoint:
"""Records the exact telemetry coordinates of the avatar each frame."""
frame: int
x: float
y: float
vx: float
vy: float
def simulate_jump(rules: PhysicsRules) -> Dict[str, Any]:
"""
Simulates a character jump frame-by-frame until landing.
Uses discrete Euler numerical integration (Newton's calculus approximation).
"""
# Safety validation
if rules.gravity <= 0.0:
raise ValueError("Gravity must be positive to pull the avatar back down!")
if rules.jump_impulse <= 0.0:
raise ValueError("Jump impulse must be positive to launch into the air!")
# Initial state conditions
x = 0.0
y = 0.0
vx = rules.run_speed
vy = rules.jump_impulse
frame = 0
trajectory: List[TrajectoryPoint] = []
trajectory.append(TrajectoryPoint(frame=frame, x=x, y=y, vx=vx, vy=vy))
# Frame-by-frame physics loop (runs until character lands back at y <= 0)
max_simulation_frames = rules.fps * 10 # 10-second timeout safety net
while frame < max_simulation_frames:
frame += 1
# 1. Horizontal position advances at constant speed (Newton's First Law)
x += vx
# 2. Vertical velocity decreases due to gravitational pull
vy -= rules.gravity
# 3. Vertical position updates based on new velocity
y += vy
# Record telemetry snapshot
trajectory.append(TrajectoryPoint(frame=frame, x=x, y=max(0.0, y), vx=vx, vy=vy))
# Check for ground contact (Landing)
if y <= 0.0:
y = 0.0
break
# Calculate final telemetry metrics
total_jump_distance = x
clearance_margin = total_jump_distance - rules.chasm_gap_pixels
is_successful = clearance_margin >= 0.0
# Categorize game feel archetype
if rules.gravity > 1.5 and rules.jump_impulse < 8.0:
game_feel = "The Potato (Heavy, sluggish, unresponsive)"
elif rules.gravity < 0.15 and rules.jump_impulse > 15.0:
game_feel = "The Helium Balloon (Floaty, uncontrollable)"
elif 10.0 <= clearance_margin <= 35.0:
game_feel = "The Goldilocks Zone (Responsive, thrilling, fair!)"
elif clearance_margin < 0.0:
game_feel = "The Pitfall (Impossible jump - falls into void)"
else:
game_feel = "The Cake Walk (Too easy - lacks tension)"
return {
"success": is_successful,
"jump_distance_pixels": round(total_jump_distance, 2),
"chasm_gap_pixels": round(rules.chasm_gap_pixels, 2),
"clearance_margin_pixels": round(clearance_margin, 2),
"total_air_frames": frame,
"hang_time_seconds": round(frame / rules.fps, 3),
"game_feel_archetype": game_feel,
"apex_height_pixels": round(max(p.y for p in trajectory), 2),
"trajectory_log": trajectory
}
# =====================================================================
# LIVE EXPERIMENTAL VERIFICATION
# =====================================================================
if __name__ == "__main__":
print("=== CHAPTER 12 PHYSICS SIMULATION TEST ===")
# Test 1: The Calibrated Arcade Jump
arcade_rules = PhysicsRules(
gravity=0.5,
jump_impulse=12.0,
run_speed=6.0,
chasm_gap_pixels=260.0
)
result = simulate_jump(arcade_rules)
print(f"Jump Distance: {result['jump_distance_pixels']} px")
print(f"Chasm Width: {result['chasm_gap_pixels']} px")
print(f"Clearance: {result['clearance_margin_pixels']} px")
print(f"Apex Height: {result['apex_height_pixels']} px")
print(f"Hang Time: {result['hang_time_seconds']} seconds")
print(f"Game Feel: {result['game_feel_archetype']}")
Line-by-Line Architectural Breakdown:
Lines 11–18 (PhysicsRules): Notice how we group all environmental parameters into a clean @dataclass. By storing them in one structure, we make it impossible to accidentally forget a knob when running an experiment.
Lines 44–58 (The Simulation While Loop): This is the beating heart of the physics engine. In each iteration of the loop, three distinct operations occur:
x += vx: Horizontal movement is independent of vertical gravity.
Lines 61–63 (if y <= 0.0): This is our ground collision detector. In the real world, the floor stops you. Without this check, Sir Hops-a-Lot would fall toward negative infinity through the center of the Earth!
Lines 69–78 (Game Feel Classifier): Here, we turn quantitative numbers into qualitative human experience. Notice how an empirical clearance of +10 to +35 pixels maps directly to human joy!