BlueGit

projects-timfalken-com meteors

Files

meteors / src / main.js

main.js

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