BlueGit

projects-timfalken-com meteors

Files

meteors / src / main.js

main.js

main.js 28.6 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.
8 */
9
10function planetImages ()
11{
12 var list = [
13 { name: 'gray', url: 'images/block-gray.png' },
14 { name: 'locked', url: 'images/block-locked.png' },
15 { name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 },
16 { name: 'cell', url: 'images/cell.png' },
17 { name: 'pixel', url: 'images/pixel.png' },
18 // Keep the original Terra placeholders as aliases (Tim may still have them).
19 { name: 'ember', url: 'images/block-ember.png' },
20 { name: 'aqua', url: 'images/block-aqua.png' },
21 { name: 'leaf', url: 'images/block-leaf.png' },
22 { name: 'sun', url: 'images/block-sun.png' },
23 { name: 'orchid', url: 'images/block-orchid.png' }
24 ];
25 var planets = (typeof Planet !== 'undefined' ? Planet.allPlanets() : []);
26 for (var i = 0; i < planets.length; i++)
27 {
28 var pl = planets[i];
29 for (var c = 0; c < pl.colors.length; c++)
30 {
31 list.push({
32 name: Planet.spriteKey(pl, c),
33 url: pl.colors[c].image
34 });
35 }
36 }
37 return list;
38}
39
40var IMAGES = planetImages();
41var GAME_OVER_DELAY = 2;
42
43var game = new Game();
44var app = {
45 mode: 'menu',
46 core: null,
47 scene: null,
48 manager: null,
49 planet: null,
50 lastScore: 0,
51 tile: 48,
52 fieldX: 0,
53 fieldY: 0,
54 fieldW: 0,
55 fieldH: 0,
56 hudH: 56,
57 sprites: Object.create(null),
58 flames: Object.create(null),
59 cells: [],
60 pointerId: null,
61 gameOverShown: false,
62 selectTween: null,
63 online: false,
64 eliminatedReported: false,
65 spectating: false,
66 miniH: 0,
67 selectedPlanetId: 'terra',
68 planetSelectContext: 'solo'
69};
70
71window.onload = function ()
72{
73 var play = document.getElementById('btn-play');
74 play.addEventListener('click', onPlay);
75 play.addEventListener('pointerup', function (e)
76 {
77 // A touch-friendly path: some mobile browsers swallow the click
78 // after a slightly sloppy tap. Ignore the following click.
79 if (e.pointerType === 'touch' || e.pointerType === 'pen')
80 {
81 e.preventDefault();
82 onPlay();
83 }
84 });
85
86 game.preloadImagesThenStart(IMAGES, function ()
87 {
88 if (game.images.flame && game.images.flame.addAnimationCycle)
89 { game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); }
90 });
91
92 bindOnlineUi();
93 bindPlanetSelect();
94 restoreSelectedPlanet();
95};
96
97function onPlay ()
98{
99 if (app.mode === 'playing')
100 { return; }
101 openPlanetSelect('solo');
102}
103
104function startPlay (opts)
105{
106 opts = opts || {};
107 hideEl('menu');
108 hideEl('game-over');
109 hideEl('online-panel');
110 hideEl('spectator');
111 hideEl('podium');
112 hideEl('planet-select');
113 showEl('hud');
114
115 var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod;
116 app.planet = opts.planet || planetMod.planetById(selectedPlanetId());
117 var miss = opts.missChance;
118 if (typeof miss !== 'number' || !isFinite(miss))
119 { miss = planetMod.missChance(app.planet); }
120 app.core = new GameCore(app.planet, Math.random, miss);
121 app.mode = 'playing';
122 app.online = !!opts.online;
123 app.gameOverShown = false;
124 app.eliminatedReported = false;
125 app.spectating = false;
126 app.sprites = Object.create(null);
127 app.flames = Object.create(null);
128 app.cells = [];
129 app.pointerId = null;
130 app.selectTween = null;
131
132 layout();
133 if (app.scene)
134 {
135 app.scene.destroy();
136 app.scene = null;
137 }
138 app.scene = new Scene(app.fieldX, app.fieldY, app.fieldW, app.fieldH);
139 app.scene.backgroundColor = { r: 12, g: 16, b: 32 };
140 app.scene.renderBackground = true;
141 game.loadScene(app.scene);
142
143 buildCells();
144 app.manager = app.scene.addObject(makeManager());
145 if (!app.spectating)
146 { bindPointer(app.scene.canvas); }
147 refreshHud();
148 if (app.online)
149 { showEl('minis'); }
150 else
151 { hideEl('minis'); }
152}
153
154function teardownPlay ()
155{
156 unbindPointer();
157 if (app.scene)
158 {
159 app.scene.destroy();
160 app.scene = null;
161 }
162 app.manager = null;
163 app.core = null;
164 app.sprites = Object.create(null);
165 app.flames = Object.create(null);
166 app.cells = [];
167 app.selectTween = null;
168 app.pointerId = null;
169 app.gameOverShown = false;
170 hideEl('hud');
171 hideEl('game-over');
172 hideEl('spectator');
173 hideEl('minis');
174 if (typeof Online !== 'undefined')
175 { Online.clearFlights(); }
176}
177
178function returnToMenu ()
179{
180 if (app.online && typeof Online !== 'undefined')
181 {
182 // Online matches do not dump you back to the solo menu:
183 // elimination becomes spectating; a finished match shows the podium.
184 return;
185 }
186 teardownPlay();
187 app.mode = 'menu';
188 app.online = false;
189 hideEl('planet-select');
190 showEl('menu');
191 var last = document.getElementById('last-score');
192 if (app.lastScore > 0)
193 {
194 last.hidden = false;
195 last.querySelector('strong').textContent = String(app.lastScore);
196 }
197}
198
199function buildCells ()
200{
201 if (!app.scene)
202 { return; }
203 var img = game.images.cell;
204 for (var row = 0; row < 13; row++)
205 {
206 for (var col = 0; col < 10; col++)
207 {
208 var obj = new GameObject(0, 0, img, 0);
209 placeTile(obj, col, row);
210 obj.renderer.alpha = 0.9;
211 app.scene.addObject(obj);
212 app.cells.push(obj);
213 }
214 }
215}
216
217function placeTile (obj, col, y)
218{
219 var t = app.tile;
220 obj.transform.position.x = col * t + t / 2;
221 obj.transform.position.y = app.fieldH - (y + 0.5) * t;
222 obj.transform.size = { x: t, y: t };
223}
224
225function layout ()
226{
227 var vw = window.innerWidth || 320;
228 var vh = window.innerHeight || 480;
229 var safeTop = 0;
230 try
231 {
232 // env(safe-area) is a CSS thing; keep a conservative HUD height.
233 safeTop = 0;
234 }
235 catch (e) { /* ignore */ }
236 app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop);
237 app.miniH = 0;
238 if (app.online)
239 { app.miniH = Math.min(150, Math.max(86, Math.round(vh * 0.20))); }
240 var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015));
241 var availW = Math.max(80, vw - margin * 2);
242 var availH = Math.max(80, vh - app.hudH - app.miniH - margin);
243 app.tile = Math.max(14, Math.floor(Math.min(availW / 10, availH / 13)));
244 app.fieldW = app.tile * 10;
245 app.fieldH = app.tile * 13;
246 app.fieldX = Math.floor((vw - app.fieldW) / 2);
247 var topBand = app.hudH + app.miniH;
248 app.fieldY = topBand + Math.floor((vh - topBand - app.fieldH - margin / 2) / 2);
249 if (app.fieldY < topBand)
250 { app.fieldY = topBand; }
251 var minis = document.getElementById('minis');
252 if (minis)
253 {
254 minis.style.top = app.hudH + 'px';
255 minis.style.maxHeight = app.miniH + 'px';
256 }
257
258 if (app.scene)
259 {
260 app.scene.position.x = app.fieldX;
261 app.scene.position.y = app.fieldY;
262 app.scene.size.x = app.fieldW;
263 app.scene.size.y = app.fieldH;
264 }
265}
266
267function spriteFor (block)
268{
269 if (block.state === 'locked')
270 { return game.images.locked; }
271 if (block.color < 0)
272 { return game.images.gray; }
273 var key = Planet.spriteKey(app.planet, block.color);
274 return game.images[key] || game.images.gray;
275}
276
277function syncSprites ()
278{
279 if (!app.core || !app.scene)
280 { return; }
281 var seen = Object.create(null);
282 var blocks = app.core.blocks;
283 for (var i = 0; i < blocks.length; i++)
284 {
285 var block = blocks[i];
286 seen[block.id] = true;
287 var obj = app.sprites[block.id];
288 if (!obj)
289 {
290 obj = new GameObject(0, 0, spriteFor(block), 2);
291 app.scene.addObject(obj);
292 app.sprites[block.id] = obj;
293 }
294 obj.renderer.sprite = spriteFor(block);
295 placeTile(obj, block.col, block.y);
296 applyBlockVisual(obj, block);
297 obj.renderer.visible = true;
298 obj.renderer.alpha = 1;
299
300 if (block.flame)
301 {
302 var flame = app.flames[block.id];
303 if (!flame)
304 {
305 flame = new GameObject(0, 0, game.images.flame, 1);
306 flame.renderer.setAnimation('burn', 0, 0.08);
307 app.scene.addObject(flame);
308 app.flames[block.id] = flame;
309 }
310 flame.renderer.visible = true;
311 var t = app.tile;
312 flame.transform.position.x = block.col * t + t / 2;
313 flame.transform.position.y = app.fieldH - block.y * t + t * 0.15;
314 flame.transform.size = { x: t * 0.85, y: t * 0.85 };
315 }
316 else if (app.flames[block.id])
317 { app.flames[block.id].renderer.visible = false; }
318 }
319
320 var ids = Object.keys(app.sprites);
321 for (var i = 0; i < ids.length; i++)
322 {
323 if (!seen[ids[i]])
324 {
325 app.sprites[ids[i]].destroy();
326 delete app.sprites[ids[i]];
327 if (app.flames[ids[i]])
328 {
329 app.flames[ids[i]].destroy();
330 delete app.flames[ids[i]];
331 }
332 }
333 }
334}
335
336function applyBlockVisual (obj, block)
337{
338 var t = app.tile;
339 var sx = 1;
340 var sy = 1;
341 var dy = 0;
342 if (block.bouncing && app.planet && app.planet.bounceDuration > 0
343 && typeof Easing !== 'undefined' && Easing.bouncePose)
344 {
345 var u = block.bounceAge / app.planet.bounceDuration;
346 var pose = Easing.bouncePose(u, app.planet.bounceSquash);
347 sx = pose.sx;
348 sy = pose.sy;
349 dy = pose.dy;
350 }
351 var sel = 1;
352 var tw = app.selectTween;
353 if (tw && tw.blockId === block.id && tw.phase !== 'idle')
354 { sel = tw.scale; }
355 obj.transform.size = { x: t * sx * sel, y: t * sy * sel };
356 if (dy)
357 { obj.transform.position.y -= dy * t; }
358}
359
360function clickTween ()
361{
362 return (typeof Easing !== 'undefined' && Easing.CLICK_TWEEN) ? Easing.CLICK_TWEEN : null;
363}
364
365function startPressTween (blockId)
366{
367 var c = clickTween();
368 if (!c)
369 { return; }
370 var from = (app.selectTween && app.selectTween.phase !== 'idle') ? app.selectTween.scale : 1;
371 app.selectTween = {
372 blockId: blockId,
373 from: from,
374 to: c.pressScale,
375 t: 0,
376 duration: c.pressDuration,
377 ease: c.pressEase,
378 scale: from,
379 phase: 'press'
380 };
381}
382
383function startReleaseTween ()
384{
385 var c = clickTween();
386 var tw = app.selectTween;
387 if (!c || !tw || tw.phase === 'idle')
388 { return; }
389 app.selectTween = {
390 blockId: tw.blockId,
391 from: tw.scale,
392 to: c.releaseScale,
393 t: 0,
394 duration: c.releaseDuration,
395 ease: c.releaseEase,
396 scale: tw.scale,
397 phase: 'release'
398 };
399}
400
401function updateSelectTween (dt)
402{
403 var tw = app.selectTween;
404 if (!tw || tw.phase === 'idle' || tw.phase === 'hold')
405 { return; }
406 tw.t += dt;
407 var u = tw.duration > 0 ? tw.t / tw.duration : 1;
408 if (u >= 1)
409 {
410 tw.scale = tw.to;
411 tw.t = tw.duration;
412 if (tw.phase === 'press')
413 { tw.phase = 'hold'; }
414 else
415 {
416 tw.phase = 'idle';
417 tw.scale = 1;
418 tw.blockId = null;
419 }
420 return;
421 }
422 var ease = tw.ease || (typeof Easing !== 'undefined' && Easing.easeOutBack);
423 tw.scale = ease ? Easing.tween(tw.from, tw.to, u, ease) : tw.from + (tw.to - tw.from) * u;
424}
425
426function refreshHud ()
427{
428 if (!app.core)
429 { return; }
430 document.getElementById('score').textContent = String(app.core.score);
431 var planet = app.planet;
432 document.getElementById('planet-name').textContent = planet.name + ' · ' + planet.people;
433 document.getElementById('planet-stats').textContent = Planet.formatStats(planet);
434}
435
436function makeManager ()
437{
438 var obj = new GameObject(0, 0, game.images.pixel, 0);
439 obj.renderer.visible = false;
440 var base = obj.update.bind(obj);
441 obj.update = function (dt)
442 {
443 base(dt);
444 tickView(dt);
445 };
446 return obj;
447}
448
449function tickView (dt)
450{
451 if (app.mode !== 'playing' || !app.core)
452 { return; }
453
454 layout();
455 for (var i = 0; i < app.cells.length; i++)
456 {
457 var col = i % 10;
458 var row = Math.floor(i / 10);
459 placeTile(app.cells[i], col, row);
460 }
461
462 app.core.tick(dt);
463 updateSelectTween(dt);
464 syncSprites();
465 refreshHud();
466 tickOnline(dt);
467
468 if (app.core.state === 'gameover' && !app.gameOverShown)
469 {
470 app.gameOverShown = true;
471 app.lastScore = app.core.score;
472 document.getElementById('go-score').textContent = String(app.lastScore);
473 if (app.online)
474 { onOnlineEliminated(); }
475 else
476 { showEl('game-over'); }
477 }
478 if (!app.online && app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY)
479 { returnToMenu(); }
480}
481
482/* ---------- pointer input (mouse + touch) --------------------------- */
483/*
484 * Both mouse and touch use Pointer Events. After pointerdown we listen
485 * on window, so a drag that leaves the canvas (needed to launch a
486 * block at the top of a full column) still reaches moveDrag. We do
487 * not treat lostpointercapture as the end of a drag: on some touch
488 * browsers that fires mid-gesture and would cancel a launch.
489 */
490
491var boundCanvas = null;
492var windowListening = false;
493
494function addWindowPointer ()
495{
496 if (windowListening)
497 { return; }
498 window.addEventListener('pointermove', onPointerMove, { capture: true, passive: false });
499 window.addEventListener('pointerup', onPointerUp, { capture: true, passive: false });
500 window.addEventListener('pointercancel', onPointerUp, { capture: true, passive: false });
501 windowListening = true;
502}
503
504function removeWindowPointer ()
505{
506 if (!windowListening)
507 { return; }
508 window.removeEventListener('pointermove', onPointerMove, { capture: true });
509 window.removeEventListener('pointerup', onPointerUp, { capture: true });
510 window.removeEventListener('pointercancel', onPointerUp, { capture: true });
511 windowListening = false;
512}
513
514function bindPointer (canvas)
515{
516 unbindPointer();
517 boundCanvas = canvas;
518 canvas.addEventListener('pointerdown', onPointerDown, { passive: false });
519 canvas.style.touchAction = 'none';
520 canvas.style.cursor = 'pointer';
521 canvas.style.webkitUserSelect = 'none';
522 canvas.style.userSelect = 'none';
523}
524
525function unbindPointer ()
526{
527 removeWindowPointer();
528 if (boundCanvas)
529 { boundCanvas.removeEventListener('pointerdown', onPointerDown); }
530 boundCanvas = null;
531 app.pointerId = null;
532}
533
534function fieldFromEvent (e)
535{
536 var canvas = app.scene && app.scene.canvas;
537 if (!canvas)
538 { return null; }
539 var rect = canvas.getBoundingClientRect();
540 if (rect.width <= 0 || rect.height <= 0)
541 { return null; }
542 // Map through the CSS box only. Using canvas.width / app.tile would
543 // scale the pointer by the backing-store ratio whenever that differs
544 // from the layout size (high-DPR devices), so a short finger move
545 // would look like a long swipe.
546 var width = Planet.FIELD_WIDTH;
547 var height = Planet.FIELD_HEIGHT;
548 var col = ((e.clientX - rect.left) / rect.width) * width;
549 var fieldY = (1 - (e.clientY - rect.top) / rect.height) * height;
550 return { col: col, y: fieldY };
551}
552
553function onPointerDown (e)
554{
555 if (!app.core || app.core.state !== 'playing')
556 { return; }
557 if (app.pointerId != null)
558 { return; }
559 e.preventDefault();
560 app.pointerId = e.pointerId;
561 try
562 { boundCanvas.setPointerCapture(e.pointerId); }
563 catch (err) { /* ignore */ }
564 addWindowPointer();
565 var pos = fieldFromEvent(e);
566 // Instant grab, no long-press or hold delay: the block is taken on
567 // pointerdown and the click tween starts in the same moment.
568 if (pos && app.core.beginDrag(pos.col, pos.y) && app.core.drag)
569 { startPressTween(app.core.drag.blockId); }
570}
571
572function onPointerMove (e)
573{
574 if (app.pointerId == null || e.pointerId !== app.pointerId)
575 { return; }
576 if (!app.core || !app.core.drag)
577 { return; }
578 e.preventDefault();
579 var pos = fieldFromEvent(e);
580 if (pos)
581 { app.core.moveDrag(pos.y); }
582}
583
584function onPointerUp (e)
585{
586 if (app.pointerId == null)
587 { return; }
588 if (e && e.pointerId != null && e.pointerId !== app.pointerId)
589 { return; }
590 if (e)
591 { e.preventDefault(); }
592 app.pointerId = null;
593 removeWindowPointer();
594 if (boundCanvas)
595 {
596 try
597 { boundCanvas.releasePointerCapture(e && e.pointerId); }
598 catch (err) { /* ignore */ }
599 }
600 startReleaseTween();
601 if (app.core)
602 { app.core.endDrag(); }
603}
604
605function hideEl (id)
606{
607 document.getElementById(id).hidden = true;
608}
609
610function showEl (id)
611{
612 document.getElementById(id).hidden = false;
613}
614
615window.addEventListener('resize', function ()
616{
617 if (app.mode === 'playing')
618 { layout(); }
619});
620
621window.addEventListener('orientationchange', function ()
622{
623 setTimeout(function ()
624 {
625 if (app.mode === 'playing')
626 { layout(); }
627 }, 120);
628});
629
630/* ---------- online play (stage 2) ---------------------------------- */
631
632function tickOnline (dt)
633{
634 if (!app.online || typeof Online === 'undefined')
635 { return; }
636 if (app.core)
637 {
638 var shots = app.core.consumeOutgoingShots();
639 for (var i = 0; i < shots.length; i++)
640 {
641 var s = shots[i];
642 var start = fieldToViewport(s.col, s.y + 1);
643 Online.rememberFlightLocal(s, start.x, start.y);
644 }
645 Online.queueShots(shots);
646 }
647 Online.tickFlights();
648 Online.renderMinis(document.getElementById('minis'));
649}
650
651function fieldToViewport (col, fieldY)
652{
653 var canvas = app.scene && app.scene.canvas;
654 if (!canvas)
655 { return { x: window.innerWidth / 2, y: 40 }; }
656 var rect = canvas.getBoundingClientRect();
657 var x = rect.left + ((col + 0.5) / 10) * rect.width;
658 var y = rect.top + (1 - (fieldY / 13)) * rect.height;
659 return { x: x, y: y };
660}
661
662function onlinePayload ()
663{
664 if (!app.online || !app.core)
665 { return {}; }
666 return {
667 snapshot: app.core.fieldSnapshot(),
668 score: app.core.score,
669 eliminated: app.core.state === 'gameover' || app.spectating || app.eliminatedReported
670 };
671}
672
673function onOnlineEliminated ()
674{
675 app.eliminatedReported = true;
676 app.spectating = true;
677 unbindPointer();
678 hideEl('game-over');
679 var lobby = typeof Online !== 'undefined' && Online.lobby;
680 if (lobby && lobby.status === 'finished')
681 {
682 showPodium(lobby);
683 return;
684 }
685 showEl('spectator');
686}
687
688function showPodium (lobby)
689{
690 hideEl('spectator');
691 hideEl('game-over');
692 hideEl('online-panel');
693 showEl('podium');
694 var list = document.getElementById('podium-list');
695 list.innerHTML = '';
696 var ranks = (lobby && lobby.rankings) || [];
697 for (var i = 0; i < ranks.length; i++)
698 {
699 var r = ranks[i];
700 var li = document.createElement('li');
701 var medal = r.place === 1 ? '1e' : (r.place === 2 ? '2e' : (r.place === 3 ? '3e' : r.place + 'e'));
702 li.textContent = medal + ' ' + r.name + ' · ' + r.score + ' punten';
703 list.appendChild(li);
704 }
705 var hint = document.getElementById('podium-hint');
706 var secs = (lobby && lobby.podium_seconds) || 5;
707 hint.textContent = 'Over ' + secs + ' seconden teruggaan naar de lobby…';
708}
709
710function startOnlineMatch ()
711{
712 if (app.mode === 'playing' && app.online)
713 { return; }
714 var planet = Planet.planetById(selectedPlanetId());
715 var me = (typeof Online !== 'undefined' && Online.mePlayer) ? Online.mePlayer() : null;
716 if (me && me.planet && me.planet.id)
717 { planet = Planet.planetById(me.planet.id); }
718 startPlay({ online: true, planet: planet, missChance: Planet.missChance(planet) });
719 if (typeof Online !== 'undefined')
720 { Online.startPolling(onlinePayload); }
721}
722
723function leaveOnlineMatch (goMenu)
724{
725 if (typeof Online !== 'undefined')
726 {
727 Online.stopPolling();
728 Online.leaveLobby();
729 Online.clearFlights();
730 }
731 teardownPlay();
732 app.online = false;
733 if (goMenu)
734 {
735 app.mode = 'menu';
736 showEl('menu');
737 }
738 else
739 {
740 app.mode = 'online';
741 openOnlinePanel();
742 }
743}
744
745function bindOnlineUi ()
746{
747 var onlineBtn = document.getElementById('btn-online');
748 if (!onlineBtn)
749 { return; }
750 onlineBtn.addEventListener('click', function ()
751 { openOnlinePanel(); });
752
753 var backs = document.querySelectorAll('[data-back-menu]');
754 for (var i = 0; i < backs.length; i++)
755 {
756 backs[i].addEventListener('click', function ()
757 {
758 if (typeof Online !== 'undefined')
759 { Online.stopPolling(); }
760 hideEl('online-panel');
761 app.mode = 'menu';
762 app.online = false;
763 showEl('menu');
764 });
765 }
766
767 document.getElementById('btn-create').addEventListener('click', function ()
768 {
769 Online.createLobby().then(function (data)
770 {
771 if (data && data.ok)
772 {
773 renderOnline();
774 Online.startPolling(onlinePayload);
775 }
776 else
777 { renderOnline(); }
778 });
779 });
780
781 document.getElementById('join-form').addEventListener('submit', function (e)
782 {
783 e.preventDefault();
784 var code = (document.getElementById('join-code').value || '').trim();
785 if (!code)
786 { return; }
787 Online.joinLobby(code).then(function ()
788 {
789 renderOnline();
790 if (Online.lobby)
791 { Online.startPolling(onlinePayload); }
792 });
793 });
794
795 document.getElementById('btn-ready').addEventListener('click', function ()
796 {
797 var me = Online.mePlayer();
798 Online.setReady(!(me && me.ready)).then(renderOnline);
799 });
800
801 document.getElementById('btn-start').addEventListener('click', function ()
802 {
803 Online.startGame().then(function (data)
804 {
805 if (data && data.ok)
806 { startOnlineMatch(); }
807 else
808 { renderOnline(); }
809 });
810 });
811
812 document.getElementById('btn-leave-lobby').addEventListener('click', function ()
813 {
814 Online.leaveLobby().then(function ()
815 {
816 Online.stopPolling();
817 renderOnline();
818 });
819 });
820
821 document.getElementById('btn-copy-code').addEventListener('click', function ()
822 {
823 var code = document.getElementById('lobby-code').textContent;
824 if (navigator.clipboard && navigator.clipboard.writeText)
825 { navigator.clipboard.writeText(code); }
826 });
827
828 document.getElementById('btn-spectate').addEventListener('click', function ()
829 {
830 hideEl('spectator');
831 app.spectating = true;
832 });
833
834 document.getElementById('btn-leave-game').addEventListener('click', function ()
835 { leaveOnlineMatch(false); });
836
837 if (typeof Online !== 'undefined')
838 {
839 Online.onChange = function ()
840 { renderOnline(); };
841 Online.onGameStart = function ()
842 { startOnlineMatch(); };
843 Online.onIncoming = function (incoming)
844 {
845 if (!app.core || app.core.state !== 'playing')
846 { return; }
847 for (var i = 0; i < incoming.length; i++)
848 { app.core.ingestGarbage(); }
849 };
850 Online.onFinished = function (lobby)
851 { showPodium(lobby); };
852 Online.onLobbyReturn = function (lobby)
853 {
854 teardownPlay();
855 app.online = false;
856 app.mode = 'online';
857 hideEl('podium');
858 showEl('online-panel');
859 renderOnline();
860 Online.startPolling(onlinePayload);
861 };
862 }
863
864 var params = new URLSearchParams(window.location.search);
865 if (params.get('online') === '1' || params.get('auth') === 'unconfigured')
866 { openOnlinePanel(); }
867}
868
869function openOnlinePanel ()
870{
871 hideEl('menu');
872 hideEl('game-over');
873 hideEl('podium');
874 hideEl('spectator');
875 hideEl('planet-select');
876 showEl('online-panel');
877 app.mode = 'online';
878 setOnlineStatus('Even kijken of online spelen beschikbaar is…');
879 if (typeof Online === 'undefined')
880 {
881 showOnlineError('Online spelen is in deze build niet geladen. Je kunt wel alleen spelen.');
882 showOnly('online-unconfigured');
883 return;
884 }
885 Online.refresh().then(function (data)
886 {
887 if (!data || data.ok === false)
888 {
889 var msg = (data && data.error) || 'Geen verbinding met de server.';
890 showOnlineError(msg + ' Je kunt wel alleen spelen.');
891 if (data && data.configured === false)
892 { showOnly('online-unconfigured'); }
893 else
894 { showOnly('online-login'); }
895 document.getElementById('btn-login').style.display = 'none';
896 return;
897 }
898 renderOnline();
899 if (Online.lobby)
900 { Online.startPolling(onlinePayload); }
901 });
902}
903
904function setOnlineStatus (text)
905{
906 var el = document.getElementById('online-status');
907 if (el)
908 { el.textContent = text; }
909}
910
911function showOnlineError (text)
912{
913 var el = document.getElementById('online-error');
914 if (!el)
915 { return; }
916 if (!text)
917 {
918 el.hidden = true;
919 el.textContent = '';
920 return;
921 }
922 el.hidden = false;
923 el.textContent = text;
924}
925
926function showOnly (id)
927{
928 var ids = ['online-unconfigured', 'online-login', 'online-home', 'online-lobby'];
929 for (var i = 0; i < ids.length; i++)
930 { document.getElementById(ids[i]).hidden = (ids[i] !== id); }
931}
932
933function renderOnline ()
934{
935 if (typeof Online === 'undefined')
936 { return; }
937 if (app.mode === 'playing' && app.online)
938 {
939 Online.renderMinis(document.getElementById('minis'));
940 if (Online.lobby && Online.lobby.status === 'finished')
941 { showPodium(Online.lobby); }
942 return;
943 }
944 showOnlineError(Online.error);
945 if (!Online.configured && !Online.me && !Online.local)
946 {
947 setOnlineStatus('Online spelen is nog niet ingesteld.');
948 showOnly('online-unconfigured');
949 return;
950 }
951 if (!Online.me)
952 {
953 setOnlineStatus('Log in om een lobby te maken of eraan deel te nemen.');
954 showOnly('online-login');
955 document.getElementById('btn-login').style.display = '';
956 document.getElementById('btn-login').href = Online.loginUrl();
957 document.getElementById('local-login').hidden = !Online.local;
958 return;
959 }
960 if (Online.lobby)
961 {
962 setOnlineStatus('Lobby');
963 showOnly('online-lobby');
964 document.getElementById('lobby-me-name').textContent = Online.me.name;
965 document.getElementById('lobby-code').textContent = Online.lobby.code;
966 var list = document.getElementById('lobby-players');
967 list.innerHTML = '';
968 var players = Online.lobby.players || [];
969 for (var i = 0; i < players.length; i++)
970 {
971 var p = players[i];
972 var li = document.createElement('li');
973 if (p.is_me)
974 { li.classList.add('you'); }
975 var label = p.name + (p.is_host ? ' (host)' : '') + (p.is_me ? ' (jij)' : '');
976 var state = p.ready ? 'Gereed' : 'Wacht…';
977 var world = (p.planet && p.planet.name) ? (p.planet.name + ' · ' + p.planet.people) : '';
978 li.innerHTML = '<span>' + escapeText(label)
979 + (world ? '<span class="planet-tag">' + escapeText(world) + '</span>' : '')
980 + '</span><span class="'
981 + (p.ready ? 'ready' : 'waiting') + '">' + state + '</span>';
982 list.appendChild(li);
983 }
984 renderPlanetGrid('lobby-planet-grid', true);
985 var me = Online.mePlayer();
986 document.getElementById('btn-ready').textContent = (me && me.ready) ? 'Niet gereed' : 'Gereed';
987 var start = document.getElementById('btn-start');
988 start.hidden = !(Online.lobby && Online.me && Online.lobby.host_id === Online.me.id);
989 start.disabled = !Online.lobby.can_start;
990 var hint = document.getElementById('lobby-hint');
991 if (Online.lobby.status === 'playing')
992 { hint.textContent = 'Het spel start…'; }
993 else if (players.length < 2)
994 { hint.textContent = 'Wacht op minstens één andere speler. Deel de code.'; }
995 else if (!Online.lobby.all_ready)
996 { hint.textContent = 'Iedereen moet op Gereed drukken. De host start daarna.'; }
997 else if (Online.lobby.can_start)
998 { hint.textContent = 'Iedereen is gereed. Druk op Starten.'; }
999 else
1000 { hint.textContent = 'Wachten tot de host start.'; }
1001 return;
1002 }
1003 setOnlineStatus('Hoi ' + Online.me.name + '. Maak een lobby of val in met een code.');
1004 showOnly('online-home');
1005 document.getElementById('me-name').textContent = Online.me.name;
1006 document.getElementById('local-login').hidden = !Online.local;
1007}
1008
1009function escapeText (s)
1010{
1011 return String(s)
1012 .replace(/&/g, '&amp;')
1013 .replace(/</g, '&lt;')
1014 .replace(/>/g, '&gt;')
1015 .replace(/"/g, '&quot;');
1016}
1017
1018
1019function selectedPlanetId ()
1020{
1021 if (app.selectedPlanetId)
1022 { return app.selectedPlanetId; }
1023 return 'terra';
1024}
1025
1026function restoreSelectedPlanet ()
1027{
1028 var id = 'terra';
1029 try
1030 { id = localStorage.getItem('meteors-planet') || 'terra'; }
1031 catch (e) {}
1032 setSelectedPlanet(id, true);
1033}
1034
1035function setSelectedPlanet (id, silent)
1036{
1037 var all = Planet.allPlanets();
1038 var found = null;
1039 for (var i = 0; i < all.length; i++)
1040 {
1041 if (all[i].id === id)
1042 { found = all[i]; break; }
1043 }
1044 if (!found)
1045 { found = Planet.defaultPlanet(); }
1046 app.selectedPlanetId = found.id;
1047 try
1048 { localStorage.setItem('meteors-planet', found.id); }
1049 catch (e) {}
1050 if (!silent)
1051 {
1052 var grid = document.getElementById('planet-grid');
1053 if (grid && !grid.hidden && grid.children.length)
1054 { renderPlanetGrid('planet-grid', false); }
1055 var lobby = document.getElementById('lobby-planet-grid');
1056 if (lobby && lobby.children.length)
1057 { renderPlanetGrid('lobby-planet-grid', true); }
1058 }
1059 return found;
1060}
1061
1062function openPlanetSelect (context)
1063{
1064 if (app.mode === 'playing')
1065 { return; }
1066 app.planetSelectContext = context || 'solo';
1067 app.mode = 'planet-select';
1068 hideEl('menu');
1069 hideEl('online-panel');
1070 hideEl('game-over');
1071 showEl('planet-select');
1072 renderPlanetGrid('planet-grid', false);
1073 var go = document.getElementById('btn-planet-go');
1074 if (go)
1075 { go.textContent = 'Spelen'; }
1076}
1077
1078function renderPlanetGrid (containerId, compact)
1079{
1080 var grid = document.getElementById(containerId);
1081 if (!grid)
1082 { return; }
1083 var current = selectedPlanetId();
1084 var all = Planet.allPlanets();
1085 grid.innerHTML = '';
1086 if (compact)
1087 { grid.classList.add('compact'); }
1088 for (var i = 0; i < all.length; i++)
1089 {
1090 var pl = all[i];
1091 var btn = document.createElement('button');
1092 btn.type = 'button';
1093 btn.className = 'planet-card' + (pl.id === current ? ' selected' : '');
1094 btn.setAttribute('role', 'listitem');
1095 btn.dataset.planet = pl.id;
1096 var swatches = '';
1097 for (var c = 0; c < pl.colors.length; c++)
1098 {
1099 swatches += '<img src="' + escapeText(pl.colors[c].image) + '" alt="'
1100 + escapeText(pl.colors[c].name) + '" title="' + escapeText(pl.colors[c].name) + '">';
1101 }
1102 btn.innerHTML = '<div class="planet-title">' + escapeText(pl.name) + '</div>'
1103 + '<div class="planet-people">' + escapeText(pl.people) + '</div>'
1104 + '<div class="planet-nums">' + escapeText(Planet.formatStats(pl)) + '</div>'
1105 + '<div class="planet-swatches">' + swatches + '</div>';
1106 btn.addEventListener('click', (function (id, isCompact)
1107 {
1108 return function ()
1109 { onPlanetPicked(id, isCompact); };
1110 })(pl.id, !!compact));
1111 grid.appendChild(btn);
1112 }
1113}
1114
1115function onPlanetPicked (id, fromLobby)
1116{
1117 setSelectedPlanet(id);
1118 if (fromLobby && typeof Online !== 'undefined' && Online.lobby)
1119 {
1120 Online.setPlanet(id).then(function ()
1121 { renderOnline(); });
1122 }
1123 else
1124 {
1125 renderPlanetGrid('planet-grid', false);
1126 }
1127}
1128
1129function confirmPlanetSelect ()
1130{
1131 var planet = setSelectedPlanet(selectedPlanetId());
1132 hideEl('planet-select');
1133 if (app.planetSelectContext === 'online')
1134 {
1135 openOnlinePanel();
1136 return;
1137 }
1138 startPlay({ planet: planet });
1139}
1140
1141function cancelPlanetSelect ()
1142{
1143 hideEl('planet-select');
1144 app.mode = 'menu';
1145 showEl('menu');
1146}
1147
1148function bindPlanetSelect ()
1149{
1150 var go = document.getElementById('btn-planet-go');
1151 var back = document.getElementById('btn-planet-back');
1152 if (go)
1153 {
1154 go.addEventListener('click', confirmPlanetSelect);
1155 }
1156 if (back)
1157 {
1158 back.addEventListener('click', cancelPlanetSelect);
1159 }
1160}