// Sled Volt: game screen. Fixed 60 Hz simulation (core.js) drawn every frame (render.js), swipe + keyboard input, // endless / daily / ghost / challenge modes, missions, garage, the daily leaderboard (toys Worker re-plays each run), // share card and challenge links. Everything personal stays on this device. (c) 2026 CyberMax. All rights reserved. import * as S from './core.js'; import { World } from './render.js'; import { Sound } from './audio.js'; import { count, store, toast, share, pwa, today, dayNumber, rr, canvasBlob, themeToggle, API } from './cmx.js'; import { createShop } from './shop.js'; const GAME = 'sledvolt'; const PATH = '/games/sledvolt/'; const ROBLOX_URL = 'https://www.roblox.com/games/134881648422275'; // the live Roblox experience (published 24 Oct 2026) const SAVE = 'sledvolt:v1'; const $ = (id) => document.getElementById(id); const fmt = (n) => Math.floor(n).toLocaleString('en-US'); const params = new URLSearchParams(location.search); const CAP = params.get('cap') === '1'; // frame-stepped capture mode for the trailer/tests // ------------------------------------------------------------------ save const DEF = { v: 1, coins: 0, best: 0, bestRun: null, daily: null, owned: { sleds: ['plank'], riders: ['juno'], trails: ['powder'] }, eq: { sled: 'plank', rider: 'juno', trail: 'powder' }, mis: { level: 1, ids: S.missionSet(1), prog: {} }, runs: 0, name: '', seen: 0, iap: [] }; let save = Object.assign(structuredClone(DEF), store(SAVE) || {}); for (const k of ['sleds', 'riders', 'trails']) if (!Array.isArray(save.owned?.[k])) save.owned = structuredClone(DEF.owned); if (!Array.isArray(save.iap)) save.iap = []; const persist = () => store(SAVE, save); // every look: the coin-bought ones plus the shop-pack ones (S.SHOP_LOOKS); looks only, every sled rides the same const LOOKS = { sleds: [...S.SLEDS, ...S.SHOP_LOOKS.sleds], riders: [...S.RIDERS, ...S.SHOP_LOOKS.riders], trails: [...S.TRAILS, ...S.SHOP_LOOKS.trails] }; const look = () => ({ sled: LOOKS.sleds.find((s) => s.id === save.eq.sled) || S.SLEDS[0], rider: LOOKS.riders.find((s) => s.id === save.eq.rider) || S.RIDERS[0], trail: LOOKS.trails.find((s) => s.id === save.eq.trail) || S.TRAILS[0] }); // ------------------------------------------------------------------ shop (coin packs + looks packs, shop.js; prices = revenue/packs/stripe/sledvolt-shop) const PACK_NAMES = { starter: 'Starter Pack', aurora: 'Aurora Garage' }; const SHOP_OFFERS = [ { ref: 'coins-1500', name: 'Coin Sack', what: '1,500 coins', price: '$0.99', coins: 1500 }, { ref: 'starter', name: 'Starter Pack', what: '3,000 coins + the Kindle Comet sled (only in this pack)', price: '$1.99', coins: 3000, looks: ['sleds:kindle'] }, { ref: 'coins-5000', name: 'Coin Chest', what: '5,000 coins', price: '$2.99', coins: 5000 }, { ref: 'aurora', name: 'Aurora Garage', what: 'Every sled, rider and trail now (all 18), plus Prism Bob, Nova and the Prism trail', price: '$4.99', looks: ['sleds:prism', 'riders:nova', 'trails:prism'] }, { ref: 'coins-15000', name: 'Coin Vault', what: '15,000 coins, the most coins per dollar', price: '$6.99', coins: 15000 }, ]; const shop = createShop({ game: GAME, name: 'Sled Volt', offers: SHOP_OFFERS, has: (code) => save.iap.includes(code), credit(g, code) { // coins, looks and the order code are saved in ONE write, so an order can never pay twice here save.coins += Math.max(0, Math.floor(g.coins || 0)); const add = (slot, id) => { if (LOOKS[slot] && LOOKS[slot].some((x) => x.id === id) && !save.owned[slot].includes(id)) save.owned[slot].push(id); }; if (g.all) for (const slot of Object.keys(LOOKS)) for (const it of LOOKS[slot]) if (!it.pack) add(slot, it.id); for (const l of g.looks || []) { const [slot, id] = String(l).split(':'); add(slot, id); } if (!save.iap.includes(code)) save.iap.push(code); persist(); if (state === 'menu') refreshMenu(); if (!$('sheet').hidden && sheetRedraw) sheetRedraw(); }, toast, count: (kind, label) => count(GAME, kind, label), }); /** The next coin sled the player can't afford yet: { it, need } or null. */ function shortOfSled() { const it = S.SLEDS.find((s) => s.cost > 0 && !save.owned.sleds.includes(s.id)); return it && it.cost > save.coins ? { it, need: it.cost - save.coins } : null; } const shortText = (need) => { const p = shop.packFor(need); return `You need ${fmt(need)} more coins: get ${fmt(p.coins)} for ${p.price}`; }; let sheetRedraw = null; // ------------------------------------------------------------------ setup const canvas = $('c'), stage = $('stage'); const low = /Android|iPhone|iPad|Mobile/i.test(navigator.userAgent) && (navigator.hardwareConcurrency || 4) <= 4; const world = new World(canvas, { low }); world.setLook(look()); const snd = new Sound(); const app = pwa(GAME, $('install')); themeToggle($('theme')); const todayIso = today(); const dayNo = dayNumber(todayIso); if (ROBLOX_URL) { $('m-roblox').href = ROBLOX_URL; $('m-roblox').textContent = 'Race friends live on Roblox'; } else { $('m-roblox').textContent = 'Live races with friends: coming to Roblox'; $('m-roblox').removeAttribute('target'); } let state = 'menu'; // menu | count | play | over | pause let run = null, prev = null, ghost = null, ghostInputs = null, gi = 0, inputs = [], queue = []; let mode = 'endless', seed = 1, level = 1, chal = null, top1 = null, beatTop = false; let acc = 0, last = performance.now(), overAt = 0, caughtT = 0, events = [], frameCard = null, lastBiome = '', countT = 0; const smashed = new Set(); let mediaFriends = []; // challenge link: ?c=... (inputs = the challenger's run: you race their ghost) function parseChallenge() { const c = params.get('c'); if (!c) return null; const [sd, sc, nm, enc] = c.split('.'); const s = Number(sd), score = Number(sc); if (!Number.isFinite(s) || s < 1 || !Number.isFinite(score)) return null; const inp = enc ? S.decodeInputs(enc) : null; return { seed: s, score, name: (nm || 'A friend').replace(/[^A-Za-z0-9 ]/g, '').slice(0, 12) || 'A friend', inputs: inp, daily: params.get('dl') || '' }; } chal = parseChallenge(); // ------------------------------------------------------------------ attract mode (a bot sleds behind the menu) function attract() { run = S.newRun(S.dailySeed(dayNo) + 11, { level: 1 }); prev = snap(run); ghost = null; inputs = []; smashed.clear(); world.reset(); } function snap(r) { return { d: r.d, x: r.x, y: r.y }; } // ------------------------------------------------------------------ start a run function start(m) { snd.unlock(); snd.play({ type: 'go' }); mode = m; ghost = null; ghostInputs = null; gi = 0; beatTop = false; if (m === 'daily') { seed = S.dailySeed(dayNo); level = 1; if (save.daily && save.daily.day === dayNo && save.daily.enc) ghostInputs = S.decodeInputs(save.daily.enc); } else if (m === 'ghost' && save.bestRun) { seed = save.bestRun.seed; level = save.bestRun.level || 1; ghostInputs = S.decodeInputs(save.bestRun.enc); } else if (m === 'chal' && chal) { seed = chal.seed; level = 1; ghostInputs = chal.inputs; } else { mode = 'endless'; seed = (Math.random() * 2147483000) | 1; level = save.mis.level; } run = S.newRun(seed, { level }); prev = snap(run); if (ghostInputs && ghostInputs.length) { ghost = S.newRun(seed, { level }); ghost.quiet = true; } inputs = []; queue = []; smashed.clear(); world.reset(); world.setLook(look()); events = []; acc = 0; caughtT = 0; lastBiome = ''; show('hud'); document.body.classList.add('playing'); world.resize(); state = 'play'; $('h-vs').hidden = true; if (mode === 'daily' && top1) { $('h-vs').hidden = false; } if (mode === 'chal' && chal) { $('h-vs').hidden = false; } const first = save.runs < 2; hint(first ? (matchMedia('(pointer:coarse)').matches ? 'Swipe ← → ↑ ↓' : '← → dodge · ↑ jump · ↓ tuck') : ''); count(GAME, 'play', mode); canvas.focus({ preventScroll: true }); } function show(which) { for (const id of ['menu', 'over', 'pause', 'sheet']) $(id).hidden = id !== which; $('hud').hidden = !(which === 'hud' || which === 'pause'); } function toMenu() { state = 'menu'; document.body.classList.remove('playing'); world.resize(); snd.quiet(); attract(); show('menu'); refreshMenu(); } // ------------------------------------------------------------------ input function act(a) { if (state === 'play') { queue.push(a); if (queue.length > 3) queue.shift(); } else if (state === 'over' && performance.now() - overAt > 350 && (a === 'U' || a === 'B')) start(mode === 'chal' ? 'chal' : mode); } const KEY = { ArrowLeft: 'L', KeyA: 'L', ArrowRight: 'R', KeyD: 'R', ArrowUp: 'U', KeyW: 'U', ArrowDown: 'D', KeyS: 'D', Space: 'B' }; addEventListener('keydown', (e) => { if (e.target && (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA')) return; const a = KEY[e.code]; if (state === 'play' && a) { e.preventDefault(); if (!e.repeat) act(a); return; } if (state === 'play' && (e.code === 'Escape' || e.code === 'KeyP')) { pause(); return; } if (state === 'pause' && (e.code === 'Escape' || e.code === 'KeyP' || e.code === 'Space')) { e.preventDefault(); resume(); return; } if (state === 'over' && (e.code === 'Space' || e.code === 'Enter' || e.code === 'KeyR') && performance.now() - overAt > 350) { e.preventDefault(); start(mode); return; } if (state === 'menu' && (e.code === 'Space' || e.code === 'Enter') && document.activeElement === document.body) { e.preventDefault(); start('endless'); } }); // swipe anywhere on the stage; a quick double tap fires VOLT let tStart = null, lastTap = 0; stage.addEventListener('pointerdown', (e) => { snd.unlock(); if (state !== 'play') return; if (e.target.closest('button')) return; tStart = { x: e.clientX, y: e.clientY, t: performance.now(), id: e.pointerId, fired: false }; }); stage.addEventListener('pointermove', (e) => { if (!tStart || tStart.id !== e.pointerId || tStart.fired || state !== 'play') return; const dx = e.clientX - tStart.x, dy = e.clientY - tStart.y; const th = Math.max(22, Math.min(window.innerWidth, window.innerHeight) * 0.045); if (Math.abs(dx) > th || Math.abs(dy) > th) { tStart.fired = true; act(Math.abs(dx) > Math.abs(dy) ? (dx < 0 ? 'L' : 'R') : (dy < 0 ? 'U' : 'D')); } }); stage.addEventListener('pointerup', (e) => { if (state === 'over' && !e.target.closest('button,input,form,a') && performance.now() - overAt > 350) { start(mode); return; } if (!tStart || tStart.id !== e.pointerId) return; if (!tStart.fired && performance.now() - tStart.t < 260) { const now = performance.now(); if (now - lastTap < 300) { act('B'); lastTap = 0; } else lastTap = now; } tStart = null; }); stage.addEventListener('contextmenu', (e) => e.preventDefault()); $('h-volt').addEventListener('pointerdown', (e) => { e.stopPropagation(); act('B'); }); $('h-pause').addEventListener('click', () => pause()); function pause() { if (state !== 'play') return; state = 'pause'; show('pause'); snd.quiet(); syncSoundBtns(); } function resume() { if (state !== 'pause') return; state = 'play'; show('hud'); last = performance.now(); acc = 0; } $('p-resume').onclick = resume; $('p-menu').onclick = () => toMenu(); document.addEventListener('visibilitychange', () => { if (document.hidden) pause(); }); addEventListener('blur', () => pause()); addEventListener('resize', () => world.resize()); function syncSoundBtns() { $('p-sound').textContent = snd.on ? '🔊 Sound on' : '🔇 Sound off'; $('p-music').textContent = snd.music ? '🎵 Music on' : '🎵 Music off'; $('m-sound').textContent = snd.on ? '🔊' : '🔇'; } $('p-sound').onclick = () => { snd.unlock(); snd.toggle(); syncSoundBtns(); }; $('p-music').onclick = () => { snd.unlock(); snd.toggleMusic(); syncSoundBtns(); }; $('m-sound').onclick = () => { snd.unlock(); snd.toggle(); syncSoundBtns(); }; // ------------------------------------------------------------------ HUD let popT = 0; function pop(text, color) { const p = $('h-pop'); p.textContent = text; p.style.color = color || '#fff'; p.classList.remove('on'); void p.offsetWidth; p.classList.add('on'); } function hint(t) { const h = $('h-hint'); if (!t) { h.hidden = true; return; } h.textContent = t; h.hidden = false; setTimeout(() => { h.hidden = true; }, 3200); } const PW_ICON = { magnet: ['🧲', '#FF4D6D'], shield: ['🛡', '#4DA6FF'], double: ['×2', '#FFC928'], glider: ['🪁', '#3FD18A'] }; function hud() { const r = run; $('h-score').textContent = fmt(r.score); $('h-coins').textContent = r.coins; const m = r.level * (r.pw.double > 0 ? 2 : 1) * (r.boost > 0 ? 2 : 1); const mu = $('h-mult'); mu.textContent = `×${m}`; mu.classList.toggle('x2', m > r.level); const cb = $('h-combo'); cb.hidden = r.combo <= 1; cb.textContent = `COMBO ×${r.combo}`; $('h-dist').textContent = `${fmt(r.d)} m`; const ring = $('h-ring'); ring.style.strokeDashoffset = String(276.5 * (1 - r.frost / 100)); const v = $('h-volt'); v.classList.toggle('full', r.frost >= 100 && r.boost <= 0); v.classList.toggle('on', r.boost > 0); let h = ''; for (const p of ['magnet', 'shield', 'double', 'glider']) if (r.pw[p] > 0) { const [ic, col] = PW_ICON[p]; h += `
${ic}
`; } const pw = $('h-pw'); if (pw._h !== h) { pw.innerHTML = h; pw._h = h; } const danger = r.beast > 0 && r.alive; $('h-beast').hidden = !danger; $('hud').classList.toggle('danger', danger); const vs = $('h-vs'); if (!vs.hidden) { const target = mode === 'chal' && chal ? chal.score : top1 ? top1.score : 0; const who = mode === 'chal' && chal ? chal.name : top1 ? `#1 ${top1.name}` : ''; if (target) { const ahead = r.score >= target; vs.classList.toggle('ahead', ahead); vs.textContent = ahead ? `AHEAD OF ${who.toUpperCase()}!` : `${who}: ${fmt(target)}`; if (ahead && !beatTop) { beatTop = true; pop(mode === 'chal' ? 'YOU BEAT THEIR SCORE!' : 'NEW #1 PACE!', '#2FD3A0'); snd.play({ type: 'record' }); } } } const b = S.biomeAt(r.d); if (b !== lastBiome) { if (lastBiome) { const el = $('h-biome'); el.textContent = S.BIOME_NAMES[b].toUpperCase(); el.classList.remove('on'); void el.offsetWidth; el.classList.add('on'); } lastBiome = b; } } function onEvents(evs) { for (const e of evs) { snd.play(e); if (e.type === 'near') pop(`CLOSE! +${fmt(e.pts)}`, '#FFE14D'); else if (e.type === 'stunt') pop(`AIR! +${fmt(e.pts)}`, '#5CE1FF'); else if (e.type === 'smash') pop(`SMASH +${fmt(e.pts)}`, '#FFE14D'); else if (e.type === 'boost') pop('VOLT!', '#5CE1FF'); else if (e.type === 'stumble' || e.type === 'bump') pop('STUMBLE!', '#FF7A5C'); else if (e.type === 'power') pop({ magnet: 'MAGNET', shield: 'SHIELD', double: 'DOUBLE SCORE', glider: 'GLIDER' }[e.p] || '', '#fff'); else if (e.type === 'gift' && e.coins) pop(`GIFT +${e.coins} ❄`, '#FFE27A'); else if (e.type === 'gift' && e.frost) pop('GIFT: FULL FROST', '#5CE1FF'); else if (e.type === 'shieldbreak') pop('SHIELD SAVED YOU', '#4DA6FF'); if (e.type === 'smashed' || e.type === 'shieldbreak') smashed.add(e.id); if (navigator.vibrate && (e.type === 'crash' || e.type === 'caught')) navigator.vibrate(120); else if (navigator.vibrate && (e.type === 'stumble' || e.type === 'bump')) navigator.vibrate(40); } } // ------------------------------------------------------------------ the loop function tick() { prev = snap(run); const a = state === 'play' ? (queue.shift() || '') : S.bot(run, 1); if (state === 'play' && a) inputs.push([run.tick + 1, a]); S.step(run, a); if (ghost) { const t = ghost.tick + 1; let ga = ''; while (gi < ghostInputs.length && ghostInputs[gi][0] < t) gi++; if (gi < ghostInputs.length && ghostInputs[gi][0] === t) { ga = ghostInputs[gi][1]; gi++; } S.step(ghost, ga); } if (state === 'play') { onEvents(run.ev); events.push(...run.ev); } else events.push(...run.ev); if (state !== 'play' && !run.alive) attract(); } let frames = 0, slowT = 0, qScale = 1; function loop(now) { const dt = Math.min(0.1, (now - last) / 1000); last = now; if (!CAP) step(dt); requestAnimationFrame(loop); } function step(dt, draw = true) { if (state === 'play' || state === 'menu' || state === 'over') { if (state !== 'over' || caughtT < 1.6) acc += dt; while (acc >= 1 / 60) { if (state === 'over') { caughtT += 1 / 60; acc -= 1 / 60; continue; } tick(); acc -= 1 / 60; if (state === 'play' && !run.alive) { endRun(); break; } } } if (state === 'play') { hud(); snd.drive({ v: run.v, alive: run.alive, ground: run.y < 0.2, air: run.air !== '', grind: !!run.grind, boost: run.boost > 0, duck: run.duck > 0 }); } if (!draw) return; const ev = events; events = []; if (mediaFriends.length) for (const f of mediaFriends) { f.d = run.d + f.dd; f.x = f.lane * S.LANE_W; } world.frame(run, { friends: mediaFriends, alpha: state === 'over' ? 1 : acc * 60, prev, dt, events: ev, ghost: ghost && (ghost.alive || ghost.tick > run.tick - 60) ? ghost : null, caught: state === 'over' && run.cause === 'beast', caughtT }); if (state === 'over' && !frameCard) frameCard = canvas.toDataURL('image/jpeg', 0.85); // adaptive resolution: hold 60 fps on mid phones frames++; slowT += dt > 1 / 45 ? dt : -dt * 0.25; if (slowT < 0) slowT = 0; if (slowT > 1.5 && qScale > 0.6) { qScale -= 0.15; world.setQuality(qScale); slowT = 0; } } // ------------------------------------------------------------------ end of run const WHY = { tree: 'Wiped out by a pine', rock: 'Smacked a rock', log: 'Tripped on a log', branch: 'Clotheslined by a branch', fence: 'Crashed a fence', snowman: 'Flattened a snowman (and you)', sledder: 'Bumped another sledder', post: 'Hugged a lamp post', banner: 'Tangled in the bunting', pillar: 'Hit an ice pillar', crystal: 'Shattered on crystals', icicles: 'Icicled', icelog: 'Slid into an ice block', boulder: 'Bounced off a boulder', ball: 'Buried by an avalanche', pylon: 'Hit a ski-lift pylon', fell: 'Fell into the chasm', beast: 'The Rimehorn caught you' }; function endRun() { state = 'over'; overAt = performance.now(); caughtT = 0; frameCard = null; snd.quiet(); hud(); const r = run, score = S.finalScore(r); const stats = S.runStats(r, mode === 'daily'); save.runs += 1; save.coins += r.coins; const rec = score > save.best; if (rec) save.best = score; if (mode === 'endless' && (!save.bestRun || score > save.bestRun.score)) save.bestRun = { seed, level, enc: S.encodeInputs(inputs), score }; let dailyRec = false; if (mode === 'daily' && (!save.daily || save.daily.day !== dayNo || score > save.daily.score)) { save.daily = { day: dayNo, score, enc: S.encodeInputs(inputs), ticks: r.tick }; dailyRec = true; } const res = S.applyMissions(save.mis, stats); save.mis = res.state; persist(); if (rec) snd.play({ type: 'record' }); $('o-why').textContent = WHY[r.cause] || 'Wipeout!'; $('o-score').textContent = fmt(score); $('o-rec').hidden = !(rec || dailyRec); $('o-rec').textContent = rec ? 'NEW BEST!' : 'BEST TODAY!'; const vsLine = mode === 'chal' && chal ? (score > chal.score ? ` · You beat ${chal.name}!` : ` · ${chal.name}: ${fmt(chal.score)}`) : ''; $('o-line').textContent = `${fmt(r.d)} m · ${S.BIOME_NAMES[S.biomeAt(r.d)]} · +${r.coins} ❄ · ${r.st.near} close calls${vsLine}`; const ul = $('o-mis'); ul.innerHTML = ''; if (res.levelUp) { const li = document.createElement('li'); li.className = 'done'; li.innerHTML = `MISSION LEVEL UP! Score ×${save.mis.level}✔`; ul.appendChild(li); } else for (const id of save.mis.ids) { const m = S.missionById(id); const p = Math.min(m.goal, save.mis.prog[id] || 0); const li = document.createElement('li'); if (p >= m.goal) li.className = 'done'; li.innerHTML = `${m.text}${p >= m.goal ? '✔' : `${fmt(p)}/${fmt(m.goal)}`}`; ul.appendChild(li); } $('o-post').hidden = mode !== 'daily'; $('o-form').hidden = true; const short = !shop.portal() && shortOfSled(); // one quiet line, only when the next sled is out of reach $('o-shop').hidden = !short; if (short) $('o-shop').textContent = `${short.it.name}: ${shortText(short.need)}`; show('over'); $('hud').hidden = false; document.body.classList.add('playing'); count(GAME, 'win', mode); if (save.runs >= 2) app.offer(); } $('o-retry').onclick = () => start(mode); $('o-shop').onclick = () => openShop('results'); $('o-menu').onclick = () => toMenu(); // ------------------------------------------------------------------ share card + challenge link function challengeUrl() { const enc = S.encodeInputs(inputs); const name = (save.name || 'A friend').replace(/[^A-Za-z0-9 ]/g, '').slice(0, 12); const u = new URL(`https://cybermaxtools.com${PATH}`); u.searchParams.set('c', `${seed}.${S.finalScore(run)}.${name}.${enc.length < 6000 ? enc : ''}`); if (mode === 'daily') u.searchParams.set('dl', String(dayNo)); return u.toString(); } function biomeEmoji(d) { const n = Math.min(8, Math.floor(d / S.BIOME_LEN) + 1); let s = ''; for (let i = 0; i < n; i++) s += ['🌲', '🏘️', '🧊', '🌌'][i % 4]; return s; } function shareText() { const r = run; return `SLED VOLT ❄️ ${mode === 'daily' ? `Daily #${dayNo}` : 'Endless run'}\n🏁 ${fmt(S.finalScore(r))} pts · ${fmt(r.d)} m\n${biomeEmoji(r.d)}\n⚡${r.st.boosts} VOLT · 💨${r.st.near} close calls · ❄${r.coins}`; } async function card() { const W = 1080, H = 1350; const cv = document.createElement('canvas'); cv.width = W; cv.height = H; const g = cv.getContext('2d'); const bgr = g.createLinearGradient(0, 0, 0, H); bgr.addColorStop(0, '#0B1830'); bgr.addColorStop(1, '#16335F'); g.fillStyle = bgr; g.fillRect(0, 0, W, H); if (frameCard) { const img = new Image(); img.src = frameCard; await img.decode().catch(() => {}); const ar = img.width / img.height || 1.6; const ih = 760, iw = ih * ar; g.save(); rr(g, 40, 40, W - 80, ih, 36); g.clip(); g.drawImage(img, (W - iw) / 2, 40, iw, ih); g.restore(); } g.textAlign = 'center'; g.fillStyle = '#fff'; g.font = '800 92px "Barlow Condensed", system-ui'; g.fillText('SLED VOLT', W / 2, 920); g.fillStyle = '#5CE1FF'; g.font = '800 46px "Barlow Condensed", system-ui'; g.fillText(mode === 'daily' ? `DAILY RUN #${dayNo}` : mode === 'chal' ? 'CHALLENGE RUN' : 'ENDLESS RUN', W / 2, 980); g.fillStyle = '#FFE14D'; g.font = '800 170px "Barlow Condensed", system-ui'; g.fillText(fmt(S.finalScore(run)), W / 2, 1150); g.fillStyle = '#E6EEFA'; g.font = '700 40px system-ui'; g.fillText(`${fmt(run.d)} m · ${S.BIOME_NAMES[S.biomeAt(run.d)]} · ${run.st.near} close calls`, W / 2, 1215); g.fillStyle = '#A3B8D8'; g.font = '700 32px system-ui'; g.fillText('Beat it free: cybermaxtools.com/games/sledvolt', W / 2, 1290); return cv; } $('o-share').onclick = async () => { snd.play({ type: 'ui' }); const cv = await card(); const blob = await canvasBlob(cv); await share(GAME, shareText(), PATH, blob, 'sledvolt.png'); }; $('o-chal').onclick = async () => { snd.play({ type: 'ui' }); if (!save.name) { const n = prompt('Your name for the challenge (up to 12 letters):', '') || ''; save.name = n.replace(/[^A-Za-z0-9 ]/g, '').slice(0, 12); persist(); } const url = challengeUrl(); const text = `I scored ${fmt(S.finalScore(run))} on Sled Volt. Same mountain, my ghost is waiting. Beat me:`; try { if (navigator.share) { await navigator.share({ text, url }); count(GAME, 'share', 'challenge'); return; } } catch (e) { if (e && e.name === 'AbortError') return; } try { await navigator.clipboard.writeText(`${text} ${url}`); toast('Challenge link copied. Send it to a friend!'); } catch { prompt('Copy your challenge link:', url); } count(GAME, 'share', 'challenge'); }; window.__card = card; // ------------------------------------------------------------------ daily board (toys Worker replays every posted run) async function loadTop() { try { const r = await fetch(`${API}/api/board?g=${GAME}&d=${todayIso}`, { signal: AbortSignal.timeout(4000) }); if (!r.ok) return null; const j = await r.json(); const list = j.top || j.rows || j.board || []; if (list.length) top1 = { name: list[0].name, score: list[0].score }; return list; } catch { return null; } } $('o-post').onclick = () => { $('o-form').hidden = false; $('o-name').value = (save.name || '').slice(0, 3).toUpperCase(); $('o-name').focus(); }; $('o-form').onsubmit = async (e) => { e.preventDefault(); const name = $('o-name').value.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 3); if (!name) { toast('Initials: 1 to 3 letters or digits.'); return; } try { const r = await fetch(`${API}/api/board`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ g: GAME, d: todayIso, name, taps: save.daily && save.daily.day === dayNo ? save.daily.enc : S.encodeInputs(inputs) }) }); const j = await r.json(); if (j.ok) { toast(j.rank ? `Posted! You're #${j.rank} today.` : 'Posted! Not in the top 20 yet. Keep going.', 3500); $('o-form').hidden = true; count(GAME, 'share', 'board'); loadTop(); } else toast(j.message || 'That run could not be posted.', 3500); } catch { toast('Could not reach the leaderboard. Try again in a minute.', 3500); } }; // ------------------------------------------------------------------ menu, sheets function refreshMenu() { $('m-coins').textContent = fmt(save.coins); $('m-best').textContent = fmt(save.best); $('m-level').textContent = `Mission Level ×${save.mis.level}`; $('m-daily-sub').textContent = save.daily && save.daily.day === dayNo ? `#${dayNo} · best ${fmt(save.daily.score)}` : `#${dayNo} · same for everyone`; $('m-ghost').disabled = !save.bestRun; $('m-ghost-sub').textContent = save.bestRun ? `beat ${fmt(save.bestRun.score)}` : 'play a run first'; const ch = $('m-chal'); if (chal) { ch.hidden = false; ch.innerHTML = `${chal.name} challenges you: beat ${fmt(chal.score)} on their course${chal.inputs ? ' and race their ghost' : ''}.`; $('m-play').textContent = '▶ ACCEPT CHALLENGE'; } $('m-keys').textContent = matchMedia('(pointer:coarse)').matches ? 'Swipe ← → dodge · ↑ jump · ↓ tuck · double-tap VOLT' : '← → dodge · ↑ jump · ↓ tuck · Space VOLT · P pause'; } $('m-play').onclick = () => start(chal ? 'chal' : 'endless'); $('m-daily').onclick = () => start('daily'); $('m-ghost').onclick = () => start('ghost'); function sheet(title, tabs, render) { snd.unlock(); snd.play({ type: 'ui' }); $('s-title').textContent = title; const tb = $('s-tabs'); tb.innerHTML = ''; let cur = tabs[0]; const draw = () => { for (const b of tb.children) b.setAttribute('aria-pressed', String(b.dataset.t === cur)); render(cur, $('s-body')); }; if (tabs.length > 1) for (const t of tabs) { const b = document.createElement('button'); b.type = 'button'; b.textContent = t; b.dataset.t = t; b.onclick = () => { cur = t; draw(); }; tb.appendChild(b); } draw(); sheetRedraw = draw; show('sheet'); } $('s-close').onclick = () => { sheetRedraw = null; show('menu'); refreshMenu(); }; function openShop(from, note = '') { if (shop.portal()) return; if (state === 'over') { state = 'menu'; document.body.classList.remove('playing'); world.resize(); snd.quiet(); attract(); } sheet('Get coins', ['shop'], (_, body) => { body.innerHTML = shop.html(from, note); shop.bind(body); }); count(GAME, 'cta', `shop-open-${from}`); } $('m-mis').onclick = () => sheet(`Missions · Level ×${save.mis.level}`, ['now'], (_, body) => { body.innerHTML = `

Finish all 3 to raise your Mission Level: a bigger score multiplier and longer power-ups.

` + save.mis.ids.map((id) => { const m = S.missionById(id); const p = Math.min(m.goal, save.mis.prog[id] || 0); return `
${m.text} ${fmt(p)} / ${fmt(m.goal)}
`; }).join(''); }); let garageNote = ''; $('m-garage').onclick = () => { garageNote = ''; sheet('Garage', ['Sleds', 'Riders', 'Trails'], (tab, body) => { const key = tab === 'Sleds' ? 'sleds' : tab === 'Riders' ? 'riders' : 'trails', ek = key.slice(0, -1); const list = LOOKS[key].filter((it) => !it.pack || !shop.portal() || save.owned[key].includes(it.id)); const getBtn = shop.portal() ? '' : ' '; body.innerHTML = `

${garageNote ? `` : `❄ ${fmt(save.coins)} coins. Looks only: every sled rides the same.`}${getBtn}

` + list.map((it) => { const own = save.owned[key].includes(it.id), eq = save.eq[ek] === it.id; const sw = tab === 'Sleds' ? `linear-gradient(135deg,${it.color} 60%,${it.accent} 60%)` : tab === 'Riders' ? `linear-gradient(135deg,${it.coat} 55%,${it.hat} 55%)` : `linear-gradient(90deg,transparent,${it.color})`; return `
${it.name}
`; }).join('') + '
'; for (const b of body.querySelectorAll('.shop-get,.shop-short')) b.onclick = () => openShop(b.classList.contains('shop-short') ? 'garage-short' : 'garage'); for (const b of body.querySelectorAll('button[data-id]')) b.onclick = () => { const it = list.find((q) => q.id === b.dataset.id); const own = save.owned[key].includes(it.id); if (!own && it.pack) { if (!shop.portal()) openShop(`garage-${it.pack}`); return; } if (!own) { if (save.coins < it.cost) { if (shop.portal()) toast(`You need ${fmt(it.cost - save.coins)} more coins.`); else { garageNote = shortText(it.cost - save.coins); sheetRedraw && sheetRedraw(); } return; } save.coins -= it.cost; save.owned[key].push(it.id); snd.play({ type: 'power' }); } garageNote = ''; save.eq[ek] = it.id; persist(); world.setLook(look()); for (const t of $('s-tabs').children) if (t.dataset.t === tab) t.click(); // redraw this tab }; }); }; $('m-board').onclick = async () => { sheet(`Daily #${dayNo} · top 20`, ['today'], (_, body) => { body.innerHTML = '

Loading the board...

'; }); const list = await loadTop(); const body = $('s-body'); if (!list) { body.innerHTML = '

The board is offline right now; your best is saved on this device.

'; return; } if (!list.length) { body.innerHTML = '

Nobody has posted today yet. Play the daily run and take #1.

'; return; } body.innerHTML = '
    ' + list.slice(0, 20).map((x, i) => `
  1. #${i + 1} ${String(x.name).replace(/[^A-Z0-9]/gi, '')}${fmt(x.score)}
  2. `).join('') + '
'; }; // ------------------------------------------------------------------ boot attract(); refreshMenu(); syncSoundBtns(); show('menu'); shop.capture(); loadTop(); if (chal && chal.daily) count(GAME, 'play', 'challenge-link'); requestAnimationFrame((t) => { last = t; requestAnimationFrame(loop); }); // Read-only state + a few hooks for tests/e2e.mjs and the trailer (the e2e plays through real keyboard/touch input). window.__sledvolt = { get state() { return state; }, get mode() { return mode; }, get run() { return run && { tick: run.tick, d: run.d, x: run.x, y: run.y, lane: run.lane, alive: run.alive, cause: run.cause, score: S.finalScore(run), coins: run.coins, frost: run.frost, air: run.air, duck: run.duck, boost: run.boost, beast: run.beast, v: run.v }; }, bot() { return run ? S.bot(run, 1) : ''; }, peekBot() { if (!run) return ''; const a = S.bot(run, 1); return a; }, frame(dt = 1 / 60, draw = true) { step(dt, draw); }, // capture mode: advance exactly one frame (draw=false skips the render) warp(ticks) { // tests/trailer: let the bot drive ahead without drawing (to see later biomes quickly) for (let i = 0; i < ticks && run.alive; i++) { prev = snap(run); const a = S.bot(run, 1); if (a) inputs.push([run.tick + 1, a]); S.step(run, a); if (ghost) S.step(ghost, ''); } world.reset(); }, inputs: () => inputs.length, // store renders (products/sledvolt/brand/render.mjs): set up a scene, then frame(dt, true) and screenshot media(o = {}) { start('endless'); if (o.seed) { seed = o.seed; run = S.newRun(seed, { level: 1 }); prev = snap(run); } if (o.warp) this.warp(o.warp); if (o.ground) { run.y = 0; run.vy = 0; run.air = ''; run.grind = 0; run.pw.glider = 0; } if (o.beast) run.beast = 380; if (o.boost) { run.boost = 140; } if (o.shield) run.pw.shield = 500; if (o.glider) { run.pw.glider = 300; run.y = 15.5; run.air = 'glide'; } if (o.look) { save.eq = o.look; world.setLook(look()); } const clear = (z, lane) => !run.course.items.some((it) => S.KINDS[it.k] && it.l === lane && Math.abs(it.z - z) < 9); mediaFriends = (o.friends || []).map((f, i) => { let lane = f.lane; for (const l of [f.lane, -1, 0, 1]) if (clear(run.d + f.dd, l) && (l !== run.lane || Math.abs(f.dd) > 5)) { lane = l; break; } return { ...f, lane, key: `${f.sled}:${f.rider}:${i}`, sled: S.SLEDS.find((x) => x.id === f.sled) || S.SLEDS[1], rider: S.RIDERS.find((x) => x.id === f.rider) || S.RIDERS[1] }; }); if (o.hideHud) $('hud').hidden = true; world.camOverride = o.cam || null; queue = []; return { d: run.d, biome: S.biomeAt(run.d) }; }, world: () => world, save: () => structuredClone(save), shop: (from = 'test') => openShop(from), challengeUrl, shareText, };