BlueGit

projects-timfalken-com meteors

Files

meteors / src / main.js

main.js

main.js 49.7 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 return list;
40}
41
42var IMAGES = planetImages();
43var GAME_OVER_DELAY = 2;
44
45var game = new Game();
46var app = {
47 mode: 'menu',
48 core: null,
49 scene: null,
50 manager: null,
51 planet: null,
52 lastScore: 0,
53 tile: 48,
54 fieldX: 0,
55 fieldY: 0,
56 fieldW: 0,
57 fieldH: 0,
58 hudH: 56,
59 sprites: Object.create(null),
60 flames: Object.create(null),
61 cells: [],
62 pointerId: null,
63 pointerType: null,
64 activeTouchId: null,
65 debugDrag: false,
66 debugPhysics: false,
67 gameOverShown: false,
68 selectTween: null,
69 online: false,
70 eliminatedReported: false,
71 spectating: false,
72 miniH: 0,
73 selectedPlanetId: 'terra',
74 planetSelectContext: 'solo',
75 offline: false,
76 battle: null,
77 swapTweens: null,
78 columnWarn: null,
79 warnClock: 0,
80 miniAcc: 0,
81 offlineResultShown: false,
82 roundWonDelay: 0,
83 roundWonHandled: false
84};
85
86window.onload = function ()
87{
88 app.debugDrag = isDragDebugEnabled();
89 app.debugPhysics = isPhysicsDebugEnabled();
90 var play = document.getElementById('btn-play');
91 play.addEventListener('click', onPlay);
92 play.addEventListener('pointerup', function (e)
93 {
94 // A touch-friendly path: some mobile browsers swallow the click
95 // after a slightly sloppy tap. Ignore the following click.
96 if (e.pointerType === 'touch' || e.pointerType === 'pen')
97 {
98 e.preventDefault();
99 onPlay();
100 }
101 });
102
103 game.preloadImagesThenStart(IMAGES, function ()
104 {
105 if (game.images.flame && game.images.flame.addAnimationCycle)
106 { game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); }
107 });
108
109 bindOnlineUi();
110 bindOfflineUi();
111 bindPlanetSelect();
112 restoreSelectedPlanet();
113};
114
115function onPlay ()
116{
117 if (app.mode === 'playing')
118 { return; }
119 openPlanetSelect('solo');
120}
121
122function startPlay (opts)
123{
124 opts = opts || {};
125 hideEl('menu');
126 hideEl('game-over');
127 hideEl('online-panel');
128 hideEl('spectator');
129 hideEl('podium');
130 hideEl('planet-select');
131 hideEl('offline-result');
132 showEl('hud');
133
134 var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod;
135 app.planet = opts.planet || planetMod.planetById(selectedPlanetId());
136 var miss = opts.missChance;
137 if (typeof miss !== 'number' || !isFinite(miss))
138 { miss = planetMod.missChance(app.planet); }
139 app.core = new GameCore(app.planet, Math.random, miss);
140 if (app.debugPhysics)
141 { app.core.debugInvariants = true; }
142 app.mode = 'playing';
143 app.online = !!opts.online;
144 app.offline = !!opts.offline;
145 app.gameOverShown = false;
146 app.eliminatedReported = false;
147 app.spectating = false;
148 app.sprites = Object.create(null);
149 app.flames = Object.create(null);
150 app.cells = [];
151 app.pointerId = null;
152 app.selectTween = null;
153 app.swapTweens = Object.create(null);
154 app.columnWarn = [];
155 app.warnClock = 0;
156 app.miniAcc = 1; // draw minis on the first frame
157 app.offlineResultShown = false;
158 if (!opts.keepBattle)
159 {
160 app.roundWonDelay = 0;
161 app.roundWonHandled = false;
162 }
163 if (app.offline && !opts.keepBattle && typeof Offline !== 'undefined')
164 {
165 app.battle = Offline.createBattle({
166 playerPlanet: app.planet,
167 rng: Math.random,
168 round: opts.round || 1
169 });
170 }
171
172 layout();
173 if (app.scene)
174 {
175 app.scene.destroy();
176 app.scene = null;
177 }
178 app.scene = new Scene(app.fieldX, app.fieldY, app.fieldW, app.fieldH);
179 app.scene.backgroundColor = { r: 12, g: 16, b: 32 };
180 app.scene.renderBackground = true;
181 game.loadScene(app.scene);
182
183 buildCells();
184 app.manager = app.scene.addObject(makeManager());
185 if (!app.spectating)
186 { bindPointer(app.scene.canvas); }
187 refreshHud();
188 if (app.online || app.offline)
189 { showEl('minis'); }
190 else
191 { hideEl('minis'); }
192 buildColumnWarn();
193 refreshOfflineHud();
194 refreshChainIndicator();
195}
196
197function teardownPlay ()
198{
199 unbindPointer();
200 if (app.scene)
201 {
202 app.scene.destroy();
203 app.scene = null;
204 }
205 app.manager = null;
206 app.core = null;
207 app.sprites = Object.create(null);
208 app.flames = Object.create(null);
209 app.cells = [];
210 app.selectTween = null;
211 app.swapTweens = Object.create(null);
212 app.columnWarn = [];
213 app.pointerId = null;
214 app.gameOverShown = false;
215 hideEl('hud');
216 hideEl('game-over');
217 hideEl('spectator');
218 hideEl('minis');
219 hideEl('offline-result');
220 hideOfflineHud();
221 hideChainIndicator();
222 if (typeof Online !== 'undefined')
223 { Online.clearFlights(); }
224 if (!app._keepBattleOnTeardown)
225 {
226 app.battle = null;
227 app.offline = false;
228 }
229 app._keepBattleOnTeardown = false;
230}
231
232function returnToMenu ()
233{
234 if (app.online && typeof Online !== 'undefined')
235 {
236 // Online matches do not dump you back to the solo menu:
237 // elimination becomes spectating; a finished match shows the podium.
238 return;
239 }
240 teardownPlay();
241 app.mode = 'menu';
242 app.online = false;
243 app.offline = false;
244 app.battle = null;
245 hideEl('planet-select');
246 showEl('menu');
247 var last = document.getElementById('last-score');
248 if (app.lastScore > 0)
249 {
250 last.hidden = false;
251 last.querySelector('strong').textContent = String(app.lastScore);
252 }
253}
254
255function buildCells ()
256{
257 if (!app.scene)
258 { return; }
259 var img = game.images.cell;
260 for (var row = 0; row < 13; row++)
261 {
262 for (var col = 0; col < 10; col++)
263 {
264 var obj = new GameObject(0, 0, img, 0);
265 placeTile(obj, col, row);
266 obj.renderer.alpha = 0.9;
267 app.scene.addObject(obj);
268 app.cells.push(obj);
269 }
270 }
271}
272
273function placeTile (obj, col, y)
274{
275 var t = app.tile;
276 obj.transform.position.x = col * t + t / 2;
277 obj.transform.position.y = app.fieldH - (y + 0.5) * t;
278 obj.transform.size = { x: t, y: t };
279}
280
281function layoutIfNeeded ()
282{
283 if (app.core && app.core.drag)
284 { return; }
285 var vw = window.innerWidth || 320;
286 var vh = window.innerHeight || 480;
287 if (app._layoutVw === vw && app._layoutVh === vh && app.scene && app.tile)
288 { return; }
289 layout();
290}
291
292function layout ()
293{
294 if (app.core && app.core.drag)
295 { return; }
296 var vw = window.innerWidth || 320;
297 var vh = window.innerHeight || 480;
298 app._layoutVw = vw;
299 app._layoutVh = vh;
300 var safeTop = 0;
301 try
302 {
303 // env(safe-area) is a CSS thing; keep a conservative HUD height.
304 safeTop = 0;
305 }
306 catch (e) { /* ignore */ }
307 app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop);
308 app.miniH = 0;
309 if (app.online || app.offline)
310 {
311 var nBots = (app.battle && app.battle.bots) ? app.battle.bots.length : 2;
312 var share = nBots > 6 ? 0.26 : 0.20;
313 app.miniH = Math.min(nBots > 6 ? 180 : 150, Math.max(86, Math.round(vh * share)));
314 }
315 var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015));
316 var availW = Math.max(80, vw - margin * 2);
317 var availH = Math.max(80, vh - app.hudH - app.miniH - margin);
318 app.tile = Math.max(14, Math.floor(Math.min(availW / 10, availH / 13)));
319 app.fieldW = app.tile * 10;
320 app.fieldH = app.tile * 13;
321 app.fieldX = Math.floor((vw - app.fieldW) / 2);
322 var topBand = app.hudH + app.miniH;
323 app.fieldY = topBand + Math.floor((vh - topBand - app.fieldH - margin / 2) / 2);
324 if (app.fieldY < topBand)
325 { app.fieldY = topBand; }
326 var minis = document.getElementById('minis');
327 if (minis)
328 {
329 minis.style.top = app.hudH + 'px';
330 minis.style.maxHeight = app.miniH + 'px';
331 }
332
333 if (app.scene)
334 {
335 app.scene.position.x = app.fieldX;
336 app.scene.position.y = app.fieldY;
337 app.scene.size.x = app.fieldW;
338 app.scene.size.y = app.fieldH;
339 }
340}
341
342function spriteFor (block)
343{
344 if (block.state === 'locked')
345 { return game.images.locked; }
346 if (block.color < 0)
347 { return game.images.gray; }
348 var key = Planet.spriteKey(app.planet, block.color);
349 return game.images[key] || game.images.gray;
350}
351
352function syncSprites (dt)
353{
354 if (!app.core || !app.scene)
355 { return; }
356 dt = dt || 0;
357 consumeAndStartSwapTweens();
358 advanceSwapTweens(dt);
359 var seen = Object.create(null);
360 var blocks = app.core.blocks;
361 for (var i = 0; i < blocks.length; i++)
362 {
363 var block = blocks[i];
364 seen[block.id] = true;
365 var obj = app.sprites[block.id];
366 if (!obj)
367 {
368 obj = new GameObject(0, 0, spriteFor(block), 2);
369 app.scene.addObject(obj);
370 app.sprites[block.id] = obj;
371 }
372 obj.renderer.sprite = spriteFor(block);
373 placeTile(obj, block.col, blockVisualY(block));
374 applyBlockVisual(obj, block);
375 obj.renderer.visible = true;
376 obj.renderer.alpha = 1;
377
378 if (block.flame)
379 {
380 var flame = app.flames[block.id];
381 if (!flame)
382 {
383 flame = new GameObject(0, 0, game.images.flame, 1);
384 flame.renderer.setAnimation('burn', 0, 0.08);
385 app.scene.addObject(flame);
386 app.flames[block.id] = flame;
387 }
388 flame.renderer.visible = true;
389 var t = app.tile;
390 // 3x as large (length and width, t1110). Keep the top of the
391 // flame at the same overlap into the block so the extra length
392 // extends downward under the rocket.
393 var flameW = t * 0.85 * 3;
394 var flameH = t * 0.85 * 3;
395 var origCenter = app.fieldH - block.y * t + t * 0.15;
396 var origTop = origCenter - (t * 0.85) / 2;
397 flame.transform.position.x = block.col * t + t / 2;
398 flame.transform.position.y = origTop + flameH / 2;
399 flame.transform.size = { x: flameW, y: flameH };
400 }
401 else if (app.flames[block.id])
402 { app.flames[block.id].renderer.visible = false; }
403 }
404
405 var ids = Object.keys(app.sprites);
406 for (var i = 0; i < ids.length; i++)
407 {
408 if (!seen[ids[i]])
409 {
410 app.sprites[ids[i]].destroy();
411 delete app.sprites[ids[i]];
412 if (app.flames[ids[i]])
413 {
414 app.flames[ids[i]].destroy();
415 delete app.flames[ids[i]];
416 }
417 }
418 }
419}
420
421function applyBlockVisual (obj, block)
422{
423 var t = app.tile;
424 var sx = 1;
425 var sy = 1;
426 var dy = 0;
427 if (block.bouncing && app.planet && app.planet.bounceDuration > 0
428 && typeof Easing !== 'undefined' && Easing.bouncePose)
429 {
430 var u = block.bounceAge / app.planet.bounceDuration;
431 var pose = Easing.bouncePose(u, app.planet.bounceSquash);
432 sx = pose.sx;
433 sy = pose.sy;
434 dy = pose.dy;
435 }
436 var sel = 1;
437 var tw = app.selectTween;
438 if (tw && tw.blockId === block.id && tw.phase !== 'idle')
439 { sel = tw.scale; }
440 obj.transform.size = { x: t * sx * sel, y: t * sy * sel };
441 if (dy)
442 { obj.transform.position.y -= dy * t; }
443}
444
445function clickTween ()
446{
447 return (typeof Easing !== 'undefined' && Easing.CLICK_TWEEN) ? Easing.CLICK_TWEEN : null;
448}
449
450function startPressTween (blockId)
451{
452 var c = clickTween();
453 if (!c)
454 { return; }
455 var from = (app.selectTween && app.selectTween.phase !== 'idle') ? app.selectTween.scale : 1;
456 app.selectTween = {
457 blockId: blockId,
458 from: from,
459 to: c.pressScale,
460 t: 0,
461 duration: c.pressDuration,
462 ease: c.pressEase,
463 scale: from,
464 phase: 'press'
465 };
466}
467
468function startReleaseTween ()
469{
470 var c = clickTween();
471 var tw = app.selectTween;
472 if (!c || !tw || tw.phase === 'idle')
473 { return; }
474 app.selectTween = {
475 blockId: tw.blockId,
476 from: tw.scale,
477 to: c.releaseScale,
478 t: 0,
479 duration: c.releaseDuration,
480 ease: c.releaseEase,
481 scale: tw.scale,
482 phase: 'release'
483 };
484}
485
486function updateSelectTween (dt)
487{
488 var tw = app.selectTween;
489 if (!tw || tw.phase === 'idle' || tw.phase === 'hold')
490 { return; }
491 tw.t += dt;
492 var u = tw.duration > 0 ? tw.t / tw.duration : 1;
493 if (u >= 1)
494 {
495 tw.scale = tw.to;
496 tw.t = tw.duration;
497 if (tw.phase === 'press')
498 { tw.phase = 'hold'; }
499 else
500 {
501 tw.phase = 'idle';
502 tw.scale = 1;
503 tw.blockId = null;
504 }
505 return;
506 }
507 var ease = tw.ease || (typeof Easing !== 'undefined' && Easing.easeOutBack);
508 tw.scale = ease ? Easing.tween(tw.from, tw.to, u, ease) : tw.from + (tw.to - tw.from) * u;
509}
510
511
512/* ---------- visual-only swap tween (t1121) -------------------------- */
513
514function swapTweenSpec ()
515{
516 if (typeof Easing !== 'undefined' && Easing.SWAP_TWEEN)
517 { return Easing.SWAP_TWEEN; }
518 return { duration: 0.100, ease: null };
519}
520
521function swapEase (u)
522{
523 if (typeof Easing !== 'undefined' && Easing.easeOutCubic)
524 { return Easing.easeOutCubic(u); }
525 var v = 1 - Math.max(0, Math.min(1, u));
526 return 1 - v * v * v;
527}
528
529function tweenVisualY (tw)
530{
531 var u = tw.duration > 0 ? Math.min(1, tw.age / tw.duration) : 1;
532 return tw.fromY + (tw.toY - tw.fromY) * swapEase(u);
533}
534
535/**
536 * Consume GameCore swap events. The currently dragged block is skipped
537 * (it follows the pointer). A block that is mid-tween and is swapped
538 * again restarts from its current visual y, so rapid swaps chain
539 * smoothly without snapping.
540 */
541function consumeAndStartSwapTweens ()
542{
543 if (!app.core || !app.core.consumeSwapEvents)
544 { return; }
545 if (!app.swapTweens)
546 { app.swapTweens = Object.create(null); }
547 var ev = app.core.consumeSwapEvents();
548 if (!ev.length)
549 { return; }
550 var dragId = app.core.drag && app.core.drag.blockId;
551 var duration = swapTweenSpec().duration;
552 for (var i = 0; i < ev.length; i++)
553 {
554 var e = ev[i];
555 if (e.id === dragId)
556 {
557 delete app.swapTweens[e.id];
558 continue;
559 }
560 var fromY = e.fromY;
561 var existing = app.swapTweens[e.id];
562 if (existing)
563 { fromY = tweenVisualY(existing); }
564 app.swapTweens[e.id] = {
565 fromY: fromY,
566 toY: e.toY,
567 age: 0,
568 duration: duration
569 };
570 }
571}
572
573function advanceSwapTweens (dt)
574{
575 if (!app.swapTweens)
576 { return; }
577 var ids = Object.keys(app.swapTweens);
578 for (var i = 0; i < ids.length; i++)
579 {
580 var tw = app.swapTweens[ids[i]];
581 tw.age += dt;
582 if (tw.age >= tw.duration)
583 { delete app.swapTweens[ids[i]]; }
584 }
585}
586
587function blockVisualY (block)
588{
589 if (!app.swapTweens)
590 { return block.y; }
591 var dragId = app.core && app.core.drag && app.core.drag.blockId;
592 if (block.id === dragId)
593 { return block.y; }
594 var tw = app.swapTweens[block.id];
595 if (!tw)
596 { return block.y; }
597 return tweenVisualY(tw);
598}
599
600function refreshHud ()
601{
602 if (!app.core)
603 { return; }
604 document.getElementById('score').textContent = String(app.core.score);
605 var planet = app.planet;
606 document.getElementById('planet-name').textContent = planet.name + ' · ' + planet.people;
607 document.getElementById('planet-stats').textContent = Planet.formatStats(planet);
608}
609
610function makeManager ()
611{
612 var obj = new GameObject(0, 0, game.images.pixel, 0);
613 obj.renderer.visible = false;
614 var base = obj.update.bind(obj);
615 obj.update = function (dt)
616 {
617 base(dt);
618 tickView(dt);
619 };
620 return obj;
621}
622
623function tickView (dt)
624{
625 if (app.mode !== 'playing' || !app.core)
626 { return; }
627
628 // Never resize the canvas mid-drag: a URL-bar hide would move the
629 // field under the finger and jump the target row. Also skip work
630 // when the viewport has not actually changed.
631 if (!(app.core && app.core.drag))
632 { layoutIfNeeded(); }
633 for (var i = 0; i < app.cells.length; i++)
634 {
635 var col = i % 10;
636 var row = Math.floor(i / 10);
637 placeTile(app.cells[i], col, row);
638 }
639
640 app.core.tick(dt);
641 if (app.offline && app.battle)
642 { tickOffline(dt); }
643 updateSelectTween(dt);
644 syncSprites(dt);
645 updateColumnWarn(dt);
646 refreshHud();
647 refreshOfflineHud();
648 refreshChainIndicator();
649 tickOnline(dt);
650 if (app.debugPhysics)
651 { logPhysicsDebug(); }
652
653 if (app.core.state === 'gameover' && !app.gameOverShown)
654 {
655 app.gameOverShown = true;
656 app.lastScore = app.core.score;
657 document.getElementById('go-score').textContent = String(app.lastScore);
658 if (app.online)
659 { onOnlineEliminated(); }
660 else if (app.offline)
661 { /* Offline result is shown from tickOffline. */ }
662 else
663 { showEl('game-over'); }
664 }
665 if (!app.online && !app.offline && app.core.state === 'gameover'
666 && app.core.gameOverTime >= GAME_OVER_DELAY)
667 { returnToMenu(); }
668}
669
670/* ---------- pointer input (mouse + touch) --------------------------- */
671/*
672 * Mouse uses Pointer Events. Touch uses Touch Events as the authority:
673 * on a real phone, pointer clientX/Y can disagree with the visual
674 * finger (zoomed visual viewport, gesture takeover, capture cancel)
675 * while changedTouches stays correct. When a touch is active, pointer
676 * move/up/cancel are ignored so a poisoned pointer coordinate cannot
677 * walk the block to the top or bottom of the stack (t1106).
678 *
679 * After a down we also listen on the document, so a drag that leaves
680 * the canvas (needed to launch a block at the top of a full column)
681 * still reaches moveDrag. We do not call setPointerCapture: on mobile
682 * that is often cancelled when the browser takes the gesture, which
683 * would fire pointercancel mid-drag.
684 *
685 * A non-passive document touchstart/touchmove preventDefault during
686 * play stops scrolling, rubber-banding and the pointercancel that
687 * follows. pointercancel / touchcancel end the drag without launch.
688 *
689 * ?debug=drag (or localStorage meteors-debug-drag=1) shows an overlay.
690 */
691
692var boundCanvas = null;
693var windowListening = false;
694var touchListening = false;
695var lastDragDebug = null;
696
697function isDragDebugEnabled ()
698{
699 try
700 {
701 var q = window.location && window.location.search;
702 if (q && /(?:\?|&)debug=drag(?:&|$)/.test(q))
703 { return true; }
704 if (window.localStorage && window.localStorage.getItem('meteors-debug-drag') === '1')
705 { return true; }
706 }
707 catch (err) { /* ignore */ }
708 return false;
709}
710
711/** ?debug, ?debug=physics, ?debug=drag, or localStorage meteors-debug=1. */
712function isPhysicsDebugEnabled ()
713{
714 try
715 {
716 var q = window.location && window.location.search;
717 if (q && /(?:\?|&)debug(?:=|&|$)/.test(q))
718 { return true; }
719 if (window.localStorage && (window.localStorage.getItem('meteors-debug') === '1'
720 || window.localStorage.getItem('meteors-debug-drag') === '1'))
721 { return true; }
722 }
723 catch (err) { /* ignore */ }
724 return false;
725}
726
727function eventClient (e)
728{
729 var t = null;
730 if (e.changedTouches && e.changedTouches.length)
731 { t = e.changedTouches[0]; }
732 else if (e.touches && e.touches.length)
733 { t = e.touches[0]; }
734 if (t)
735 { return { x: t.clientX, y: t.clientY, id: t.identifier, src: 'touch' }; }
736 if (e.clientX != null && e.clientY != null)
737 { return { x: e.clientX, y: e.clientY, id: e.pointerId, src: 'pointer' }; }
738 return null;
739}
740
741function addWindowPointer ()
742{
743 if (windowListening)
744 { return; }
745 window.addEventListener('pointermove', onPointerMove, { capture: true, passive: false });
746 window.addEventListener('pointerup', onPointerUp, { capture: true, passive: false });
747 window.addEventListener('pointercancel', onPointerCancel, { capture: true, passive: false });
748 windowListening = true;
749}
750
751function removeWindowPointer ()
752{
753 if (!windowListening)
754 { return; }
755 window.removeEventListener('pointermove', onPointerMove, { capture: true });
756 window.removeEventListener('pointerup', onPointerUp, { capture: true });
757 window.removeEventListener('pointercancel', onPointerCancel, { capture: true });
758 windowListening = false;
759}
760
761function addTouchListeners ()
762{
763 if (touchListening)
764 { return; }
765 var opts = { capture: true, passive: false };
766 document.addEventListener('touchstart', onTouchStart, opts);
767 document.addEventListener('touchmove', onTouchMove, opts);
768 document.addEventListener('touchend', onTouchEnd, opts);
769 document.addEventListener('touchcancel', onTouchCancel, opts);
770 touchListening = true;
771}
772
773function removeTouchListeners ()
774{
775 if (!touchListening)
776 { return; }
777 var opts = { capture: true };
778 document.removeEventListener('touchstart', onTouchStart, opts);
779 document.removeEventListener('touchmove', onTouchMove, opts);
780 document.removeEventListener('touchend', onTouchEnd, opts);
781 document.removeEventListener('touchcancel', onTouchCancel, opts);
782 touchListening = false;
783}
784
785function bindPointer (canvas)
786{
787 unbindPointer();
788 boundCanvas = canvas;
789 canvas.addEventListener('pointerdown', onPointerDown, { passive: false });
790 canvas.style.touchAction = 'none';
791 canvas.style.position = 'fixed';
792 canvas.style.cursor = 'pointer';
793 canvas.style.webkitUserSelect = 'none';
794 canvas.style.userSelect = 'none';
795 addTouchListeners();
796 if (app.debugDrag)
797 { ensureDragDebugOverlay(); }
798}
799
800function unbindPointer ()
801{
802 removeWindowPointer();
803 removeTouchListeners();
804 if (boundCanvas)
805 { boundCanvas.removeEventListener('pointerdown', onPointerDown); }
806 boundCanvas = null;
807 app.pointerId = null;
808 app.pointerType = null;
809 app.activeTouchId = null;
810}
811
812function fieldFromEvent (e)
813{
814 var canvas = app.scene && app.scene.canvas;
815 if (!canvas)
816 { return null; }
817 var rect = canvas.getBoundingClientRect();
818 if (rect.width <= 0 || rect.height <= 0)
819 { return null; }
820 var pt = eventClient(e);
821 if (!pt)
822 { return null; }
823 // Map through the CSS box only. Using canvas.width / app.tile would
824 // scale the pointer by the backing-store ratio whenever that differs
825 // from the layout size (high-DPR devices), so a short finger move
826 // would look like a long swipe.
827 var width = Planet.FIELD_WIDTH;
828 var height = Planet.FIELD_HEIGHT;
829 var col = ((pt.x - rect.left) / rect.width) * width;
830 var fieldY = (1 - (pt.y - rect.top) / rect.height) * height;
831 return { col: col, y: fieldY, src: pt.src, clientX: pt.x, clientY: pt.y, rect: rect };
832}
833
834function playingForDrag ()
835{
836 return app.core && app.core.state === 'playing';
837}
838
839function startDragFromEvent (e)
840{
841 var pos = fieldFromEvent(e);
842 if (!pos)
843 { return; }
844 if (app.core.drag)
845 {
846 app.core.moveDrag(pos.y);
847 logDragDebug(e, pos, 'move-already');
848 return;
849 }
850 if (app.core.beginDrag(pos.col, pos.y) && app.core.drag)
851 { startPressTween(app.core.drag.blockId); }
852 logDragDebug(e, pos, 'down');
853}
854
855function moveDragFromEvent (e)
856{
857 if (!app.core || !app.core.drag)
858 { return; }
859 var pos = fieldFromEvent(e);
860 if (pos)
861 { app.core.moveDrag(pos.y); }
862 logDragDebug(e, pos, 'move');
863}
864
865function finishDrag (opts)
866{
867 opts = opts || {};
868 app.pointerId = null;
869 app.pointerType = null;
870 app.activeTouchId = null;
871 removeWindowPointer();
872 if (boundCanvas)
873 {
874 try
875 {
876 if (opts.pointerId != null && boundCanvas.releasePointerCapture)
877 { boundCanvas.releasePointerCapture(opts.pointerId); }
878 }
879 catch (err) { /* ignore */ }
880 }
881 startReleaseTween();
882 if (app.core && app.core.drag)
883 {
884 if (opts.noLaunch)
885 { app.core.drag.launchIntent = false; }
886 app.core.endDrag();
887 }
888 else if (app.core)
889 { app.core.endDrag(); }
890 logDragDebug(null, null, opts.noLaunch ? 'cancel' : 'up');
891}
892
893function onPointerDown (e)
894{
895 if (!playingForDrag())
896 { return; }
897 if (app.pointerId != null && e.pointerId !== app.pointerId)
898 { return; }
899 if (e.preventDefault)
900 { e.preventDefault(); }
901 app.pointerId = e.pointerId;
902 app.pointerType = e.pointerType || 'mouse';
903 addWindowPointer();
904 // If a touch is already in charge, do not reset the grab from pointerdown.
905 if (app.activeTouchId != null)
906 { return; }
907 startDragFromEvent(e);
908}
909
910function onPointerMove (e)
911{
912 if (app.pointerId == null || e.pointerId !== app.pointerId)
913 { return; }
914 if (!app.core || !app.core.drag)
915 { return; }
916 // Touch coordinates are the authority; ignore pointer moves for a
917 // live touch so a wrong clientY cannot walk the whole column.
918 // Only skip when touchstart has actually arrived — some environments
919 // deliver touch-pointer events without a TouchEvent stream.
920 if (app.activeTouchId != null)
921 {
922 if (e.preventDefault)
923 { e.preventDefault(); }
924 logDragDebug(e, fieldFromEvent(e), 'pointer-ignored');
925 return;
926 }
927 if (e.preventDefault)
928 { e.preventDefault(); }
929 moveDragFromEvent(e);
930}
931
932function onPointerUp (e)
933{
934 if (app.pointerId == null)
935 { return; }
936 if (e && e.pointerId != null && e.pointerId !== app.pointerId)
937 { return; }
938 if (app.activeTouchId != null)
939 {
940 // touchend will finish the drag.
941 if (e && e.preventDefault)
942 { e.preventDefault(); }
943 logDragDebug(e, fieldFromEvent(e), 'pointer-up-ignored');
944 return;
945 }
946 if (e && e.preventDefault)
947 { e.preventDefault(); }
948 finishDrag({ pointerId: e && e.pointerId });
949}
950
951function onPointerCancel (e)
952{
953 if (app.pointerId == null)
954 { return; }
955 if (e && e.pointerId != null && e.pointerId !== app.pointerId)
956 { return; }
957 if (app.activeTouchId != null)
958 {
959 if (e && e.preventDefault)
960 { e.preventDefault(); }
961 logDragDebug(e, fieldFromEvent(e), 'pointer-cancel-ignored');
962 return;
963 }
964 if (e && e.preventDefault)
965 { e.preventDefault(); }
966 // A cancelled gesture is not a launch pull.
967 finishDrag({ pointerId: e && e.pointerId, noLaunch: true });
968}
969
970function touchById (list, id)
971{
972 if (!list)
973 { return null; }
974 for (var i = 0; i < list.length; i++)
975 {
976 if (list[i].identifier === id)
977 { return list[i]; }
978 }
979 return null;
980}
981
982function onTouchStart (e)
983{
984 if (!playingForDrag())
985 { return; }
986 if (app.activeTouchId != null)
987 {
988 if (e.preventDefault)
989 { e.preventDefault(); }
990 return;
991 }
992 var t = e.changedTouches && e.changedTouches[0];
993 if (!t)
994 { return; }
995 if (e.preventDefault)
996 { e.preventDefault(); }
997 app.activeTouchId = t.identifier;
998 addWindowPointer();
999 startDragFromEvent(e);
1000}
1001
1002function onTouchMove (e)
1003{
1004 if (app.activeTouchId == null)
1005 { return; }
1006 if (!touchById(e.changedTouches, app.activeTouchId)
1007 && !touchById(e.touches, app.activeTouchId))
1008 { return; }
1009 if (e.preventDefault)
1010 { e.preventDefault(); }
1011 moveDragFromEvent(e);
1012}
1013
1014function onTouchEnd (e)
1015{
1016 if (app.activeTouchId == null)
1017 { return; }
1018 if (!touchById(e.changedTouches, app.activeTouchId))
1019 { return; }
1020 if (e.preventDefault)
1021 { e.preventDefault(); }
1022 finishDrag({});
1023}
1024
1025function onTouchCancel (e)
1026{
1027 if (app.activeTouchId == null)
1028 { return; }
1029 if (!touchById(e.changedTouches, app.activeTouchId))
1030 { return; }
1031 if (e.preventDefault)
1032 { e.preventDefault(); }
1033 finishDrag({ noLaunch: true });
1034}
1035
1036function logPhysicsDebug ()
1037{
1038 if (!app.debugPhysics || !app.core)
1039 { return; }
1040 ensureDragDebugOverlay();
1041 var el = document.getElementById('drag-debug');
1042 if (!el)
1043 { return; }
1044 var issues = app.core.lastInvariantViolations || [];
1045 var flying = 0;
1046 var manuals = 0;
1047 var clusters = app.core.clusters ? Object.keys(app.core.clusters).length : 0;
1048 for (var i = 0; i < app.core.blocks.length; i++)
1049 {
1050 if (app.core.blocks[i].state === 'flying')
1051 { flying++; }
1052 if (app.core.blocks[i].state === 'manual')
1053 { manuals++; }
1054 }
1055 var status = issues.length
1056 ? ('PHYSICS FAIL x' + issues.length + '\n' + issues.slice(0, 6).join('\n'))
1057 : ('physics ok blocks=' + app.core.blocks.length
1058 + ' fly=' + flying + ' man=' + manuals + ' cl=' + clusters);
1059 // Keep any live drag line above the physics status.
1060 var dragLine = '';
1061 if (app.debugDrag && lastDragDebug)
1062 {
1063 dragLine = el.textContent && el.textContent.indexOf('drag ') === 0
1064 ? el.textContent.split('\n')[0] + '\n'
1065 : '';
1066 }
1067 el.textContent = dragLine + status;
1068 el.hidden = false;
1069 el.style.color = issues.length ? '#ffb4b4' : '#c6f6c8';
1070}
1071
1072function ensureDragDebugOverlay ()
1073{
1074 if (document.getElementById('drag-debug'))
1075 { return; }
1076 var el = document.createElement('div');
1077 el.id = 'drag-debug';
1078 el.setAttribute('aria-live', 'polite');
1079 document.body.appendChild(el);
1080}
1081
1082function logDragDebug (e, pos, phase)
1083{
1084 if (!app.debugDrag)
1085 { return; }
1086 ensureDragDebugOverlay();
1087 var el = document.getElementById('drag-debug');
1088 if (!el)
1089 { return; }
1090 var block = null;
1091 if (app.core && app.core.drag)
1092 { block = app.core.blockById(app.core.drag.blockId); }
1093 var pt = e ? eventClient(e) : null;
1094 var evType = e ? e.type : phase;
1095 var info = {
1096 phase: phase,
1097 ev: evType,
1098 src: pos && pos.src,
1099 fieldY: pos && Math.round(pos.y * 100) / 100,
1100 col: pos && Math.round(pos.col * 100) / 100,
1101 cy: pt && Math.round(pt.y * 10) / 10,
1102 blockY: block && Math.round(block.y * 100) / 100,
1103 target: block && Math.floor((pos && pos.y) + 1e-12),
1104 launch: app.core && app.core.drag && app.core.drag.launchIntent,
1105 touchId: app.activeTouchId,
1106 pid: app.pointerId,
1107 ptype: app.pointerType
1108 };
1109 lastDragDebug = info;
1110 el.textContent = 'drag ' + phase
1111 + ' ev=' + evType
1112 + ' src=' + (info.src || '-')
1113 + ' y=' + (info.fieldY != null ? info.fieldY : '-')
1114 + ' → ' + (info.target != null ? info.target : '-')
1115 + ' block=' + (info.blockY != null ? info.blockY : '-')
1116 + (info.launch ? ' LAUNCH' : '')
1117 + ' tId=' + info.touchId
1118 + ' pId=' + info.pid;
1119 el.hidden = false;
1120}
1121
1122
1123function hideEl (id)
1124{
1125 document.getElementById(id).hidden = true;
1126}
1127
1128function showEl (id)
1129{
1130 document.getElementById(id).hidden = false;
1131}
1132
1133window.addEventListener('resize', function ()
1134{
1135 if (app.mode === 'playing')
1136 { layout(); }
1137});
1138
1139window.addEventListener('orientationchange', function ()
1140{
1141 setTimeout(function ()
1142 {
1143 if (app.mode === 'playing')
1144 { layout(); }
1145 }, 120);
1146});
1147
1148/* ---------- online play (stage 2) ---------------------------------- */
1149
1150function tickOnline (dt)
1151{
1152 if (!app.online || typeof Online === 'undefined')
1153 { return; }
1154 if (app.core)
1155 {
1156 var shots = app.core.consumeOutgoingShots();
1157 for (var i = 0; i < shots.length; i++)
1158 {
1159 var s = shots[i];
1160 var start = fieldToViewport(s.col, s.y + 1);
1161 Online.rememberFlightLocal(s, start.x, start.y);
1162 }
1163 Online.queueShots(shots);
1164 }
1165 Online.tickFlights();
1166 Online.renderMinis(document.getElementById('minis'));
1167}
1168
1169
1170/* ---------- Offline Strijd (t1119) + column warn (t1123) ----------- */
1171
1172function bindOfflineUi ()
1173{
1174 var btn = document.getElementById('btn-offline');
1175 if (btn)
1176 {
1177 btn.addEventListener('click', onOffline);
1178 btn.addEventListener('pointerup', function (e)
1179 {
1180 if (e.pointerType === 'touch' || e.pointerType === 'pen')
1181 {
1182 e.preventDefault();
1183 onOffline();
1184 }
1185 });
1186 }
1187 var back = document.getElementById('btn-offline-menu');
1188 if (back)
1189 {
1190 back.addEventListener('click', function ()
1191 {
1192 teardownPlay();
1193 app.mode = 'menu';
1194 app.offline = false;
1195 app.battle = null;
1196 hideEl('offline-result');
1197 showEl('menu');
1198 });
1199 }
1200}
1201
1202function onOffline ()
1203{
1204 openPlanetSelect('offline');
1205}
1206
1207function tickOffline (dt)
1208{
1209 if (!app.battle || !app.core || typeof Offline === 'undefined')
1210 { return; }
1211
1212 if (app.battle.state === 'round_won')
1213 {
1214 if (!app.roundWonHandled)
1215 {
1216 app.roundWonHandled = true;
1217 app.roundWonDelay = Offline.ROUND_WON_DELAY || 1.5;
1218 }
1219 app.roundWonDelay -= dt;
1220 if (app.roundWonDelay <= 0)
1221 { startNextOfflineRound(); }
1222 updateOfflineMinis(dt, true);
1223 return;
1224 }
1225
1226 var result = app.battle.tick(dt, app.core);
1227 if (result && result.flights && result.flights.length
1228 && typeof Online !== 'undefined' && Online.spawnFlights)
1229 {
1230 var locals = Object.create(null);
1231 var list = result.locals || [];
1232 for (var i = 0; i < list.length; i++)
1233 {
1234 var s = list[i];
1235 var start;
1236 if (s.from_id === 'player')
1237 { start = fieldToViewport(s.col, s.y + 1); }
1238 else
1239 { start = miniViewportCenter(s.from_id); }
1240 locals[s.client_id] = {
1241 col: s.col,
1242 y: s.y,
1243 color: s.color,
1244 startX: start.x,
1245 startY: start.y
1246 };
1247 }
1248 Online.spawnFlights(result.flights, locals);
1249 }
1250 if (typeof Online !== 'undefined' && Online.tickFlights)
1251 { Online.tickFlights(); }
1252 updateOfflineMinis(dt, false);
1253
1254 if (app.battle.state === 'lost' && !app.offlineResultShown)
1255 { showOfflineResult(); }
1256}
1257
1258function startNextOfflineRound ()
1259{
1260 if (!app.battle)
1261 { return; }
1262 app.battle.advanceRound();
1263 app.roundWonHandled = false;
1264 app.roundWonDelay = 0;
1265 app._keepBattleOnTeardown = true;
1266 // Tear down the current scene then start a fresh player field,
1267 // keeping the same battle (already advanced).
1268 var planet = app.battle.playerPlanet;
1269 app._keepBattleOnTeardown = true;
1270 teardownPlay();
1271 app.offline = true;
1272 app.battle = app.battle; // kept
1273 startPlay({ planet: planet, offline: true, keepBattle: true });
1274}
1275
1276function showOfflineResult ()
1277{
1278 app.offlineResultShown = true;
1279 var battle = app.battle;
1280 var reached = document.getElementById('offline-reached');
1281 if (reached)
1282 { reached.textContent = String(battle.round); }
1283 var detail = document.getElementById('offline-result-detail');
1284 if (detail)
1285 {
1286 var sch = battle.schedule;
1287 var n = sch.opponents;
1288 var noun = n === 1 ? 'tegenstander' : 'tegenstanders';
1289 detail.textContent = 'Je speelde tegen ' + n + ' ' + noun
1290 + ' met skill ' + Math.round(sch.skill * 100) + '%.';
1291 }
1292 hideEl('game-over');
1293 showEl('offline-result');
1294}
1295
1296function refreshOfflineHud ()
1297{
1298 var el = document.getElementById('offline-hud');
1299 if (!el)
1300 { return; }
1301 if (!(app.offline && app.battle && app.mode === 'playing'))
1302 {
1303 el.hidden = true;
1304 return;
1305 }
1306 el.hidden = false;
1307 var sch = app.battle.schedule;
1308 var n = sch.opponents;
1309 var noun = n === 1 ? 'tegenstander' : 'tegenstanders';
1310 var r = document.getElementById('offline-round');
1311 var o = document.getElementById('offline-opponents');
1312 var s = document.getElementById('offline-skill');
1313 if (r)
1314 { r.textContent = 'Ronde ' + sch.round; }
1315 if (o)
1316 { o.textContent = n + ' ' + noun; }
1317 if (s)
1318 { s.textContent = 'Skill ' + Math.round(sch.skill * 100) + '%'; }
1319}
1320
1321function hideOfflineHud ()
1322{
1323 var el = document.getElementById('offline-hud');
1324 if (el)
1325 { el.hidden = true; }
1326}
1327
1328function refreshChainIndicator ()
1329{
1330 var el = document.getElementById('chain-indicator');
1331 if (!el)
1332 { return; }
1333 var info = app.core && app.core.lastChainIndicator;
1334 var active = app.core && app.core.hasActiveLandingChain
1335 && app.core.hasActiveLandingChain();
1336 // Show only while a chained cluster is still in the air.
1337 if (!info || info.chain < 1 || app.mode !== 'playing' || !active)
1338 {
1339 el.hidden = true;
1340 return;
1341 }
1342 el.hidden = false;
1343 el.textContent = 'x' + info.chain + ' +' + info.bonusPct + '%';
1344}
1345
1346function hideChainIndicator ()
1347{
1348 var el = document.getElementById('chain-indicator');
1349 if (el)
1350 { el.hidden = true; }
1351}
1352
1353function miniViewportCenter (botId)
1354{
1355 var el = document.querySelector('#minis .mini[data-player="' + botId + '"] canvas');
1356 if (!el)
1357 { return { x: window.innerWidth / 2, y: 40 }; }
1358 var rect = el.getBoundingClientRect();
1359 return { x: rect.left + rect.width / 2, y: rect.bottom };
1360}
1361
1362function offlineMiniSize (n)
1363{
1364 if (n >= 10)
1365 { return { w: 40, h: 52 }; }
1366 if (n >= 6)
1367 { return { w: 56, h: 73 }; }
1368 return { w: 80, h: 104 };
1369}
1370
1371function updateOfflineMinis (dt, force)
1372{
1373 app.miniAcc = (app.miniAcc || 0) + dt;
1374 if (!force && app.miniAcc < 0.1)
1375 { return; }
1376 app.miniAcc = 0;
1377 renderOfflineMinis();
1378}
1379
1380function renderOfflineMinis ()
1381{
1382 var container = document.getElementById('minis');
1383 if (!container || !app.battle)
1384 { return; }
1385 var bots = app.battle.bots;
1386 var size = offlineMiniSize(bots.length);
1387 container.classList.toggle('crowded', bots.length > 5);
1388 var existing = {};
1389 var kids = container.querySelectorAll('[data-player]');
1390 for (var i = 0; i < kids.length; i++)
1391 { existing[kids[i].getAttribute('data-player')] = kids[i]; }
1392 var seen = Object.create(null);
1393 for (var i = 0; i < bots.length; i++)
1394 {
1395 var bot = bots[i];
1396 seen[bot.id] = true;
1397 var el = existing[bot.id];
1398 if (!el)
1399 {
1400 el = document.createElement('div');
1401 el.className = 'mini';
1402 el.setAttribute('data-player', bot.id);
1403 el.innerHTML = '<div class="mini-name"></div>'
1404 + '<canvas class="mini-canvas" width="' + size.w
1405 + '" height="' + size.h + '"></canvas>'
1406 + '<div class="mini-meta"></div>';
1407 container.appendChild(el);
1408 }
1409 var canvas = el.querySelector('canvas');
1410 if (canvas && (canvas.width !== size.w || canvas.height !== size.h))
1411 {
1412 canvas.width = size.w;
1413 canvas.height = size.h;
1414 }
1415 el.classList.toggle('eliminated', !!bot.eliminated);
1416 var planetName = bot.planet && bot.planet.name ? bot.planet.name : '';
1417 el.querySelector('.mini-name').textContent = bot.name
1418 + (planetName ? ' · ' + planetName : '');
1419 el.querySelector('.mini-meta').textContent = bot.eliminated
1420 ? 'Uit'
1421 : ('Punten ' + (bot.score || 0));
1422 var snap = bot.core ? bot.core.fieldSnapshot() : { blocks: [] };
1423 if (typeof Online !== 'undefined' && Online._drawMini)
1424 { Online._drawMini(canvas, snap, bot.planet); }
1425 }
1426 for (var id in existing)
1427 {
1428 if (!seen[id])
1429 { existing[id].remove(); }
1430 }
1431}
1432
1433function buildColumnWarn ()
1434{
1435 app.columnWarn = [];
1436 if (!app.scene)
1437 { return; }
1438 var img = (game.images && (game.images.columnWarn || game.images.pixel)) || null;
1439 if (!img)
1440 { return; }
1441 for (var c = 0; c < 10; c++)
1442 {
1443 var obj = new GameObject(0, 0, img, 0);
1444 obj.renderer.alpha = 0;
1445 obj.renderer.visible = false;
1446 app.scene.addObject(obj);
1447 app.columnWarn.push(obj);
1448 }
1449 updateColumnWarn(0);
1450}
1451
1452function updateColumnWarn (dt)
1453{
1454 if (!app.columnWarn || !app.core)
1455 { return; }
1456 app.warnClock = (app.warnClock || 0) + (dt || 0);
1457 var pulse = (typeof GameCore !== 'undefined' && GameCore.columnWarnPulse)
1458 ? GameCore.columnWarnPulse(app.warnClock)
1459 : 0.16 + 0.28 * (0.5 + 0.5 * Math.sin(app.warnClock * 3.45575));
1460 var t = app.tile;
1461 for (var c = 0; c < app.columnWarn.length; c++)
1462 {
1463 var obj = app.columnWarn[c];
1464 var on = app.core.columnNeedsWarn && app.core.columnNeedsWarn(c);
1465 obj.renderer.visible = !!on;
1466 obj.renderer.alpha = on ? pulse : 0;
1467 if (t)
1468 {
1469 obj.transform.position.x = c * t + t / 2;
1470 obj.transform.position.y = app.fieldH / 2;
1471 obj.transform.size = { x: t, y: app.fieldH };
1472 }
1473 }
1474}
1475
1476function fieldToViewport (col, fieldY)
1477{
1478 var canvas = app.scene && app.scene.canvas;
1479 if (!canvas)
1480 { return { x: window.innerWidth / 2, y: 40 }; }
1481 var rect = canvas.getBoundingClientRect();
1482 var x = rect.left + ((col + 0.5) / 10) * rect.width;
1483 var y = rect.top + (1 - (fieldY / 13)) * rect.height;
1484 return { x: x, y: y };
1485}
1486
1487function onlinePayload ()
1488{
1489 if (!app.online || !app.core)
1490 { return {}; }
1491 return {
1492 snapshot: app.core.fieldSnapshot(),
1493 score: app.core.score,
1494 eliminated: app.core.state === 'gameover' || app.spectating || app.eliminatedReported
1495 };
1496}
1497
1498function onOnlineEliminated ()
1499{
1500 app.eliminatedReported = true;
1501 app.spectating = true;
1502 unbindPointer();
1503 hideEl('game-over');
1504 var lobby = typeof Online !== 'undefined' && Online.lobby;
1505 if (lobby && lobby.status === 'finished')
1506 {
1507 showPodium(lobby);
1508 return;
1509 }
1510 showEl('spectator');
1511}
1512
1513function showPodium (lobby)
1514{
1515 hideEl('spectator');
1516 hideEl('game-over');
1517 hideEl('online-panel');
1518 showEl('podium');
1519 var list = document.getElementById('podium-list');
1520 list.innerHTML = '';
1521 var ranks = (lobby && lobby.rankings) || [];
1522 for (var i = 0; i < ranks.length; i++)
1523 {
1524 var r = ranks[i];
1525 var li = document.createElement('li');
1526 var medal = r.place === 1 ? '1e' : (r.place === 2 ? '2e' : (r.place === 3 ? '3e' : r.place + 'e'));
1527 li.textContent = medal + ' ' + r.name + ' · ' + r.score + ' punten';
1528 list.appendChild(li);
1529 }
1530 var hint = document.getElementById('podium-hint');
1531 var secs = (lobby && lobby.podium_seconds) || 5;
1532 hint.textContent = 'Over ' + secs + ' seconden teruggaan naar de lobby…';
1533}
1534
1535function startOnlineMatch ()
1536{
1537 if (app.mode === 'playing' && app.online)
1538 { return; }
1539 var planet = Planet.planetById(selectedPlanetId());
1540 var me = (typeof Online !== 'undefined' && Online.mePlayer) ? Online.mePlayer() : null;
1541 if (me && me.planet && me.planet.id)
1542 { planet = Planet.planetById(me.planet.id); }
1543 startPlay({ online: true, planet: planet, missChance: Planet.missChance(planet) });
1544 if (typeof Online !== 'undefined')
1545 { Online.startPolling(onlinePayload); }
1546}
1547
1548function leaveOnlineMatch (goMenu)
1549{
1550 if (typeof Online !== 'undefined')
1551 {
1552 Online.stopPolling();
1553 Online.leaveLobby();
1554 Online.clearFlights();
1555 }
1556 teardownPlay();
1557 app.online = false;
1558 if (goMenu)
1559 {
1560 app.mode = 'menu';
1561 showEl('menu');
1562 }
1563 else
1564 {
1565 app.mode = 'online';
1566 openOnlinePanel();
1567 }
1568}
1569
1570function bindOnlineUi ()
1571{
1572 var onlineBtn = document.getElementById('btn-online');
1573 if (!onlineBtn)
1574 { return; }
1575 onlineBtn.addEventListener('click', function ()
1576 { openOnlinePanel(); });
1577
1578 var backs = document.querySelectorAll('[data-back-menu]');
1579 for (var i = 0; i < backs.length; i++)
1580 {
1581 backs[i].addEventListener('click', function ()
1582 {
1583 if (typeof Online !== 'undefined')
1584 { Online.stopPolling(); }
1585 hideEl('online-panel');
1586 app.mode = 'menu';
1587 app.online = false;
1588 showEl('menu');
1589 });
1590 }
1591
1592 document.getElementById('btn-create').addEventListener('click', function ()
1593 {
1594 Online.createLobby().then(function (data)
1595 {
1596 if (data && data.ok)
1597 {
1598 renderOnline();
1599 Online.startPolling(onlinePayload);
1600 }
1601 else
1602 { renderOnline(); }
1603 });
1604 });
1605
1606 document.getElementById('join-form').addEventListener('submit', function (e)
1607 {
1608 e.preventDefault();
1609 var code = (document.getElementById('join-code').value || '').trim();
1610 if (!code)
1611 { return; }
1612 Online.joinLobby(code).then(function ()
1613 {
1614 renderOnline();
1615 if (Online.lobby)
1616 { Online.startPolling(onlinePayload); }
1617 });
1618 });
1619
1620 document.getElementById('btn-ready').addEventListener('click', function ()
1621 {
1622 var me = Online.mePlayer();
1623 Online.setReady(!(me && me.ready)).then(renderOnline);
1624 });
1625
1626 document.getElementById('btn-start').addEventListener('click', function ()
1627 {
1628 Online.startGame().then(function (data)
1629 {
1630 if (data && data.ok)
1631 { startOnlineMatch(); }
1632 else
1633 { renderOnline(); }
1634 });
1635 });
1636
1637 document.getElementById('btn-leave-lobby').addEventListener('click', function ()
1638 {
1639 Online.leaveLobby().then(function ()
1640 {
1641 Online.stopPolling();
1642 renderOnline();
1643 });
1644 });
1645
1646 document.getElementById('btn-copy-code').addEventListener('click', function ()
1647 {
1648 var code = document.getElementById('lobby-code').textContent;
1649 if (navigator.clipboard && navigator.clipboard.writeText)
1650 { navigator.clipboard.writeText(code); }
1651 });
1652
1653 document.getElementById('btn-spectate').addEventListener('click', function ()
1654 {
1655 hideEl('spectator');
1656 app.spectating = true;
1657 });
1658
1659 document.getElementById('btn-leave-game').addEventListener('click', function ()
1660 { leaveOnlineMatch(false); });
1661
1662 if (typeof Online !== 'undefined')
1663 {
1664 Online.onChange = function ()
1665 { renderOnline(); };
1666 Online.onGameStart = function ()
1667 { startOnlineMatch(); };
1668 Online.onIncoming = function (incoming)
1669 {
1670 if (!app.core || app.core.state !== 'playing')
1671 { return; }
1672 for (var i = 0; i < incoming.length; i++)
1673 { app.core.ingestGarbage(); }
1674 };
1675 Online.onFinished = function (lobby)
1676 { showPodium(lobby); };
1677 Online.onLobbyReturn = function (lobby)
1678 {
1679 teardownPlay();
1680 app.online = false;
1681 app.mode = 'online';
1682 hideEl('podium');
1683 showEl('online-panel');
1684 renderOnline();
1685 Online.startPolling(onlinePayload);
1686 };
1687 }
1688
1689 var params = new URLSearchParams(window.location.search);
1690 if (params.get('online') === '1' || params.get('auth') === 'unconfigured')
1691 { openOnlinePanel(); }
1692}
1693
1694function openOnlinePanel ()
1695{
1696 hideEl('menu');
1697 hideEl('game-over');
1698 hideEl('podium');
1699 hideEl('spectator');
1700 hideEl('planet-select');
1701 showEl('online-panel');
1702 app.mode = 'online';
1703 setOnlineStatus('Even kijken of online spelen beschikbaar is…');
1704 if (typeof Online === 'undefined')
1705 {
1706 showOnlineError('Online spelen is in deze build niet geladen. Je kunt wel alleen spelen.');
1707 showOnly('online-unconfigured');
1708 return;
1709 }
1710 Online.refresh().then(function (data)
1711 {
1712 if (!data || data.ok === false)
1713 {
1714 var msg = (data && data.error) || 'Geen verbinding met de server.';
1715 showOnlineError(msg + ' Je kunt wel alleen spelen.');
1716 if (data && data.configured === false)
1717 { showOnly('online-unconfigured'); }
1718 else
1719 { showOnly('online-login'); }
1720 document.getElementById('btn-login').style.display = 'none';
1721 return;
1722 }
1723 renderOnline();
1724 if (Online.lobby)
1725 { Online.startPolling(onlinePayload); }
1726 });
1727}
1728
1729function setOnlineStatus (text)
1730{
1731 var el = document.getElementById('online-status');
1732 if (el)
1733 { el.textContent = text; }
1734}
1735
1736function showOnlineError (text)
1737{
1738 var el = document.getElementById('online-error');
1739 if (!el)
1740 { return; }
1741 if (!text)
1742 {
1743 el.hidden = true;
1744 el.textContent = '';
1745 return;
1746 }
1747 el.hidden = false;
1748 el.textContent = text;
1749}
1750
1751function showOnly (id)
1752{
1753 var ids = ['online-unconfigured', 'online-login', 'online-home', 'online-lobby'];
1754 for (var i = 0; i < ids.length; i++)
1755 { document.getElementById(ids[i]).hidden = (ids[i] !== id); }
1756}
1757
1758function renderOnline ()
1759{
1760 if (typeof Online === 'undefined')
1761 { return; }
1762 if (app.mode === 'playing' && app.online)
1763 {
1764 Online.renderMinis(document.getElementById('minis'));
1765 if (Online.lobby && Online.lobby.status === 'finished')
1766 { showPodium(Online.lobby); }
1767 return;
1768 }
1769 showOnlineError(Online.error);
1770 if (!Online.configured && !Online.me && !Online.local)
1771 {
1772 setOnlineStatus('Online spelen is nog niet ingesteld.');
1773 showOnly('online-unconfigured');
1774 return;
1775 }
1776 if (!Online.me)
1777 {
1778 setOnlineStatus('Log in om een lobby te maken of eraan deel te nemen.');
1779 showOnly('online-login');
1780 document.getElementById('btn-login').style.display = '';
1781 document.getElementById('btn-login').href = Online.loginUrl();
1782 document.getElementById('local-login').hidden = !Online.local;
1783 return;
1784 }
1785 if (Online.lobby)
1786 {
1787 setOnlineStatus('Lobby');
1788 showOnly('online-lobby');
1789 document.getElementById('lobby-me-name').textContent = Online.me.name;
1790 document.getElementById('lobby-code').textContent = Online.lobby.code;
1791 var list = document.getElementById('lobby-players');
1792 list.innerHTML = '';
1793 var players = Online.lobby.players || [];
1794 for (var i = 0; i < players.length; i++)
1795 {
1796 var p = players[i];
1797 var li = document.createElement('li');
1798 if (p.is_me)
1799 { li.classList.add('you'); }
1800 var label = p.name + (p.is_host ? ' (host)' : '') + (p.is_me ? ' (jij)' : '');
1801 var state = p.ready ? 'Gereed' : 'Wacht…';
1802 var world = (p.planet && p.planet.name) ? (p.planet.name + ' · ' + p.planet.people) : '';
1803 li.innerHTML = '<span>' + escapeText(label)
1804 + (world ? '<span class="planet-tag">' + escapeText(world) + '</span>' : '')
1805 + '</span><span class="'
1806 + (p.ready ? 'ready' : 'waiting') + '">' + state + '</span>';
1807 list.appendChild(li);
1808 }
1809 renderPlanetGrid('lobby-planet-grid', true);
1810 var me = Online.mePlayer();
1811 document.getElementById('btn-ready').textContent = (me && me.ready) ? 'Niet gereed' : 'Gereed';
1812 var start = document.getElementById('btn-start');
1813 start.hidden = !(Online.lobby && Online.me && Online.lobby.host_id === Online.me.id);
1814 start.disabled = !Online.lobby.can_start;
1815 var hint = document.getElementById('lobby-hint');
1816 if (Online.lobby.status === 'playing')
1817 { hint.textContent = 'Het spel start…'; }
1818 else if (players.length < 2)
1819 { hint.textContent = 'Wacht op minstens één andere speler. Deel de code.'; }
1820 else if (!Online.lobby.all_ready)
1821 { hint.textContent = 'Iedereen moet op Gereed drukken. De host start daarna.'; }
1822 else if (Online.lobby.can_start)
1823 { hint.textContent = 'Iedereen is gereed. Druk op Starten.'; }
1824 else
1825 { hint.textContent = 'Wachten tot de host start.'; }
1826 return;
1827 }
1828 setOnlineStatus('Hoi ' + Online.me.name + '. Maak een lobby of val in met een code.');
1829 showOnly('online-home');
1830 document.getElementById('me-name').textContent = Online.me.name;
1831 document.getElementById('local-login').hidden = !Online.local;
1832}
1833
1834function escapeText (s)
1835{
1836 return String(s)
1837 .replace(/&/g, '&amp;')
1838 .replace(/</g, '&lt;')
1839 .replace(/>/g, '&gt;')
1840 .replace(/"/g, '&quot;');
1841}
1842
1843
1844function selectedPlanetId ()
1845{
1846 if (app.selectedPlanetId)
1847 { return app.selectedPlanetId; }
1848 return 'terra';
1849}
1850
1851function restoreSelectedPlanet ()
1852{
1853 var id = 'terra';
1854 try
1855 { id = localStorage.getItem('meteors-planet') || 'terra'; }
1856 catch (e) {}
1857 setSelectedPlanet(id, true);
1858}
1859
1860function setSelectedPlanet (id, silent)
1861{
1862 var all = Planet.allPlanets();
1863 var found = null;
1864 for (var i = 0; i < all.length; i++)
1865 {
1866 if (all[i].id === id)
1867 { found = all[i]; break; }
1868 }
1869 if (!found)
1870 { found = Planet.defaultPlanet(); }
1871 app.selectedPlanetId = found.id;
1872 try
1873 { localStorage.setItem('meteors-planet', found.id); }
1874 catch (e) {}
1875 if (!silent)
1876 {
1877 var grid = document.getElementById('planet-grid');
1878 if (grid && !grid.hidden && grid.children.length)
1879 { renderPlanetGrid('planet-grid', false); }
1880 var lobby = document.getElementById('lobby-planet-grid');
1881 if (lobby && lobby.children.length)
1882 { renderPlanetGrid('lobby-planet-grid', true); }
1883 }
1884 return found;
1885}
1886
1887function openPlanetSelect (context)
1888{
1889 if (app.mode === 'playing')
1890 { return; }
1891 app.planetSelectContext = context || 'solo';
1892 app.mode = 'planet-select';
1893 hideEl('menu');
1894 hideEl('online-panel');
1895 hideEl('game-over');
1896 showEl('planet-select');
1897 renderPlanetGrid('planet-grid', false);
1898 var go = document.getElementById('btn-planet-go');
1899 if (go)
1900 { go.textContent = 'Spelen'; }
1901}
1902
1903function renderPlanetGrid (containerId, compact)
1904{
1905 var grid = document.getElementById(containerId);
1906 if (!grid)
1907 { return; }
1908 var current = selectedPlanetId();
1909 var all = Planet.allPlanets();
1910 grid.innerHTML = '';
1911 if (compact)
1912 { grid.classList.add('compact'); }
1913 for (var i = 0; i < all.length; i++)
1914 {
1915 var pl = all[i];
1916 var btn = document.createElement('button');
1917 btn.type = 'button';
1918 btn.className = 'planet-card' + (pl.id === current ? ' selected' : '');
1919 btn.setAttribute('role', 'listitem');
1920 btn.dataset.planet = pl.id;
1921 var swatches = '';
1922 for (var c = 0; c < pl.colors.length; c++)
1923 {
1924 swatches += '<img src="' + escapeText(pl.colors[c].image) + '" alt="'
1925 + escapeText(pl.colors[c].name) + '" title="' + escapeText(pl.colors[c].name) + '">';
1926 }
1927 btn.innerHTML = '<div class="planet-title">' + escapeText(pl.name) + '</div>'
1928 + '<div class="planet-people">' + escapeText(pl.people) + '</div>'
1929 + '<div class="planet-nums">' + escapeText(Planet.formatStats(pl)) + '</div>'
1930 + '<div class="planet-swatches">' + swatches + '</div>';
1931 btn.addEventListener('click', (function (id, isCompact)
1932 {
1933 return function ()
1934 { onPlanetPicked(id, isCompact); };
1935 })(pl.id, !!compact));
1936 grid.appendChild(btn);
1937 }
1938}
1939
1940function onPlanetPicked (id, fromLobby)
1941{
1942 setSelectedPlanet(id);
1943 if (fromLobby && typeof Online !== 'undefined' && Online.lobby)
1944 {
1945 Online.setPlanet(id).then(function ()
1946 { renderOnline(); });
1947 }
1948 else
1949 {
1950 renderPlanetGrid('planet-grid', false);
1951 }
1952}
1953
1954function confirmPlanetSelect ()
1955{
1956 var planet = setSelectedPlanet(selectedPlanetId());
1957 hideEl('planet-select');
1958 if (app.planetSelectContext === 'online')
1959 {
1960 openOnlinePanel();
1961 return;
1962 }
1963 if (app.planetSelectContext === 'offline')
1964 {
1965 startPlay({ planet: planet, offline: true });
1966 return;
1967 }
1968 startPlay({ planet: planet });
1969}
1970
1971function cancelPlanetSelect ()
1972{
1973 hideEl('planet-select');
1974 app.mode = 'menu';
1975 showEl('menu');
1976}
1977
1978function bindPlanetSelect ()
1979{
1980 var go = document.getElementById('btn-planet-go');
1981 var back = document.getElementById('btn-planet-back');
1982 if (go)
1983 {
1984 go.addEventListener('click', confirmPlanetSelect);
1985 }
1986 if (back)
1987 {
1988 back.addEventListener('click', cancelPlanetSelect);
1989 }
1990}