skidlark / core.js
CyberMax-tools's picture
Deploy skidlark
16781ef verified
Raw History Blame Contribute Delete
36.4 kB
// Skidlark core: deterministic simulation parts (road generator, car physics, scoring rules, garage maths, save data).
// No DOM here, so node --test can check it. Units: 10 units = 1 metre, time in seconds, fixed 60 Hz ticks.
// (c) 2026 CyberMax. All rights reserved.
import { rng, hash, dayNumber } from './cmx.js';
export const DT = 1 / 60;
export const STEP = 16; // road sample spacing (units)
export const BIOME_LEN = 25000; // 2.5 km per biome
export const BIOMES = [
{ id: 'dusk', name: 'Desert Dusk', emoji: '🌵', ground: '#C7714A', ground2: '#B5603E', road: '#3A2F3A', line: '#FFD27A', curbA: '#F5EBDD', curbB: '#D8443C', grip: 1 },
{ id: 'neon', name: 'Neon City', emoji: '🏙️', ground: '#1C1A33', ground2: '#25213F', road: '#2B2E45', line: '#5CF2FF', curbA: '#FF4FD8', curbB: '#4FE3FF', grip: 1 },
{ id: 'snow', name: 'Snowy Pass', emoji: '❄️', ground: '#DCE7EF', ground2: '#C8D7E3', road: '#56606E', line: '#FFFFFF', curbA: '#FFFFFF', curbB: '#3E7CC9', grip: 0.9 },
];
export const biomeIndex = (d) => Math.floor(Math.max(0, d) / BIOME_LEN) % 3;
/** Biome at distance d on a road that starts `off` biomes in (levels start in the Neon City or the Snowy Pass). */
export const biomeOf = (d, off = 0) => (biomeIndex(d) + off) % 3;
export const CARS = [
{ id: 'lark', name: 'Lark', cost: 0, top: 440, accel: 300, grip: 640, steer: 1, slide: 0.45, color: '#FF6A3D', note: 'Balanced, forgiving' },
{ id: 'mule', name: 'Mule', cost: 600, top: 410, accel: 340, grip: 760, steer: 0.9, slide: 0.55, color: '#7BC86C', note: 'Heavy grip, easy to hold' },
{ id: 'viper', name: 'Viper', cost: 1400, top: 510, accel: 320, grip: 610, steer: 1, slide: 0.38, color: '#E8344E', note: 'Fast and loose' },
{ id: 'pixie', name: 'Pixie', cost: 2400, top: 460, accel: 380, grip: 680, steer: 1.25, slide: 0.42, color: '#FFD23F', note: 'Twitchy, flicks into drifts' },
{ id: 'comet', name: 'Comet', cost: 4000, top: 570, accel: 360, grip: 650, steer: 1.05, slide: 0.36, color: '#6C8CFF', note: 'Top speed monster' },
];
export const carById = (id) => CARS.find((c) => c.id === id) || CARS[0];
export const UPGRADES = [
{ id: 'grip', name: 'Grip', icon: '🛞', base: 120, desc: '+7% tyre grip' },
{ id: 'speed', name: 'Top speed', icon: '🏁', base: 150, desc: '+6% top speed' },
{ id: 'boost', name: 'Boost', icon: '🚀', base: 140, desc: 'Stronger, longer nitro' },
{ id: 'tank', name: 'Fuel tank', icon: '⛽', base: 130, desc: '+3 s tank, +0.25 s per gate' },
{ id: 'magnet', name: 'Coin magnet', icon: '🧲', base: 100, desc: 'Pull coins from further' },
{ id: 'nitro', name: 'Nitro', icon: '💨', base: 110, desc: 'Drifts fill nitro 25% faster' },
];
export const MAX_LVL = 5;
export const upgradeCost = (id, lvl) => {
const u = UPGRADES.find((x) => x.id === id);
return lvl >= MAX_LVL || !u ? Infinity : Math.round((u.base * Math.pow(1.75, lvl)) / 10) * 10;
};
export const LIVERIES = [
{ id: 'factory', name: 'Factory', pass: false },
{ id: 'chalk', name: 'Chalk', pass: false, body: '#EDEAE3', stripe: '#11141B' },
{ id: 'ink', name: 'Midnight', pass: false, body: '#1B2233', stripe: '#FFC857' },
{ id: 'aurora', name: 'Aurora', pass: true, body: '#2A1B4F', stripe: '#3CFFC4', stripe2: '#B36BFF' },
{ id: 'koi', name: 'Koi', pass: true, body: '#F7F1E3', stripe: '#FF5A36', stripe2: '#11141B' },
{ id: 'solar', name: 'Solar Flare', pass: true, body: '#FFB000', stripe: '#FF2E63', stripe2: '#FFF4C2' },
];
export const MODS = [
{ id: 'ice', name: 'Black ice', desc: 'Grip -15%', grip: 0.85 },
{ id: 'leak', name: 'Fuel leak', desc: 'Fuel drains 20% faster', drain: 1.2 },
{ id: 'narrow', name: 'Narrow pass', desc: 'Road 15% narrower', width: 0.85 },
{ id: 'rush', name: 'Coin rush', desc: 'Double coins on the road', coins: 2 },
{ id: 'cones', name: 'Cone alley', desc: 'Twice the cones', cones: 2 },
{ id: 'turbo', name: 'Turbo day', desc: 'Top speed +10%, grip -5%', top: 1.1, grip: 0.95 },
];
/** Same road, car and modifier for everyone on a given local date. */
export function dailySetup(iso) {
const n = dayNumber(iso);
const r = rng(hash(`skidlark:${iso}`));
const car = CARS[Math.floor(r() * CARS.length)];
const mod = MODS[Math.floor(r() * MODS.length)];
return { n, seed: hash(`skidlark-road:${iso}`), car: car.id, mod: mod.id };
}
/** Handling numbers for a car + garage levels + modifier. Daily runs pass empty levels (stock car). */
export function carStats(carId, up = {}, modId = null) {
const c = carById(carId);
const m = MODS.find((x) => x.id === modId) || {};
const L = (k) => Math.max(0, Math.min(MAX_LVL, up[k] | 0));
return {
top: c.top * (1 + 0.06 * L('speed')) * (m.top || 1),
accel: c.accel,
grip: c.grip * (1 + 0.07 * L('grip')) * (m.grip || 1),
steer: c.steer,
slide: c.slide,
tank: 20 + 3 * L('tank'),
gateBonus: 3.4 + 0.25 * L('tank'),
magnet: 34 + 24 * L('magnet'),
nitroFill: 1 + 0.25 * L('nitro'),
boost: 1.32 + 0.06 * L('boost'),
boostTime: 1.8 + 0.3 * L('boost'),
drain: m.drain || 1,
width: m.width || 1,
coins: m.coins || 1,
cones: m.cones || 1,
};
}
// ------------------------------------------------------------------ road
/** Endless winding road. Points every STEP units; heading kept within ±75° of north so the road never folds back. */
export class Road {
constructor(seed, opts = {}) {
this.r = rng(seed);
this.wMul = opts.width || 1;
this.coinMul = opts.coins || 1;
this.coneMul = opts.cones || 1;
// level options (all off for the endless and daily roads, so those stay exactly as they were)
this.bOff = opts.biome || 0; // start in another biome
this.barrelP = opts.barrels || 0; // chance that a cone row starts with a barrel, from the first metre
this.hardOff = opts.hard || 0; // extra curviness, as if this many units further down the road
this.pts = [];
this.base = 0; // absolute index of pts[0]
this.items = []; // cones, barrels, coins, gates
this.decos = [];
this.x = 0; this.y = 0; this.a = -Math.PI / 2; this.k = 0; this.kT = 0; this.left = 30; this.d = 0;
this.nextGate = opts.gates === false ? Infinity : 50; this.nextCoins = 18; this.nextCone = 40; this.decoAt = 0;
while (this.pts.length < 260) this.gen();
}
get end() { return this.base + this.pts.length; }
at(i) { return this.pts[i - this.base]; }
gen() {
const r = this.r;
const i = this.end;
const d = this.d;
if (this.left-- <= 0) {
const hard = Math.min(1, (d + this.hardOff) / 120000);
const dev = this.a + Math.PI / 2;
if (r() < 0.22 - hard * 0.1) { this.kT = 0; this.left = 14 + Math.floor(r() * 30); }
else {
const R = 170 + r() * (480 - hard * 220);
let s = r() < 0.5 ? -1 : 1;
if (Math.abs(dev) > 0.55) s = -Math.sign(dev);
this.kT = s / R;
this.left = 18 + Math.floor(r() * 34);
}
}
this.k += (this.kT - this.k) * 0.09;
this.a += this.k * STEP;
const dev = this.a + Math.PI / 2;
if (Math.abs(dev) > 1.3) { this.a = -Math.PI / 2 + Math.sign(dev) * 1.3; this.kT = -this.kT; }
const w = (300 - Math.min(80, d / 1500)) * this.wMul;
const p = { i, x: this.x, y: this.y, a: this.a, nx: -Math.sin(this.a), ny: Math.cos(this.a), w, d, k: this.k, b: biomeOf(d, this.bOff) };
this.pts.push(p);
this.x += Math.cos(this.a) * STEP; this.y += Math.sin(this.a) * STEP; this.d += STEP;
// items
if (i === this.nextGate) {
this.items.push({ t: 'gate', i, x: p.x, y: p.y, nx: p.nx, ny: p.ny, w, on: true });
this.nextGate = i + 64 + Math.min(70, Math.floor(d / 1500));
} else if (i >= this.nextCoins && i > 20 && Math.abs(i - this.nextGate) > 4) {
const off = (r() - 0.5) * (w - 80);
const n = 5 * this.coinMul;
for (let j = 0; j < n; j++) this.items.push({ t: 'coin', i: i + j * 2, ox: off, on: true, x: 0, y: 0 });
this.nextCoins = i + 16 + Math.floor(r() * 20);
} else if (i >= this.nextCone && i > 30) {
const curve = Math.abs(this.k) > 1 / 600;
if (curve || r() < 0.5) {
const inner = curve ? -Math.sign(this.k) : (r() < 0.5 ? -1 : 1);
const late = (d > 9000 || this.barrelP) && r() < Math.max(this.barrelP, Math.min(0.45, d / 80000));
const n = Math.round((2 + Math.floor(r() * 3)) * this.coneMul);
for (let j = 0; j < n; j++) {
const off = inner * (w / 2 - 34 - r() * (w * 0.32));
this.items.push({ t: late && j === 0 ? 'barrel' : 'cone', i: i + j * 3, ox: off, on: true, x: 0, y: 0, vx: 0, vy: 0, rot: 0, near: false });
}
}
this.nextCone = i + 22 + Math.floor(r() * 26);
}
// place pending items whose road point now exists
for (const it of this.items) {
if (it.ox !== undefined && !it.placed && it.i < this.end) {
const q = this.at(it.i);
if (q) { it.x = q.x + q.nx * it.ox; it.y = q.y + q.ny * it.ox; it.placed = true; }
}
}
// decorations lag 60 points behind generation so they can avoid all road nearby
const di = i - 60;
if (di >= this.base + 60) {
const q = this.at(di);
for (let side = -1; side <= 1; side += 2) {
if (r() < 0.3) {
const off = side * (q.w / 2 + 50 + r() * r() * 520);
const size = 18 + r() * 40;
const x = q.x + q.nx * off + (r() - 0.5) * 30, y = q.y + q.ny * off + (r() - 0.5) * 30;
if (this.clear(x, y, size + 20, di)) this.decos.push({ i: di, b: q.b, x, y, s: size, h: 0.3 + r() * 0.9, v: r() });
}
}
}
}
clear(x, y, rad, i) {
for (let j = Math.max(this.base, i - 60); j < Math.min(this.end, i + 60); j += 2) {
const q = this.at(j);
const dx = x - q.x, dy = y - q.y;
const lim = q.w / 2 + rad;
if (dx * dx + dy * dy < lim * lim) return false;
}
return true;
}
/** Keep ~200 points ahead of `idx`, drop what is far behind. */
ensure(idx) {
while (this.end < idx + 200) this.gen();
const drop = idx - 80 - this.base;
if (drop > 120) {
this.pts.splice(0, drop);
this.base += drop;
this.items = this.items.filter((it) => it.i >= this.base);
this.decos = this.decos.filter((it) => it.i >= this.base);
}
}
/** Nearest road sample to (x,y) starting from a hint index; returns the index. */
nearest(x, y, hint) {
let i = Math.max(this.base, Math.min(this.end - 2, hint));
const d2 = (j) => { const q = this.at(j); return (q.x - x) ** 2 + (q.y - y) ** 2; };
let best = d2(i);
for (;;) {
if (i + 1 < this.end - 1 && d2(i + 1) < best) { i++; best = d2(i); continue; }
if (i - 1 >= this.base && d2(i - 1) < best) { i--; best = d2(i); continue; }
return i;
}
}
}
// ------------------------------------------------------------------ car physics
export function newCar(x, y, a) {
return { x, y, h: a, vx: Math.cos(a) * 160, vy: Math.sin(a) * 160, w: 0, slide: false, hold: 0, slip: 0, speed: 160, nitro: 0, boostT: 0, steer: 0 };
}
const wrap = (a) => { while (a > Math.PI) a -= 2 * Math.PI; while (a < -Math.PI) a += 2 * Math.PI; return a; };
/** One fixed tick. inp = {steer:-1..1, brake:bool}. env = {gripMul}. Mutates car. */
export function stepCar(c, inp, st, env = {}, dt = DT) {
const s = inp.steer;
c.hold = s !== 0 && Math.sign(s) === Math.sign(c.steer || s) ? c.hold + dt : 0;
c.steer = s;
const fx = Math.cos(c.h), fy = Math.sin(c.h), rx = -fy, ry = fx;
let vf = c.vx * fx + c.vy * fy;
let vr = c.vx * rx + c.vy * ry;
const speed = Math.hypot(vf, vr);
const boosting = c.boostT > 0;
const top = st.top * (boosting ? st.boost : 1);
// engine (always on: arcade auto-throttle)
vf += (boosting ? st.accel * 1.8 : st.accel) * Math.max(-0.4, 1 - vf / top) * dt;
if (inp.brake) vf -= 160 * dt;
// steering yaw: a short tap turns on grip, holding winds the yaw up past what the tyres can hold -> drift
const sf = Math.min(1, speed / 170);
const wind = 1.5 + Math.min(c.hold, 0.7) * 2.1;
let wt = s * st.steer * wind * sf;
const vdir = Math.atan2(c.vy, c.vx);
c.slip = speed > 40 ? wrap(c.h - vdir) : 0;
if (c.slide) wt -= c.slip * 4.2; // self-aligning: holds a steady angle instead of spinning out
if (inp.brake && s) wt += s * 1.2;
c.w += (wt - c.w) * Math.min(1, (c.slide ? 7 : 12) * dt);
// lateral tyre force
const grip = st.grip * (env.gripMul || 1);
if (!c.slide && (Math.abs(vr) > 70 || (inp.brake && speed > 120))) c.slide = true;
let lat = grip;
if (c.slide) {
const counter = s !== 0 && Math.sign(s) === -Math.sign(c.slip) ? 1 : 0;
lat = grip * (inp.brake ? 0.25 : st.slide + counter * 0.35);
if (!inp.brake && Math.abs(vr) < 28 && Math.abs(c.slip) < 0.14) c.slide = false;
vf -= Math.abs(vr) * 0.55 * dt; // scrubbing speed while sideways
}
const dv = Math.min(Math.abs(vr), lat * dt);
vr -= Math.sign(vr) * dv;
c.vx = fx * vf + rx * vr;
c.vy = fy * vf + ry * vr;
c.h += c.w * dt;
c.x += c.vx * dt;
c.y += c.vy * dt;
c.speed = Math.hypot(c.vx, c.vy);
if (c.boostT > 0) c.boostT -= dt;
return c;
}
/** Drift points for one tick: angle (degrees) × speed, only while really sideways. */
export function driftPoints(slip, speed, dt = DT) {
const deg = Math.abs(slip) * 57.2958;
if (deg < 10 || speed < 140) return 0;
return Math.min(deg, 70) * (speed / 100) * dt * 6;
}
export const comboMult = (links) => Math.min(8, 1 + 0.5 * Math.max(0, links - 1));
// ------------------------------------------------------------------ missions
export const MISSIONS = [
{ id: 'chain400', text: 'Drift 400 m in one chain', stat: 'bestChainM', goal: 400, reward: 250 },
{ id: 'gates10', text: 'Pass 10 gates in one run', stat: 'gates', goal: 10, reward: 150 },
{ id: 'score20k', text: 'Score 20,000 in one run', stat: 'score', goal: 20000, reward: 200 },
{ id: 'near12', text: 'Near-miss 12 cones in one run', stat: 'near', goal: 12, reward: 200 },
{ id: 'combo5', text: 'Reach a x5 combo', stat: 'maxMult', goal: 5, reward: 250 },
{ id: 'coins60', text: 'Collect 60 coins in one run', stat: 'coins', goal: 60, reward: 150 },
{ id: 'dist3k', text: 'Drive 3 km in one run', stat: 'km', goal: 3, reward: 250 },
{ id: 'dgates5', text: 'Drift through 5 gates in one run', stat: 'driftGates', goal: 5, reward: 250 },
{ id: 'neon', text: 'Reach the Neon City', stat: 'km', goal: 2.5, reward: 200 },
{ id: 'score60k', text: 'Score 60,000 in one run', stat: 'score', goal: 60000, reward: 400 },
{ id: 'chain1k', text: 'Drift 1 km in one chain', stat: 'bestChainM', goal: 1000, reward: 500 },
{ id: 'snow', text: 'Reach the Snowy Pass', stat: 'km', goal: 5, reward: 400 },
{ id: 'combo8', text: 'Hit the x8 max combo', stat: 'maxMult', goal: 8, reward: 600 },
{ id: 'gates30', text: 'Pass 30 gates in one run', stat: 'gates', goal: 30, reward: 500 },
];
/** Checks the active missions against a finished run; returns {done:[missions], coins}. Mutates save. */
export function checkMissions(save, run) {
const done = [];
save.missions = save.missions.filter((id) => {
const m = MISSIONS.find((x) => x.id === id);
if (m && (run[m.stat] || 0) >= m.goal) { done.push(m); return false; }
return !!m;
});
let coins = 0;
for (const m of done) { coins += m.reward; save.missionsDone.push(m.id); }
refillMissions(save);
save.coins += coins;
return { done, coins };
}
export function refillMissions(save) {
for (const m of MISSIONS) {
if (save.missions.length >= 3) break;
if (!save.missions.includes(m.id) && !save.missionsDone.includes(m.id)) save.missions.push(m.id);
}
}
// ------------------------------------------------------------------ save data
export function defaultSave() {
const s = { v: 1, coins: 0, best: 0, up: {}, cars: ['lark'], car: 'lark', livery: 'factory', missions: [], missionsDone: [], daily: {}, runs: 0, km: 0, ta: {} };
for (const u of UPGRADES) s.up[u.id] = 0;
refillMissions(s);
return s;
}
/** Accepts anything (old, broken or edited JSON) and returns a valid save. */
export function loadSave(raw) {
const s = defaultSave();
if (!raw || typeof raw !== 'object') return s;
const num = (v, d = 0) => (Number.isFinite(+v) && +v >= 0 ? Math.floor(+v) : d);
s.coins = num(raw.coins); s.best = num(raw.best); s.runs = num(raw.runs); s.km = Number.isFinite(+raw.km) ? Math.max(0, +raw.km) : 0;
if (raw.up && typeof raw.up === 'object') for (const u of UPGRADES) s.up[u.id] = Math.min(MAX_LVL, num(raw.up[u.id]));
if (Array.isArray(raw.cars)) s.cars = ['lark', ...raw.cars.filter((c) => CARS.some((x) => x.id === c) && c !== 'lark')];
if (s.cars.includes(raw.car)) s.car = raw.car;
if (LIVERIES.some((l) => l.id === raw.livery)) s.livery = raw.livery;
if (Array.isArray(raw.missionsDone)) s.missionsDone = raw.missionsDone.filter((id) => MISSIONS.some((m) => m.id === id));
if (Array.isArray(raw.missions)) s.missions = raw.missions.filter((id) => MISSIONS.some((m) => m.id === id) && !s.missionsDone.includes(id)).slice(0, 3);
refillMissions(s);
if (raw.daily && typeof raw.daily === 'object') for (const [k, v] of Object.entries(raw.daily)) if (/^\d{4}-\d\d-\d\d$/.test(k) && v) s.daily[k] = { best: num(v.best), tries: num(v.tries), strip: String(v.strip || '').slice(0, 80) };
if (raw.ta && typeof raw.ta === 'object') for (const [k, v] of Object.entries(raw.ta)) { const n = +k, t = +v; if (Number.isInteger(n) && n >= 1 && n <= LEVELS.length && Number.isFinite(t) && t > 1 && t < 600) s.ta[n] = Math.round(t * 100) / 100; }
return s;
}
export function buyUpgrade(save, id) {
const lvl = save.up[id] | 0;
const cost = upgradeCost(id, lvl);
if (save.coins < cost) return false;
save.coins -= cost; save.up[id] = lvl + 1;
return true;
}
export function buyCar(save, id) {
const c = carById(id);
if (save.cars.includes(id) || save.coins < c.cost) return false;
save.coins -= c.cost; save.cars.push(id); save.car = id;
return true;
}
/** Coins paid out at the end of a run: what you picked up plus 1 per 250 points. */
export const runCoins = (picked, score) => picked + Math.floor(score / 250);
/** Emoji strip: one cell per gate segment. 🔥 big combo, 🟪 drifted the gate, 🟩 gate, 💥 crash, 🏁 end. */
export function emojiStrip(cells) {
const map = { fire: '🔥', drift: '🟪', gate: '🟩', crash: '💥' };
const out = cells.slice(0, 14).map((c) => map[c] || '⬜').join('');
return out + (cells.length > 14 ? `+${cells.length - 14}` : '') + '🏁';
}
/** Keeps the car inside the walls. Returns the impact speed into the wall (0 = no contact), and sets c.wallSide. */
export function wallCheck(road, c, idx) {
const p = road.at(idx);
const off = (c.x - p.x) * p.nx + (c.y - p.y) * p.ny;
const lim = p.w / 2 - 13;
c.off = off;
if (Math.abs(off) <= lim) { c.wallSide = 0; return 0; }
{
let da = p.a - c.h;
while (da > Math.PI) da -= 2 * Math.PI;
while (da < -Math.PI) da += 2 * Math.PI;
if (c.speed < 120) c.h += da * 0.08; // slow and scraping: ease the nose round
}
const s = Math.sign(off);
c.x -= p.nx * (Math.abs(off) - lim) * s;
c.y -= p.ny * (Math.abs(off) - lim) * s;
const vn = (c.vx * p.nx + c.vy * p.ny) * s;
c.wallSide = s;
if (vn <= 0) return 0.001;
c.vx -= p.nx * vn * s * 1.3; c.vy -= p.ny * vn * s * 1.3;
c.vx *= 0.97; c.vy *= 0.97;
// glance off: swing the nose back along the road so the car never pins itself against a wall
let da = p.a - c.h;
while (da > Math.PI) da -= 2 * Math.PI;
while (da < -Math.PI) da += 2 * Math.PI;
c.h += da * Math.min(1, 0.06 + vn / 900);
c.w *= 0.6;
return vn;
}
/** Progress along the road (units) for a car at sample idx. */
export function progress(road, c, idx) {
const p = road.at(idx);
return p.d + (c.x - p.x) * Math.cos(p.a) + (c.y - p.y) * Math.sin(p.a);
}
/** Simple driver used by the attract/demo mode and the tests: aims down the road, drifts on corners by holding. */
export function autoSteer(road, c, idx) {
const ahead = Math.min(road.end - 1, idx + 6 + Math.floor(c.speed / 45));
const q = road.at(ahead);
const want = Math.atan2(q.y - c.y, q.x - c.x);
const vdir = Math.atan2(c.vy, c.vx);
let diff = want - vdir;
while (diff > Math.PI) diff -= 2 * Math.PI;
while (diff < -Math.PI) diff += 2 * Math.PI;
const steer = diff > 0.045 ? 1 : diff < -0.045 ? -1 : 0;
return { steer, brake: Math.abs(diff) > 0.55 && c.speed > 300 };
}
// ------------------------------------------------------------------ run simulation (one fixed tick; used by the game and by the node tests)
// Pure game rules: no drawing, sound or particles. ev(type, ...args) reports what happened so the game can add juice.
const NOEV = () => {};
/** A fresh run. opts: { seed, carId, up, mod, daily, night, level } (level = a LEVELS entry number, 1-based). */
export function newRunState({ seed, carId = 'lark', up = {}, mod = null, daily = false, night = false, level = 0 } = {}) {
const L = level ? LEVELS[level - 1] : null;
let st, roadOpts;
if (L) {
// levels: the level's stock car for everyone (fair "beat my score" links), tuned road, its own fuel tank
st = { ...carStats(L.car || 'lark', {}, null) };
st.grip *= L.grip || 1; st.top *= L.top || 1; st.tank = L.fuel; st.drain = L.drain || 1;
roadOpts = { width: L.width || 1, coins: L.coins || 1, cones: L.cones || 1, biome: L.biome || 0, barrels: L.barrels || 0, hard: L.hard || 0, gates: L.gates !== false };
carId = L.car || 'lark'; night = !!L.night;
} else {
st = carStats(carId, up, mod);
roadOpts = { width: st.width, coins: st.coins, cones: st.cones };
}
const road = new Road(seed, roadOpts);
const p = road.at(4);
const car = newCar(p.x, p.y, p.a);
return {
road, st, car, carId, idx: 4, seed, daily, night, mod, level, L, finishD: L ? L.dist * 10 : 0, over: null, hitstop: 0,
fuel: st.tank, score: 0, coins: 0, gates: 0, driftGates: 0, near: 0, crashes: 0, d: 0, t: 0,
chain: false, inDrift: false, links: 0, chainPts: 0, chainDist: 0, grace: 0, maxMult: 1, bestChainM: 0,
biome: 0, biomeT: 0, cells: [], seg: { crash: false, fire: false }, trail: [], straight: 0, prompt: 4,
px: car.x, py: car.y, ph: car.h, auto: false, wallT: 0, lastBank: 0,
};
}
export const runMult = (R) => comboMult(R.links);
/** Bank the current drift chain: points × combo, a little fuel back for long chains. */
export function bankChain(R, ev = NOEV) {
if (!R.chain) return;
const m = runMult(R);
const gained = Math.round(R.chainPts * m);
R.score += gained;
const meters = R.chainDist / 10;
R.bestChainM = Math.max(R.bestChainM, meters);
const bonusT = Math.min(2, meters / 200);
R.fuel = Math.min(R.st.tank, R.fuel + bonusT);
ev('bank', gained, bonusT, R.links);
R.chain = false; R.links = 0; R.chainPts = 0; R.chainDist = 0; R.lastBank = R.t;
}
export function breakChain(R, why, ev = NOEV) {
ev('lost', why, R.chain && R.chainPts > 50);
R.chain = false; R.links = 0; R.chainPts = 0; R.chainDist = 0; R.inDrift = false;
}
/** One 60 Hz tick of the rules. inp = { steer, brake, nitro }. Returns false while frozen by a crash hit-stop. */
export function simTick(R, inp, ev = NOEV) {
if (R.hitstop > 0) { R.hitstop--; return false; }
const c = R.car, road = R.road, st = R.st, dt = DT;
R.t += dt;
if (R.prompt > 0) R.prompt -= dt;
const b = BIOMES[biomeOf(R.d, road.bOff)];
stepCar(c, inp, st, { gripMul: b.grip });
R.idx = road.nearest(c.x, c.y, R.idx);
road.ensure(R.idx);
R.d = Math.max(R.d, progress(road, c, R.idx));
// walls
const imp = wallCheck(road, c, R.idx);
if (imp > 0) {
const p = road.at(R.idx);
const wx = c.x + p.nx * c.wallSide * 12, wy = c.y + p.ny * c.wallSide * 12;
ev('spark', wx, wy);
if (imp > 170) {
R.crashes++; R.seg.crash = true;
R.fuel -= 2.5; R.hitstop = 7;
c.w *= -0.4; c.slide = false;
breakChain(R, 'CRASH −2.5s', ev); ev('crash', wx, wy);
} else if (imp > 45) {
ev('wall'); breakChain(R, 'WALL', ev);
} else if (R.wallT <= 0) { ev('scrape'); R.wallT = 0.2; }
}
if (R.wallT > 0) R.wallT -= dt;
R.fuel -= dt * st.drain;
// drift scoring and chains
const pts = c.slide ? driftPoints(c.slip, c.speed) : 0;
if (pts > 0) {
if (!R.chain) { R.chain = true; R.links = 1; R.chainPts = 0; R.chainDist = 0; }
else if (!R.inDrift) { R.links++; if (R.links > 1) ev('link', R.links, runMult(R)); }
R.inDrift = true;
R.chainPts += pts; R.chainDist += c.speed * dt; R.grace = 1.15;
c.nitro = Math.min(1, c.nitro + pts * 0.00025 * st.nitroFill);
R.maxMult = Math.max(R.maxMult, runMult(R));
if (runMult(R) >= 4) R.seg.fire = true;
} else {
R.inDrift = false;
if (R.chain) { R.grace -= dt; if (R.grace <= 0) bankChain(R, ev); }
}
// nitro: fires itself once full and the car is straight, or on W / ↑ / Shift
if (!c.slide && Math.abs(inp.steer) === 0) R.straight += dt; else R.straight = 0;
if (c.nitro >= 1 && c.boostT <= 0 && (inp.nitro || R.straight > 0.35)) {
c.nitro = 0; c.boostT = st.boostTime; ev('nitro');
}
// items
const ci = R.idx;
const mg = st.magnet;
for (const it of road.items) {
if (it.i < ci - 40 || it.i > ci + 40) continue;
if (it.t === 'gate') {
if (it.on && ci >= it.i) {
it.on = false;
const drift = c.slide && Math.abs(c.slip) > 0.17;
R.gates++;
R.fuel = Math.min(st.tank, R.fuel + st.gateBonus + (drift ? 1 : 0));
const gp = Math.round((drift ? 1200 : 300) * runMult(R));
R.score += gp;
if (drift) R.driftGates++;
R.cells.push(R.seg.crash ? 'crash' : drift ? 'drift' : R.seg.fire ? 'fire' : 'gate');
R.seg.crash = false; R.seg.fire = false;
ev('gate', drift, gp);
}
} else if (it.t === 'coin') {
if (!it.on || !it.placed) continue;
const dx = c.x - it.x, dy = c.y - it.y, d2 = dx * dx + dy * dy;
if (d2 < 26 * 26) { it.on = false; R.coins++; R.score += 25; ev('coin', it.x, it.y); }
else if (d2 < mg * mg) { it.x += dx * 0.16; it.y += dy * 0.16; }
} else if (it.placed) {
if (it.on) {
const dx = c.x - it.x, dy = c.y - it.y, d = Math.hypot(dx, dy);
const hit = it.t === 'barrel' ? 30 : 24;
if (d < hit) {
it.on = false;
it.vx = c.vx * 1.1 + (Math.random() - 0.5) * 120; it.vy = c.vy * 1.1 + (Math.random() - 0.5) * 120; it.spin = (Math.random() - 0.5) * 20;
if (it.t === 'barrel') {
c.vx *= 0.6; c.vy *= 0.6; R.fuel -= 1.5; R.hitstop = 5; R.seg.crash = true; R.crashes++;
breakChain(R, 'BARREL −1.5s', ev); ev('barrel');
} else { c.vx *= 0.93; c.vy *= 0.93; breakChain(R, 'CONE HIT', ev); ev('cone'); }
} else if (d < 62 && c.speed > 200) it.near = true;
if (it.near && it.i < ci - 2) {
it.near = false; it.done = true; it.on = false; it.passed = true;
R.near++;
const np = Math.round(150 * runMult(R));
if (R.chain) { R.chainPts += 150; R.grace = Math.max(R.grace, 0.9); } else R.score += np;
ev('near');
}
} else if (!it.passed) {
it.x += it.vx * dt; it.y += it.vy * dt; it.vx *= 0.97; it.vy *= 0.97; it.rot += it.spin * dt; it.spin *= 0.97;
}
}
}
// biome change banner
const bi = biomeOf(R.d, road.bOff);
if (bi !== R.biome) { R.biome = bi; R.biomeT = 2.5; ev('biome', bi); }
if (R.biomeT > 0) R.biomeT -= dt;
// level: crossing the finish line ends the run (cleared if the goal is met)
if (R.finishD && R.d >= R.finishD && !R.over) {
bankChain(R, ev);
R.over = goalMet(R) ? 'win' : 'goal';
} else if (R.fuel <= 0 && !R.over) R.over = 'fuel';
return true;
}
// ------------------------------------------------------------------ levels (30 hand-tuned roads)
// Each level is a fixed road with a finish line and one goal to meet by the finish. 1 star = cleared, 2 and 3 stars
// = points at the finish. A new twist about every 5 levels; every 10th level is a challenge (boss) level.
// Level roads use their own seed space (skidlark-lv:<n>), so the endless and daily roads above are unchanged.
// goal: { t: 'finish' | 'score' | 'coins' | 'gates' | 'dgates' | 'near' | 'chain', n }. dist in metres, fuel in seconds.
// Road: width/coins/cones multipliers, biome (0 desert, 1 neon, 2 snow), barrels (chance per cone row), hard (curviness
// offset in units), gates:false (no fuel gates). Car: car id, grip/top multipliers, drain, night.
export const LEVELS = [
// World 1: Desert Dusk
{ name: 'First Slide', dist: 300, fuel: 20, goal: { t: 'finish', n: 0 }, stars: [3000, 5000] },
{ name: 'Sand Bends', dist: 450, fuel: 20, goal: { t: 'finish', n: 0 }, stars: [2500, 7000] },
{ name: 'Coin Trail', dist: 500, fuel: 18, goal: { t: 'coins', n: 20 }, coins: 1.5, twist: 'Coin goals: grab the coins', stars: [5000, 8000] },
{ name: 'Cone Garden', dist: 600, fuel: 18, goal: { t: 'near', n: 2 }, cones: 2, stars: [4500, 9000] },
{ name: 'Long Dune', dist: 850, fuel: 12, goal: { t: 'finish', n: 0 }, stars: [7500, 14000] },
{ name: 'Sideways', dist: 600, fuel: 16, goal: { t: 'score', n: 2000 }, twist: 'Score goals: chain drifts for points', stars: [4500, 14000] },
{ name: 'Hairpins', dist: 700, fuel: 16, goal: { t: 'score', n: 3000 }, hard: 60000, stars: [5000, 16000] },
{ name: 'Dune Chain', dist: 700, fuel: 16, goal: { t: 'chain', n: 50 }, hard: 30000, stars: [8000, 17000] },
{ name: 'Barrel Bend', dist: 800, fuel: 14, goal: { t: 'score', n: 4000 }, barrels: 0.45, twist: 'Barrels: hit one and lose 1.5 s of fuel', stars: [6500, 20000] },
{ name: 'Dune King', dist: 1200, fuel: 12, goal: { t: 'score', n: 7500 }, hard: 50000, cones: 1.5, barrels: 0.35, boss: true, stars: [10000, 15000] },
// World 2: Neon City
{ name: 'Neon Lights', dist: 600, fuel: 16, goal: { t: 'coins', n: 40 }, biome: 1, coins: 2, twist: 'Neon City streets', stars: [7500, 11500] },
{ name: 'Night Shift', dist: 700, fuel: 16, goal: { t: 'near', n: 6 }, biome: 1, cones: 2, stars: [7000, 9500] },
{ name: 'Drift Gates', dist: 800, fuel: 16, goal: { t: 'dgates', n: 2 }, biome: 1, hard: 40000, twist: 'Drift through the gates', stars: [11000, 16000] },
{ name: 'Pixie Flick', dist: 800, fuel: 16, goal: { t: 'score', n: 3500 }, biome: 1, car: 'pixie', stars: [7000, 17000] },
{ name: 'Viper Run', dist: 1000, fuel: 14, goal: { t: 'score', n: 6000 }, biome: 1, car: 'viper', stars: [11000, 20000] },
{ name: 'Narrow Streets', dist: 900, fuel: 14, goal: { t: 'score', n: 5000 }, biome: 1, width: 0.8, twist: 'Narrow streets', stars: [8500, 11000] },
{ name: 'Back Alleys', dist: 900, fuel: 14, goal: { t: 'near', n: 7 }, biome: 1, width: 0.82, barrels: 0.4, cones: 1.5, stars: [7500, 10500] },
{ name: 'Neon Chain', dist: 900, fuel: 14, goal: { t: 'chain', n: 60 }, biome: 1, hard: 60000, stars: [13000, 20000] },
{ name: 'Fuel Leak', dist: 1000, fuel: 11, drain: 1.4, goal: { t: 'finish', n: 0 }, biome: 1, twist: 'Fuel leak: the tank drains faster', stars: [6500, 8500] },
{ name: 'Neon Grand Prix', dist: 800, fuel: 26, gates: false, goal: { t: 'score', n: 2500 }, biome: 1, hard: 40000, boss: true, stars: [4000, 5500] },
// World 3: Snowy Pass (Fun Pass)
{ name: 'Black Ice', dist: 800, fuel: 16, goal: { t: 'finish', n: 0 }, biome: 2, grip: 0.85, twist: 'Black ice: less grip', stars: [10500, 16000] },
{ name: 'Snow Coins', dist: 900, fuel: 15, goal: { t: 'coins', n: 45 }, biome: 2, grip: 0.9, coins: 2, stars: [13500, 20000] },
{ name: 'Comet Pass', dist: 1300, fuel: 14, goal: { t: 'score', n: 8000 }, biome: 2, car: 'comet', twist: 'Comet: top-speed monster', stars: [16000, 25000] },
{ name: 'Pine Chain', dist: 1000, fuel: 14, goal: { t: 'chain', n: 60 }, biome: 2, grip: 0.9, hard: 60000, stars: [15000, 20000] },
{ name: 'Frozen Gates', dist: 1100, fuel: 14, goal: { t: 'dgates', n: 3 }, biome: 2, grip: 0.88, hard: 50000, stars: [17000, 24000] },
{ name: 'Night Pass', dist: 1000, fuel: 14, goal: { t: 'finish', n: 0 }, biome: 2, night: true, twist: 'Night: headlights only', stars: [12000, 17000] },
{ name: 'Moonlit Cones', dist: 1000, fuel: 14, goal: { t: 'near', n: 12 }, biome: 2, night: true, cones: 2, stars: [10000, 16000] },
{ name: 'Blizzard', dist: 1200, fuel: 13, goal: { t: 'score', n: 9000 }, biome: 2, grip: 0.8, width: 0.85, barrels: 0.4, stars: [16000, 24000] },
{ name: 'Avalanche', dist: 1400, fuel: 13, drain: 1.15, goal: { t: 'score', n: 10000 }, biome: 2, hard: 80000, stars: [15000, 22000] },
{ name: 'Summit Night', dist: 1500, fuel: 12, goal: { t: 'score', n: 9000 }, biome: 2, night: true, grip: 0.88, hard: 70000, barrels: 0.35, boss: true, stars: [25000, 41000] },
];
/** Seed of level n's road (its own seed space). */
export const levelSeed = (n) => hash(`skidlark-lv:${n}`);
/** The live value of a level goal (for the HUD and the finish check). */
export function goalValue(R) {
const g = R.L && R.L.goal;
if (!g) return 0;
switch (g.t) {
case 'score': return R.score;
case 'coins': return R.coins;
case 'gates': return R.gates;
case 'dgates': return R.driftGates;
case 'near': return R.near;
case 'chain': return Math.floor(Math.max(R.bestChainM, R.chain ? R.chainDist / 10 : 0));
default: return Math.floor(Math.min(R.d, R.finishD) / 10);
}
}
export const goalMet = (R) => !R.L || R.L.goal.t === 'finish' || goalValue(R) >= R.L.goal.n;
/** Stars for a finished level run: 0 = not cleared, 1 = cleared, +1 for each points threshold reached. */
export function levelStars(L, won, score) {
if (!won) return 0;
return 1 + (score >= L.stars[0] ? 1 : 0) + (score >= L.stars[1] ? 1 : 0);
}
/** One-line goal text, e.g. "Collect 12 coins" (the finish line always ends the level). */
export function goalText(L) {
const g = L.goal, n = g.n.toLocaleString('en-US');
return { finish: `Reach the finish (${L.dist} m)`, score: `Score ${n} points`, coins: `Collect ${n} coins`, gates: `Pass ${n} gates`, dgates: `Drift through ${n} gates`, near: `Near-miss ${n} cones`, chain: `Drift ${n} m in one chain` }[g.t];
}
/** Short goal unit for the HUD counter. */
export const goalUnit = (L) => ({ finish: 'm', score: 'pts', coins: 'coins', gates: 'gates', dgates: 'drift gates', near: 'near-misses', chain: 'm chain' }[L.goal.t]);
/** Run level n with a driver (default: the autoSteer bot) to the end; returns the finished run. For tests and tuning. */
export function simLevel(n, driver = (R) => autoSteer(R.road, R.car, R.idx), maxT = 180) {
const R = newRunState({ seed: levelSeed(n), level: n });
while (!R.over && R.t < maxT) simTick(R, driver(R));
return R;
}
// ------------------------------------------------------------------ Time Attack (full-game mode, games lane GM 9 Oct 2026)
/** Medal times for level n (seconds to a cleared finish): the plain autopilot's clear time sets silver; gold is 8%
* faster than the bot (drift lines and nitro), bronze 20% slower. Deterministic: the same for every player. */
export const TA_FREE = 5; // Time Attack medals on levels 1-5 for everyone; every level with the full game or Fun Pass
export const TA_COINS = [50, 100, 200]; // garage coins the first time each medal is won on a level
const taCache = {};
export function medalTimes(n) {
if (!taCache[n]) { const R = simLevel(n); const t = Math.max(4, R.t); taCache[n] = { gold: +(t * 0.92).toFixed(1), silver: +t.toFixed(1), bronze: +(t * 1.2).toFixed(1) }; }
return taCache[n];
}
/** 0 none, 1 bronze, 2 silver, 3 gold for a cleared time. */
export function medalOf(n, t) { const m = medalTimes(n); return t <= m.gold ? 3 : t <= m.silver ? 2 : t <= m.bronze ? 1 : 0; }
export const MEDAL = ['', '🥉', '🥈', '🥇'];
export const MEDAL_NAME = ['', 'Bronze', 'Silver', 'Gold'];
/** Record a cleared time. Returns { best, medal, prev, coins } (coins for each medal tier won for the first time). */
export function recordTime(save, n, t) {
const before = save.ta[n], prev = before ? medalOf(n, before) : 0;
if (!before || t < before) save.ta[n] = Math.round(t * 100) / 100;
const medal = medalOf(n, save.ta[n]);
let coins = 0;
for (let k = prev; k < medal; k++) coins += TA_COINS[k];
save.coins += coins;
return { best: save.ta[n], medal, prev, coins, improved: !before || t < before };
}
export const totalMedals = (save) => Object.entries(save.ta).reduce((a, [n, t]) => a + medalOf(+n, t), 0);