BlueGit

projects-timfalken-com meteors

Files

meteors / src / main.js

main.js

main.js 64.4 KiB Download Raw
1'use strict';
2
3/**
4 * View and input for Meteors. The simulation lives in GameCore; this file
5 * only draws it, scales it to the viewport, and translates pointer events
6 * into beginDrag / moveDrag / endDrag. Online play (stage 2) is wired
7 * through Online (src/online.js) and the same GameCore. Offline Strijd
8 * (t1119) uses Offline (src/offline.js) against local bots.
9 */
10
11function planetImages ()
12{
13 var list = [
14 { name: 'gray', url: 'images/block-gray.png' },
15 { name: 'locked', url: 'images/block-locked.png' },
16 { name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 },
17 { name: 'cell', url: 'images/cell.png' },
18 { name: 'pixel', url: 'images/pixel.png' },
19 { name: 'columnWarn', url: 'images/column-warn.png' },
20 // Keep the original Terra placeholders as aliases (Tim may still have them).
21 { name: 'ember', url: 'images/block-ember.png' },
22 { name: 'aqua', url: 'images/block-aqua.png' },
23 { name: 'leaf', url: 'images/block-leaf.png' },
24 { name: 'sun', url: 'images/block-sun.png' },
25 { name: 'orchid', url: 'images/block-orchid.png' }
26 ];
27 var planets = (typeof Planet !== 'undefined' ? Planet.allPlanets() : []);
28 for (var i = 0; i < planets.length; i++)
29 {
30 var pl = planets[i];
31 for (var c = 0; c < pl.colors.length; c++)
32 {
33 list.push({
34 name: Planet.spriteKey(pl, c),
35 url: pl.colors[c].image
36 });
37 }
38 }
39 if (typeof Blocks !== 'undefined' && Blocks.images)
40 {
41 var extra = Blocks.images();
42 for (var b = 0; b < extra.length; b++)
43 { list.push(extra[b]); }
44 }
45 return list;
46}
47
48var IMAGES = planetImages();
49var GAME_OVER_DELAY = 2;
50
51var game = new Game();
52var app = {
53 mode: 'menu',
54 core: null,
55 scene: null,
56 manager: null,
57 planet: null,
58 lastScore: 0,
59 tile: 48,
60 fieldX: 0,
61 fieldY: 0,
62 fieldW: 0,
63 fieldH: 0,
64 hudH: 56,
65 sprites: Object.create(null),
66 flames: Object.create(null),
67 cells: [],
68 pointerId: null,
69 pointerType: null,
70 activeTouchId: null,
71 debugDrag: false,
72 debugPhysics: false,
73 gameOverShown: false,
74 selectTween: null,
75 online: false,
76 eliminatedReported: false,
77 spectating: false,
78 miniH: 0,
79 selectedPlanetId: 'terra',
80 planetSelectContext: 'solo',
81 offline: false,
82 battle: null,
83 swapTweens: null,
84 columnWarn: null,
85 warnClock: 0,
86 miniAcc: 0,
87 offlineResultShown: false,
88 roundWonDelay: 0,
89 roundWonHandled: false
90};
91
92window.onload = function ()
93{
94 app.debugDrag = isDragDebugEnabled();
95 app.debugPhysics = isPhysicsDebugEnabled();
96 var play = document.getElementById('btn-play');
97 play.addEventListener('click', onPlay);
98 play.addEventListener('pointerup', function (e)
99 {
100 // A touch-friendly path: some mobile browsers swallow the click
101 // after a slightly sloppy tap. Ignore the following click.
102 if (e.pointerType === 'touch' || e.pointerType === 'pen')
103 {
104 e.preventDefault();
105 onPlay();
106 }
107 });
108
109 game.preloadImagesThenStart(IMAGES, function ()
110 {
111 if (game.images.flame && game.images.flame.addAnimationCycle)
112 { game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); }
113 });
114
115 if (typeof I18n !== 'undefined')
116 {
117 I18n.init();
118 I18n.bindPicker();
119 I18n.onChange(function ()
120 { refreshAllUi(); });
121 }
122 bindOnlineUi();
123 bindOfflineUi();
124 bindPlanetSelect();
125 restoreSelectedPlanet();
126 if (typeof Designer !== 'undefined' && Designer.bind)
127 { Designer.bind(); }
128 if (typeof Online !== 'undefined' && Online.refresh)
129 {
130 Online.refresh().then(function ()
131 {
132 applyProfileLocale();
133 refreshMenuAccount();
134 restoreSelectedPlanet();
135 renderPlanetGrid('planet-grid', false);
136 renderPlanetGrid('lobby-planet-grid', true);
137 });
138 }
139 else
140 { refreshMenuAccount(); }
141};
142
143function onPlay ()
144{
145 if (app.mode === 'playing')
146 { return; }
147 clearStartError();
148 openPlanetSelect('solo');
149}
150
151function startPlay (opts)
152{
153 opts = opts || {};
154 var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod;
155 var planet = opts.planet || planetMod.planetById(selectedPlanetId());
156 var miss = opts.missChance;
157 if (typeof miss !== 'number' || !isFinite(miss))
158 { miss = planetMod.missChance(planet); }
159
160 hideEl('menu');
161 hideEl('game-over');
162 hideEl('online-panel');
163 hideEl('spectator');
164 hideEl('podium');
165 hideEl('planet-select');
166 hideEl('offline-result');
167 hideEl('designer');
168 hideEl('designer-edit');
169 if (typeof Designer !== 'undefined' && Designer.closeModal)
170 { Designer.closeModal(); }
171 // Do not show the HUD until the scene is on screen. Showing it first
172 // left the default "Terra" / "0" labels on a blank starfield when
173 // `new Scene` threw (WebGL unavailable) after inserting a transparent
174 // canvas — the t1143 live blank-screen report.
175
176 app.planet = planet;
177 app.core = new GameCore(planet, Math.random, miss);
178 if (app.debugPhysics)
179 { app.core.debugInvariants = true; }
180 app.mode = 'playing';
181 app.online = !!opts.online;
182 app.offline = !!opts.offline;
183 app.gameOverShown = false;
184 app.eliminatedReported = false;
185 app.spectating = false;
186 app.sprites = Object.create(null);
187 app.flames = Object.create(null);
188 app.cells = [];
189 app.pointerId = null;
190 app.selectTween = null;
191 app.swapTweens = Object.create(null);
192 app.columnWarn = [];
193 app.warnClock = 0;
194 app.miniAcc = 1; // draw minis on the first frame
195 app.offlineResultShown = false;
196 if (!opts.keepBattle)
197 {
198 app.roundWonDelay = 0;
199 app.roundWonHandled = false;
200 }
201 if (app.offline && !opts.keepBattle && typeof Offline !== 'undefined')
202 {
203 app.battle = Offline.createBattle({
204 playerPlanet: app.planet,
205 rng: Math.random,
206 round: opts.round || 1
207 });
208 }
209
210 layout();
211 if (app.scene)
212 {
213 app.scene.destroy();
214 app.scene = null;
215 }
216 try
217 {
218 app.scene = new Scene(app.fieldX, app.fieldY, app.fieldW, app.fieldH);
219 app.scene.backgroundColor = { r: 12, g: 16, b: 32 };
220 app.scene.renderBackground = true;
221 game.loadScene(app.scene);
222 buildCells();
223 app.manager = app.scene.addObject(makeManager());
224 if (!app.spectating)
225 { bindPointer(app.scene.canvas); }
226 refreshHud();
227 showEl('hud');
228 }
229 catch (err)
230 {
231 abortStartPlay(err);
232 return;
233 }
234 if (app.online || app.offline)
235 { showEl('minis'); }
236 else
237 { hideEl('minis'); }
238 buildColumnWarn();
239 refreshOfflineHud();
240 refreshChainIndicator();
241 if (!opts.online)
242 { beginPlaySession(opts.offline ? 'offline' : 'solo'); }
243}
244
245function removeOrphanPlayCanvases ()
246{
247 // Scene's constructor inserts a body canvas, then GLContext may throw,
248 // leaving a transparent leftover that hides nothing and shows stars.
249 var nodes = document.querySelectorAll('body > canvas');
250 for (var i = 0; i < nodes.length; i++)
251 {
252 if (nodes[i].parentNode)
253 { nodes[i].parentNode.removeChild(nodes[i]); }
254 }
255}
256
257function abortStartPlay (err)
258{
259 if (typeof console !== 'undefined' && console.error)
260 { console.error('startPlay failed', err); }
261 try
262 {
263 unbindPointer();
264 if (app.scene && app.scene.destroy)
265 { app.scene.destroy(); }
266 }
267 catch (e) { /* ignore cleanup errors */ }
268 app.scene = null;
269 app.core = null;
270 app.manager = null;
271 app.mode = 'menu';
272 app.online = false;
273 app.offline = false;
274 app.battle = null;
275 app.cells = [];
276 removeOrphanPlayCanvases();
277 hideEl('hud');
278 hideEl('minis');
279 hideEl('planet-select');
280 showEl('menu');
281 refreshMenuAccount();
282 var box = document.getElementById('start-error');
283 if (box)
284 {
285 var msg = (err && err.message) ? String(err.message) : '';
286 var webgl = /webgl/i.test(msg);
287 if (typeof I18n !== 'undefined')
288 { box.textContent = I18n.t(webgl ? 'error.webgl' : 'error.startFailed'); }
289 else
290 {
291 box.textContent = webgl
292 ? 'This game needs WebGL. Please try another browser, or turn on hardware acceleration.'
293 : 'Could not start the game.';
294 }
295 box.hidden = false;
296 }
297}
298
299function clearStartError ()
300{
301 var box = document.getElementById('start-error');
302 if (box)
303 {
304 box.hidden = true;
305 box.textContent = '';
306 }
307}
308
309function teardownPlay ()
310{
311 unbindPointer();
312 if (app.scene)
313 {
314 app.scene.destroy();
315 app.scene = null;
316 }
317 app.manager = null;
318 app.core = null;
319 app.sprites = Object.create(null);
320 app.flames = Object.create(null);
321 app.cells = [];
322 app.selectTween = null;
323 app.swapTweens = Object.create(null);
324 app.columnWarn = [];
325 app.pointerId = null;
326 app.gameOverShown = false;
327 hideEl('hud');
328 hideEl('game-over');
329 hideEl('spectator');
330 hideEl('minis');
331 hideEl('offline-result');
332 hideOfflineHud();
333 hideChainIndicator();
334 if (typeof Online !== 'undefined')
335 { Online.clearFlights(); }
336 if (!app._keepBattleOnTeardown)
337 {
338 app.battle = null;
339 app.offline = false;
340 }
341 app._keepBattleOnTeardown = false;
342}
343
344function returnToMenu ()
345{
346 clearStartError();
347 if (app.online && typeof Online !== 'undefined')
348 {
349 // Online matches do not dump you back to the solo menu:
350 // elimination becomes spectating; a finished match shows the podium.
351 return;
352 }
353 teardownPlay();
354 app.mode = 'menu';
355 app.online = false;
356 app.offline = false;
357 app.battle = null;
358 hideEl('planet-select');
359 showEl('menu');
360 var last = document.getElementById('last-score');
361 if (app.lastScore > 0)
362 {
363 last.hidden = false;
364 last.querySelector('strong').textContent = String(app.lastScore);
365 }
366}
367
368function buildCells ()
369{
370 if (!app.scene)
371 { return; }
372 var img = game.images.cell;
373 for (var row = 0; row < 13; row++)
374 {
375 for (var col = 0; col < 10; col++)
376 {
377 var obj = new GameObject(0, 0, img, 0);
378 placeTile(obj, col, row);
379 obj.renderer.alpha = 0.9;
380 app.scene.addObject(obj);
381 app.cells.push(obj);
382 }
383 }
384}
385
386function placeTile (obj, col, y)
387{
388 var t = app.tile;
389 obj.transform.position.x = col * t + t / 2;
390 obj.transform.position.y = app.fieldH - (y + 0.5) * t;
391 obj.transform.size = { x: t, y: t };
392}
393
394function opponentCount ()
395{
396 if (app.offline && app.battle && app.battle.bots)
397 { return app.battle.bots.length; }
398 if (app.online && typeof Online !== 'undefined' && Online.opponents)
399 { return Online.opponents().length; }
400 return 0;
401}
402
403function currentMiniSize ()
404{
405 if (app.miniLayout && app.miniLayout.mini)
406 { return { w: app.miniLayout.mini.w, h: app.miniLayout.mini.h }; }
407 var n = opponentCount();
408 var mode = (app.miniLayout && app.miniLayout.mode) || 'top';
409 if (typeof MiniLayout !== 'undefined' && MiniLayout.canvasSize)
410 { return MiniLayout.canvasSize(n, mode, 0); }
411 if (n >= 10)
412 { return { w: 40, h: 52 }; }
413 if (n >= 6)
414 { return { w: 56, h: 73 }; }
415 return { w: 80, h: 104 };
416}
417
418function applyMinisContainer (plan)
419{
420 var minis = document.getElementById('minis');
421 if (!minis)
422 { return; }
423 var n = plan ? plan.n : 0;
424 minis.classList.toggle('crowded', n > 5);
425 if (!plan || n === 0 || plan.mode !== 'sides')
426 {
427 minis.classList.remove('sides');
428 minis.style.top = (app.hudH || 56) + 'px';
429 minis.style.maxHeight = (plan && plan.miniH ? plan.miniH : 0) + 'px';
430 minis.style.bottom = '';
431 minis.style.left = '';
432 minis.style.right = '';
433 var kids = minis.querySelectorAll('.mini');
434 for (var i = 0; i < kids.length; i++)
435 {
436 kids[i].style.left = '';
437 kids[i].style.top = '';
438 kids[i].style.width = '';
439 kids[i].style.position = '';
440 }
441 return;
442 }
443 minis.classList.add('sides');
444 minis.style.top = '0';
445 minis.style.bottom = '0';
446 minis.style.left = '0';
447 minis.style.right = '0';
448 minis.style.maxHeight = 'none';
449}
450
451function applyMinisLayout ()
452{
453 var plan = app.miniLayout;
454 var minis = document.getElementById('minis');
455 if (!minis)
456 { return; }
457 applyMinisContainer(plan);
458 if (!plan || plan.mode !== 'sides')
459 { return; }
460 var positions = plan.positions || [];
461 var kids = minis.querySelectorAll('.mini');
462 for (var i = 0; i < positions.length && i < kids.length; i++)
463 {
464 var p = positions[i];
465 var el = kids[i];
466 el.style.position = 'absolute';
467 el.style.left = p.x + 'px';
468 el.style.top = p.y + 'px';
469 el.style.width = p.w + 'px';
470 var canvas = el.querySelector('canvas');
471 if (canvas)
472 {
473 canvas.style.width = p.canvasW + 'px';
474 canvas.style.height = p.canvasH + 'px';
475 }
476 }
477}
478
479function applyFlightsBackClip ()
480{
481 var back = document.getElementById('flights-back');
482 if (!back)
483 { return; }
484 var x = app.fieldX || 0;
485 var y = app.fieldY || 0;
486 var w = app.fieldW || 0;
487 var h = app.fieldH || 0;
488 if (!w || !h)
489 {
490 back.style.clipPath = '';
491 return;
492 }
493 // Even-odd polygon: full viewport with a hole over the player's field,
494 // so enemy-to-enemy arcs travel behind the field (t1125).
495 back.style.clipPath = 'polygon(evenodd, 0 0, 100% 0, 100% 100%, 0 100%, 0 0, '
496 + x + 'px ' + y + 'px, ' + (x + w) + 'px ' + y + 'px, '
497 + (x + w) + 'px ' + (y + h) + 'px, ' + x + 'px ' + (y + h) + 'px, '
498 + x + 'px ' + y + 'px)';
499}
500
501function layoutIfNeeded ()
502{
503 if (app.core && app.core.drag)
504 { return; }
505 var vw = window.innerWidth || 320;
506 var vh = window.innerHeight || 480;
507 var n = (app.online || app.offline) ? opponentCount() : 0;
508 if (app._layoutVw === vw && app._layoutVh === vh && app._layoutN === n
509 && app.scene && app.tile)
510 { return; }
511 layout();
512}
513
514function layout ()
515{
516 if (app.core && app.core.drag)
517 { return; }
518 var vw = window.innerWidth || 320;
519 var vh = window.innerHeight || 480;
520 var n = (app.online || app.offline) ? opponentCount() : 0;
521 app._layoutVw = vw;
522 app._layoutVh = vh;
523 app._layoutN = n;
524 var safeTop = 0;
525 try
526 {
527 // env(safe-area) is a CSS thing; keep a conservative HUD height.
528 safeTop = 0;
529 }
530 catch (e) { /* ignore */ }
531 app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop);
532 var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015));
533 var plan;
534 if (typeof MiniLayout !== 'undefined' && MiniLayout.plan)
535 { plan = MiniLayout.plan(vw, vh, n, app.hudH, margin); }
536 else
537 {
538 plan = {
539 mode: 'top',
540 tile: 14,
541 fieldW: 140,
542 fieldH: 182,
543 fieldX: Math.floor((vw - 140) / 2),
544 fieldY: app.hudH,
545 miniH: n > 0 ? 100 : 0,
546 mini: { w: 80, h: 104 },
547 positions: [],
548 n: n
549 };
550 }
551 app.miniLayout = plan;
552 app.miniH = plan.miniH;
553 app.tile = plan.tile;
554 app.fieldW = plan.fieldW;
555 app.fieldH = plan.fieldH;
556 app.fieldX = plan.fieldX;
557 app.fieldY = plan.fieldY;
558 applyMinisLayout();
559 applyFlightsBackClip();
560
561 if (app.scene)
562 {
563 app.scene.position.x = app.fieldX;
564 app.scene.position.y = app.fieldY;
565 app.scene.size.x = app.fieldW;
566 app.scene.size.y = app.fieldH;
567 }
568}
569
570function spriteFor (block)
571{
572 if (block.state === 'locked')
573 { return game.images.locked; }
574 if (block.color < 0)
575 { return game.images.gray; }
576 var key = Planet.spriteKey(app.planet, block.color);
577 return game.images[key] || game.images.gray;
578}
579
580function syncSprites (dt)
581{
582 if (!app.core || !app.scene)
583 { return; }
584 dt = dt || 0;
585 consumeAndStartSwapTweens();
586 advanceSwapTweens(dt);
587 var seen = Object.create(null);
588 var blocks = app.core.blocks;
589 for (var i = 0; i < blocks.length; i++)
590 {
591 var block = blocks[i];
592 seen[block.id] = true;
593 var obj = app.sprites[block.id];
594 if (!obj)
595 {
596 obj = new GameObject(0, 0, spriteFor(block), 2);
597 app.scene.addObject(obj);
598 app.sprites[block.id] = obj;
599 }
600 obj.renderer.sprite = spriteFor(block);
601 placeTile(obj, block.col, blockVisualY(block));
602 applyBlockVisual(obj, block);
603 obj.renderer.visible = true;
604 obj.renderer.alpha = 1;
605 if (typeof Online !== 'undefined' && Online.hasExitVisual && Online.hasExitVisual(block.id))
606 {
607 obj.renderer.visible = false;
608 obj.renderer.alpha = 0;
609 }
610
611 if (block.flame)
612 {
613 var flame = app.flames[block.id];
614 if (!flame)
615 {
616 flame = new GameObject(0, 0, game.images.flame, 1);
617 flame.renderer.setAnimation('burn', 0, 0.08);
618 app.scene.addObject(flame);
619 app.flames[block.id] = flame;
620 }
621 flame.renderer.visible = true;
622 var t = app.tile;
623 // 3x as large (length and width, t1110). Keep the top of the
624 // flame at the same overlap into the block so the extra length
625 // extends downward under the rocket.
626 var flameW = t * 0.85 * 3;
627 var flameH = t * 0.85 * 3;
628 var origCenter = app.fieldH - block.y * t + t * 0.15;
629 var origTop = origCenter - (t * 0.85) / 2;
630 flame.transform.position.x = block.col * t + t / 2;
631 flame.transform.position.y = origTop + flameH / 2;
632 flame.transform.size = { x: flameW, y: flameH };
633 }
634 else if (app.flames[block.id])
635 { app.flames[block.id].renderer.visible = false; }
636 if (block.flame && app.flames[block.id]
637 && typeof Online !== 'undefined' && Online.hasExitVisual
638 && Online.hasExitVisual(block.id))
639 { app.flames[block.id].renderer.visible = false; }
640 }
641
642 var ids = Object.keys(app.sprites);
643 for (var i = 0; i < ids.length; i++)
644 {
645 if (!seen[ids[i]])
646 {
647 app.sprites[ids[i]].destroy();
648 delete app.sprites[ids[i]];
649 if (app.flames[ids[i]])
650 {
651 app.flames[ids[i]].destroy();
652 delete app.flames[ids[i]];
653 }
654 }
655 }
656}
657
658function applyBlockVisual (obj, block)
659{
660 var t = app.tile;
661 var sx = 1;
662 var sy = 1;
663 var dy = 0;
664 if (block.bouncing && app.planet && app.planet.bounceDuration > 0
665 && typeof Easing !== 'undefined' && Easing.bouncePose)
666 {
667 var u = block.bounceAge / app.planet.bounceDuration;
668 var pose = Easing.bouncePose(u, app.planet.bounceSquash);
669 sx = pose.sx;
670 sy = pose.sy;
671 dy = pose.dy;
672 }
673 var sel = 1;
674 var tw = app.selectTween;
675 if (tw && tw.blockId === block.id && tw.phase !== 'idle')
676 { sel = tw.scale; }
677 obj.transform.size = { x: t * sx * sel, y: t * sy * sel };
678 if (dy)
679 { obj.transform.position.y -= dy * t; }
680}
681
682function clickTween ()
683{
684 return (typeof Easing !== 'undefined' && Easing.CLICK_TWEEN) ? Easing.CLICK_TWEEN : null;
685}
686
687function startPressTween (blockId)
688{
689 var c = clickTween();
690 if (!c)
691 { return; }
692 var from = (app.selectTween && app.selectTween.phase !== 'idle') ? app.selectTween.scale : 1;
693 app.selectTween = {
694 blockId: blockId,
695 from: from,
696 to: c.pressScale,
697 t: 0,
698 duration: c.pressDuration,
699 ease: c.pressEase,
700 scale: from,
701 phase: 'press'
702 };
703}
704
705function startReleaseTween ()
706{
707 var c = clickTween();
708 var tw = app.selectTween;
709 if (!c || !tw || tw.phase === 'idle')
710 { return; }
711 app.selectTween = {
712 blockId: tw.blockId,
713 from: tw.scale,
714 to: c.releaseScale,
715 t: 0,
716 duration: c.releaseDuration,
717 ease: c.releaseEase,
718 scale: tw.scale,
719 phase: 'release'
720 };
721}
722
723function updateSelectTween (dt)
724{
725 var tw = app.selectTween;
726 if (!tw || tw.phase === 'idle' || tw.phase === 'hold')
727 { return; }
728 tw.t += dt;
729 var u = tw.duration > 0 ? tw.t / tw.duration : 1;
730 if (u >= 1)
731 {
732 tw.scale = tw.to;
733 tw.t = tw.duration;
734 if (tw.phase === 'press')
735 { tw.phase = 'hold'; }
736 else
737 {
738 tw.phase = 'idle';
739 tw.scale = 1;
740 tw.blockId = null;
741 }
742 return;
743 }
744 var ease = tw.ease || (typeof Easing !== 'undefined' && Easing.easeOutBack);
745 tw.scale = ease ? Easing.tween(tw.from, tw.to, u, ease) : tw.from + (tw.to - tw.from) * u;
746}
747
748
749/* ---------- visual-only swap tween (t1121) -------------------------- */
750
751function swapTweenSpec ()
752{
753 if (typeof Easing !== 'undefined' && Easing.SWAP_TWEEN)
754 { return Easing.SWAP_TWEEN; }
755 return { duration: 0.100, ease: null };
756}
757
758function swapEase (u)
759{
760 if (typeof Easing !== 'undefined' && Easing.easeOutCubic)
761 { return Easing.easeOutCubic(u); }
762 var v = 1 - Math.max(0, Math.min(1, u));
763 return 1 - v * v * v;
764}
765
766function tweenVisualY (tw)
767{
768 var u = tw.duration > 0 ? Math.min(1, tw.age / tw.duration) : 1;
769 return tw.fromY + (tw.toY - tw.fromY) * swapEase(u);
770}
771
772/**
773 * Consume GameCore swap events. The currently dragged block is skipped
774 * (it follows the pointer). A block that is mid-tween and is swapped
775 * again restarts from its current visual y, so rapid swaps chain
776 * smoothly without snapping.
777 */
778function consumeAndStartSwapTweens ()
779{
780 if (!app.core || !app.core.consumeSwapEvents)
781 { return; }
782 if (!app.swapTweens)
783 { app.swapTweens = Object.create(null); }
784 var ev = app.core.consumeSwapEvents();
785 if (!ev.length)
786 { return; }
787 var dragId = app.core.drag && app.core.drag.blockId;
788 var duration = swapTweenSpec().duration;
789 for (var i = 0; i < ev.length; i++)
790 {
791 var e = ev[i];
792 if (e.id === dragId)
793 {
794 delete app.swapTweens[e.id];
795 continue;
796 }
797 var fromY = e.fromY;
798 var existing = app.swapTweens[e.id];
799 if (existing)
800 { fromY = tweenVisualY(existing); }
801 app.swapTweens[e.id] = {
802 fromY: fromY,
803 toY: e.toY,
804 age: 0,
805 duration: duration
806 };
807 }
808}
809
810function advanceSwapTweens (dt)
811{
812 if (!app.swapTweens)
813 { return; }
814 var ids = Object.keys(app.swapTweens);
815 for (var i = 0; i < ids.length; i++)
816 {
817 var tw = app.swapTweens[ids[i]];
818 tw.age += dt;
819 if (tw.age >= tw.duration)
820 { delete app.swapTweens[ids[i]]; }
821 }
822}
823
824function blockVisualY (block)
825{
826 if (!app.swapTweens)
827 { return block.y; }
828 var dragId = app.core && app.core.drag && app.core.drag.blockId;
829 if (block.id === dragId)
830 { return block.y; }
831 var tw = app.swapTweens[block.id];
832 if (!tw)
833 { return block.y; }
834 return tweenVisualY(tw);
835}
836
837function refreshHud ()
838{
839 if (!app.core)
840 { return; }
841 document.getElementById('score').textContent = String(app.core.score);
842 var planet = app.planet;
843 var pname = (typeof I18n !== 'undefined') ? I18n.planetName(planet) : planet.name;
844 var people = (typeof I18n !== 'undefined') ? I18n.peopleName(planet) : planet.people;
845 document.getElementById('planet-name').textContent = pname + ' · ' + people;
846 document.getElementById('planet-stats').textContent = Planet.formatStats(planet);
847}
848
849function makeManager ()
850{
851 var obj = new GameObject(0, 0, game.images.pixel, 0);
852 obj.renderer.visible = false;
853 var base = obj.update.bind(obj);
854 obj.update = function (dt)
855 {
856 base(dt);
857 tickView(dt);
858 };
859 return obj;
860}
861
862function tickView (dt)
863{
864 if (app.mode !== 'playing' || !app.core)
865 { return; }
866
867 // Never resize the canvas mid-drag: a URL-bar hide would move the
868 // field under the finger and jump the target row. Also skip work
869 // when the viewport has not actually changed.
870 if (!(app.core && app.core.drag))
871 { layoutIfNeeded(); }
872 for (var i = 0; i < app.cells.length; i++)
873 {
874 var col = i % 10;
875 var row = Math.floor(i / 10);
876 placeTile(app.cells[i], col, row);
877 }
878
879 app.core.tick(dt);
880 if (app.offline && app.battle)
881 { tickOffline(dt); }
882 updateSelectTween(dt);
883 syncSprites(dt);
884 updateColumnWarn(dt);
885 refreshHud();
886 refreshOfflineHud();
887 refreshChainIndicator();
888 tickOnline(dt);
889 if (app.debugPhysics)
890 { logPhysicsDebug(); }
891
892 if (app.core.state === 'gameover' && !app.gameOverShown)
893 {
894 app.gameOverShown = true;
895 app.lastScore = app.core.score;
896 document.getElementById('go-score').textContent = String(app.lastScore);
897 if (app.online)
898 { onOnlineEliminated(); }
899 else if (app.offline)
900 { /* Offline result is shown from tickOffline. */ }
901 else
902 {
903 showEl('game-over');
904 finishPlaySession(app.lastScore);
905 }
906 }
907 if (!app.online && !app.offline && app.core.state === 'gameover'
908 && app.core.gameOverTime >= GAME_OVER_DELAY)
909 { returnToMenu(); }
910}
911
912/* ---------- pointer input (mouse + touch) --------------------------- */
913/*
914 * Mouse uses Pointer Events. Touch uses Touch Events as the authority:
915 * on a real phone, pointer clientX/Y can disagree with the visual
916 * finger (zoomed visual viewport, gesture takeover, capture cancel)
917 * while changedTouches stays correct. When a touch is active, pointer
918 * move/up/cancel are ignored so a poisoned pointer coordinate cannot
919 * walk the block to the top or bottom of the stack (t1106).
920 *
921 * After a down we also listen on the document, so a drag that leaves
922 * the canvas (needed to launch a block at the top of a full column)
923 * still reaches moveDrag. We do not call setPointerCapture: on mobile
924 * that is often cancelled when the browser takes the gesture, which
925 * would fire pointercancel mid-drag.
926 *
927 * A non-passive document touchstart/touchmove preventDefault during
928 * play stops scrolling, rubber-banding and the pointercancel that
929 * follows. pointercancel / touchcancel end the drag without launch.
930 *
931 * ?debug=drag (or localStorage meteors-debug-drag=1) shows an overlay.
932 */
933
934var boundCanvas = null;
935var windowListening = false;
936var touchListening = false;
937var lastDragDebug = null;
938
939function isDragDebugEnabled ()
940{
941 try
942 {
943 var q = window.location && window.location.search;
944 if (q && /(?:\?|&)debug=drag(?:&|$)/.test(q))
945 { return true; }
946 if (window.localStorage && window.localStorage.getItem('meteors-debug-drag') === '1')
947 { return true; }
948 }
949 catch (err) { /* ignore */ }
950 return false;
951}
952
953/** ?debug, ?debug=physics, ?debug=drag, or localStorage meteors-debug=1. */
954function isPhysicsDebugEnabled ()
955{
956 try
957 {
958 var q = window.location && window.location.search;
959 if (q && /(?:\?|&)debug(?:=|&|$)/.test(q))
960 { return true; }
961 if (window.localStorage && (window.localStorage.getItem('meteors-debug') === '1'
962 || window.localStorage.getItem('meteors-debug-drag') === '1'))
963 { return true; }
964 }
965 catch (err) { /* ignore */ }
966 return false;
967}
968
969function eventClient (e)
970{
971 var t = null;
972 if (e.changedTouches && e.changedTouches.length)
973 { t = e.changedTouches[0]; }
974 else if (e.touches && e.touches.length)
975 { t = e.touches[0]; }
976 if (t)
977 { return { x: t.clientX, y: t.clientY, id: t.identifier, src: 'touch' }; }
978 if (e.clientX != null && e.clientY != null)
979 { return { x: e.clientX, y: e.clientY, id: e.pointerId, src: 'pointer' }; }
980 return null;
981}
982
983function addWindowPointer ()
984{
985 if (windowListening)
986 { return; }
987 window.addEventListener('pointermove', onPointerMove, { capture: true, passive: false });
988 window.addEventListener('pointerup', onPointerUp, { capture: true, passive: false });
989 window.addEventListener('pointercancel', onPointerCancel, { capture: true, passive: false });
990 windowListening = true;
991}
992
993function removeWindowPointer ()
994{
995 if (!windowListening)
996 { return; }
997 window.removeEventListener('pointermove', onPointerMove, { capture: true });
998 window.removeEventListener('pointerup', onPointerUp, { capture: true });
999 window.removeEventListener('pointercancel', onPointerCancel, { capture: true });
1000 windowListening = false;
1001}
1002
1003function addTouchListeners ()
1004{
1005 if (touchListening)
1006 { return; }
1007 var opts = { capture: true, passive: false };
1008 document.addEventListener('touchstart', onTouchStart, opts);
1009 document.addEventListener('touchmove', onTouchMove, opts);
1010 document.addEventListener('touchend', onTouchEnd, opts);
1011 document.addEventListener('touchcancel', onTouchCancel, opts);
1012 touchListening = true;
1013}
1014
1015function removeTouchListeners ()
1016{
1017 if (!touchListening)
1018 { return; }
1019 var opts = { capture: true };
1020 document.removeEventListener('touchstart', onTouchStart, opts);
1021 document.removeEventListener('touchmove', onTouchMove, opts);
1022 document.removeEventListener('touchend', onTouchEnd, opts);
1023 document.removeEventListener('touchcancel', onTouchCancel, opts);
1024 touchListening = false;
1025}
1026
1027function bindPointer (canvas)
1028{
1029 unbindPointer();
1030 boundCanvas = canvas;
1031 canvas.addEventListener('pointerdown', onPointerDown, { passive: false });
1032 canvas.style.touchAction = 'none';
1033 canvas.style.position = 'fixed';
1034 canvas.style.cursor = 'pointer';
1035 canvas.style.webkitUserSelect = 'none';
1036 canvas.style.userSelect = 'none';
1037 addTouchListeners();
1038 if (app.debugDrag)
1039 { ensureDragDebugOverlay(); }
1040}
1041
1042function unbindPointer ()
1043{
1044 removeWindowPointer();
1045 removeTouchListeners();
1046 if (boundCanvas)
1047 { boundCanvas.removeEventListener('pointerdown', onPointerDown); }
1048 boundCanvas = null;
1049 app.pointerId = null;
1050 app.pointerType = null;
1051 app.activeTouchId = null;
1052}
1053
1054function fieldFromEvent (e)
1055{
1056 var canvas = app.scene && app.scene.canvas;
1057 if (!canvas)
1058 { return null; }
1059 var rect = canvas.getBoundingClientRect();
1060 if (rect.width <= 0 || rect.height <= 0)
1061 { return null; }
1062 var pt = eventClient(e);
1063 if (!pt)
1064 { return null; }
1065 // Map through the CSS box only. Using canvas.width / app.tile would
1066 // scale the pointer by the backing-store ratio whenever that differs
1067 // from the layout size (high-DPR devices), so a short finger move
1068 // would look like a long swipe.
1069 var width = Planet.FIELD_WIDTH;
1070 var height = Planet.FIELD_HEIGHT;
1071 var col = ((pt.x - rect.left) / rect.width) * width;
1072 var fieldY = (1 - (pt.y - rect.top) / rect.height) * height;
1073 return { col: col, y: fieldY, src: pt.src, clientX: pt.x, clientY: pt.y, rect: rect };
1074}
1075
1076function playingForDrag ()
1077{
1078 return app.core && app.core.state === 'playing';
1079}
1080
1081function startDragFromEvent (e)
1082{
1083 var pos = fieldFromEvent(e);
1084 if (!pos)
1085 { return; }
1086 if (app.core.drag)
1087 {
1088 app.core.moveDrag(pos.y);
1089 logDragDebug(e, pos, 'move-already');
1090 return;
1091 }
1092 if (app.core.beginDrag(pos.col, pos.y) && app.core.drag)
1093 { startPressTween(app.core.drag.blockId); }
1094 logDragDebug(e, pos, 'down');
1095}
1096
1097function moveDragFromEvent (e)
1098{
1099 if (!app.core || !app.core.drag)
1100 { return; }
1101 var pos = fieldFromEvent(e);
1102 if (pos)
1103 { app.core.moveDrag(pos.y); }
1104 logDragDebug(e, pos, 'move');
1105}
1106
1107function finishDrag (opts)
1108{
1109 opts = opts || {};
1110 app.pointerId = null;
1111 app.pointerType = null;
1112 app.activeTouchId = null;
1113 removeWindowPointer();
1114 if (boundCanvas)
1115 {
1116 try
1117 {
1118 if (opts.pointerId != null && boundCanvas.releasePointerCapture)
1119 { boundCanvas.releasePointerCapture(opts.pointerId); }
1120 }
1121 catch (err) { /* ignore */ }
1122 }
1123 startReleaseTween();
1124 if (app.core && app.core.drag)
1125 {
1126 if (opts.noLaunch)
1127 { app.core.drag.launchIntent = false; }
1128 app.core.endDrag();
1129 }
1130 else if (app.core)
1131 { app.core.endDrag(); }
1132 logDragDebug(null, null, opts.noLaunch ? 'cancel' : 'up');
1133}
1134
1135function onPointerDown (e)
1136{
1137 if (!playingForDrag())
1138 { return; }
1139 if (app.pointerId != null && e.pointerId !== app.pointerId)
1140 { return; }
1141 if (e.preventDefault)
1142 { e.preventDefault(); }
1143 app.pointerId = e.pointerId;
1144 app.pointerType = e.pointerType || 'mouse';
1145 addWindowPointer();
1146 // If a touch is already in charge, do not reset the grab from pointerdown.
1147 if (app.activeTouchId != null)
1148 { return; }
1149 startDragFromEvent(e);
1150}
1151
1152function onPointerMove (e)
1153{
1154 if (app.pointerId == null || e.pointerId !== app.pointerId)
1155 { return; }
1156 if (!app.core || !app.core.drag)
1157 { return; }
1158 // Touch coordinates are the authority; ignore pointer moves for a
1159 // live touch so a wrong clientY cannot walk the whole column.
1160 // Only skip when touchstart has actually arrived — some environments
1161 // deliver touch-pointer events without a TouchEvent stream.
1162 if (app.activeTouchId != null)
1163 {
1164 if (e.preventDefault)
1165 { e.preventDefault(); }
1166 logDragDebug(e, fieldFromEvent(e), 'pointer-ignored');
1167 return;
1168 }
1169 if (e.preventDefault)
1170 { e.preventDefault(); }
1171 moveDragFromEvent(e);
1172}
1173
1174function onPointerUp (e)
1175{
1176 if (app.pointerId == null)
1177 { return; }
1178 if (e && e.pointerId != null && e.pointerId !== app.pointerId)
1179 { return; }
1180 if (app.activeTouchId != null)
1181 {
1182 // touchend will finish the drag.
1183 if (e && e.preventDefault)
1184 { e.preventDefault(); }
1185 logDragDebug(e, fieldFromEvent(e), 'pointer-up-ignored');
1186 return;
1187 }
1188 if (e && e.preventDefault)
1189 { e.preventDefault(); }
1190 finishDrag({ pointerId: e && e.pointerId });
1191}
1192
1193function onPointerCancel (e)
1194{
1195 if (app.pointerId == null)
1196 { return; }
1197 if (e && e.pointerId != null && e.pointerId !== app.pointerId)
1198 { return; }
1199 if (app.activeTouchId != null)
1200 {
1201 if (e && e.preventDefault)
1202 { e.preventDefault(); }
1203 logDragDebug(e, fieldFromEvent(e), 'pointer-cancel-ignored');
1204 return;
1205 }
1206 if (e && e.preventDefault)
1207 { e.preventDefault(); }
1208 // A cancelled gesture is not a launch pull.
1209 finishDrag({ pointerId: e && e.pointerId, noLaunch: true });
1210}
1211
1212function touchById (list, id)
1213{
1214 if (!list)
1215 { return null; }
1216 for (var i = 0; i < list.length; i++)
1217 {
1218 if (list[i].identifier === id)
1219 { return list[i]; }
1220 }
1221 return null;
1222}
1223
1224function onTouchStart (e)
1225{
1226 if (!playingForDrag())
1227 { return; }
1228 if (app.activeTouchId != null)
1229 {
1230 if (e.preventDefault)
1231 { e.preventDefault(); }
1232 return;
1233 }
1234 var t = e.changedTouches && e.changedTouches[0];
1235 if (!t)
1236 { return; }
1237 if (e.preventDefault)
1238 { e.preventDefault(); }
1239 app.activeTouchId = t.identifier;
1240 addWindowPointer();
1241 startDragFromEvent(e);
1242}
1243
1244function onTouchMove (e)
1245{
1246 if (app.activeTouchId == null)
1247 { return; }
1248 if (!touchById(e.changedTouches, app.activeTouchId)
1249 && !touchById(e.touches, app.activeTouchId))
1250 { return; }
1251 if (e.preventDefault)
1252 { e.preventDefault(); }
1253 moveDragFromEvent(e);
1254}
1255
1256function onTouchEnd (e)
1257{
1258 if (app.activeTouchId == null)
1259 { return; }
1260 if (!touchById(e.changedTouches, app.activeTouchId))
1261 { return; }
1262 if (e.preventDefault)
1263 { e.preventDefault(); }
1264 finishDrag({});
1265}
1266
1267function onTouchCancel (e)
1268{
1269 if (app.activeTouchId == null)
1270 { return; }
1271 if (!touchById(e.changedTouches, app.activeTouchId))
1272 { return; }
1273 if (e.preventDefault)
1274 { e.preventDefault(); }
1275 finishDrag({ noLaunch: true });
1276}
1277
1278function logPhysicsDebug ()
1279{
1280 if (!app.debugPhysics || !app.core)
1281 { return; }
1282 ensureDragDebugOverlay();
1283 var el = document.getElementById('drag-debug');
1284 if (!el)
1285 { return; }
1286 var issues = app.core.lastInvariantViolations || [];
1287 var flying = 0;
1288 var manuals = 0;
1289 var clusters = app.core.clusters ? Object.keys(app.core.clusters).length : 0;
1290 for (var i = 0; i < app.core.blocks.length; i++)
1291 {
1292 if (app.core.blocks[i].state === 'flying')
1293 { flying++; }
1294 if (app.core.blocks[i].state === 'manual')
1295 { manuals++; }
1296 }
1297 var status = issues.length
1298 ? ('PHYSICS FAIL x' + issues.length + '\n' + issues.slice(0, 6).join('\n'))
1299 : ('physics ok blocks=' + app.core.blocks.length
1300 + ' fly=' + flying + ' man=' + manuals + ' cl=' + clusters);
1301 // Keep any live drag line above the physics status.
1302 var dragLine = '';
1303 if (app.debugDrag && lastDragDebug)
1304 {
1305 dragLine = el.textContent && el.textContent.indexOf('drag ') === 0
1306 ? el.textContent.split('\n')[0] + '\n'
1307 : '';
1308 }
1309 el.textContent = dragLine + status;
1310 el.hidden = false;
1311 el.style.color = issues.length ? '#ffb4b4' : '#c6f6c8';
1312}
1313
1314function ensureDragDebugOverlay ()
1315{
1316 if (document.getElementById('drag-debug'))
1317 { return; }
1318 var el = document.createElement('div');
1319 el.id = 'drag-debug';
1320 el.setAttribute('aria-live', 'polite');
1321 document.body.appendChild(el);
1322}
1323
1324function logDragDebug (e, pos, phase)
1325{
1326 if (!app.debugDrag)
1327 { return; }
1328 ensureDragDebugOverlay();
1329 var el = document.getElementById('drag-debug');
1330 if (!el)
1331 { return; }
1332 var block = null;
1333 if (app.core && app.core.drag)
1334 { block = app.core.blockById(app.core.drag.blockId); }
1335 var pt = e ? eventClient(e) : null;
1336 var evType = e ? e.type : phase;
1337 var info = {
1338 phase: phase,
1339 ev: evType,
1340 src: pos && pos.src,
1341 fieldY: pos && Math.round(pos.y * 100) / 100,
1342 col: pos && Math.round(pos.col * 100) / 100,
1343 cy: pt && Math.round(pt.y * 10) / 10,
1344 blockY: block && Math.round(block.y * 100) / 100,
1345 target: block && Math.floor((pos && pos.y) + 1e-12),
1346 launch: app.core && app.core.drag && app.core.drag.launchIntent,
1347 touchId: app.activeTouchId,
1348 pid: app.pointerId,
1349 ptype: app.pointerType
1350 };
1351 lastDragDebug = info;
1352 el.textContent = 'drag ' + phase
1353 + ' ev=' + evType
1354 + ' src=' + (info.src || '-')
1355 + ' y=' + (info.fieldY != null ? info.fieldY : '-')
1356 + ' → ' + (info.target != null ? info.target : '-')
1357 + ' block=' + (info.blockY != null ? info.blockY : '-')
1358 + (info.launch ? ' LAUNCH' : '')
1359 + ' tId=' + info.touchId
1360 + ' pId=' + info.pid;
1361 el.hidden = false;
1362}
1363
1364
1365function hideEl (id)
1366{
1367 document.getElementById(id).hidden = true;
1368}
1369
1370function showEl (id)
1371{
1372 document.getElementById(id).hidden = false;
1373}
1374
1375window.addEventListener('resize', function ()
1376{
1377 if (app.mode === 'playing')
1378 { layout(); }
1379});
1380
1381window.addEventListener('orientationchange', function ()
1382{
1383 setTimeout(function ()
1384 {
1385 if (app.mode === 'playing')
1386 { layout(); }
1387 }, 120);
1388});
1389
1390/* ---------- online play (stage 2) ---------------------------------- */
1391
1392function tickOnline (dt)
1393{
1394 if (!app.online || typeof Online === 'undefined')
1395 { return; }
1396 if (app.core)
1397 {
1398 var shots = app.core.consumeOutgoingShots();
1399 for (var i = 0; i < shots.length; i++)
1400 {
1401 var s = shots[i];
1402 var start = fieldToViewport(s.col, s.y);
1403 Online.rememberFlightLocal(s, start.x, start.y);
1404 }
1405 Online.queueShots(shots);
1406 }
1407 Online.tickFlights();
1408 Online.renderMinis(document.getElementById('minis'));
1409 applyMinisLayout();
1410}
1411
1412
1413/* ---------- Offline Strijd (t1119) + column warn (t1123) ----------- */
1414
1415function bindOfflineUi ()
1416{
1417 var btn = document.getElementById('btn-offline');
1418 if (btn)
1419 {
1420 btn.addEventListener('click', onOffline);
1421 btn.addEventListener('pointerup', function (e)
1422 {
1423 if (e.pointerType === 'touch' || e.pointerType === 'pen')
1424 {
1425 e.preventDefault();
1426 onOffline();
1427 }
1428 });
1429 }
1430 var back = document.getElementById('btn-offline-menu');
1431 if (back)
1432 {
1433 back.addEventListener('click', function ()
1434 {
1435 teardownPlay();
1436 app.mode = 'menu';
1437 app.offline = false;
1438 app.battle = null;
1439 hideEl('offline-result');
1440 showEl('menu');
1441 });
1442 }
1443}
1444
1445function onOffline ()
1446{
1447 openPlanetSelect('offline');
1448}
1449
1450function tickOffline (dt)
1451{
1452 if (!app.battle || !app.core || typeof Offline === 'undefined')
1453 { return; }
1454
1455 if (app.battle.state === 'round_won')
1456 {
1457 if (!app.roundWonHandled)
1458 {
1459 app.roundWonHandled = true;
1460 app.roundWonDelay = Offline.ROUND_WON_DELAY || 1.5;
1461 }
1462 app.roundWonDelay -= dt;
1463 if (app.roundWonDelay <= 0)
1464 { startNextOfflineRound(); }
1465 updateOfflineMinis(dt, true);
1466 return;
1467 }
1468
1469 var result = app.battle.tick(dt, app.core);
1470 if (result && result.flights && result.flights.length
1471 && typeof Online !== 'undefined' && Online.spawnFlights)
1472 {
1473 var locals = Object.create(null);
1474 var list = result.locals || [];
1475 for (var i = 0; i < list.length; i++)
1476 {
1477 var s = list[i];
1478 var start;
1479 if (s.from_id === 'player')
1480 { start = fieldToViewport(s.col, s.y); }
1481 else if (typeof Online !== 'undefined' && Online.miniCellViewport)
1482 { start = Online.miniCellViewport(s.from_id, s.col, s.y != null ? s.y : 12); }
1483 else
1484 { start = miniViewportCenter(s.from_id); }
1485 locals[s.client_id] = {
1486 col: s.col,
1487 y: s.y,
1488 color: s.color,
1489 startX: start.x,
1490 startY: start.y,
1491 from_id: s.from_id,
1492 land_col: s.land_col
1493 };
1494 }
1495 Online.spawnFlights(result.flights, locals);
1496 }
1497 if (typeof Online !== 'undefined' && Online.tickFlights)
1498 { Online.tickFlights(); }
1499 updateOfflineMinis(dt, false);
1500
1501 if (app.battle.state === 'lost' && !app.offlineResultShown)
1502 { showOfflineResult(); }
1503}
1504
1505function startNextOfflineRound ()
1506{
1507 if (!app.battle)
1508 { return; }
1509 app.battle.advanceRound();
1510 app.roundWonHandled = false;
1511 app.roundWonDelay = 0;
1512 app._keepBattleOnTeardown = true;
1513 // Tear down the current scene then start a fresh player field,
1514 // keeping the same battle (already advanced).
1515 var planet = app.battle.playerPlanet;
1516 var roundScore = app.core ? app.core.score : 0;
1517 finishPlaySession(roundScore);
1518 app._keepBattleOnTeardown = true;
1519 teardownPlay();
1520 app.offline = true;
1521 app.battle = app.battle; // kept
1522 startPlay({ planet: planet, offline: true, keepBattle: true });
1523}
1524
1525function showOfflineResult ()
1526{
1527 app.offlineResultShown = true;
1528 var battle = app.battle;
1529 var reached = document.getElementById('offline-reached');
1530 var sch = battle.schedule;
1531 var n = sch.opponents;
1532 var skill = Math.round(sch.skill * 100);
1533 var line = document.getElementById('offline-reached-line');
1534 if (line && typeof I18n !== 'undefined')
1535 { line.textContent = I18n.t('offline.reached', { n: battle.round }); }
1536 else if (reached)
1537 { reached.textContent = String(battle.round); }
1538 var detail = document.getElementById('offline-result-detail');
1539 if (detail)
1540 {
1541 if (typeof I18n !== 'undefined')
1542 {
1543 detail.textContent = I18n.t('offline.detail', {
1544 n: n,
1545 opponents: I18n.plural('hud.opponent', n),
1546 skill: skill
1547 });
1548 }
1549 else
1550 {
1551 var noun = n === 1 ? 'opponent' : 'opponents';
1552 detail.textContent = 'You played against ' + n + ' ' + noun
1553 + ' at skill ' + skill + '%.';
1554 }
1555 }
1556 hideEl('game-over');
1557 showEl('offline-result');
1558 finishPlaySession(app.core ? app.core.score : 0);
1559}
1560
1561function refreshOfflineHud ()
1562{
1563 var el = document.getElementById('offline-hud');
1564 if (!el)
1565 { return; }
1566 if (!(app.offline && app.battle && app.mode === 'playing'))
1567 {
1568 el.hidden = true;
1569 return;
1570 }
1571 el.hidden = false;
1572 var sch = app.battle.schedule;
1573 var n = sch.opponents;
1574 var r = document.getElementById('offline-round');
1575 var o = document.getElementById('offline-opponents');
1576 var s = document.getElementById('offline-skill');
1577 if (typeof I18n !== 'undefined')
1578 {
1579 if (r)
1580 { r.textContent = I18n.t('hud.round', { n: sch.round }); }
1581 if (o)
1582 {
1583 o.textContent = I18n.t('hud.opponentsLine', {
1584 n: n, word: I18n.plural('hud.opponent', n)
1585 });
1586 }
1587 if (s)
1588 { s.textContent = I18n.t('hud.skill', { n: Math.round(sch.skill * 100) }); }
1589 }
1590 else
1591 {
1592 var noun = n === 1 ? 'opponent' : 'opponents';
1593 if (r)
1594 { r.textContent = 'Round ' + sch.round; }
1595 if (o)
1596 { o.textContent = n + ' ' + noun; }
1597 if (s)
1598 { s.textContent = 'Skill ' + Math.round(sch.skill * 100) + '%'; }
1599 }
1600}
1601
1602function hideOfflineHud ()
1603{
1604 var el = document.getElementById('offline-hud');
1605 if (el)
1606 { el.hidden = true; }
1607}
1608
1609function refreshChainIndicator ()
1610{
1611 var el = document.getElementById('chain-indicator');
1612 if (!el)
1613 { return; }
1614 var info = app.core && app.core.lastChainIndicator;
1615 var active = app.core && app.core.hasActiveLandingChain
1616 && app.core.hasActiveLandingChain();
1617 // Show only while a chained cluster is still in the air.
1618 if (!info || info.chain < 1 || app.mode !== 'playing' || !active)
1619 {
1620 el.hidden = true;
1621 return;
1622 }
1623 el.hidden = false;
1624 el.textContent = 'x' + info.chain + ' +' + info.bonusPct + '%';
1625}
1626
1627function hideChainIndicator ()
1628{
1629 var el = document.getElementById('chain-indicator');
1630 if (el)
1631 { el.hidden = true; }
1632}
1633
1634function miniViewportCenter (botId)
1635{
1636 var el = document.querySelector('#minis .mini[data-player="' + botId + '"] canvas');
1637 if (!el)
1638 { return { x: window.innerWidth / 2, y: 40 }; }
1639 var rect = el.getBoundingClientRect();
1640 var plan = app.miniLayout;
1641 if (plan && plan.mode === 'sides')
1642 {
1643 // Leave from the top of the mini, then the arc goes up and over (t1131).
1644 return { x: rect.left + rect.width / 2, y: rect.top + 4 };
1645 }
1646 return { x: rect.left + rect.width / 2, y: rect.bottom };
1647}
1648
1649function offlineMiniSize (n)
1650{
1651 return currentMiniSize();
1652}
1653
1654function updateOfflineMinis (dt, force)
1655{
1656 app.miniAcc = (app.miniAcc || 0) + dt;
1657 if (!force && app.miniAcc < 0.1)
1658 { return; }
1659 app.miniAcc = 0;
1660 renderOfflineMinis();
1661}
1662
1663function renderOfflineMinis ()
1664{
1665 var container = document.getElementById('minis');
1666 if (!container || !app.battle)
1667 { return; }
1668 var bots = app.battle.bots;
1669 var size = offlineMiniSize(bots.length);
1670 container.classList.toggle('crowded', bots.length > 5);
1671 var existing = {};
1672 var kids = container.querySelectorAll('[data-player]');
1673 for (var i = 0; i < kids.length; i++)
1674 { existing[kids[i].getAttribute('data-player')] = kids[i]; }
1675 var seen = Object.create(null);
1676 for (var i = 0; i < bots.length; i++)
1677 {
1678 var bot = bots[i];
1679 seen[bot.id] = true;
1680 var el = existing[bot.id];
1681 if (!el)
1682 {
1683 el = document.createElement('div');
1684 el.className = 'mini';
1685 el.setAttribute('data-player', bot.id);
1686 el.innerHTML = '<div class="mini-name"></div>'
1687 + '<canvas class="mini-canvas" width="' + size.w
1688 + '" height="' + size.h + '"></canvas>'
1689 + '<div class="mini-meta"></div>';
1690 container.appendChild(el);
1691 }
1692 var canvas = el.querySelector('canvas');
1693 if (canvas && (canvas.width !== size.w || canvas.height !== size.h))
1694 {
1695 canvas.width = size.w;
1696 canvas.height = size.h;
1697 }
1698 el.classList.toggle('eliminated', !!bot.eliminated);
1699 var planetName = bot.planet && bot.planet.name ? bot.planet.name : '';
1700 var shownPlanet = planetName;
1701 if (bot.planet && typeof I18n !== 'undefined')
1702 { shownPlanet = I18n.planetName(bot.planet); }
1703 el.querySelector('.mini-name').textContent = bot.name
1704 + (shownPlanet ? ' · ' + shownPlanet : '');
1705 el.querySelector('.mini-meta').textContent = bot.eliminated
1706 ? ((typeof I18n !== 'undefined') ? I18n.t('hud.out') : 'Out')
1707 : ((typeof I18n !== 'undefined') ? I18n.t('hud.miniPoints', { n: bot.score || 0 }) : ('Points ' + (bot.score || 0)));
1708 var snap = bot.core ? bot.core.fieldSnapshot() : { blocks: [] };
1709 if (typeof Online !== 'undefined' && Online._drawMini)
1710 { Online._drawMini(canvas, snap, bot.planet); }
1711 }
1712 for (var id in existing)
1713 {
1714 if (!seen[id])
1715 { existing[id].remove(); }
1716 }
1717 applyMinisLayout();
1718}
1719
1720function buildColumnWarn ()
1721{
1722 app.columnWarn = [];
1723 if (!app.scene)
1724 { return; }
1725 var img = (game.images && (game.images.columnWarn || game.images.pixel)) || null;
1726 if (!img)
1727 { return; }
1728 for (var c = 0; c < 10; c++)
1729 {
1730 var obj = new GameObject(0, 0, img, 0);
1731 obj.renderer.alpha = 0;
1732 obj.renderer.visible = false;
1733 app.scene.addObject(obj);
1734 app.columnWarn.push(obj);
1735 }
1736 updateColumnWarn(0);
1737}
1738
1739function updateColumnWarn (dt)
1740{
1741 if (!app.columnWarn || !app.core)
1742 { return; }
1743 app.warnClock = (app.warnClock || 0) + (dt || 0);
1744 var pulse = (typeof GameCore !== 'undefined' && GameCore.columnWarnPulse)
1745 ? GameCore.columnWarnPulse(app.warnClock)
1746 : 0.16 + 0.28 * (0.5 + 0.5 * Math.sin(app.warnClock * 3.45575));
1747 var t = app.tile;
1748 for (var c = 0; c < app.columnWarn.length; c++)
1749 {
1750 var obj = app.columnWarn[c];
1751 var on = app.core.columnNeedsWarn && app.core.columnNeedsWarn(c);
1752 obj.renderer.visible = !!on;
1753 obj.renderer.alpha = on ? pulse : 0;
1754 if (t)
1755 {
1756 obj.transform.position.x = c * t + t / 2;
1757 obj.transform.position.y = app.fieldH / 2;
1758 obj.transform.size = { x: t, y: app.fieldH };
1759 }
1760 }
1761}
1762
1763/**
1764 * A flight starts only when a block has actually left the field
1765 * (y ≥ height, the same threshold as cullOffTop). Rockets that
1766 * peak below the top and fall back must never get an arc (t1137).
1767 * Shared by the player's field, enemy minis, offline and online.
1768 */
1769function previewOutgoingFlights ()
1770{
1771 // Intentionally not called before core.tick: a block still on
1772 // the field (y < 13) is not a shot yet. Flights are spawned
1773 // from consumeOutgoingShots after cull, at the exit pose.
1774 if (typeof Online === 'undefined' || !Online.previewExit)
1775 { return; }
1776 if (app.core)
1777 { previewCoreExits(app.core, null); }
1778 if (app.offline && app.battle && app.battle.bots)
1779 {
1780 var bots = app.battle.bots;
1781 for (var i = 0; i < bots.length; i++)
1782 {
1783 var bot = bots[i];
1784 if (bot && bot.core && !bot.eliminated)
1785 { previewCoreExits(bot.core, bot.id); }
1786 }
1787 }
1788}
1789
1790function previewCoreExits (core, fromId)
1791{
1792 if (!core || !core.blocks)
1793 { return; }
1794 var height = core.height != null ? core.height : 13;
1795 var blocks = core.blocks;
1796 for (var i = 0; i < blocks.length; i++)
1797 {
1798 var b = blocks[i];
1799 if (b.state === 'manual')
1800 { continue; }
1801 if (typeof Online.hasLeftTheField === 'function'
1802 ? !Online.hasLeftTheField(b.y, height)
1803 : !(b.y >= height - 1e-9))
1804 { continue; }
1805 if (!(b.vy > 0))
1806 { continue; }
1807 var start = fromId
1808 ? (Online.miniCellViewport
1809 ? Online.miniCellViewport(fromId, b.col, b.y)
1810 : miniViewportCenter(fromId))
1811 : fieldToViewport(b.col, b.y);
1812 Online.previewExit({
1813 id: b.id,
1814 col: b.col,
1815 y: b.y,
1816 vy: b.vy,
1817 color: b.color,
1818 start: start,
1819 from_id: fromId || null
1820 });
1821 }
1822}
1823
1824function fieldToViewport (col, fieldY)
1825{
1826 var canvas = app.scene && app.scene.canvas;
1827 if (!canvas)
1828 { return { x: window.innerWidth / 2, y: 40 }; }
1829 var rect = canvas.getBoundingClientRect();
1830 var x = rect.left + ((col + 0.5) / 10) * rect.width;
1831 // Cell centre matches placeTile: y = fieldH - (fieldY + 0.5) * tile (t1134).
1832 var y = rect.top + (1 - ((fieldY + 0.5) / 13)) * rect.height;
1833 return { x: x, y: y };
1834}
1835
1836function onlinePayload ()
1837{
1838 if (!app.online || !app.core)
1839 { return {}; }
1840 return {
1841 snapshot: app.core.fieldSnapshot(),
1842 score: app.core.score,
1843 eliminated: app.core.state === 'gameover' || app.spectating || app.eliminatedReported
1844 };
1845}
1846
1847function onOnlineEliminated ()
1848{
1849 app.eliminatedReported = true;
1850 app.spectating = true;
1851 unbindPointer();
1852 hideEl('game-over');
1853 var lobby = typeof Online !== 'undefined' && Online.lobby;
1854 if (lobby && lobby.status === 'finished')
1855 {
1856 showPodium(lobby);
1857 return;
1858 }
1859 showEl('spectator');
1860}
1861
1862function showPodium (lobby)
1863{
1864 hideEl('spectator');
1865 hideEl('game-over');
1866 hideEl('online-panel');
1867 showEl('podium');
1868 var list = document.getElementById('podium-list');
1869 list.innerHTML = '';
1870 var ranks = (lobby && lobby.rankings) || [];
1871 for (var i = 0; i < ranks.length; i++)
1872 {
1873 var r = ranks[i];
1874 var li = document.createElement('li');
1875 var medal = (typeof I18n !== 'undefined') ? I18n.place(r.place)
1876 : (r.place === 1 ? '1st' : (r.place === 2 ? '2nd' : (r.place === 3 ? '3rd' : r.place + 'th')));
1877 li.textContent = (typeof I18n !== 'undefined')
1878 ? I18n.t('podium.line', { place: medal, name: r.name, score: r.score })
1879 : (medal + ' ' + r.name + ' · ' + r.score + ' points');
1880 list.appendChild(li);
1881 }
1882 var hint = document.getElementById('podium-hint');
1883 var secs = (lobby && lobby.podium_seconds) || 5;
1884 if (hint)
1885 {
1886 hint.textContent = (typeof I18n !== 'undefined')
1887 ? I18n.t('podium.hint', { n: secs })
1888 : ('Returning to the lobby in ' + secs + ' seconds…');
1889 }
1890}
1891
1892function startOnlineMatch ()
1893{
1894 if (app.mode === 'playing' && app.online)
1895 { return; }
1896 var planet = Planet.planetById(selectedPlanetId());
1897 var miss = Planet.missChance(planet);
1898 var me = (typeof Online !== 'undefined' && Online.mePlayer) ? Online.mePlayer() : null;
1899 if (me && me.planet)
1900 {
1901 if (typeof Planet.rememberPlanet === 'function')
1902 { planet = Planet.rememberPlanet(me.planet) || planet; }
1903 else if (me.planet.id)
1904 { planet = Planet.planetById(me.planet.id); }
1905 if (typeof me.planet.miss_chance === 'number')
1906 { miss = me.planet.miss_chance; }
1907 }
1908 startPlay({ online: true, planet: planet, missChance: miss });
1909 if (typeof Online !== 'undefined')
1910 { Online.startPolling(onlinePayload); }
1911}
1912
1913function leaveOnlineMatch (goMenu)
1914{
1915 if (typeof Online !== 'undefined')
1916 {
1917 Online.stopPolling();
1918 Online.leaveLobby();
1919 Online.clearFlights();
1920 }
1921 teardownPlay();
1922 app.online = false;
1923 if (goMenu)
1924 {
1925 app.mode = 'menu';
1926 showEl('menu');
1927 }
1928 else
1929 {
1930 app.mode = 'online';
1931 openOnlinePanel();
1932 }
1933}
1934
1935function bindOnlineUi ()
1936{
1937 var onlineBtn = document.getElementById('btn-online');
1938 if (!onlineBtn)
1939 { return; }
1940 onlineBtn.addEventListener('click', function ()
1941 { openOnlinePanel(); });
1942
1943 var backs = document.querySelectorAll('[data-back-menu]');
1944 for (var i = 0; i < backs.length; i++)
1945 {
1946 backs[i].addEventListener('click', function ()
1947 {
1948 if (typeof Online !== 'undefined')
1949 { Online.stopPolling(); }
1950 hideEl('online-panel');
1951 app.mode = 'menu';
1952 app.online = false;
1953 showEl('menu');
1954 });
1955 }
1956
1957 document.getElementById('btn-create').addEventListener('click', function ()
1958 {
1959 Online.createLobby().then(function (data)
1960 {
1961 if (data && data.ok)
1962 {
1963 renderOnline();
1964 Online.startPolling(onlinePayload);
1965 }
1966 else
1967 { renderOnline(); }
1968 });
1969 });
1970
1971 document.getElementById('join-form').addEventListener('submit', function (e)
1972 {
1973 e.preventDefault();
1974 var code = (document.getElementById('join-code').value || '').trim();
1975 if (!code)
1976 { return; }
1977 Online.joinLobby(code).then(function ()
1978 {
1979 renderOnline();
1980 if (Online.lobby)
1981 { Online.startPolling(onlinePayload); }
1982 });
1983 });
1984
1985 document.getElementById('btn-ready').addEventListener('click', function ()
1986 {
1987 var me = Online.mePlayer();
1988 Online.setReady(!(me && me.ready)).then(renderOnline);
1989 });
1990
1991 document.getElementById('btn-start').addEventListener('click', function ()
1992 {
1993 Online.startGame().then(function (data)
1994 {
1995 if (data && data.ok)
1996 { startOnlineMatch(); }
1997 else
1998 { renderOnline(); }
1999 });
2000 });
2001
2002 document.getElementById('btn-leave-lobby').addEventListener('click', function ()
2003 {
2004 Online.leaveLobby().then(function ()
2005 {
2006 Online.stopPolling();
2007 renderOnline();
2008 });
2009 });
2010
2011 document.getElementById('btn-copy-code').addEventListener('click', function ()
2012 {
2013 var code = document.getElementById('lobby-code').textContent;
2014 var btn = document.getElementById('btn-copy-code');
2015 var done = function ()
2016 {
2017 if (!btn)
2018 { return; }
2019 btn.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.copied') : 'Copied';
2020 setTimeout(function ()
2021 {
2022 btn.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.copy') : 'Copy';
2023 }, 1500);
2024 };
2025 if (navigator.clipboard && navigator.clipboard.writeText)
2026 { navigator.clipboard.writeText(code).then(done, done); }
2027 else
2028 { done(); }
2029 });
2030
2031 document.getElementById('btn-spectate').addEventListener('click', function ()
2032 {
2033 hideEl('spectator');
2034 app.spectating = true;
2035 });
2036
2037 document.getElementById('btn-leave-game').addEventListener('click', function ()
2038 { leaveOnlineMatch(false); });
2039
2040 if (typeof Online !== 'undefined')
2041 {
2042 Online.onChange = function ()
2043 { renderOnline(); };
2044 Online.onGameStart = function ()
2045 { startOnlineMatch(); };
2046 Online.onIncoming = function (incoming)
2047 {
2048 if (!app.core || app.core.state !== 'playing')
2049 { return; }
2050 for (var i = 0; i < incoming.length; i++)
2051 {
2052 var col = Online.takeLandCol ? Online.takeLandCol(incoming[i]) : incoming[i].land_col;
2053 app.core.ingestGarbage(col);
2054 }
2055 };
2056 Online.onFinished = function (lobby)
2057 { showPodium(lobby); };
2058 Online.onLobbyReturn = function (lobby)
2059 {
2060 teardownPlay();
2061 app.online = false;
2062 app.mode = 'online';
2063 hideEl('podium');
2064 showEl('online-panel');
2065 renderOnline();
2066 Online.startPolling(onlinePayload);
2067 };
2068 }
2069
2070 var params = new URLSearchParams(window.location.search);
2071 if (params.get('online') === '1' || params.get('auth') === 'unconfigured')
2072 { openOnlinePanel(); }
2073}
2074
2075function openOnlinePanel ()
2076{
2077 hideEl('menu');
2078 hideEl('game-over');
2079 hideEl('podium');
2080 hideEl('spectator');
2081 hideEl('planet-select');
2082 showEl('online-panel');
2083 app.mode = 'online';
2084 setOnlineStatus((typeof I18n !== 'undefined') ? I18n.t('online.checking') : 'Checking whether online play is available…');
2085 if (typeof Online === 'undefined')
2086 {
2087 showOnlineError((typeof I18n !== 'undefined') ? I18n.t('online.notLoaded') : 'Online play is not included in this build. You can still play solo.');
2088 showOnly('online-unconfigured');
2089 return;
2090 }
2091 Online.refresh().then(function (data)
2092 {
2093 if (!data || data.ok === false)
2094 {
2095 var msg = (data && data.error)
2096 ? ((typeof I18n !== 'undefined') ? I18n.error(data.error) : data.error)
2097 : ((typeof I18n !== 'undefined') ? I18n.t('error.connection') : 'No connection to the server.');
2098 showOnlineError(msg + ' ' + ((typeof I18n !== 'undefined') ? I18n.t('online.canPlaySolo') : 'You can still play solo.'));
2099 if (data && data.configured === false)
2100 { showOnly('online-unconfigured'); }
2101 else
2102 { showOnly('online-login'); }
2103 document.getElementById('btn-login').style.display = 'none';
2104 return;
2105 }
2106 renderOnline();
2107 if (Online.lobby)
2108 { Online.startPolling(onlinePayload); }
2109 });
2110}
2111
2112function setOnlineStatus (text)
2113{
2114 var el = document.getElementById('online-status');
2115 if (el)
2116 { el.textContent = text; }
2117}
2118
2119function showOnlineError (text)
2120{
2121 var el = document.getElementById('online-error');
2122 if (!el)
2123 { return; }
2124 if (!text)
2125 {
2126 el.hidden = true;
2127 el.textContent = '';
2128 return;
2129 }
2130 el.hidden = false;
2131 el.textContent = text;
2132}
2133
2134function showOnly (id)
2135{
2136 var ids = ['online-unconfigured', 'online-login', 'online-home', 'online-lobby'];
2137 for (var i = 0; i < ids.length; i++)
2138 { document.getElementById(ids[i]).hidden = (ids[i] !== id); }
2139}
2140
2141function renderOnline ()
2142{
2143 if (typeof Online === 'undefined')
2144 { return; }
2145 if (app.mode === 'playing' && app.online)
2146 {
2147 Online.renderMinis(document.getElementById('minis'));
2148 if (Online.lobby && Online.lobby.status === 'finished')
2149 { showPodium(Online.lobby); }
2150 return;
2151 }
2152 showOnlineError((typeof I18n !== 'undefined' && Online.error) ? I18n.error(Online.error) : Online.error);
2153 if (!Online.configured && !Online.me && !Online.local)
2154 {
2155 setOnlineStatus((typeof I18n !== 'undefined') ? I18n.t('online.statusUnconfigured') : 'Online play is not set up yet.');
2156 showOnly('online-unconfigured');
2157 return;
2158 }
2159 if (!Online.me)
2160 {
2161 setOnlineStatus((typeof I18n !== 'undefined') ? I18n.t('online.statusLogin') : 'Log in to create a lobby or join one.');
2162 showOnly('online-login');
2163 document.getElementById('btn-login').style.display = '';
2164 document.getElementById('btn-login').href = Online.loginUrl();
2165 document.getElementById('local-login').hidden = !Online.local;
2166 return;
2167 }
2168 if (Online.lobby)
2169 {
2170 setOnlineStatus((typeof I18n !== 'undefined') ? I18n.t('online.statusLobby') : 'Lobby');
2171 showOnly('online-lobby');
2172 document.getElementById('lobby-me-name').textContent = Online.me.name;
2173 document.getElementById('lobby-code').textContent = Online.lobby.code;
2174 var list = document.getElementById('lobby-players');
2175 list.innerHTML = '';
2176 var players = Online.lobby.players || [];
2177 for (var i = 0; i < players.length; i++)
2178 {
2179 var p = players[i];
2180 var li = document.createElement('li');
2181 if (p.is_me)
2182 { li.classList.add('you'); }
2183 var host = (typeof I18n !== 'undefined') ? I18n.t('online.host') : 'host';
2184 var you = (typeof I18n !== 'undefined') ? I18n.t('online.you') : 'you';
2185 var label = p.name + (p.is_host ? ' (' + host + ')' : '') + (p.is_me ? ' (' + you + ')' : '');
2186 var state = p.ready ? 'Gereed' : 'Wacht…';
2187 var world = (p.planet && p.planet.name) ? (p.planet.name + ' · ' + p.planet.people) : '';
2188 li.innerHTML = '<span>' + escapeText(label)
2189 + (world ? '<span class="planet-tag">' + escapeText(world) + '</span>' : '')
2190 + '</span><span class="'
2191 + (p.ready ? 'ready' : 'waiting') + '">' + state + '</span>';
2192 list.appendChild(li);
2193 }
2194 renderPlanetGrid('lobby-planet-grid', true);
2195 var me = Online.mePlayer();
2196 document.getElementById('btn-ready').textContent = (me && me.ready)
2197 ? ((typeof I18n !== 'undefined') ? I18n.t('online.notReady') : 'Not ready')
2198 : ((typeof I18n !== 'undefined') ? I18n.t('online.ready') : 'Ready');
2199 var start = document.getElementById('btn-start');
2200 start.hidden = !(Online.lobby && Online.me && Online.lobby.host_id === Online.me.id);
2201 start.disabled = !Online.lobby.can_start;
2202 var hint = document.getElementById('lobby-hint');
2203 if (Online.lobby.status === 'playing')
2204 { hint.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.hintStarting') : 'The game is starting…'; }
2205 else if (players.length < 2)
2206 { hint.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.hintNeedPlayers') : 'Wait for at least one other player. Share the code.'; }
2207 else if (!Online.lobby.all_ready)
2208 { hint.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.hintNeedReady') : 'Everyone must press Ready. The host starts afterwards.'; }
2209 else if (Online.lobby.can_start)
2210 { hint.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.hintHostStart') : 'Everyone is ready. Press Start.'; }
2211 else
2212 { hint.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.hintWaitHost') : 'Waiting for the host to start.'; }
2213 return;
2214 }
2215 setOnlineStatus((typeof I18n !== 'undefined') ? I18n.t('online.statusHome', { name: Online.me.name }) : ('Hi ' + Online.me.name + '. Create a lobby or join with a code.'));
2216 showOnly('online-home');
2217 document.getElementById('me-name').textContent = Online.me.name;
2218 document.getElementById('local-login').hidden = !Online.local;
2219}
2220
2221function escapeText (s)
2222{
2223 return String(s)
2224 .replace(/&/g, '&amp;')
2225 .replace(/</g, '&lt;')
2226 .replace(/>/g, '&gt;')
2227 .replace(/"/g, '&quot;');
2228}
2229
2230
2231function selectedPlanetId ()
2232{
2233 if (app.selectedPlanetId)
2234 { return app.selectedPlanetId; }
2235 return 'terra';
2236}
2237
2238function restoreSelectedPlanet ()
2239{
2240 var id = 'terra';
2241 try
2242 { id = localStorage.getItem('meteors-planet') || 'terra'; }
2243 catch (e) {}
2244 setSelectedPlanet(id, true);
2245}
2246
2247function setSelectedPlanet (id, silent)
2248{
2249 var all = Planet.allPlanets();
2250 var found = null;
2251 for (var i = 0; i < all.length; i++)
2252 {
2253 if (all[i].id === id)
2254 { found = all[i]; break; }
2255 }
2256 if (!found)
2257 { found = Planet.defaultPlanet(); }
2258 app.selectedPlanetId = found.id;
2259 try
2260 { localStorage.setItem('meteors-planet', found.id); }
2261 catch (e) {}
2262 if (!silent)
2263 {
2264 var grid = document.getElementById('planet-grid');
2265 if (grid && !grid.hidden && grid.children.length)
2266 { renderPlanetGrid('planet-grid', false); }
2267 var lobby = document.getElementById('lobby-planet-grid');
2268 if (lobby && lobby.children.length)
2269 { renderPlanetGrid('lobby-planet-grid', true); }
2270 }
2271 return found;
2272}
2273
2274function openPlanetSelect (context)
2275{
2276 if (app.mode === 'playing')
2277 { return; }
2278 app.planetSelectContext = context || 'solo';
2279 app.mode = 'planet-select';
2280 hideEl('menu');
2281 hideEl('online-panel');
2282 hideEl('game-over');
2283 showEl('planet-select');
2284 renderPlanetGrid('planet-grid', false);
2285 var go = document.getElementById('btn-planet-go');
2286 if (go)
2287 { go.textContent = (typeof I18n !== 'undefined') ? I18n.t('menu.play') : 'Play'; }
2288}
2289
2290function renderPlanetGrid (containerId, compact)
2291{
2292 var grid = document.getElementById(containerId);
2293 if (!grid)
2294 { return; }
2295 var current = selectedPlanetId();
2296 var all = Planet.allPlanets();
2297 grid.innerHTML = '';
2298 if (compact)
2299 { grid.classList.add('compact'); }
2300 for (var i = 0; i < all.length; i++)
2301 {
2302 var pl = all[i];
2303 var btn = document.createElement('button');
2304 btn.type = 'button';
2305 btn.className = 'planet-card' + (pl.id === current ? ' selected' : '')
2306 + (pl.custom ? ' custom' : '');
2307 btn.setAttribute('role', 'listitem');
2308 btn.dataset.planet = pl.id;
2309 var swatches = '';
2310 var colors = pl.colors || [];
2311 for (var c = 0; c < colors.length; c++)
2312 {
2313 var cname = colors[c].name;
2314 if (typeof I18n !== 'undefined' && (colors[c].block || (!pl.custom && colors[c].name)))
2315 { cname = I18n.blockName(colors[c].block || (pl.id + '-' + colors[c].name), colors[c].name); }
2316 swatches += '<img src="' + escapeText(colors[c].image) + '" alt="'
2317 + escapeText(cname) + '" title="' + escapeText(cname) + '">';
2318 }
2319 var title = (typeof I18n !== 'undefined') ? I18n.planetName(pl) : pl.name;
2320 var people = (typeof I18n !== 'undefined') ? I18n.peopleName(pl) : pl.people;
2321 var badge = (typeof I18n !== 'undefined') ? I18n.t('planet.customBadge') : 'Yours';
2322 btn.innerHTML = '<div class="planet-title">' + escapeText(title) + '</div>'
2323 + '<div class="planet-people">' + escapeText(people) + '</div>'
2324 + '<div class="planet-nums">' + escapeText(Planet.formatStats(pl)) + '</div>'
2325 + '<div class="planet-swatches">' + swatches + '</div>'
2326 + (pl.custom ? '<span class="custom-badge">' + escapeText(badge) + '</span>' : '');
2327 btn.addEventListener('click', (function (id, isCompact)
2328 {
2329 return function ()
2330 { onPlanetPicked(id, isCompact); };
2331 })(pl.id, !!compact));
2332 grid.appendChild(btn);
2333 }
2334}
2335
2336function onPlanetPicked (id, fromLobby)
2337{
2338 setSelectedPlanet(id);
2339 if (fromLobby && typeof Online !== 'undefined' && Online.lobby)
2340 {
2341 Online.setPlanet(id).then(function ()
2342 { renderOnline(); });
2343 }
2344 else
2345 {
2346 renderPlanetGrid('planet-grid', false);
2347 }
2348}
2349
2350function confirmPlanetSelect ()
2351{
2352 var planet = setSelectedPlanet(selectedPlanetId());
2353 hideEl('planet-select');
2354 if (app.planetSelectContext === 'online')
2355 {
2356 openOnlinePanel();
2357 return;
2358 }
2359 if (app.planetSelectContext === 'offline')
2360 {
2361 startPlay({ planet: planet, offline: true });
2362 return;
2363 }
2364 startPlay({ planet: planet });
2365}
2366
2367function cancelPlanetSelect ()
2368{
2369 hideEl('planet-select');
2370 app.mode = 'menu';
2371 showEl('menu');
2372}
2373
2374function bindPlanetSelect ()
2375{
2376 var go = document.getElementById('btn-planet-go');
2377 var back = document.getElementById('btn-planet-back');
2378 if (go)
2379 {
2380 go.addEventListener('click', confirmPlanetSelect);
2381 }
2382 if (back)
2383 {
2384 back.addEventListener('click', cancelPlanetSelect);
2385 }
2386}
2387
2388
2389function refreshMenuAccount ()
2390{
2391 var guest = document.getElementById('menu-guest');
2392 var user = document.getElementById('menu-user');
2393 var designerBtn = document.getElementById('btn-designer');
2394 var localLogin = document.getElementById('menu-local-login');
2395 var me = (typeof Online !== 'undefined') ? Online.me : null;
2396 if (me)
2397 {
2398 if (guest)
2399 { guest.hidden = true; }
2400 if (user)
2401 { user.hidden = false; }
2402 var name = document.getElementById('menu-name');
2403 if (name)
2404 { name.textContent = me.name || me.id || ((typeof I18n !== 'undefined') ? I18n.t('menu.player') : 'player'); }
2405 var pts = document.getElementById('menu-points');
2406 if (pts)
2407 { pts.textContent = String((typeof Online !== 'undefined' && Online.lifetimePoints) || 0); }
2408 if (designerBtn)
2409 { designerBtn.hidden = false; }
2410 }
2411 else
2412 {
2413 if (guest)
2414 { guest.hidden = false; }
2415 if (user)
2416 { user.hidden = true; }
2417 if (designerBtn)
2418 { designerBtn.hidden = true; }
2419 }
2420 if (localLogin)
2421 { localLogin.hidden = !(typeof Online !== 'undefined' && Online.local); }
2422}
2423
2424function beginPlaySession (mode)
2425{
2426 if (app.playToken)
2427 { finishPlaySession(app.core ? app.core.score : (app.lastScore || 0)); }
2428 app.playToken = null;
2429 if (typeof Online === 'undefined' || !Online.me || !Online.playBegin)
2430 { return; }
2431 Online.playBegin(mode || 'solo').then(function (data)
2432 {
2433 if (data && data.ok && data.token)
2434 { app.playToken = data.token; }
2435 });
2436}
2437
2438function finishPlaySession (score)
2439{
2440 var token = app.playToken;
2441 app.playToken = null;
2442 if (!token || typeof Online === 'undefined' || !Online.playFinish)
2443 { return; }
2444 Online.playFinish(token, score || 0).then(function ()
2445 { refreshMenuAccount(); });
2446}
2447
2448
2449
2450function applyProfileLocale ()
2451{
2452 if (typeof I18n === 'undefined' || typeof Online === 'undefined')
2453 { return; }
2454 if (Online.locale)
2455 { I18n.applyFromProfile(Online.locale); }
2456 else if (Online.me)
2457 { Online.setLocale(I18n.locale); }
2458}
2459
2460function refreshAllUi ()
2461{
2462 if (typeof I18n !== 'undefined')
2463 { I18n.apply(); }
2464 refreshMenuAccount();
2465 if (typeof renderPlanetGrid === 'function')
2466 {
2467 renderPlanetGrid('planet-grid', false);
2468 renderPlanetGrid('lobby-planet-grid', true);
2469 }
2470 if (app && app.mode === 'online' && typeof renderOnline === 'function')
2471 { renderOnline(); }
2472 if (typeof Designer !== 'undefined')
2473 {
2474 var des = document.getElementById('designer');
2475 var edit = document.getElementById('designer-edit');
2476 if (des && !des.hidden)
2477 { Designer.renderList(); }
2478 if (edit && !edit.hidden)
2479 {
2480 Designer.syncPreview();
2481 Designer.renderSlots();
2482 var modal = document.getElementById('des-modal');
2483 if (modal && !modal.hidden)
2484 { Designer.openModal(Designer.openSlot); }
2485 }
2486 }
2487 if (app && app.mode === 'playing')
2488 {
2489 if (typeof refreshHud === 'function')
2490 { refreshHud(); }
2491 if (typeof refreshOfflineHud === 'function')
2492 { refreshOfflineHud(); }
2493 }
2494}