// PEPE RUN deterministic simulation — rules version "peperun-physics/1". // // One module is shared by free practice (browser), the authoritative game // server and the independent replay verifier. It has no imports and uses only // integer arithmetic (every value stays far below 2^53), so any conforming // implementation that follows game/ENGINE.md reproduces the same states bit // for bit. // // createRun(seed, royal = false) -> state seed: uint32 // stepRun(state, buttons) -> next state buttons: 0..3 (1 jump, 2 duck) // // One stepRun call is exactly one tick of 1/60 s. stepRun never mutates its // input; it returns a fresh state object. export const RULES_VERSION = 'peperun-physics/1'; export const TICK_RATE = 60; // ticks per second export const MM_PER_PX = 20; // 1 px of world space is 20 mm export const SUBPX = 256; // vertical sub-pixel units per px (Q8) export const BUTTON_JUMP = 1; export const BUTTON_DUCK = 2; // Horizontal speed (mm per second) is a pure function of distance run. export const BASE_SPEED_MM_S = 7000; export const MAX_SPEED_MM_S = 18000; export const SPEED_RAMP_MM = 80; // +1 mm/s for every 80 mm run // Vertical motion, Q8 px per tick (and per tick^2). export const JUMP_VY_Q8 = 2458; // ≈ 9.60 px/tick take-off export const GRAVITY_Q8 = 123; // ≈ 0.48 px/tick^2 export const FAST_FALL_GRAVITY_Q8 = 369; // duck held in the air export const JUMP_CUT_VY_Q8 = 768; // released jump caps rise at 3 px/tick export const JUMP_BUFFER_TICKS = 6; // a held press made up to 6 ticks before the first grounded tick still jumps // Player hitbox: identical for Classic (skin 0) and premium skins 1..20. export const SKIN_COUNT = 20; export const PLAYER_WIDTH_PX = 32; export const PLAYER_WIDTH_MM = PLAYER_WIDTH_PX * MM_PER_PX; export const PLAYER_STAND_HEIGHT_PX = 44; export const PLAYER_DUCK_HEIGHT_PX = 24; // Obstacle geometry. bottomPx is height of the obstacle's underside above ground. export const OBSTACLE_KINDS = Object.freeze({ ground_small: Object.freeze({ widthPx: 24, bottomPx: 0, heightPx: 30, overhead: false }), ground_tall: Object.freeze({ widthPx: 22, bottomPx: 0, heightPx: 46, overhead: false }), ground_wide: Object.freeze({ widthPx: 56, bottomPx: 0, heightPx: 28, overhead: false }), overhead: Object.freeze({ widthPx: 64, bottomPx: 30, heightPx: 120, overhead: true }), }); export const KIND_CODES = Object.freeze(['ground_small', 'ground_tall', 'ground_wide', 'overhead']); // Course generation. export const FIRST_OBSTACLE_MM = 30000; // first obstacle's leading edge (30 m) export const VIEW_AHEAD_MM = 800 * MM_PER_PX; // obstacles are on screen within 800 px of the player export const SPAWN_AHEAD_MM = 1000 * MM_PER_PX; // spawned 1000 px ahead, i.e. off screen export const DESPAWN_BEHIND_MM = 200 * MM_PER_PX; // kept 200 px behind the player's back for rendering export const LEVEL_LENGTH_MM = 150000; // difficulty level rises every 150 m export const MAX_LEVEL = 6; export const MIN_GAP_TICKS = Object.freeze([72, 66, 60, 56, 52, 48, 46]); export const EXTRA_GAP_TICKS = Object.freeze([48, 44, 40, 36, 32, 28, 24]); // Cumulative weights out of 100, in KIND_CODES order. export const KIND_WEIGHTS = Object.freeze([ Object.freeze([60, 40, 0, 0]), Object.freeze([40, 30, 0, 30]), Object.freeze([30, 25, 20, 25]), Object.freeze([30, 25, 20, 25]), Object.freeze([28, 25, 22, 25]), Object.freeze([26, 25, 22, 27]), Object.freeze([25, 25, 22, 28]), ]); const UINT32 = 4294967296; function assertSeed(seed) { if (!Number.isInteger(seed) || seed < 0 || seed >= UINT32) { throw new RangeError('seed must be an integer in [0, 2^32)'); } } function floorDiv(a, b) { return Math.floor(a / b); } /** mulberry32 step. Returns [uint32 output, next uint32 state]. */ export function rngNext(rngState) { const s = (rngState + 0x6d2b79f5) >>> 0; let t = s; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return [(t ^ (t >>> 14)) >>> 0, s]; } /** Uniform integer in [0, n) from one uint32 draw: floor(u * n / 2^32). n < 2^21. */ export function drawInt(u, n) { return Math.floor((u * n) / UINT32); } /** Speed in mm/s applied to the tick that starts at `distanceMm`. */ export function speedAt(distanceMm) { const s = BASE_SPEED_MM_S + floorDiv(distanceMm, SPEED_RAMP_MM); return s > MAX_SPEED_MM_S ? MAX_SPEED_MM_S : s; } /** Difficulty level of an obstacle whose leading edge is at world `xMm`. */ export function levelAt(xMm) { const l = floorDiv(xMm, LEVEL_LENGTH_MM); return l > MAX_LEVEL ? MAX_LEVEL : l; } /** Collision geometry for a skin. Skins are cosmetic: every skin gets the same box. */ export function playerHitbox(skinId = 0, ducking = false) { if (!Number.isInteger(skinId) || skinId < 0 || skinId > SKIN_COUNT) { throw new RangeError(`skinId must be 0 (Classic) .. ${SKIN_COUNT}`); } return { widthPx: PLAYER_WIDTH_PX, widthMm: PLAYER_WIDTH_MM, heightPx: ducking ? PLAYER_DUCK_HEIGHT_PX : PLAYER_STAND_HEIGHT_PX, }; } /** * Exact collision test. Player box: x in [-PLAYER_WIDTH_MM, 0) relative to its * leading edge, y in [heightPx, heightPx + h). Obstacle box: x in [xMm, xMm + widthPx*20), * y in [bottomPx, bottomPx + heightPx). Half-open intervals: touching is not a hit. */ export function overlapsPlayer(ob, heightPx, ducking) { const playerTop = heightPx + (ducking ? PLAYER_DUCK_HEIGHT_PX : PLAYER_STAND_HEIGHT_PX); return ( ob.xMm < 0 && ob.xMm + ob.widthPx * MM_PER_PX > -PLAYER_WIDTH_MM && ob.bottomPx < playerTop && ob.bottomPx + ob.heightPx > heightPx ); } /** * Generate the obstacle placed at gen.nextSpawnMm and advance the generator. * Content depends only on the seed and the order of spawns, never on input. */ function spawnObstacle(gen) { const xMm = gen.nextSpawnMm; const level = levelAt(xMm); let draw; [draw, gen.rngState] = rngNext(gen.rngState); const roll = drawInt(draw, 100); const weights = KIND_WEIGHTS[level]; let k = 0; let acc = weights[0]; while (roll >= acc) { k += 1; acc += weights[k]; } const kind = KIND_CODES[k]; const g = OBSTACLE_KINDS[kind]; [draw, gen.rngState] = rngNext(gen.rngState); const gapTicks = MIN_GAP_TICKS[level] + drawInt(draw, EXTRA_GAP_TICKS[level] + 1); const endMm = xMm + g.widthPx * MM_PER_PX; // Conservative speed: the fastest the player can be while crossing this gap. const v = speedAt(endMm + Math.ceil((gapTicks * MAX_SPEED_MM_S) / TICK_RATE)); const gapMm = Math.ceil((gapTicks * v) / TICK_RATE); const ob = { id: gen.nextObstacleId, kind, worldMm: xMm, widthPx: g.widthPx, bottomPx: g.bottomPx, heightPx: g.heightPx, gapTicks, }; gen.nextObstacleId += 1; gen.nextSpawnMm = endMm + gapMm; return ob; } /** Course without a player: every obstacle with leading edge before untilMm. */ export function generateCourse(seed, untilMm) { assertSeed(seed); const gen = { rngState: seed >>> 0, nextSpawnMm: FIRST_OBSTACLE_MM, nextObstacleId: 1 }; const out = []; while (gen.nextSpawnMm < untilMm) out.push(spawnObstacle(gen)); return out; } function viewObstacle(ob, distanceMm) { const xMm = ob.worldMm - distanceMm; return { id: ob.id, kind: ob.kind, xPx: floorDiv(xMm, MM_PER_PX), widthPx: ob.widthPx, bottomPx: ob.bottomPx, heightPx: ob.heightPx, xMm, worldMm: ob.worldMm, gapTicks: ob.gapTicks, }; } function fillCourse(gen, obstacles, distanceMm) { while (gen.nextSpawnMm < distanceMm + SPAWN_AHEAD_MM) { obstacles.push(viewObstacle(spawnObstacle(gen), distanceMm)); } } /** A fresh run. royal = one automatic save from the first lethal contact. */ export function createRun(seed, royal = false) { assertSeed(seed); if (typeof royal !== 'boolean') throw new TypeError('royal must be a boolean'); const state = { rulesVersion: RULES_VERSION, seed: seed >>> 0, royal, tick: 0, distanceMm: 0, distanceRem: 0, // fraction of a mm, in 1/60 mm (0..59) speedMmPerSec: speedAt(0), heightPx: 0, yQ8: 0, vyQ8: 0, airborne: false, ducking: false, alive: true, livesLeft: royal ? 1 : 0, prevButtons: 0, jumpBuffer: 0, jumps: 0, savedAtTick: -1, deathTick: -1, killedBy: 0, rngState: seed >>> 0, nextSpawnMm: FIRST_OBSTACLE_MM, nextObstacleId: 1, obstacles: [], }; fillCourse(state, state.obstacles, 0); return state; } /** Advance exactly one tick (1/60 s). buttons is the held mask: 1 jump, 2 duck. */ export function stepRun(state, buttons) { if (!Number.isInteger(buttons) || buttons < 0 || buttons > 3) { throw new RangeError('buttons must be an integer mask 0..3'); } if (!state.alive) return state; // terminal // 1. Input edges. const jumpHeld = (buttons & BUTTON_JUMP) !== 0; const duckHeld = (buttons & BUTTON_DUCK) !== 0; const jumpEdge = jumpHeld && (state.prevButtons & BUTTON_JUMP) === 0; // jumpBuffer = ticks, including this one, in which the held press may still start a jump. let jumpBuffer = !jumpHeld ? 0 : jumpEdge ? JUMP_BUFFER_TICKS + 1 : Math.max(0, state.jumpBuffer - 1); // 2. Vertical motion. let y = state.yQ8; let vy = state.vyQ8; let airborne = state.airborne; let jumps = state.jumps; if (!airborne && jumpBuffer > 0) { vy = JUMP_VY_Q8; airborne = true; jumpBuffer = 0; jumps += 1; } if (airborne) { if (!jumpHeld && vy > JUMP_CUT_VY_Q8) vy = JUMP_CUT_VY_Q8; y += vy; vy -= duckHeld ? FAST_FALL_GRAVITY_Q8 : GRAVITY_Q8; if (y <= 0) { y = 0; vy = 0; airborne = false; } } const ducking = !airborne && duckHeld; const heightPx = y >> 8; // 3. Horizontal motion at the speed fixed by distance at the start of the tick. const v = speedAt(state.distanceMm); const total = state.distanceRem + v; const distanceMm = state.distanceMm + Math.floor(total / TICK_RATE); const distanceRem = total % TICK_RATE; // 4. Course: re-position, spawn ahead, drop obstacles far behind. const gen = { rngState: state.rngState, nextSpawnMm: state.nextSpawnMm, nextObstacleId: state.nextObstacleId, }; let obstacles = []; for (const ob of state.obstacles) { const view = viewObstacle(ob, distanceMm); if (view.xMm + view.widthPx * MM_PER_PX >= -(PLAYER_WIDTH_MM + DESPAWN_BEHIND_MM)) obstacles.push(view); } fillCourse(gen, obstacles, distanceMm); // 5. Collision. const tick = state.tick + 1; let alive = true; let livesLeft = state.livesLeft; let savedAtTick = state.savedAtTick; let deathTick = -1; let killedBy = 0; let hitIds = null; for (const ob of obstacles) { if (overlapsPlayer(ob, heightPx, ducking)) (hitIds ??= []).push(ob.id); } if (hitIds) { if (livesLeft > 0) { livesLeft -= 1; savedAtTick = tick; obstacles = obstacles.filter((ob) => !hitIds.includes(ob.id)); } else { alive = false; deathTick = tick; killedBy = hitIds[0]; } } return { rulesVersion: RULES_VERSION, seed: state.seed, royal: state.royal, tick, distanceMm, distanceRem, speedMmPerSec: speedAt(distanceMm), heightPx, yQ8: y, vyQ8: vy, airborne, ducking, alive, livesLeft, prevButtons: buttons, jumpBuffer, jumps, savedAtTick, deathTick, killedBy, rngState: gen.rngState, nextSpawnMm: gen.nextSpawnMm, nextObstacleId: gen.nextObstacleId, obstacles, }; } /** Score: whole metres run. */ export function scoreOf(state) { return { distanceM: Math.floor(state.distanceMm / 1000), distanceMm: state.distanceMm, tick: state.tick, alive: state.alive, royalUsed: state.savedAtTick >= 0, }; } // ---------------------------------------------------------------- serialization export const STATE_KEYS = Object.freeze([ 'rulesVersion', 'seed', 'royal', 'tick', 'distanceMm', 'distanceRem', 'speedMmPerSec', 'heightPx', 'yQ8', 'vyQ8', 'airborne', 'ducking', 'alive', 'livesLeft', 'prevButtons', 'jumpBuffer', 'jumps', 'savedAtTick', 'deathTick', 'killedBy', 'rngState', 'nextSpawnMm', 'nextObstacleId', 'obstacles', ]); export const OBSTACLE_KEYS = Object.freeze([ 'id', 'kind', 'xPx', 'widthPx', 'bottomPx', 'heightPx', 'xMm', 'worldMm', 'gapTicks', ]); /** Canonical JSON: fixed key order, no whitespace. */ export function serializeState(state) { const parts = []; for (const k of STATE_KEYS) { let v; if (k === 'obstacles') { v = '[' + state.obstacles.map((ob) => '{' + OBSTACLE_KEYS.map((ok) => JSON.stringify(ok) + ':' + JSON.stringify(ob[ok])).join(',') + '}').join(',') + ']'; } else { v = JSON.stringify(state[k]); } parts.push(JSON.stringify(k) + ':' + v); } return '{' + parts.join(',') + '}'; } export function deserializeState(json) { const raw = JSON.parse(json); if (raw.rulesVersion !== RULES_VERSION) throw new Error(`unsupported rules version ${raw.rulesVersion}`); for (const k of STATE_KEYS) if (!(k in raw)) throw new Error(`missing state key ${k}`); const state = {}; for (const k of STATE_KEYS) state[k] = raw[k]; state.obstacles = raw.obstacles.map((ob) => { const o = {}; for (const k of OBSTACLE_KEYS) { if (!(k in ob)) throw new Error(`missing obstacle key ${k}`); o[k] = ob[k]; } return o; }); return state; } /** FNV-1a 64 over the canonical serialization (ASCII), as 16 lowercase hex digits. */ export function hashState(state) { const s = serializeState(state); let h = 0xcbf29ce484222325n; for (let i = 0; i < s.length; i++) { h ^= BigInt(s.charCodeAt(i) & 0xff); h = (h * 0x100000001b3n) & 0xffffffffffffffffn; } return h.toString(16).padStart(16, '0'); } // ---------------------------------------------------------------- inputs & replay /** Run-length encode masks as "mask:count,mask:count". */ export function encodeInputs(masks) { const runs = []; let i = 0; while (i < masks.length) { const m = masks[i]; let j = i + 1; while (j < masks.length && masks[j] === m) j++; runs.push(`${m}:${j - i}`); i = j; } return runs.join(','); } export function decodeInputs(text, maxTicks = 60 * 60 * 60 * 6) { if (text === '') return new Uint8Array(0); const runs = text.split(','); let total = 0; const parsed = runs.map((r) => { const m = /^([0-3]):([1-9][0-9]{0,8})$/.exec(r); if (!m) throw new Error(`bad input run "${r}"`); const count = Number(m[2]); total += count; if (total > maxTicks) throw new Error('input longer than maxTicks'); return [Number(m[1]), count]; }); const out = new Uint8Array(total); let p = 0; for (const [mask, count] of parsed) { out.fill(mask, p, p + count); p += count; } return out; } /** * Replay inputs from a fresh run. Stops at death; trailingInputs counts masks * supplied after the death tick (a valid submission has none). */ export function replay(seed, royal, inputs) { let state = createRun(seed, royal); let i = 0; for (; i < inputs.length; i++) { if (!state.alive) break; state = stepRun(state, inputs[i]); } return { state, ticks: state.tick, trailingInputs: inputs.length - i }; }