← AI & Me Studios

02 State, levels and landing

The game's memory: every variable, the constants that tune how it feels, the level generator, and the landing-zone scoring that pays PERFECT +500.

Code
// ---------- state ----------
const GRAV = 1750, THRUST = -540, MAXFALL = 880;
// Burn model (2026-10-31): a tap fires the bottom rockets for BURN_TIME.
// Governor burn (2026-10-31): the burn steers the ship toward one fixed
// climb speed, so every tap ends near -540 no matter how fast the ship
// was falling or rising when tapped.
const BURN_TIME = 0.15;
const SHIP_X = 108, SHIP_R = 15;
const GATE_W = 74, GATE_EVERY = 248;
const PAD_TOP = H - 30;
let state = 'ready'; // ready | playing | over | clear
let shipY, shipV, shipTilt;
let burnT = 0; // seconds of rocket burn left; 0 = rockets off
let gates, gateTimer, speed, score, best, frames;
let level = 1, bestLevel = 0, levelScore = 0, pad = null, overReason = '', clearBonus = 0, clearZone = '', courseX = 0;
try { bestLevel = parseInt(localStorage.getItem('glidepath-best-level') || localStorage.getItem('astrohop-best-level') || '0', 10) || 0; } catch (e) { bestLevel = 0; }
function saveBestLevel() { try { localStorage.setItem('glidepath-best-level', String(bestLevel)); } catch (e) {} }
let stars = [], rocks = [];
let parts = []; // exhaust particles from the bottom rockets
let flash = 0, shake = 0;
let muted = false;

try { best = parseInt(localStorage.getItem('glidepath-best') || localStorage.getItem('astrohop-best') || '0', 10) || 0; }
catch (e) { best = 0; }

function saveBest() {
  try { localStorage.setItem('glidepath-best', String(best)); } catch (e) {}
}

// Starfield: 3 parallax layers.
function makeStars() {
  stars = [];
  for (let i = 0; i < 90; i++) {
    const layer = i < 45 ? 0 : (i < 75 ? 1 : 2);
    stars.push({
      x: Math.random() * W, y: Math.random() * H,
      r: layer === 0 ? 1 : (layer === 1 ? 1.6 : 2.4),
      sp: [14, 30, 55][layer],
      tw: Math.random() * Math.PI * 2
    });
  }
  // A couple of distant planets for depth.
  rocks = [
    { x: 350, y: 90, r: 26, hue: '#3b5bdb', ring: true },
    { x: 90, y: 520, r: 16, hue: '#7048e8', ring: false }
  ];
}
makeStars();

function courseLen() { return 1500 + (level - 1) * 700; }
function padWidth() { return Math.max(70, 112 - (level - 1) * 6); }
function gapFor() { return Math.max(134, 176 - (level - 1) * 6 - Math.floor(levelScore / 4) * 3); }

function reset() {
  shipY = H * 0.45; shipV = 0; shipTilt = 0;
  burnT = 0; parts = [];
  gates = []; gateTimer = 0; speed = Math.min(280, 178 + (level - 1) * 10); frames = 0;
  flash = 0; shake = 0;
  levelScore = 0; overReason = ''; clearBonus = 0; clearZone = ''; courseX = 0;
  // Pre-generate the whole level: gates in course coordinates, then the pad.
  let cx = W + 160;
  const len = courseLen();
  while (cx < len) {
    const gap = gapFor();
    const margin = 70;
    const cy = margin + gap / 2 + Math.random() * (H - margin * 2 - gap);
    gates.push({ cx: cx, cy: cy, gap: gap, passed: false, seed: Math.random() * 1000 });
    cx += GATE_EVERY;
  }
  pad = { cx: len + 240, w: padWidth() };
}

function startGame() {
  level = 1; score = 0;
  reset();
  state = 'playing';
}

function nextLevel() {
  level++;
  reset();
  state = 'playing';
}

function gameOver(reason) {
  state = 'over';
  overReason = reason || 'CRASHED!';
  flash = 14; shake = 10;
  if (score > best) { best = score; saveBest(); }
  sfx('crash');
}

function landPad() {
  const landV = shipV;
  state = 'clear';
  overAt = performance.now();
  shipY = PAD_TOP - SHIP_R; shipV = 0;
  // Point zones: judged by where the ship's center touches down, as a
  // fraction of the pad width from its center. Center third = PERFECT,
  // next bands = GREAT, outer edges = GOOD. Zones only add bonus —
  // any safe landing still clears the level.
  const padX = pad.cx - courseX;
  const d = Math.abs(SHIP_X - (padX + pad.w / 2)) / pad.w;
  let zoneBonus = 100; clearZone = 'GOOD';
  if (d <= 1 / 6) { zoneBonus = 500; clearZone = 'PERFECT'; }
  else if (d <= 1 / 3) { zoneBonus = 250; clearZone = 'GREAT'; }
  clearBonus = 100 + Math.max(0, Math.round((660 - landV) / 2)) + zoneBonus;
  score += clearBonus;
  if (score > best) { best = score; saveBest(); }
  if (level > bestLevel) { bestLevel = level; saveBestLevel(); }
  sfx('score');
}
What it does

This file holds the game's memory: every variable that describes what's happening right now, the constants that tune how it feels, the level generator, and the two big moments — crashing and landing.

THE PHYSICS CONSTANTS

    const GRAV = 1750, THRUST = -540, MAXFALL = 880;
    const BURN_TIME = 0.15;
    const SHIP_X = 108, SHIP_R = 15;
    const GATE_W = 74, GATE_EVERY = 248;
    const PAD_TOP = H - 30;
  • GRAV = 1750: gravity pulls the ship down at 1750 pixels per second squared. Bigger number = falls faster, feels heavier.
  • THRUST = -540: the climb speed a burn is supposed to end at. (It's a reference value — the governor burn in file 05 actually targets -665 so gravity drags it to about -540 by the end of the burn.)
  • MAXFALL = 880: terminal velocity. The ship can never fall faster than this, no matter how long it drops.
  • BURN_TIME = 0.15: each tap fires the rockets for 0.15 seconds.
  • SHIP_X = 108: the ship's horizontal position. It NEVER changes — the ship doesn't fly left or right, the world scrolls past it.
  • SHIP_R = 15: the ship's collision radius. The ship is treated as a circle of radius 15 for all collision checks.
  • GATE_W = 74: how wide each gate slab is.
  • GATE_EVERY = 248: the horizontal distance between one gate and the next.
  • PAD_TOP = H - 30 = 610: the y-coordinate of the top of the landing pad, 30 pixels above the bottom of the screen.

THE STATE VARIABLE

    let state = 'ready'; // ready | playing | over | clear

One word describes the whole game at any moment:

  • 'ready': title screen, waiting for the first tap.
  • 'playing': the run is live.
  • 'over': you crashed (or missed the pad).
  • 'clear': you landed and cleared the level.

Almost every function checks state before it does anything. That's how the game knows whether a tap should start a run, fire the rockets, or restart after a crash.

THE SHIP'S VARIABLES

  • shipY: the ship's height (vertical position).
  • shipV: its vertical speed. Positive = falling, negative = climbing.
  • shipTilt: how much the ship leans, set from shipV each frame.
  • burnT: seconds of rocket burn left. 0 means the rockets are off.

THE RUN'S VARIABLES

  • gates: the list of gates in the current level (each has a course x-position, a gap center, a gap size, a passed flag, and a random seed for its rock drawing).
  • gateTimer: unused leftover, kept for compatibility.
  • speed: how fast the world scrolls. Starts around 178, +3 per gate passed, capped at 280.
  • score: your points this run. best: your all-time best, saved in localStorage.
  • frames: a frame counter, used for blinking lights and intro timing.
  • level: which level you're on. bestLevel: the highest level you've reached, saved in localStorage.
  • levelScore: points earned on this level (drives the gate gap shrinking).
  • pad: the landing pad (course x-position and width).
  • overReason: the crash message shown on the game-over screen ('CRASHED!', 'TOO FAST TO LAND!', 'MISSED THE PAD!').
  • clearBonus, clearZone: the landing bonus and zone name (PERFECT / GREAT / GOOD) shown on the level-clear screen.
  • courseX: the camera position — how far the world has scrolled.

BEST SCORES (localStorage)

best and bestLevel are loaded from localStorage when the game starts and saved whenever you beat them. The code also checks the old 'astrohop-best' keys first — that's the game's previous name, so players who had a best score under the old name keep it. The try/catch around each read is there because localStorage can throw (private browsing, storage full), and a game should never crash over a saved score.

STARS AND ROCKS (BACKGROUND)

makeStars() builds 90 stars in 3 parallax layers — near stars are bigger and move faster, far stars are smaller and slower. That depth is what makes the background feel like space instead of a flat picture. rocks are the two distant planets drawn behind everything.

DIFFICULTY SCALING

    function courseLen() { return 1500 + (level - 1) * 700; }
    function padWidth() { return Math.max(70, 112 - (level - 1) * 6); }
    function gapFor() { return Math.max(134, 176 - (level - 1) * 6
        - Math.floor(levelScore / 4) * 3); }

Each level the course gets 700 units longer, the pad gets 6 pixels narrower (down to a minimum of 70), and the gate gaps shrink by 6 per level plus 3 more for every 4 points you've scored on this level. The Math.max calls are floors — the pad never goes below 70 wide and the gaps never go below 134, so the game stays possible.

reset() — BUILDING A LEVEL

reset() puts the ship at 45% down the screen with zero speed, clears the burn, particles, flash and shake, and resets the score for the level. Then it pre-generates the WHOLE level up front: starting 160 past the right edge, it places a gate every 248 units until it passes the course length, each with a random gap center, then puts the pad 240 past the end. Pre-generating means the level is fixed before you start — no surprises spawning in front of you.

startGame() and nextLevel()

startGame() sets level to 1, score to 0, calls reset(), and sets state to 'playing'. nextLevel() bumps the level by 1, calls reset(), and sets state to 'playing'. Both are one-liners because reset() does the work.

gameOver(reason)

Sets state to 'over', records the reason, sets flash to 14 and shake to 10 (the white flash and screen shake you see on a crash), saves your best score if you beat it, and plays the crash sound.

landPad() — THE LANDING AND THE PAD ZONES

This is where the points are decided. When you touch down safely:

  • The ship is snapped to the pad top and its speed is zeroed.
  • The landing zone is judged by where the ship's center touched down, as a fraction of the pad width from its center: d = |SHIP_X - pad center| / pad width d <= 1/6 -> PERFECT, +500 d <= 1/3 -> GREAT, +250 otherwise -> GOOD, +100 The center third of the pad is PERFECT, the next bands out are GREAT, the outer edges are GOOD.
  • A speed bonus is added: 100 + max(0, (660 - landV) / 2). Land slower and you earn more — touching down at 660 (the fastest safe speed) gives no speed bonus, touching down gently gives up to +330.
  • clearBonus is the total (100 base + speed bonus + zone bonus). score += clearBonus.
  • Best score and best level are saved if you beat them, and the score sound plays.