'use strict'; /** * View and input for Meteors. The simulation lives in GameCore; this file * only draws it, scales it to the viewport, and translates pointer events * into beginDrag / moveDrag / endDrag. Online play (stage 2) is wired * through Online (src/online.js) and the same GameCore. Offline Strijd * (t1119) uses Offline (src/offline.js) against local bots. */ function planetImages () { var list = [ { name: 'gray', url: 'images/block-gray.png' }, { name: 'locked', url: 'images/block-locked.png' }, { name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 }, { name: 'cell', url: 'images/cell.png' }, { name: 'pixel', url: 'images/pixel.png' }, { name: 'columnWarn', url: 'images/column-warn.png' }, // Keep the original Terra placeholders as aliases (Tim may still have them). { name: 'ember', url: 'images/block-ember.png' }, { name: 'aqua', url: 'images/block-aqua.png' }, { name: 'leaf', url: 'images/block-leaf.png' }, { name: 'sun', url: 'images/block-sun.png' }, { name: 'orchid', url: 'images/block-orchid.png' } ]; var planets = (typeof Planet !== 'undefined' ? Planet.allPlanets() : []); for (var i = 0; i < planets.length; i++) { var pl = planets[i]; for (var c = 0; c < pl.colors.length; c++) { list.push({ name: Planet.spriteKey(pl, c), url: pl.colors[c].image }); } } if (typeof Blocks !== 'undefined' && Blocks.images) { var extra = Blocks.images(); for (var b = 0; b < extra.length; b++) { list.push(extra[b]); } } return list; } var IMAGES = planetImages(); var GAME_OVER_DELAY = 2; var game = new Game(); var app = { mode: 'menu', core: null, scene: null, manager: null, planet: null, lastScore: 0, tile: 48, fieldX: 0, fieldY: 0, fieldW: 0, fieldH: 0, hudH: 56, sprites: Object.create(null), flames: Object.create(null), cells: [], pointerId: null, pointerType: null, activeTouchId: null, debugDrag: false, debugPhysics: false, gameOverShown: false, selectTween: null, online: false, eliminatedReported: false, spectating: false, miniH: 0, selectedPlanetId: 'terra', planetSelectContext: 'solo', offline: false, battle: null, swapTweens: null, columnWarn: null, warnClock: 0, miniAcc: 0, offlineResultShown: false, roundWonDelay: 0, roundWonHandled: false, rewardActive: false, onlineBefore: 0, pendingLobbyReturn: null }; window.onload = function () { app.debugDrag = isDragDebugEnabled(); app.debugPhysics = isPhysicsDebugEnabled(); var play = document.getElementById('btn-play'); play.addEventListener('click', onPlay); bindGameMenu(); play.addEventListener('pointerup', function (e) { // A touch-friendly path: some mobile browsers swallow the click // after a slightly sloppy tap. Ignore the following click. if (e.pointerType === 'touch' || e.pointerType === 'pen') { e.preventDefault(); onPlay(); } }); game.preloadImagesThenStart(IMAGES, function () { if (game.images.flame && game.images.flame.addAnimationCycle) { game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); } }); if (typeof I18n !== 'undefined') { I18n.init(); I18n.bindPicker(); I18n.onChange(function () { refreshAllUi(); }); } bindOnlineUi(); bindLeaderboard(); bindOfflineUi(); bindPlanetSelect(); restoreSelectedPlanet(); if (typeof Designer !== 'undefined' && Designer.bind) { Designer.bind(); } bindLoginPrompt(); if (typeof Online !== 'undefined' && Online.refresh) { Online.refresh().then(function () { applyProfileLocale(); refreshMenuAccount(); restoreSelectedPlanet(); renderPlanetGrid('planet-grid', false); renderPlanetGrid('lobby-planet-grid', true); maybeShowLoginPrompt(); }); } else { refreshMenuAccount(); maybeShowLoginPrompt(); } }; /** * t1201: the big "Play" button starts the rounds against bots (internal * mode 'offline', formerly "Offline Battle"); "Survival" starts the endless * solo game (internal mode 'solo', formerly "Play"). Internal ids and * play_finish modes are unchanged. */ function onPlay () { if (app.mode === 'playing') { return; } clearStartError(); openPlanetSelect('offline'); } function onSurvival () { if (app.mode === 'playing') { return; } clearStartError(); openPlanetSelect('solo'); } /** t1201: player-facing name of a mode / planet-select context. */ function modeLabel (context) { var key = context === 'offline' ? 'menu.play' : (context === 'online' ? 'menu.online' : 'menu.survival'); var fallback = context === 'offline' ? 'Play' : (context === 'online' ? 'Play online' : 'Survival'); if (typeof I18n === 'undefined') { return fallback; } var s = I18n.t(key); return (s && s !== key) ? s : fallback; } function startPlay (opts) { opts = opts || {}; var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod; var planet = opts.planet || planetMod.planetById(selectedPlanetId()); var miss = opts.missChance; if (typeof miss !== 'number' || !isFinite(miss)) { miss = planetMod.missChance(planet); } hideEl('menu'); hideEl('game-over'); hideEl('online-panel'); hideEl('spectator'); hideEl('podium'); hideEl('planet-select'); hideEl('offline-result'); hideEl('designer'); hideEl('designer-edit'); if (typeof Designer !== 'undefined' && Designer.closeModal) { Designer.closeModal(); } // Do not show the HUD until the scene is on screen. Showing it first // left the default "Terra" / "0" labels on a blank starfield when // `new Scene` threw (WebGL unavailable) after inserting a transparent // canvas — the t1143 live blank-screen report. app.planet = planet; app.core = new GameCore(planet, Math.random, miss); if (app.debugPhysics) { app.core.debugInvariants = true; } app.mode = 'playing'; app.online = !!opts.online; app.offline = !!opts.offline; app.gameOverShown = false; app.eliminatedReported = false; app.spectating = false; app.sprites = Object.create(null); app.flames = Object.create(null); app.cells = []; app.pointerId = null; app.selectTween = null; app.swapTweens = Object.create(null); app.columnWarn = []; app.warnClock = 0; app.miniAcc = 1; // draw minis on the first frame app.offlineResultShown = false; if (!opts.keepBattle) { app.roundWonDelay = 0; app.roundWonHandled = false; } if (app.offline && !opts.keepBattle && typeof Offline !== 'undefined') { app.battle = Offline.createBattle({ playerPlanet: app.planet, rng: Math.random, round: opts.round || 1 }); } layout(); if (app.scene) { app.scene.destroy(); app.scene = null; } try { app.scene = new Scene(app.fieldX, app.fieldY, app.fieldW, app.fieldH); app.scene.backgroundColor = { r: 12, g: 16, b: 32 }; app.scene.renderBackground = true; game.loadScene(app.scene); buildCells(); app.manager = app.scene.addObject(makeManager()); if (!app.spectating) { bindPointer(app.scene.canvas); } refreshHud(); showEl('hud'); setGameMenuButton(!app.online && !app.spectating); } catch (err) { abortStartPlay(err); return; } if (app.online || app.offline) { showEl('minis'); } else { hideEl('minis'); } buildColumnWarn(); refreshOfflineHud(); refreshChainIndicator(); if (!opts.online) { beginPlaySession(opts.offline ? 'offline' : 'solo'); } } function removeOrphanPlayCanvases () { // Scene's constructor inserts a body canvas, then GLContext may throw, // leaving a transparent leftover that hides nothing and shows stars. var nodes = document.querySelectorAll('body > canvas'); for (var i = 0; i < nodes.length; i++) { if (nodes[i].parentNode) { nodes[i].parentNode.removeChild(nodes[i]); } } } function abortStartPlay (err) { if (typeof console !== 'undefined' && console.error) { console.error('startPlay failed', err); } try { unbindPointer(); if (app.scene && app.scene.destroy) { app.scene.destroy(); } } catch (e) { /* ignore cleanup errors */ } app.scene = null; app.core = null; app.manager = null; app.mode = 'menu'; app.online = false; app.offline = false; app.battle = null; app.cells = []; removeOrphanPlayCanvases(); hideEl('hud'); hideEl('minis'); hideEl('planet-select'); showEl('menu'); refreshMenuAccount(); var box = document.getElementById('start-error'); if (box) { var msg = (err && err.message) ? String(err.message) : ''; var webgl = /webgl/i.test(msg); if (typeof I18n !== 'undefined') { box.textContent = I18n.t(webgl ? 'error.webgl' : 'error.startFailed'); } else { box.textContent = webgl ? 'This game needs WebGL. Please try another browser, or turn on hardware acceleration.' : 'Could not start the game.'; } box.hidden = false; } } function clearStartError () { var box = document.getElementById('start-error'); if (box) { box.hidden = true; box.textContent = ''; } } function teardownPlay () { unbindPointer(); if (app.scene) { app.scene.destroy(); app.scene = null; } app.manager = null; app.core = null; app.sprites = Object.create(null); app.flames = Object.create(null); app.cells = []; app.selectTween = null; app.swapTweens = Object.create(null); app.columnWarn = []; app.pointerId = null; app.gameOverShown = false; app.paused = false; app.quitting = false; hideEl('game-menu'); setGameMenuButton(false); hideEl('hud'); hideEl('game-over'); hideEl('spectator'); hideEl('minis'); hideEl('offline-result'); hideOfflineHud(); hideChainIndicator(); if (typeof Online !== 'undefined') { Online.clearFlights(); } if (!app._keepBattleOnTeardown) { app.battle = null; app.offline = false; } app._keepBattleOnTeardown = false; } function returnToMenu () { clearStartError(); if (app.online && typeof Online !== 'undefined') { // Online matches do not dump you back to the solo menu: // elimination becomes spectating; a finished match shows the podium. return; } teardownPlay(); app.mode = 'menu'; app.online = false; app.offline = false; app.battle = null; hideEl('planet-select'); showEl('menu'); var last = document.getElementById('last-score'); if (app.lastScore > 0) { last.hidden = false; last.querySelector('strong').textContent = String(app.lastScore); } } function buildCells () { if (!app.scene) { return; } var img = game.images.cell; for (var row = 0; row < 13; row++) { for (var col = 0; col < 10; col++) { var obj = new GameObject(0, 0, img, 0); placeTile(obj, col, row); obj.renderer.alpha = 0.9; app.scene.addObject(obj); app.cells.push(obj); } } } function placeTile (obj, col, y) { var t = app.tile; obj.transform.position.x = col * t + t / 2; obj.transform.position.y = app.fieldH - (y + 0.5) * t; obj.transform.size = { x: t, y: t }; } function opponentCount () { if (app.offline && app.battle && app.battle.bots) { return app.battle.bots.length; } if (app.online && typeof Online !== 'undefined' && Online.opponents) { return Online.opponents().length; } return 0; } function currentMiniSize () { if (app.miniLayout && app.miniLayout.mini) { return { w: app.miniLayout.mini.w, h: app.miniLayout.mini.h }; } var n = opponentCount(); var mode = (app.miniLayout && app.miniLayout.mode) || 'top'; if (typeof MiniLayout !== 'undefined' && MiniLayout.canvasSize) { return MiniLayout.canvasSize(n, mode, 0); } if (n >= 10) { return { w: 40, h: 52 }; } if (n >= 6) { return { w: 56, h: 73 }; } return { w: 80, h: 104 }; } function applyMinisContainer (plan) { var minis = document.getElementById('minis'); if (!minis) { return; } var n = plan ? plan.n : 0; minis.classList.toggle('crowded', n > 5); if (plan && n > 0 && plan.mode === 'top' && plan.mini && plan.mini.cols) { // t1203: top row is placed absolutely too, scaled to fit above the field. minis.classList.remove('sides'); minis.classList.add('placed'); minis.style.top = '0'; minis.style.bottom = '0'; minis.style.left = '0'; minis.style.right = '0'; minis.style.maxHeight = 'none'; return; } minis.classList.remove('placed'); if (!plan || n === 0 || plan.mode !== 'sides') { minis.classList.remove('sides'); minis.style.top = (app.hudH || 56) + 'px'; minis.style.maxHeight = (plan && plan.miniH ? plan.miniH : 0) + 'px'; minis.style.bottom = ''; minis.style.left = ''; minis.style.right = ''; var kids = minis.querySelectorAll('.mini'); for (var i = 0; i < kids.length; i++) { kids[i].style.left = ''; kids[i].style.top = ''; kids[i].style.width = ''; kids[i].style.position = ''; kids[i].style.fontSize = ''; } return; } minis.classList.add('sides'); minis.style.top = '0'; minis.style.bottom = '0'; minis.style.left = '0'; minis.style.right = '0'; minis.style.maxHeight = 'none'; } function applyMinisLayout () { var plan = app.miniLayout; var minis = document.getElementById('minis'); if (!minis) { return; } applyMinisContainer(plan); if (!plan || !plan.n || (plan.mode !== 'sides' && plan.mode !== 'top')) { return; } var positions = plan.positions || []; var kids = minis.querySelectorAll('.mini'); if (plan.mode === 'top' && kids.length && typeof MiniLayout !== 'undefined' && MiniLayout.topPositions) { // t1203: if they do not all fit even at the minimum size, defeated // opponents move to the back (stable), so the living stay visible. var elim = []; for (var k = 0; k < kids.length; k++) { elim.push(kids[k].classList.contains('eliminated')); } positions = MiniLayout.topPositions(elim, plan); plan.positions = positions; } for (var i = 0; i < positions.length && i < kids.length; i++) { var p = positions[i]; var el = kids[i]; el.style.position = 'absolute'; el.style.left = p.x + 'px'; el.style.top = p.y + 'px'; el.style.width = p.w + 'px'; el.style.fontSize = p.font ? p.font + 'px' : ''; el.setAttribute('data-slot', p.slot != null ? String(p.slot) : String(i)); var canvas = el.querySelector('canvas'); if (canvas) { canvas.style.width = p.canvasW + 'px'; canvas.style.height = p.canvasH + 'px'; } } } function applyFlightsBackClip () { var back = document.getElementById('flights-back'); if (!back) { return; } var x = app.fieldX || 0; var y = app.fieldY || 0; var w = app.fieldW || 0; var h = app.fieldH || 0; if (!w || !h) { back.style.clipPath = ''; return; } // Even-odd polygon: full viewport with a hole over the player's field, // so enemy-to-enemy arcs travel behind the field (t1125). back.style.clipPath = 'polygon(evenodd, 0 0, 100% 0, 100% 100%, 0 100%, 0 0, ' + x + 'px ' + y + 'px, ' + (x + w) + 'px ' + y + 'px, ' + (x + w) + 'px ' + (y + h) + 'px, ' + x + 'px ' + (y + h) + 'px, ' + x + 'px ' + y + 'px)'; } function layoutIfNeeded () { if (app.core && app.core.drag) { return; } var vw = window.innerWidth || 320; var vh = window.innerHeight || 480; var n = (app.online || app.offline) ? opponentCount() : 0; if (app._layoutVw === vw && app._layoutVh === vh && app._layoutN === n && app.scene && app.tile) { return; } layout(); } function layout () { if (app.core && app.core.drag) { return; } var vw = window.innerWidth || 320; var vh = window.innerHeight || 480; var n = (app.online || app.offline) ? opponentCount() : 0; app._layoutVw = vw; app._layoutVh = vh; app._layoutN = n; var safeTop = 0; try { // env(safe-area) is a CSS thing; keep a conservative HUD height. safeTop = 0; } catch (e) { /* ignore */ } app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop); var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015)); var plan; if (typeof MiniLayout !== 'undefined' && MiniLayout.plan) { plan = MiniLayout.plan(vw, vh, n, app.hudH, margin); } else { plan = { mode: 'top', tile: 14, fieldW: 140, fieldH: 182, fieldX: Math.floor((vw - 140) / 2), fieldY: app.hudH, miniH: n > 0 ? 100 : 0, mini: { w: 80, h: 104 }, positions: [], n: n }; } app.miniLayout = plan; app.miniH = plan.miniH; app.tile = plan.tile; app.fieldW = plan.fieldW; app.fieldH = plan.fieldH; app.fieldX = plan.fieldX; app.fieldY = plan.fieldY; applyMinisLayout(); applyFlightsBackClip(); if (app.scene) { app.scene.position.x = app.fieldX; app.scene.position.y = app.fieldY; app.scene.size.x = app.fieldW; app.scene.size.y = app.fieldH; } } function spriteFor (block) { if (block.state === 'locked') { return game.images.locked; } if (block.color < 0) { return game.images.gray; } var key = Planet.spriteKey(app.planet, block.color); return game.images[key] || game.images.gray; } /** Frames in the flame sprite (from the loaded image, default 4). */ function flameFrameCount () { var img = typeof game !== 'undefined' && game.images ? game.images.flame : null; return img && img.subImages ? img.subImages : 4; } function syncSprites (dt) { if (!app.core || !app.scene) { return; } dt = dt || 0; consumeAndStartSwapTweens(); advanceSwapTweens(dt); var seen = Object.create(null); var blocks = app.core.blocks; for (var i = 0; i < blocks.length; i++) { var block = blocks[i]; seen[block.id] = true; var obj = app.sprites[block.id]; if (!obj) { obj = new GameObject(0, 0, spriteFor(block), 2); app.scene.addObject(obj); app.sprites[block.id] = obj; } obj.renderer.sprite = spriteFor(block); placeTile(obj, block.col, blockVisualY(block)); applyBlockVisual(obj, block); obj.renderer.visible = true; obj.renderer.alpha = 1; if (typeof Online !== 'undefined' && Online.hasExitVisual && Online.hasExitVisual(block.id)) { obj.renderer.visible = false; obj.renderer.alpha = 0; } if (block.flame) { var flame = app.flames[block.id]; if (!flame) { flame = new GameObject(0, 0, game.images.flame, 1); // t1183: frames are chosen by FlameFx, not the framework cycle. flame.fx = FlameFx.create(flameFrameCount(), Math.random, FlameFx.reducedMotion()); flame.renderer.setSubImage(flame.fx.frame); app.scene.addObject(flame); app.flames[block.id] = flame; } flame.renderer.visible = true; FlameFx.advance(flame.fx, dt, Math.random, FlameFx.reducedMotion()); var t = app.tile; // 3x as large (length and width, t1110). Keep the top of the // flame at the same overlap into the block so the extra length // extends downward under the rocket. t1183: random frame, flip, // scale and rotation all pivot on that top-centre anchor. var flameW = t * 0.85 * 3; var flameH = t * 0.85 * 3; var origCenter = app.fieldH - block.y * t + t * 0.15; var origTop = origCenter - (t * 0.85) / 2; var pose = FlameFx.pose(flame.fx, block.col * t + t / 2, origTop, flameW, flameH); flame.renderer.subImage = pose.frame; flame.renderer.mirrorX = pose.mirrorX; flame.transform.rotation = pose.rotation; flame.transform.position.x = pose.x; flame.transform.position.y = pose.y; flame.transform.size = { x: pose.w, y: pose.h }; } else if (app.flames[block.id]) { app.flames[block.id].renderer.visible = false; } if (block.flame && app.flames[block.id] && typeof Online !== 'undefined' && Online.hasExitVisual && Online.hasExitVisual(block.id)) { app.flames[block.id].renderer.visible = false; } } var ids = Object.keys(app.sprites); for (var i = 0; i < ids.length; i++) { if (!seen[ids[i]]) { app.sprites[ids[i]].destroy(); delete app.sprites[ids[i]]; if (app.flames[ids[i]]) { app.flames[ids[i]].destroy(); delete app.flames[ids[i]]; } } } } function applyBlockVisual (obj, block) { var t = app.tile; var sx = 1; var sy = 1; var dy = 0; if (block.bouncing && app.planet && app.planet.bounceDuration > 0 && typeof Easing !== 'undefined' && Easing.bouncePose) { var u = block.bounceAge / app.planet.bounceDuration; var pose = Easing.bouncePose(u, app.planet.bounceSquash); sx = pose.sx; sy = pose.sy; dy = pose.dy; } var sel = 1; var tw = app.selectTween; if (tw && tw.blockId === block.id && tw.phase !== 'idle') { sel = tw.scale; } obj.transform.size = { x: t * sx * sel, y: t * sy * sel }; if (dy) { obj.transform.position.y -= dy * t; } } function clickTween () { return (typeof Easing !== 'undefined' && Easing.CLICK_TWEEN) ? Easing.CLICK_TWEEN : null; } function startPressTween (blockId) { var c = clickTween(); if (!c) { return; } var from = (app.selectTween && app.selectTween.phase !== 'idle') ? app.selectTween.scale : 1; app.selectTween = { blockId: blockId, from: from, to: c.pressScale, t: 0, duration: c.pressDuration, ease: c.pressEase, scale: from, phase: 'press' }; } function startReleaseTween () { var c = clickTween(); var tw = app.selectTween; if (!c || !tw || tw.phase === 'idle') { return; } app.selectTween = { blockId: tw.blockId, from: tw.scale, to: c.releaseScale, t: 0, duration: c.releaseDuration, ease: c.releaseEase, scale: tw.scale, phase: 'release' }; } function updateSelectTween (dt) { var tw = app.selectTween; if (!tw || tw.phase === 'idle' || tw.phase === 'hold') { return; } tw.t += dt; var u = tw.duration > 0 ? tw.t / tw.duration : 1; if (u >= 1) { tw.scale = tw.to; tw.t = tw.duration; if (tw.phase === 'press') { tw.phase = 'hold'; } else { tw.phase = 'idle'; tw.scale = 1; tw.blockId = null; } return; } var ease = tw.ease || (typeof Easing !== 'undefined' && Easing.easeOutBack); tw.scale = ease ? Easing.tween(tw.from, tw.to, u, ease) : tw.from + (tw.to - tw.from) * u; } /* ---------- visual-only swap tween (t1121) -------------------------- */ function swapTweenSpec () { if (typeof Easing !== 'undefined' && Easing.SWAP_TWEEN) { return Easing.SWAP_TWEEN; } return { duration: 0.100, ease: null }; } function swapEase (u) { if (typeof Easing !== 'undefined' && Easing.easeOutCubic) { return Easing.easeOutCubic(u); } var v = 1 - Math.max(0, Math.min(1, u)); return 1 - v * v * v; } function tweenVisualY (tw) { var u = tw.duration > 0 ? Math.min(1, tw.age / tw.duration) : 1; return tw.fromY + (tw.toY - tw.fromY) * swapEase(u); } /** * Consume GameCore swap events. The currently dragged block is skipped * (it follows the pointer). A block that is mid-tween and is swapped * again restarts from its current visual y, so rapid swaps chain * smoothly without snapping. */ function consumeAndStartSwapTweens () { if (!app.core || !app.core.consumeSwapEvents) { return; } if (!app.swapTweens) { app.swapTweens = Object.create(null); } var ev = app.core.consumeSwapEvents(); if (!ev.length) { return; } var dragId = app.core.drag && app.core.drag.blockId; var duration = swapTweenSpec().duration; for (var i = 0; i < ev.length; i++) { var e = ev[i]; if (e.id === dragId) { delete app.swapTweens[e.id]; continue; } var fromY = e.fromY; var existing = app.swapTweens[e.id]; if (existing) { fromY = tweenVisualY(existing); } app.swapTweens[e.id] = { fromY: fromY, toY: e.toY, age: 0, duration: duration }; } } function advanceSwapTweens (dt) { if (!app.swapTweens) { return; } var ids = Object.keys(app.swapTweens); for (var i = 0; i < ids.length; i++) { var tw = app.swapTweens[ids[i]]; tw.age += dt; if (tw.age >= tw.duration) { delete app.swapTweens[ids[i]]; } } } function blockVisualY (block) { if (!app.swapTweens) { return block.y; } var dragId = app.core && app.core.drag && app.core.drag.blockId; if (block.id === dragId) { return block.y; } var tw = app.swapTweens[block.id]; if (!tw) { return block.y; } return tweenVisualY(tw); } function refreshHud () { if (!app.core) { return; } document.getElementById('score').textContent = String(app.core.score); var planet = app.planet; var pname = (typeof I18n !== 'undefined') ? I18n.planetName(planet) : planet.name; var people = (typeof I18n !== 'undefined') ? I18n.peopleName(planet) : planet.people; document.getElementById('planet-name').textContent = pname + ' · ' + people; document.getElementById('planet-stats').textContent = Planet.formatStats(planet); } function makeManager () { var obj = new GameObject(0, 0, game.images.pixel, 0); obj.renderer.visible = false; var base = obj.update.bind(obj); obj.update = function (dt) { base(dt); tickView(dt); }; return obj; } function tickView (dt) { if (app.mode !== 'playing' || !app.core) { return; } // Never resize the canvas mid-drag: a URL-bar hide would move the // field under the finger and jump the target row. Also skip work // when the viewport has not actually changed. if (!(app.core && app.core.drag)) { layoutIfNeeded(); } for (var i = 0; i < app.cells.length; i++) { var col = i % 10; var row = Math.floor(i / 10); placeTile(app.cells[i], col, row); } // t1193: in-game menu open (Spelen / Offline Strijd) or quitting: // the field, bots and timers stand still; only the view is kept. if (app.paused) { syncSprites(0); return; } app.core.tick(dt); if (app.offline && app.battle) { tickOffline(dt); } updateSelectTween(dt); syncSprites(dt); updateColumnWarn(dt); refreshHud(); refreshOfflineHud(); refreshChainIndicator(); tickOnline(dt); if (app.debugPhysics) { logPhysicsDebug(); } if (app.core.state === 'gameover' && !app.gameOverShown) { app.gameOverShown = true; app.lastScore = app.core.score; document.getElementById('go-score').textContent = String(app.lastScore); if (app.online) { onOnlineEliminated(); } else if (app.offline) { /* Offline result is shown from tickOffline. */ } else if (rewardEnabled()) { showReward(false, finishPlaySession(app.lastScore), returnToMenu); } else { showEl('game-over'); finishPlaySession(app.lastScore); } } if (!app.online && !app.offline && !app.rewardActive && app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY) { returnToMenu(); } } /* ---------- pointer input (mouse + touch) --------------------------- */ /* * Mouse uses Pointer Events. Touch uses Touch Events as the authority: * on a real phone, pointer clientX/Y can disagree with the visual * finger (zoomed visual viewport, gesture takeover, capture cancel) * while changedTouches stays correct. When a touch is active, pointer * move/up/cancel are ignored so a poisoned pointer coordinate cannot * walk the block to the top or bottom of the stack (t1106). * * After a down we also listen on the document, so a drag that leaves * the canvas (needed to launch a block at the top of a full column) * still reaches moveDrag. We do not call setPointerCapture: on mobile * that is often cancelled when the browser takes the gesture, which * would fire pointercancel mid-drag. * * A non-passive document touchstart/touchmove preventDefault during * play stops scrolling, rubber-banding and the pointercancel that * follows. pointercancel / touchcancel end the drag without launch. * * ?debug=drag (or localStorage meteors-debug-drag=1) shows an overlay. */ var boundCanvas = null; var windowListening = false; var touchListening = false; var lastDragDebug = null; function isDragDebugEnabled () { try { var q = window.location && window.location.search; if (q && /(?:\?|&)debug=drag(?:&|$)/.test(q)) { return true; } if (window.localStorage && window.localStorage.getItem('meteors-debug-drag') === '1') { return true; } } catch (err) { /* ignore */ } return false; } /** ?debug, ?debug=physics, ?debug=drag, or localStorage meteors-debug=1. */ function isPhysicsDebugEnabled () { try { var q = window.location && window.location.search; if (q && /(?:\?|&)debug(?:=|&|$)/.test(q)) { return true; } if (window.localStorage && (window.localStorage.getItem('meteors-debug') === '1' || window.localStorage.getItem('meteors-debug-drag') === '1')) { return true; } } catch (err) { /* ignore */ } return false; } function eventClient (e) { var t = null; if (e.changedTouches && e.changedTouches.length) { t = e.changedTouches[0]; } else if (e.touches && e.touches.length) { t = e.touches[0]; } if (t) { return { x: t.clientX, y: t.clientY, id: t.identifier, src: 'touch' }; } if (e.clientX != null && e.clientY != null) { return { x: e.clientX, y: e.clientY, id: e.pointerId, src: 'pointer' }; } return null; } function addWindowPointer () { if (windowListening) { return; } window.addEventListener('pointermove', onPointerMove, { capture: true, passive: false }); window.addEventListener('pointerup', onPointerUp, { capture: true, passive: false }); window.addEventListener('pointercancel', onPointerCancel, { capture: true, passive: false }); windowListening = true; } function removeWindowPointer () { if (!windowListening) { return; } window.removeEventListener('pointermove', onPointerMove, { capture: true }); window.removeEventListener('pointerup', onPointerUp, { capture: true }); window.removeEventListener('pointercancel', onPointerCancel, { capture: true }); windowListening = false; } function addTouchListeners () { if (touchListening) { return; } var opts = { capture: true, passive: false }; document.addEventListener('touchstart', onTouchStart, opts); document.addEventListener('touchmove', onTouchMove, opts); document.addEventListener('touchend', onTouchEnd, opts); document.addEventListener('touchcancel', onTouchCancel, opts); touchListening = true; } function removeTouchListeners () { if (!touchListening) { return; } var opts = { capture: true }; document.removeEventListener('touchstart', onTouchStart, opts); document.removeEventListener('touchmove', onTouchMove, opts); document.removeEventListener('touchend', onTouchEnd, opts); document.removeEventListener('touchcancel', onTouchCancel, opts); touchListening = false; } function bindPointer (canvas) { unbindPointer(); boundCanvas = canvas; canvas.addEventListener('pointerdown', onPointerDown, { passive: false }); canvas.style.touchAction = 'none'; canvas.style.position = 'fixed'; canvas.style.cursor = 'pointer'; canvas.style.webkitUserSelect = 'none'; canvas.style.userSelect = 'none'; addTouchListeners(); if (app.debugDrag) { ensureDragDebugOverlay(); } } function unbindPointer () { removeWindowPointer(); removeTouchListeners(); if (boundCanvas) { boundCanvas.removeEventListener('pointerdown', onPointerDown); } boundCanvas = null; app.pointerId = null; app.pointerType = null; app.activeTouchId = null; } function fieldFromEvent (e) { var canvas = app.scene && app.scene.canvas; if (!canvas) { return null; } var rect = canvas.getBoundingClientRect(); if (rect.width <= 0 || rect.height <= 0) { return null; } var pt = eventClient(e); if (!pt) { return null; } // Map through the CSS box only. Using canvas.width / app.tile would // scale the pointer by the backing-store ratio whenever that differs // from the layout size (high-DPR devices), so a short finger move // would look like a long swipe. var width = Planet.FIELD_WIDTH; var height = Planet.FIELD_HEIGHT; var col = ((pt.x - rect.left) / rect.width) * width; var fieldY = (1 - (pt.y - rect.top) / rect.height) * height; return { col: col, y: fieldY, src: pt.src, clientX: pt.x, clientY: pt.y, rect: rect }; } function playingForDrag () { return app.core && app.core.state === 'playing' && !app.paused; } /** Touches on HUD buttons / menus are UI taps, not field drags (t1193). */ function isUiTouchTarget (e) { var el = e && e.target; if (!el || !el.closest) { return false; } return !!el.closest('button, a, input, select, #game-menu, #reward'); } function startDragFromEvent (e) { var pos = fieldFromEvent(e); if (!pos) { return; } if (app.core.drag) { app.core.moveDrag(pos.y); logDragDebug(e, pos, 'move-already'); return; } if (app.core.beginDrag(pos.col, pos.y) && app.core.drag) { startPressTween(app.core.drag.blockId); } logDragDebug(e, pos, 'down'); } function moveDragFromEvent (e) { if (!app.core || !app.core.drag) { return; } var pos = fieldFromEvent(e); if (pos) { app.core.moveDrag(pos.y); } logDragDebug(e, pos, 'move'); } function finishDrag (opts) { opts = opts || {}; app.pointerId = null; app.pointerType = null; app.activeTouchId = null; removeWindowPointer(); if (boundCanvas) { try { if (opts.pointerId != null && boundCanvas.releasePointerCapture) { boundCanvas.releasePointerCapture(opts.pointerId); } } catch (err) { /* ignore */ } } startReleaseTween(); if (app.core && app.core.drag) { if (opts.noLaunch) { app.core.drag.launchIntent = false; } app.core.endDrag(); } else if (app.core) { app.core.endDrag(); } logDragDebug(null, null, opts.noLaunch ? 'cancel' : 'up'); } function onPointerDown (e) { if (!playingForDrag()) { return; } if (app.pointerId != null && e.pointerId !== app.pointerId) { return; } if (e.preventDefault) { e.preventDefault(); } app.pointerId = e.pointerId; app.pointerType = e.pointerType || 'mouse'; addWindowPointer(); // If a touch is already in charge, do not reset the grab from pointerdown. if (app.activeTouchId != null) { return; } startDragFromEvent(e); } function onPointerMove (e) { if (app.pointerId == null || e.pointerId !== app.pointerId) { return; } if (!app.core || !app.core.drag) { return; } // Touch coordinates are the authority; ignore pointer moves for a // live touch so a wrong clientY cannot walk the whole column. // Only skip when touchstart has actually arrived — some environments // deliver touch-pointer events without a TouchEvent stream. if (app.activeTouchId != null) { if (e.preventDefault) { e.preventDefault(); } logDragDebug(e, fieldFromEvent(e), 'pointer-ignored'); return; } if (e.preventDefault) { e.preventDefault(); } moveDragFromEvent(e); } function onPointerUp (e) { if (app.pointerId == null) { return; } if (e && e.pointerId != null && e.pointerId !== app.pointerId) { return; } if (app.activeTouchId != null) { // touchend will finish the drag. if (e && e.preventDefault) { e.preventDefault(); } logDragDebug(e, fieldFromEvent(e), 'pointer-up-ignored'); return; } if (e && e.preventDefault) { e.preventDefault(); } finishDrag({ pointerId: e && e.pointerId }); } function onPointerCancel (e) { if (app.pointerId == null) { return; } if (e && e.pointerId != null && e.pointerId !== app.pointerId) { return; } if (app.activeTouchId != null) { if (e && e.preventDefault) { e.preventDefault(); } logDragDebug(e, fieldFromEvent(e), 'pointer-cancel-ignored'); return; } if (e && e.preventDefault) { e.preventDefault(); } // A cancelled gesture is not a launch pull. finishDrag({ pointerId: e && e.pointerId, noLaunch: true }); } function touchById (list, id) { if (!list) { return null; } for (var i = 0; i < list.length; i++) { if (list[i].identifier === id) { return list[i]; } } return null; } function onTouchStart (e) { if (!playingForDrag()) { return; } if (app.activeTouchId == null && isUiTouchTarget(e)) { return; } if (app.activeTouchId != null) { if (e.preventDefault) { e.preventDefault(); } return; } var t = e.changedTouches && e.changedTouches[0]; if (!t) { return; } if (e.preventDefault) { e.preventDefault(); } app.activeTouchId = t.identifier; addWindowPointer(); startDragFromEvent(e); } function onTouchMove (e) { if (app.activeTouchId == null) { return; } if (!touchById(e.changedTouches, app.activeTouchId) && !touchById(e.touches, app.activeTouchId)) { return; } if (e.preventDefault) { e.preventDefault(); } moveDragFromEvent(e); } function onTouchEnd (e) { if (app.activeTouchId == null) { return; } if (!touchById(e.changedTouches, app.activeTouchId)) { return; } if (e.preventDefault) { e.preventDefault(); } finishDrag({}); } function onTouchCancel (e) { if (app.activeTouchId == null) { return; } if (!touchById(e.changedTouches, app.activeTouchId)) { return; } if (e.preventDefault) { e.preventDefault(); } finishDrag({ noLaunch: true }); } function logPhysicsDebug () { if (!app.debugPhysics || !app.core) { return; } ensureDragDebugOverlay(); var el = document.getElementById('drag-debug'); if (!el) { return; } var issues = app.core.lastInvariantViolations || []; var flying = 0; var manuals = 0; var clusters = app.core.clusters ? Object.keys(app.core.clusters).length : 0; for (var i = 0; i < app.core.blocks.length; i++) { if (app.core.blocks[i].state === 'flying') { flying++; } if (app.core.blocks[i].state === 'manual') { manuals++; } } var status = issues.length ? ('PHYSICS FAIL x' + issues.length + '\n' + issues.slice(0, 6).join('\n')) : ('physics ok blocks=' + app.core.blocks.length + ' fly=' + flying + ' man=' + manuals + ' cl=' + clusters); // Keep any live drag line above the physics status. var dragLine = ''; if (app.debugDrag && lastDragDebug) { dragLine = el.textContent && el.textContent.indexOf('drag ') === 0 ? el.textContent.split('\n')[0] + '\n' : ''; } el.textContent = dragLine + status; el.hidden = false; el.style.color = issues.length ? '#ffb4b4' : '#c6f6c8'; } function ensureDragDebugOverlay () { if (document.getElementById('drag-debug')) { return; } var el = document.createElement('div'); el.id = 'drag-debug'; el.setAttribute('aria-live', 'polite'); document.body.appendChild(el); } function logDragDebug (e, pos, phase) { if (!app.debugDrag) { return; } ensureDragDebugOverlay(); var el = document.getElementById('drag-debug'); if (!el) { return; } var block = null; if (app.core && app.core.drag) { block = app.core.blockById(app.core.drag.blockId); } var pt = e ? eventClient(e) : null; var evType = e ? e.type : phase; var info = { phase: phase, ev: evType, src: pos && pos.src, fieldY: pos && Math.round(pos.y * 100) / 100, col: pos && Math.round(pos.col * 100) / 100, cy: pt && Math.round(pt.y * 10) / 10, blockY: block && Math.round(block.y * 100) / 100, target: block && Math.floor((pos && pos.y) + 1e-12), launch: app.core && app.core.drag && app.core.drag.launchIntent, touchId: app.activeTouchId, pid: app.pointerId, ptype: app.pointerType }; lastDragDebug = info; el.textContent = 'drag ' + phase + ' ev=' + evType + ' src=' + (info.src || '-') + ' y=' + (info.fieldY != null ? info.fieldY : '-') + ' → ' + (info.target != null ? info.target : '-') + ' block=' + (info.blockY != null ? info.blockY : '-') + (info.launch ? ' LAUNCH' : '') + ' tId=' + info.touchId + ' pId=' + info.pid; el.hidden = false; } function hideEl (id) { document.getElementById(id).hidden = true; } function showEl (id) { document.getElementById(id).hidden = false; } window.addEventListener('resize', function () { if (app.mode === 'playing') { layout(); } }); window.addEventListener('orientationchange', function () { setTimeout(function () { if (app.mode === 'playing') { layout(); } }, 120); }); /* ---------- online play (stage 2) ---------------------------------- */ function tickOnline (dt) { if (!app.online || typeof Online === 'undefined') { return; } if (app.core) { var shots = app.core.consumeOutgoingShots(); for (var i = 0; i < shots.length; i++) { var s = shots[i]; var start = fieldToViewport(s.col, s.y); Online.rememberFlightLocal(s, start.x, start.y); // Draw the flight locally right away (t1181); the server // answer only retargets it. if (Online.startLocalShot) { Online.startLocalShot(s, start); } } Online.queueShots(shots); if (shots.length && Online.flushShotsSoon) { Online.flushShotsSoon(); } } Online.tickFlights(); Online.renderMinis(document.getElementById('minis')); applyMinisLayout(); } /* ---------- Offline Strijd (t1119) + column warn (t1123) ----------- */ function bindOfflineUi () { // t1201: the second menu button is now "Survival" (endless solo). var btn = document.getElementById('btn-survival'); if (btn) { btn.addEventListener('click', onSurvival); btn.addEventListener('pointerup', function (e) { if (e.pointerType === 'touch' || e.pointerType === 'pen') { e.preventDefault(); onSurvival(); } }); } var back = document.getElementById('btn-offline-menu'); if (back) { back.addEventListener('click', function () { teardownPlay(); app.mode = 'menu'; app.offline = false; app.battle = null; hideEl('offline-result'); showEl('menu'); }); } } function tickOffline (dt) { if (!app.battle || !app.core || typeof Offline === 'undefined') { return; } if (app.battle.state === 'round_won') { if (!app.roundWonHandled) { app.roundWonHandled = true; app.roundWonDelay = Offline.ROUND_WON_DELAY || 1.5; if (rewardEnabled()) { showReward(true, finishPlaySession(app.core.score), startNextOfflineRound); } } if (app.rewardActive) { updateOfflineMinis(dt, true); return; } app.roundWonDelay -= dt; if (app.roundWonDelay <= 0) { startNextOfflineRound(); } updateOfflineMinis(dt, true); return; } var result = app.battle.tick(dt, app.core); if (result && result.flights && result.flights.length && typeof Online !== 'undefined' && Online.spawnFlights) { var locals = Object.create(null); var list = result.locals || []; for (var i = 0; i < list.length; i++) { var s = list[i]; var start; if (s.from_id === 'player') { start = fieldToViewport(s.col, s.y); } else if (typeof Online !== 'undefined' && Online.miniCellViewport) { start = Online.miniCellViewport(s.from_id, s.col, s.y != null ? s.y : 12); } else { start = miniViewportCenter(s.from_id); } locals[s.client_id] = { col: s.col, y: s.y, color: s.color, startX: start.x, startY: start.y, from_id: s.from_id, land_col: s.land_col }; } Online.spawnFlights(result.flights, locals); } if (typeof Online !== 'undefined' && Online.tickFlights) { Online.tickFlights(); } updateOfflineMinis(dt, false); if (app.battle.state === 'lost' && !app.offlineResultShown) { if (rewardEnabled()) { // Guard against starting the reward twice; showOfflineResult // sets the flag again when it runs afterwards. app.offlineResultShown = true; showReward(false, finishPlaySession(app.core ? app.core.score : 0), showOfflineResult); } else { showOfflineResult(); } } } function startNextOfflineRound () { if (!app.battle) { return; } app.battle.advanceRound(); app.roundWonHandled = false; app.roundWonDelay = 0; app._keepBattleOnTeardown = true; // Tear down the current scene then start a fresh player field, // keeping the same battle (already advanced). var planet = app.battle.playerPlanet; var roundScore = app.core ? app.core.score : 0; finishPlaySession(roundScore); app._keepBattleOnTeardown = true; teardownPlay(); app.offline = true; app.battle = app.battle; // kept startPlay({ planet: planet, offline: true, keepBattle: true }); } function showOfflineResult () { app.offlineResultShown = true; var battle = app.battle; var reached = document.getElementById('offline-reached'); var line = document.getElementById('offline-reached-line'); if (line && typeof I18n !== 'undefined') { line.textContent = I18n.t('offline.reached', { n: battle.round }); } else if (reached) { reached.textContent = String(battle.round); } // t1198: "X opponents defeated" over all rounds (replaces the // opponents / skill line). var detail = document.getElementById('offline-result-detail'); if (detail) { var beaten = battle.defeated || 0; detail.textContent = (typeof I18n !== 'undefined') ? I18n.plural('offline.defeated', beaten, { n: beaten }) : beaten + (beaten === 1 ? ' opponent defeated' : ' opponents defeated'); } hideEl('game-over'); showEl('offline-result'); finishPlaySession(app.core ? app.core.score : 0); } function refreshOfflineHud () { var el = document.getElementById('offline-hud'); if (!el) { return; } if (!(app.offline && app.battle && app.mode === 'playing')) { el.hidden = true; return; } el.hidden = false; // t1195: the Offline Strijd HUD shows only "Round N". var sch = app.battle.schedule; var r = document.getElementById('offline-round'); if (r) { r.textContent = (typeof I18n !== 'undefined') ? I18n.t('hud.round', { n: sch.round }) : 'Round ' + sch.round; } } function hideOfflineHud () { var el = document.getElementById('offline-hud'); if (el) { el.hidden = true; } } function refreshChainIndicator () { var el = document.getElementById('chain-indicator'); if (!el) { return; } // t1200: the yellow "+x%" shows ONLY the combo bonus // (0.01·min(combo, 30)); the landing-chain bonus still boosts the jump // but is not part of this number. Visible while that bonus is > 0. var pct = (app.core && app.core.comboBonusPct) ? app.core.comboBonusPct() : 0; if (!(pct > 0) || app.mode !== 'playing') { el.hidden = true; return; } el.hidden = false; el.textContent = '+' + pct + '%'; } function hideChainIndicator () { var el = document.getElementById('chain-indicator'); if (el) { el.hidden = true; } } function miniViewportCenter (botId) { var el = document.querySelector('#minis .mini[data-player="' + botId + '"] canvas'); if (!el) { return { x: window.innerWidth / 2, y: 40 }; } var rect = el.getBoundingClientRect(); var plan = app.miniLayout; if (plan && plan.mode === 'sides') { // Leave from the top of the mini, then the arc goes up and over (t1131). return { x: rect.left + rect.width / 2, y: rect.top + 4 }; } return { x: rect.left + rect.width / 2, y: rect.bottom }; } function offlineMiniSize (n) { return currentMiniSize(); } function updateOfflineMinis (dt, force) { app.miniAcc = (app.miniAcc || 0) + dt; if (!force && app.miniAcc < 0.1) { return; } app.miniAcc = 0; renderOfflineMinis(); } function renderOfflineMinis () { var container = document.getElementById('minis'); if (!container || !app.battle) { return; } var bots = app.battle.bots; var size = offlineMiniSize(bots.length); container.classList.toggle('crowded', bots.length > 5); var existing = {}; var kids = container.querySelectorAll('[data-player]'); for (var i = 0; i < kids.length; i++) { existing[kids[i].getAttribute('data-player')] = kids[i]; } var seen = Object.create(null); for (var i = 0; i < bots.length; i++) { var bot = bots[i]; seen[bot.id] = true; var el = existing[bot.id]; if (!el) { el = document.createElement('div'); el.className = 'mini'; el.setAttribute('data-player', bot.id); el.innerHTML = '
' + '' + '
'; container.appendChild(el); } var canvas = el.querySelector('canvas'); if (canvas && (canvas.width !== size.w || canvas.height !== size.h)) { canvas.width = size.w; canvas.height = size.h; } el.classList.toggle('eliminated', !!bot.eliminated); var planetName = bot.planet && bot.planet.name ? bot.planet.name : ''; var shownPlanet = planetName; if (bot.planet && typeof I18n !== 'undefined') { shownPlanet = I18n.planetName(bot.planet); } el.querySelector('.mini-name').textContent = bot.name + (shownPlanet ? ' · ' + shownPlanet : ''); el.querySelector('.mini-meta').textContent = bot.eliminated ? ((typeof I18n !== 'undefined') ? I18n.t('hud.out') : 'Out') : ((typeof I18n !== 'undefined') ? I18n.t('hud.miniPoints', { n: bot.score || 0 }) : ('Points ' + (bot.score || 0))); var snap = bot.core ? bot.core.fieldSnapshot() : { blocks: [] }; if (typeof Online !== 'undefined' && Online._drawMini) { Online._drawMini(canvas, snap, bot.planet); } } for (var id in existing) { if (!seen[id]) { existing[id].remove(); } } applyMinisLayout(); } function buildColumnWarn () { app.columnWarn = []; if (!app.scene) { return; } var img = (game.images && (game.images.columnWarn || game.images.pixel)) || null; if (!img) { return; } for (var c = 0; c < 10; c++) { var obj = new GameObject(0, 0, img, 0); obj.renderer.alpha = 0; obj.renderer.visible = false; app.scene.addObject(obj); app.columnWarn.push(obj); } updateColumnWarn(0); } function updateColumnWarn (dt) { if (!app.columnWarn || !app.core) { return; } app.warnClock = (app.warnClock || 0) + (dt || 0); var pulse = (typeof GameCore !== 'undefined' && GameCore.columnWarnPulse) ? GameCore.columnWarnPulse(app.warnClock) : 0.16 + 0.28 * (0.5 + 0.5 * Math.sin(app.warnClock * 3.45575)); var t = app.tile; for (var c = 0; c < app.columnWarn.length; c++) { var obj = app.columnWarn[c]; var on = app.core.columnNeedsWarn && app.core.columnNeedsWarn(c); obj.renderer.visible = !!on; obj.renderer.alpha = on ? pulse : 0; if (t) { obj.transform.position.x = c * t + t / 2; obj.transform.position.y = app.fieldH / 2; obj.transform.size = { x: t, y: app.fieldH }; } } } /** * A flight starts only when a block has actually left the field * (y ≥ height, the same threshold as cullOffTop). Rockets that * peak below the top and fall back must never get an arc (t1137). * Shared by the player's field, enemy minis, offline and online. */ function previewOutgoingFlights () { // Intentionally not called before core.tick: a block still on // the field (y < 13) is not a shot yet. Flights are spawned // from consumeOutgoingShots after cull, at the exit pose. if (typeof Online === 'undefined' || !Online.previewExit) { return; } if (app.core) { previewCoreExits(app.core, null); } if (app.offline && app.battle && app.battle.bots) { var bots = app.battle.bots; for (var i = 0; i < bots.length; i++) { var bot = bots[i]; if (bot && bot.core && !bot.eliminated) { previewCoreExits(bot.core, bot.id); } } } } function previewCoreExits (core, fromId) { if (!core || !core.blocks) { return; } var height = core.height != null ? core.height : 13; var blocks = core.blocks; for (var i = 0; i < blocks.length; i++) { var b = blocks[i]; if (b.state === 'manual') { continue; } if (typeof Online.hasLeftTheField === 'function' ? !Online.hasLeftTheField(b.y, height) : !(b.y >= height - 1e-9)) { continue; } if (!(b.vy > 0)) { continue; } var start = fromId ? (Online.miniCellViewport ? Online.miniCellViewport(fromId, b.col, b.y) : miniViewportCenter(fromId)) : fieldToViewport(b.col, b.y); Online.previewExit({ id: b.id, col: b.col, y: b.y, vy: b.vy, color: b.color, start: start, from_id: fromId || null }); } } function fieldToViewport (col, fieldY) { var canvas = app.scene && app.scene.canvas; if (!canvas) { return { x: window.innerWidth / 2, y: 40 }; } var rect = canvas.getBoundingClientRect(); var x = rect.left + ((col + 0.5) / 10) * rect.width; // Cell centre matches placeTile: y = fieldH - (fieldY + 0.5) * tile (t1134). var y = rect.top + (1 - ((fieldY + 0.5) / 13)) * rect.height; return { x: x, y: y }; } function onlinePayload () { if (!app.online || !app.core) { return {}; } var snap = app.core.fieldSnapshot(); // t1182: sender time (ms) so opponents can place the snapshot in // time and predict falling blocks smoothly. Visual only. snap.t = Math.round(typeof performance !== 'undefined' ? performance.now() : Date.now()); return { snapshot: snap, score: app.core.score, eliminated: app.core.state === 'gameover' || app.spectating || app.eliminatedReported }; } function onOnlineEliminated () { app.eliminatedReported = true; app.spectating = true; unbindPointer(); hideEl('game-over'); if (app.rewardActive) { return; } var lobby = typeof Online !== 'undefined' && Online.lobby; if (lobby && lobby.status === 'finished') { showPodium(lobby); return; } showEl('spectator'); } function showPodium (lobby) { hideEl('spectator'); hideEl('game-over'); hideEl('online-panel'); showEl('podium'); var list = document.getElementById('podium-list'); list.innerHTML = ''; var ranks = (lobby && lobby.rankings) || []; for (var i = 0; i < ranks.length; i++) { var r = ranks[i]; var li = document.createElement('li'); var medal = (typeof I18n !== 'undefined') ? I18n.place(r.place) : (r.place === 1 ? '1st' : (r.place === 2 ? '2nd' : (r.place === 3 ? '3rd' : r.place + 'th'))); li.textContent = (typeof I18n !== 'undefined') ? I18n.t('podium.line', { place: medal, name: r.name, score: r.score }) : (medal + ' ' + r.name + ' · ' + r.score + ' points'); list.appendChild(li); } var hint = document.getElementById('podium-hint'); var secs = (lobby && lobby.podium_seconds) || 5; if (hint) { hint.textContent = (typeof I18n !== 'undefined') ? I18n.t('podium.hint', { n: secs }) : ('Returning to the lobby in ' + secs + ' seconds…'); } } function startOnlineMatch () { if (app.mode === 'playing' && app.online) { return; } var planet = Planet.planetById(selectedPlanetId()); var miss = Planet.missChance(planet); var me = (typeof Online !== 'undefined' && Online.mePlayer) ? Online.mePlayer() : null; if (me && me.planet) { if (typeof Planet.rememberPlanet === 'function') { planet = Planet.rememberPlanet(me.planet) || planet; } else if (me.planet.id) { planet = Planet.planetById(me.planet.id); } if (typeof me.planet.miss_chance === 'number') { miss = me.planet.miss_chance; } } app.onlineBefore = Number((typeof Online !== 'undefined' && Online.lifetimePoints) || 0) || 0; if (typeof Online !== 'undefined') { Online.onlineAwarded = null; } app.pendingLobbyReturn = null; startPlay({ online: true, planet: planet, missChance: miss }); if (typeof Online !== 'undefined') { Online.startPolling(onlinePayload); } } function leaveOnlineMatch (goMenu) { if (typeof Online !== 'undefined') { Online.stopPolling(); Online.leaveLobby(); Online.clearFlights(); } teardownPlay(); app.online = false; if (goMenu) { app.mode = 'menu'; showEl('menu'); } else { app.mode = 'online'; openOnlinePanel(); } } function bindOnlineUi () { var onlineBtn = document.getElementById('btn-online'); if (!onlineBtn) { return; } onlineBtn.addEventListener('click', function () { openOnlinePanel(); }); var backs = document.querySelectorAll('[data-back-menu]'); for (var i = 0; i < backs.length; i++) { backs[i].addEventListener('click', function () { if (typeof Online !== 'undefined') { Online.stopPolling(); } hideEl('online-panel'); app.mode = 'menu'; app.online = false; showEl('menu'); }); } document.getElementById('btn-create').addEventListener('click', function () { Online.createLobby().then(function (data) { if (data && data.ok) { renderOnline(); Online.startPolling(onlinePayload); } else { renderOnline(); } }); }); document.getElementById('join-form').addEventListener('submit', function (e) { e.preventDefault(); var code = (document.getElementById('join-code').value || '').trim(); if (!code) { return; } Online.joinLobby(code).then(function () { renderOnline(); if (Online.lobby) { Online.startPolling(onlinePayload); } }); }); document.getElementById('btn-ready').addEventListener('click', function () { var me = Online.mePlayer(); Online.setReady(!(me && me.ready)).then(renderOnline); }); document.getElementById('btn-start').addEventListener('click', function () { Online.startGame().then(function (data) { if (data && data.ok) { startOnlineMatch(); } else { renderOnline(); } }); }); document.getElementById('btn-leave-lobby').addEventListener('click', function () { Online.leaveLobby().then(function () { Online.stopPolling(); renderOnline(); }); }); document.getElementById('btn-copy-code').addEventListener('click', function () { var code = document.getElementById('lobby-code').textContent; var btn = document.getElementById('btn-copy-code'); var done = function () { if (!btn) { return; } btn.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.copied') : 'Copied'; setTimeout(function () { btn.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.copy') : 'Copy'; }, 1500); }; if (navigator.clipboard && navigator.clipboard.writeText) { navigator.clipboard.writeText(code).then(done, done); } else { done(); } }); document.getElementById('btn-spectate').addEventListener('click', function () { hideEl('spectator'); app.spectating = true; }); document.getElementById('btn-leave-game').addEventListener('click', function () { leaveOnlineMatch(false); }); if (typeof Online !== 'undefined') { Online.onChange = function () { renderOnline(); }; Online.onGameStart = function () { startOnlineMatch(); }; Online.onIncoming = function (incoming) { if (!app.core || app.core.state !== 'playing') { return; } for (var i = 0; i < incoming.length; i++) { var col = Online.takeLandCol ? Online.takeLandCol(incoming[i]) : incoming[i].land_col; app.core.ingestGarbage(col); } }; Online.onFinished = function (lobby) { if (app.mode === 'playing' && app.online && rewardEnabled() && !app.rewardActive) { // Prefer the poll's online_awarded (t1278): same formula as // play_finish. Rematches in a reused lobby used to leave // lifetimePoints unchanged, so before === after and the // tally never started even though "You won!" still rose. var result = (typeof Online.rewardResult === 'function') ? Online.rewardResult({ lifetimePoints: Online.lifetimePoints, awarded: Online.onlineAwarded, before: app.onlineBefore }) : { before: app.onlineBefore || 0, after: Online.lifetimePoints || 0 }; showReward(myOnlinePlace(lobby) === 1, Promise.resolve(result), function () { var pending = app.pendingLobbyReturn; app.pendingLobbyReturn = null; if (pending || !(Online.lobby && Online.lobby.status === 'finished')) { Online.onLobbyReturn(pending || Online.lobby); } else { showPodium(Online.lobby); } }); return; } showPodium(lobby); }; Online.onLobbyReturn = function (lobby) { if (app.rewardActive) { app.pendingLobbyReturn = lobby; return; } teardownPlay(); app.online = false; app.mode = 'online'; hideEl('podium'); showEl('online-panel'); renderOnline(); Online.startPolling(onlinePayload); }; } var params = new URLSearchParams(window.location.search); if (params.get('online') === '1' || params.get('auth') === 'unconfigured') { openOnlinePanel(); // t1193: one-shot; a reload must not jump to online play again. try { params.delete('online'); var rest = params.toString(); window.history.replaceState(null, '', window.location.pathname + (rest ? '?' + rest : '') + window.location.hash); } catch (e) { /* ignore */ } } } function openOnlinePanel () { hideEl('menu'); hideEl('game-over'); hideEl('podium'); hideEl('spectator'); hideEl('planet-select'); showEl('online-panel'); app.mode = 'online'; setOnlineStatus((typeof I18n !== 'undefined') ? I18n.t('online.checking') : 'Checking whether online play is available…'); if (typeof Online === 'undefined') { showOnlineError((typeof I18n !== 'undefined') ? I18n.t('online.notLoaded') : 'Online play is not included in this build. You can still play offline.'); showOnly('online-unconfigured'); return; } Online.refresh().then(function (data) { if (!data || data.ok === false) { var msg = (data && data.error) ? ((typeof I18n !== 'undefined') ? I18n.error(data.error) : data.error) : ((typeof I18n !== 'undefined') ? I18n.t('error.connection') : 'No connection to the server.'); showOnlineError(msg + ' ' + ((typeof I18n !== 'undefined') ? I18n.t('online.canPlaySolo') : 'You can still play offline.')); if (data && data.configured === false) { showOnly('online-unconfigured'); } else { showOnly('online-login'); } document.getElementById('btn-login').style.display = 'none'; return; } renderOnline(); if (Online.lobby) { Online.startPolling(onlinePayload); } }); } function setOnlineStatus (text) { var el = document.getElementById('online-status'); if (el) { el.textContent = text; } } function showOnlineError (text) { var el = document.getElementById('online-error'); if (!el) { return; } if (!text) { el.hidden = true; el.textContent = ''; return; } el.hidden = false; el.textContent = text; } function showOnly (id) { var ids = ['online-unconfigured', 'online-login', 'online-home', 'online-lobby']; for (var i = 0; i < ids.length; i++) { document.getElementById(ids[i]).hidden = (ids[i] !== id); } } function renderOnline () { if (typeof Online === 'undefined') { return; } if (app.mode === 'playing' && app.online) { Online.renderMinis(document.getElementById('minis')); if (Online.lobby && Online.lobby.status === 'finished' && !app.rewardActive) { showPodium(Online.lobby); } return; } showOnlineError((typeof I18n !== 'undefined' && Online.error) ? I18n.error(Online.error) : Online.error); if (!Online.configured && !Online.me && !Online.local) { setOnlineStatus((typeof I18n !== 'undefined') ? I18n.t('online.statusUnconfigured') : 'Online play is not set up yet.'); showOnly('online-unconfigured'); return; } if (!Online.me) { setOnlineStatus((typeof I18n !== 'undefined') ? I18n.t('online.statusLogin') : 'Log in to create a lobby or join one.'); showOnly('online-login'); document.getElementById('btn-login').style.display = ''; document.getElementById('btn-login').href = Online.loginUrl(); document.getElementById('local-login').hidden = !Online.local; return; } if (Online.lobby) { setOnlineStatus((typeof I18n !== 'undefined') ? I18n.t('online.statusLobby') : 'Lobby'); showOnly('online-lobby'); document.getElementById('lobby-me-name').textContent = Online.me.name; document.getElementById('lobby-code').textContent = Online.lobby.code; var list = document.getElementById('lobby-players'); list.innerHTML = ''; var players = Online.lobby.players || []; for (var i = 0; i < players.length; i++) { var p = players[i]; var li = document.createElement('li'); if (p.is_me) { li.classList.add('you'); } var host = (typeof I18n !== 'undefined') ? I18n.t('online.host') : 'host'; var you = (typeof I18n !== 'undefined') ? I18n.t('online.you') : 'you'; var label = p.name + (p.is_host ? ' (' + host + ')' : '') + (p.is_me ? ' (' + you + ')' : ''); var state = p.ready ? 'Gereed' : 'Wacht…'; var world = (p.planet && p.planet.name) ? (p.planet.name + ' · ' + p.planet.people) : ''; li.innerHTML = '' + escapeText(label) + (world ? '' + escapeText(world) + '' : '') + '' + state + ''; list.appendChild(li); } renderPlanetGrid('lobby-planet-grid', true); var me = Online.mePlayer(); document.getElementById('btn-ready').textContent = (me && me.ready) ? ((typeof I18n !== 'undefined') ? I18n.t('online.notReady') : 'Not ready') : ((typeof I18n !== 'undefined') ? I18n.t('online.ready') : 'Ready'); var start = document.getElementById('btn-start'); start.hidden = !(Online.lobby && Online.me && Online.lobby.host_id === Online.me.id); start.disabled = !Online.lobby.can_start; var hint = document.getElementById('lobby-hint'); if (Online.lobby.status === 'playing') { hint.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.hintStarting') : 'The game is starting…'; } else if (players.length < 2) { hint.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.hintNeedPlayers') : 'Wait for at least one other player. Share the code.'; } else if (!Online.lobby.all_ready) { hint.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.hintNeedReady') : 'Everyone must press Ready. The host starts afterwards.'; } else if (Online.lobby.can_start) { hint.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.hintHostStart') : 'Everyone is ready. Press Start.'; } else { hint.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.hintWaitHost') : 'Waiting for the host to start.'; } return; } setOnlineStatus((typeof I18n !== 'undefined') ? I18n.t('online.statusHome', { name: Online.me.name }) : ('Hi ' + Online.me.name + '. Create a lobby or join with a code.')); showOnly('online-home'); document.getElementById('me-name').textContent = Online.me.name; document.getElementById('local-login').hidden = !Online.local; } function escapeText (s) { return String(s) .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"'); } function selectedPlanetId () { if (app.selectedPlanetId) { return app.selectedPlanetId; } return 'terra'; } /** * Pre-select the last chosen planet (t1196): logged in the profile value * (server), otherwise / as fallback localStorage, otherwise Terra. A * deleted custom planet falls back to the default (setSelectedPlanet). */ function restoreSelectedPlanet () { var id = null; if (typeof Online !== 'undefined' && Online.me && Online.lastPlanet) { id = Online.lastPlanet; } if (!id) { try { id = localStorage.getItem('meteors-planet'); } catch (e) {} } setSelectedPlanet(id || 'terra', true); } function rememberPlanetChoice (id) { if (typeof Online === 'undefined' || !Online.me || !Online.setLastPlanet) { return; } if (Online.lastPlanet === id) { return; } Promise.resolve(Online.setLastPlanet(id)).then(null, function () {}); } function setSelectedPlanet (id, silent) { var all = Planet.allPlanets(); var found = null; for (var i = 0; i < all.length; i++) { if (all[i].id === id) { found = all[i]; break; } } if (!found) { found = Planet.defaultPlanet(); } app.selectedPlanetId = found.id; try { localStorage.setItem('meteors-planet', found.id); } catch (e) {} if (!silent) { rememberPlanetChoice(found.id); var grid = document.getElementById('planet-grid'); if (grid && !grid.hidden && grid.children.length) { renderPlanetGrid('planet-grid', false); } var lobby = document.getElementById('lobby-planet-grid'); if (lobby && lobby.children.length) { renderPlanetGrid('lobby-planet-grid', true); } } return found; } function openPlanetSelect (context) { if (app.mode === 'playing') { return; } app.planetSelectContext = context || 'solo'; app.mode = 'planet-select'; hideEl('menu'); hideEl('online-panel'); hideEl('game-over'); showEl('planet-select'); renderPlanetGrid('planet-grid', false); var go = document.getElementById('btn-planet-go'); if (go) { go.textContent = (typeof I18n !== 'undefined') ? I18n.t('menu.play') : 'Play'; } // t1201: show which mode this planet choice is for. var modeEl = document.getElementById('planet-mode'); if (modeEl) { modeEl.textContent = modeLabel(app.planetSelectContext); } } function renderPlanetGrid (containerId, compact) { var grid = document.getElementById(containerId); if (!grid) { return; } var current = selectedPlanetId(); var all = Planet.allPlanets(); grid.innerHTML = ''; if (compact) { grid.classList.add('compact'); } for (var i = 0; i < all.length; i++) { var pl = all[i]; var btn = document.createElement('button'); btn.type = 'button'; btn.className = 'planet-card' + (pl.id === current ? ' selected' : '') + (pl.custom ? ' custom' : ''); btn.setAttribute('role', 'listitem'); btn.dataset.planet = pl.id; var swatches = ''; var colors = pl.colors || []; for (var c = 0; c < colors.length; c++) { var cname = colors[c].name; if (typeof I18n !== 'undefined' && (colors[c].block || (!pl.custom && colors[c].name))) { cname = I18n.blockName(colors[c].block || (pl.id + '-' + colors[c].name), colors[c].name); } swatches += ''
				+ escapeText(cname) + ''; } var title = (typeof I18n !== 'undefined') ? I18n.planetName(pl) : pl.name; var people = (typeof I18n !== 'undefined') ? I18n.peopleName(pl) : pl.people; var badge = (typeof I18n !== 'undefined') ? I18n.t('planet.customBadge') : 'Yours'; btn.innerHTML = '
' + escapeText(title) + '
' + '
' + escapeText(people) + '
' + '
' + escapeText(Planet.formatStats(pl)) + '
' + '
' + swatches + '
' + (pl.custom ? '' + escapeText(badge) + '' : ''); btn.addEventListener('click', (function (id, isCompact) { return function () { onPlanetPicked(id, isCompact); }; })(pl.id, !!compact)); grid.appendChild(btn); } } function onPlanetPicked (id, fromLobby) { setSelectedPlanet(id); if (fromLobby && typeof Online !== 'undefined' && Online.lobby) { Online.setPlanet(id).then(function () { renderOnline(); }); } else { renderPlanetGrid('planet-grid', false); } } function confirmPlanetSelect () { var planet = setSelectedPlanet(selectedPlanetId()); hideEl('planet-select'); if (app.planetSelectContext === 'online') { openOnlinePanel(); return; } if (app.planetSelectContext === 'offline') { startPlay({ planet: planet, offline: true }); return; } startPlay({ planet: planet }); } function cancelPlanetSelect () { hideEl('planet-select'); app.mode = 'menu'; showEl('menu'); } function bindPlanetSelect () { var go = document.getElementById('btn-planet-go'); var back = document.getElementById('btn-planet-back'); if (go) { go.addEventListener('click', confirmPlanetSelect); } if (back) { back.addEventListener('click', cancelPlanetSelect); } } /** t1246: ask a logged-out player to log in, or continue as guest. */ function bindLoginPrompt () { if (typeof LoginPrompt !== 'undefined' && LoginPrompt.isAuthReturn) { var search = (window.location && window.location.search) || ''; var referrer = (typeof document !== 'undefined' && document.referrer) || ''; if (LoginPrompt.isAuthReturn(search, referrer)) { LoginPrompt.remember(); } } var guest = document.getElementById('btn-play-guest'); if (guest) { guest.addEventListener('click', playAsGuest); } var login = document.getElementById('btn-login-prompt'); if (login) { login.addEventListener('click', function () { if (typeof LoginPrompt !== 'undefined') { LoginPrompt.remember(); } }); } var local = document.getElementById('login-prompt-local'); if (local) { local.addEventListener('click', function (e) { var a = e.target && e.target.closest ? e.target.closest('a') : null; if (a && typeof LoginPrompt !== 'undefined') { LoginPrompt.remember(); } }); } } function maybeShowLoginPrompt () { var me = (typeof Online !== 'undefined') ? Online.me : null; var remembered = (typeof LoginPrompt !== 'undefined') && LoginPrompt.remembered(); var fromAuth = (typeof LoginPrompt !== 'undefined') && LoginPrompt.isAuthReturn( (window.location && window.location.search) || '', (typeof document !== 'undefined' && document.referrer) || '' ); var show = (typeof LoginPrompt === 'undefined') ? (!me && !remembered && !fromAuth) : LoginPrompt.shouldShow({ me: me, remembered: remembered, fromAuthReturn: fromAuth }); if (show) { showLoginPrompt(); } else { hideLoginPrompt(); } app.loginPromptReady = true; } function showLoginPrompt () { var el = document.getElementById('login-prompt'); if (!el) { return; } el.hidden = false; var login = document.getElementById('btn-login-prompt'); if (login && login.focus) { login.focus(); } } function hideLoginPrompt () { var el = document.getElementById('login-prompt'); if (el) { el.hidden = true; } } function playAsGuest () { if (typeof LoginPrompt !== 'undefined') { LoginPrompt.remember(); } hideLoginPrompt(); } function refreshMenuAccount () { var guest = document.getElementById('menu-guest'); var user = document.getElementById('menu-user'); var designerBtn = document.getElementById('btn-designer'); var localLogin = document.getElementById('menu-local-login'); var me = (typeof Online !== 'undefined') ? Online.me : null; if (me) { if (guest) { guest.hidden = true; } if (user) { user.hidden = false; } var name = document.getElementById('menu-name'); if (name) { name.textContent = me.name || me.id || ((typeof I18n !== 'undefined') ? I18n.t('menu.player') : 'player'); } var pts = document.getElementById('menu-points'); if (pts) { pts.textContent = String((typeof Online !== 'undefined' && Online.lifetimePoints) || 0); } if (designerBtn) { designerBtn.hidden = false; } } else { if (guest) { guest.hidden = false; } if (user) { user.hidden = true; } if (designerBtn) { designerBtn.hidden = true; } } if (localLogin) { localLogin.hidden = !(typeof Online !== 'undefined' && Online.local); } var promptLocal = document.getElementById('login-prompt-local'); if (promptLocal) { promptLocal.hidden = !(typeof Online !== 'undefined' && Online.local); } } /* ---------- t1193 in-game menu (Spelen / Offline Strijd) ----------- */ function setGameMenuButton (show) { var btn = document.getElementById('btn-game-menu'); if (btn) { btn.hidden = !show; } } /** The menu can open during a running solo / offline field only. */ function canOpenGameMenu () { return app.mode === 'playing' && !!app.core && !app.online && !app.spectating && app.core.state === 'playing' && !app.rewardActive && !app.quitting && !(app.offline && app.battle && app.battle.state !== 'playing'); } function openGameMenu () { if (!canOpenGameMenu()) { return false; } if (app.core.drag) { finishDrag({ noLaunch: true }); } app.paused = true; // t1201: name the running mode ("Play" = rounds vs bots, "Survival" = endless). var modeEl = document.getElementById('game-menu-mode'); if (modeEl) { modeEl.textContent = modeLabel(app.offline ? 'offline' : 'solo'); } showEl('game-menu'); var resume = document.getElementById('btn-game-resume'); if (resume && resume.focus) { resume.focus(); } return true; } function resumeFromGameMenu () { hideEl('game-menu'); if (!app.quitting) { app.paused = false; } } /** * "Back to main menu": ends the match now. Logged in, the points so far * go through the normal play_finish + reward screen first (the server * still applies its caps); logged out, straight to the menu. Offline * Strijd ends the whole battle (no next round). */ function quitToMainMenu () { if (!app.core || app.quitting) { return; } hideEl('game-menu'); app.paused = true; app.quitting = true; app.gameOverShown = true; app.lastScore = app.core.score || 0; setGameMenuButton(false); var score = app.lastScore; var done = function () { app.quitting = false; app.paused = false; returnToMenu(); }; if (rewardEnabled()) { var title = (typeof I18n !== 'undefined') ? I18n.t('reward.ended') : 'Game ended'; showReward(false, finishPlaySession(score), done, title); } else { finishPlaySession(score); done(); } } function bindGameMenu () { var btn = document.getElementById('btn-game-menu'); if (btn) { btn.addEventListener('click', function () { openGameMenu(); }); } var resume = document.getElementById('btn-game-resume'); if (resume) { resume.addEventListener('click', resumeFromGameMenu); } var quit = document.getElementById('btn-game-quit'); if (quit) { quit.addEventListener('click', quitToMainMenu); } document.addEventListener('keydown', function (e) { if (e.key !== 'Escape') { return; } var menu = document.getElementById('game-menu'); if (menu && !menu.hidden) { resumeFromGameMenu(); } else { openGameMenu(); } }); } function beginPlaySession (mode) { if (app.playToken) { finishPlaySession(app.core ? app.core.score : (app.lastScore || 0)); } app.playToken = null; if (typeof Online === 'undefined' || !Online.me || !Online.playBegin) { return; } Online.playBegin(mode || 'solo').then(function (data) { if (data && data.ok && data.token) { app.playToken = data.token; } }); } /** * Ends the solo/offline play session. Resolves to the server-confirmed * { before, after } profile totals (t1173), or null when there is no * logged-in user or the server did not confirm. Without a token (e.g. * play_begin failed) a logged-in player gets { before = after = current }. */ function finishPlaySession (score) { var token = app.playToken; app.playToken = null; var hasOnline = typeof Online !== 'undefined'; var current = hasOnline ? (Online.lifetimePoints || 0) : 0; if (!token || !hasOnline || !Online.playFinish) { return Promise.resolve(hasOnline && Online.me ? { before: current, after: current } : null); } return Promise.resolve(Online.playFinish(token, score || 0)).then(function (data) { refreshMenuAccount(); if (data && data.ok !== false && typeof data.lifetime_points === 'number') { var awarded = Math.max(0, Number(data.awarded) || 0); return { before: data.lifetime_points - awarded, after: data.lifetime_points }; } return null; }, function () { return null; }); } /* ---------- t1173 reward screen (logged in only) ------------------- */ function rewardEnabled () { return typeof Reward !== 'undefined' && typeof Online !== 'undefined' && !!Online.me; } /** * Shows "You won!" / "You lost..." and the points fly-in, then calls * next() — the same destination the mode used before (menu, next * offline round, offline result, or the online lobby/podium). */ function showReward (won, resultPromise, next, title) { app.rewardActive = true; hideEl('game-over'); hideEl('spectator'); hideEl('podium'); var handle = Reward.play({ won: won, title: title || null, planet: app.planet, result: resultPromise, onDone: function () { app.rewardActive = false; if (next) { next(); } } }); if (!handle) { app.rewardActive = false; // No reward overlay (e.g. missing DOM): still continue (t1193). if (title && next) { next(); } } } function myOnlinePlace (lobby) { var me = typeof Online !== 'undefined' ? Online.me : null; var ranks = (lobby && lobby.rankings) || []; for (var i = 0; i < ranks.length; i++) { if (me && ranks[i].id === me.id) { return ranks[i].place; } } return null; } function applyProfileLocale () { if (typeof I18n === 'undefined' || typeof Online === 'undefined') { return; } if (!Online.me) { return; } I18n.applyPreferred({ explicit: !!(Online.localeExplicit && Online.locale), locale: Online.locale, authLocale: Online.authLocale, syncExplicit: true }); } /* ---------- t1247 leaderboard -------------------------------------- */ function bindLeaderboard () { var btn = document.getElementById('btn-leaderboard'); if (btn) { var open = function () { openLeaderboard(); }; btn.addEventListener('click', open); // Same mobile path as Play / Survival: some browsers swallow click // after a slightly sloppy tap. btn.addEventListener('pointerup', function (e) { if (e.pointerType === 'touch' || e.pointerType === 'pen') { e.preventDefault(); open(); } }); } var back = document.getElementById('btn-lb-back'); if (back) { back.addEventListener('click', closeLeaderboard); } var globalTab = document.getElementById('lb-tab-global'); var friendsTab = document.getElementById('lb-tab-friends'); if (globalTab) { globalTab.addEventListener('click', function () { setLeaderboardTab('global'); }); } if (friendsTab) { friendsTab.addEventListener('click', function () { setLeaderboardTab('friends'); }); } } function openLeaderboard (tab) { if (app.mode === 'leaderboard') { return; } hideEl('menu'); hideEl('online-panel'); hideEl('planet-select'); hideEl('login-prompt'); app.mode = 'leaderboard'; app.leaderboardTab = tab || app.leaderboardTab || 'global'; showEl('leaderboard'); setLeaderboardTab(app.leaderboardTab); } function closeLeaderboard () { hideEl('leaderboard'); app.mode = 'menu'; showEl('menu'); } function setLeaderboardTab (tab) { tab = tab === 'friends' ? 'friends' : 'global'; app.leaderboardTab = tab; var globalTab = document.getElementById('lb-tab-global'); var friendsTab = document.getElementById('lb-tab-friends'); if (globalTab) { globalTab.setAttribute('aria-selected', tab === 'global' ? 'true' : 'false'); } if (friendsTab) { friendsTab.setAttribute('aria-selected', tab === 'friends' ? 'true' : 'false'); } loadLeaderboard(tab); } function loadLeaderboard (tab) { tab = tab || app.leaderboardTab || 'global'; var login = document.getElementById('lb-login'); var list = document.getElementById('lb-list'); var empty = document.getElementById('lb-empty'); var err = document.getElementById('lb-error'); if (err) { err.hidden = true; err.textContent = ''; } if (empty) { empty.hidden = true; } if (list) { list.innerHTML = ''; } var loggedIn = typeof Online !== 'undefined' && !!Online.me; if (tab === 'friends' && !loggedIn) { if (login) { login.hidden = false; } return; } if (login) { login.hidden = true; } if (typeof Online === 'undefined' || !Online.leaderboard) { showLeaderboardError((typeof I18n !== 'undefined') ? I18n.t('leaderboard.loadError') : 'The leaderboard could not be loaded.'); return; } Online.leaderboard(tab).then(function (data) { if (app.mode !== 'leaderboard' || app.leaderboardTab !== tab) { return; } if (!data || data.ok === false) { var msg = (data && data.error) ? ((typeof I18n !== 'undefined') ? I18n.error(data.error) : data.error) : ((typeof I18n !== 'undefined') ? I18n.t('leaderboard.loadError') : 'The leaderboard could not be loaded.'); showLeaderboardError(msg); return; } if (tab === 'friends' && data.login_required) { if (login) { login.hidden = false; } return; } renderLeaderboard(data.players || [], tab); }); } function showLeaderboardError (text) { var err = document.getElementById('lb-error'); if (!err) { return; } err.hidden = !text; err.textContent = text || ''; } function renderLeaderboard (players, tab) { var list = document.getElementById('lb-list'); var empty = document.getElementById('lb-empty'); var login = document.getElementById('lb-login'); if (login) { login.hidden = true; } if (!list) { return; } list.innerHTML = ''; if (!players || !players.length) { if (empty) { empty.hidden = false; } return; } if (empty) { empty.hidden = true; } var meId = (typeof Online !== 'undefined' && Online.me) ? Online.me.id : null; for (var i = 0; i < players.length; i++) { var p = players[i]; var li = document.createElement('li'); var you = !!(p.you || (meId && p.id === meId)); li.className = 'lb-row' + (you ? ' you' : ''); var rank = document.createElement('span'); rank.className = 'lb-rank'; rank.textContent = String(p.rank || (i + 1)); li.appendChild(rank); if (typeof Avatar !== 'undefined' && Avatar.piece) { li.appendChild(Avatar.piece({ id: p.id, name: p.name, avatar: p.avatar }, { size: 40 })); } var name = document.createElement('span'); name.className = 'lb-name'; name.textContent = p.name || ''; li.appendChild(name); var pts = document.createElement('span'); pts.className = 'lb-points'; var n = p.points || 0; pts.textContent = (typeof I18n !== 'undefined') ? I18n.t('leaderboard.points', { n: n }, n + ' points') : (n + ' points'); li.appendChild(pts); list.appendChild(li); } } function refreshAllUi () { if (typeof I18n !== 'undefined') { I18n.apply(); } refreshMenuAccount(); if (typeof renderPlanetGrid === 'function') { renderPlanetGrid('planet-grid', false); renderPlanetGrid('lobby-planet-grid', true); } if (app && app.mode === 'online' && typeof renderOnline === 'function') { renderOnline(); } if (typeof Designer !== 'undefined') { var des = document.getElementById('designer'); var edit = document.getElementById('designer-edit'); if (des && !des.hidden) { Designer.renderList(); } if (edit && !edit.hidden) { Designer.syncPreview(); Designer.renderSlots(); var modal = document.getElementById('des-modal'); if (modal && !modal.hidden) { Designer.openModal(Designer.openSlot); } } } if (app && app.mode === 'playing') { if (typeof refreshHud === 'function') { refreshHud(); } if (typeof refreshOfflineHud === 'function') { refreshOfflineHud(); } } if (app && app.mode === 'leaderboard' && typeof loadLeaderboard === 'function') { loadLeaderboard(app.leaderboardTab); } }