BlueGit

projects-timfalken-com meteors

feat: wire the online lobby, minis, shots and podium into the game

main.js talks to Online for login, lobby create/join/ready/start,
polling, opponent miniatures above the field, incoming grey garbage,
flight tweens, spectating and the 5s podium. Solo play is unchanged.
online.js is concatenated into game.js; startGame also fires the
playing transition so the host enters the match immediately.

timfa Grok Bot · pushed by timfa

Authored 2026-11-13 · 4 days ago

Hash
02ce71445408474302a998df556dc8990c0d49d7
Parent
0140f754
4 files changed +1559 −32
build/game.js +1079 −16
@@ -443,6 +443,17 @@ function GameCore (planet, rng)
443 443 this.state = 'playing';
444 444 this.drag = null;
445 445 this.gameOverTime = 0;
446 this.outgoingShots = [];
447 // Stage-2 default; stage 3 replaces this with Planet.missChance (Power).
448 this.missChance = optsMissChance(arguments);
449 }
450
451 function optsMissChance (args)
452 {
453 // GameCore(planet, rng, missChance) — third arg is optional.
454 if (args.length >= 3 && typeof args[2] === 'number' && isFinite(args[2]))
455 { return Math.max(0, Math.min(1, args[2])); }
456 return GameCore.DEFAULT_MISS_CHANCE;
446 457 }
447 458
448 459 GameCore.COLOR_GRAY = COLOR_GRAY;
@@ -450,6 +461,7 @@ GameCore.LAUNCH_PULL = LAUNCH_PULL;
450 461 GameCore.SWAP_DISTANCE = SWAP_DISTANCE;
451 462 GameCore.SNAP_Y = SNAP_Y;
452 463 GameCore.HORIZONTAL_SLOP = HORIZONTAL_SLOP;
464 GameCore.DEFAULT_MISS_CHANCE = 0.30;
453 465 GameCore.STATE_STILL = STATE_STILL;
454 466 GameCore.STATE_FALLING = STATE_FALLING;
455 467 GameCore.STATE_FLYING = STATE_FLYING;
@@ -1508,9 +1520,88 @@ GameCore.prototype.cullOffTop = function ()
1508 1520 }
1509 1521 for (var i = 0; i < gone.length; i++)
1510 1522 {
1523 var block = gone[i];
1524 this.outgoingShots.push({
1525 id: block.id,
1526 color: block.color,
1527 col: block.col,
1528 y: block.y
1529 });
1511 1530 this.score += 1;
1512 this.removeBlock(gone[i]);
1531 this.removeBlock(block);
1532 }
1533 };
1534
1535 GameCore.prototype.consumeOutgoingShots = function ()
1536 {
1537 var shots = this.outgoingShots;
1538 this.outgoingShots = [];
1539 return shots;
1540 };
1541
1542 /**
1543 * A compact field picture for the multiplayer snapshot (miniatures).
1544 * Includes every block's col, y, color, state and flame.
1545 */
1546 GameCore.prototype.fieldSnapshot = function ()
1547 {
1548 var blocks = [];
1549 for (var i = 0; i < this.blocks.length; i++)
1550 {
1551 var b = this.blocks[i];
1552 blocks.push({
1553 id: b.id,
1554 col: b.col,
1555 y: Math.round(b.y * 1000) / 1000,
1556 color: b.color,
1557 state: b.state,
1558 flame: !!b.flame
1559 });
1560 }
1561 return {
1562 score: this.score,
1563 state: this.state,
1564 width: this.width,
1565 height: this.height,
1566 locked: this.lockedColumnCount(),
1567 blocks: blocks
1568 };
1569 };
1570
1571 /**
1572 * Incoming garbage from another player: a dark-grey block that falls
1573 * normally from the top of an open column. After landing it uses the
1574 * usual 3s settle and then a random colour (landFallingBlock).
1575 * `col` is optional; a random eligible column is used otherwise.
1576 * Returns the new block, or null if every column is locked or full.
1577 */
1578 GameCore.prototype.ingestGarbage = function (col)
1579 {
1580 if (this.state !== 'playing')
1581 { return null; }
1582 var chosen = null;
1583 if (col != null && col >= 0 && col < this.width
1584 && !this.isColumnLocked(col) && this.groundedCount(col) < this.height)
1585 { chosen = col | 0; }
1586 else
1587 {
1588 var eligible = [];
1589 for (var c = 0; c < this.width; c++)
1590 {
1591 if (this.isColumnLocked(c))
1592 { continue; }
1593 if (this.groundedCount(c) >= this.height)
1594 { continue; }
1595 eligible.push(c);
1596 }
1597 if (!eligible.length)
1598 { return null; }
1599 chosen = eligible[Math.floor(this.rng() * eligible.length) % eligible.length];
1513 1600 }
1601 var block = this.createBlock(chosen, this.height, COLOR_GRAY, STATE_FALLING);
1602 block.vy = -this.planet.fallSpeed;
1603 block.flame = false;
1604 return block;
1514 1605 };
1515 1606
1516 1607 GameCore.prototype.advanceSettle = function (dt)
@@ -2188,6 +2279,538 @@ else if (typeof globalThis !== 'undefined')
2188 2279 * /workspace/meteors/src/gameCore.js
2189 2280 */
2190 2281
2282 /*
2283 * Start File:
2284 * /workspace/meteors/src/online.js
2285 */
2286 'use strict';
2287
2288 /**
2289 * Online play: talks to api.php (cookie session), polls lobby and game
2290 * state, and draws opponent miniatures plus flying-block tweens.
2291 * Real-time sync is not required; a 0.75 s poll is enough.
2292 */
2293
2294 var Online = {
2295 POLL_MS: 750,
2296 DEFAULT_MISS_CHANCE: 0.30,
2297 FLIGHT_DURATION: 1.2,
2298 configured: false,
2299 local: false,
2300 csrf: '',
2301 me: null,
2302 lobby: null,
2303 incoming: [],
2304 shotResults: [],
2305 error: '',
2306 _timer: null,
2307 _pendingShots: [],
2308 _flights: [],
2309 _lastStatus: null,
2310 onChange: null,
2311 onGameStart: null,
2312 onIncoming: null,
2313 onFinished: null,
2314 onLobbyReturn: null
2315 };
2316
2317 Online._headers = function (json)
2318 {
2319 var h = { 'Accept': 'application/json' };
2320 if (json)
2321 { h['Content-Type'] = 'application/json'; }
2322 if (this.csrf)
2323 { h['X-CSRF-Token'] = this.csrf; }
2324 return h;
2325 };
2326
2327 Online._apply = function (data)
2328 {
2329 if (!data)
2330 { return; }
2331 if (typeof data.configured === 'boolean')
2332 { this.configured = data.configured; }
2333 if (typeof data.local === 'boolean')
2334 { this.local = data.local; }
2335 if (data.csrf)
2336 { this.csrf = data.csrf; }
2337 if (data.me !== undefined)
2338 { this.me = data.me; }
2339 if (data.lobby !== undefined)
2340 { this.lobby = data.lobby; }
2341 if (data.incoming)
2342 { this.incoming = data.incoming; }
2343 if (data.shot_results)
2344 { this.shotResults = data.shot_results; }
2345 if (data.miss_chance_default != null)
2346 { this.DEFAULT_MISS_CHANCE = data.miss_chance_default; }
2347 if (data.flight_duration != null)
2348 { this.FLIGHT_DURATION = data.flight_duration; }
2349 if (data.error)
2350 { this.error = data.error; }
2351 else if (data.ok)
2352 { this.error = ''; }
2353 };
2354
2355 Online.request = function (action, body)
2356 {
2357 var self = this;
2358 var isGet = action === 'me' || action === '';
2359 var url = 'api.php?action=' + encodeURIComponent(action || 'me');
2360 var opts = {
2361 method: isGet && !body ? 'GET' : 'POST',
2362 credentials: 'same-origin',
2363 headers: this._headers(!!body || !isGet)
2364 };
2365 if (opts.method === 'POST')
2366 {
2367 var payload = body ? Object.assign({ action: action }, body) : { action: action };
2368 opts.body = JSON.stringify(payload);
2369 }
2370 return fetch(url, opts).then(function (res)
2371 {
2372 return res.json().then(function (data)
2373 {
2374 data = data || {};
2375 if (!res.ok && !data.error)
2376 { data.error = 'De server gaf ' + res.status; data.ok = false; }
2377 self._apply(data);
2378 return data;
2379 }, function ()
2380 {
2381 var fail = { ok: false, error: 'Geen geldig antwoord van de server.' };
2382 self.error = fail.error;
2383 return fail;
2384 });
2385 }).catch(function (err)
2386 {
2387 var fail = { ok: false, error: 'Geen verbinding met de server.' };
2388 self.error = fail.error;
2389 return fail;
2390 });
2391 };
2392
2393 Online.refresh = function ()
2394 {
2395 return this.request('me');
2396 };
2397
2398 Online.testLogin = function (who)
2399 {
2400 return this.request('test_login', { user: who });
2401 };
2402
2403 Online.createLobby = function ()
2404 {
2405 return this.request('lobby_create', { miss_chance: this.DEFAULT_MISS_CHANCE });
2406 };
2407
2408 Online.joinLobby = function (code)
2409 {
2410 return this.request('lobby_join', { code: code });
2411 };
2412
2413 Online.leaveLobby = function ()
2414 {
2415 return this.request('lobby_leave');
2416 };
2417
2418 Online.setReady = function (ready)
2419 {
2420 return this.request('lobby_ready', { ready: !!ready });
2421 };
2422
2423 Online.startGame = function ()
2424 {
2425 var self = this;
2426 var prev = this.lobby && this.lobby.status;
2427 return this.request('lobby_start').then(function (data)
2428 {
2429 self._handleTransitions(prev, data);
2430 return data;
2431 });
2432 };
2433
2434 Online.queueShots = function (shots)
2435 {
2436 for (var i = 0; i < shots.length; i++)
2437 {
2438 this._pendingShots.push({
2439 client_id: String(shots[i].id),
2440 color: shots[i].color,
2441 col: shots[i].col,
2442 y: shots[i].y
2443 });
2444 }
2445 };
2446
2447 Online.poll = function (opts)
2448 {
2449 opts = opts || {};
2450 var body = {};
2451 if (opts.snapshot)
2452 { body.snapshot = opts.snapshot; }
2453 if (opts.score != null)
2454 { body.score = opts.score; }
2455 if (opts.eliminated)
2456 { body.eliminated = true; }
2457 if (this._pendingShots.length)
2458 {
2459 body.outgoing_shots = this._pendingShots.splice(0, this._pendingShots.length);
2460 }
2461 var self = this;
2462 var prevStatus = this.lobby && this.lobby.status;
2463 return this.request('poll', body).then(function (data)
2464 {
2465 self._handleTransitions(prevStatus, data);
2466 if (self.onChange)
2467 { self.onChange(self); }
2468 return data;
2469 });
2470 };
2471
2472 Online._handleTransitions = function (prevStatus, data)
2473 {
2474 var lobby = this.lobby;
2475 var status = lobby && lobby.status;
2476 if (status === 'playing' && prevStatus !== 'playing' && this.onGameStart)
2477 { this.onGameStart(lobby); }
2478 if (data && data.incoming && data.incoming.length && this.onIncoming)
2479 { this.onIncoming(data.incoming); }
2480 if (data && data.shot_results && data.shot_results.length)
2481 { this.spawnFlights(data.shot_results, this._lastQueuedMeta); }
2482 if (status === 'finished' && prevStatus !== 'finished' && this.onFinished)
2483 { this.onFinished(lobby); }
2484 if (status === 'waiting' && prevStatus === 'finished' && this.onLobbyReturn)
2485 { this.onLobbyReturn(lobby); }
2486 };
2487
2488 Online.startPolling = function (getPayload)
2489 {
2490 this.stopPolling();
2491 var self = this;
2492 var tick = function ()
2493 {
2494 var payload = getPayload ? getPayload() : {};
2495 self.poll(payload);
2496 };
2497 tick();
2498 this._timer = setInterval(tick, this.POLL_MS);
2499 };
2500
2501 Online.stopPolling = function ()
2502 {
2503 if (this._timer)
2504 {
2505 clearInterval(this._timer);
2506 this._timer = null;
2507 }
2508 };
2509
2510 Online.loginUrl = function ()
2511 {
2512 return 'auth.php';
2513 };
2514
2515 Online.logoutUrl = function ()
2516 {
2517 return 'logout.php';
2518 };
2519
2520 Online.opponents = function ()
2521 {
2522 if (!this.lobby || !this.lobby.players)
2523 { return []; }
2524 return this.lobby.players.filter(function (p) { return !p.is_me; });
2525 };
2526
2527 Online.aliveOpponents = function ()
2528 {
2529 return this.opponents().filter(function (p) { return !p.eliminated; });
2530 };
2531
2532 Online.mePlayer = function ()
2533 {
2534 if (!this.lobby || !this.lobby.players)
2535 { return null; }
2536 for (var i = 0; i < this.lobby.players.length; i++)
2537 {
2538 if (this.lobby.players[i].is_me)
2539 { return this.lobby.players[i]; }
2540 }
2541 return null;
2542 };
2543
2544 /* ---------- miniatures --------------------------------------------- */
2545
2546 Online.renderMinis = function (container)
2547 {
2548 if (!container)
2549 { return; }
2550 var opponents = this.opponents();
2551 var existing = {};
2552 var kids = container.querySelectorAll('[data-player]');
2553 for (var i = 0; i < kids.length; i++)
2554 { existing[kids[i].getAttribute('data-player')] = kids[i]; }
2555
2556 var seen = Object.create(null);
2557 for (var i = 0; i < opponents.length; i++)
2558 {
2559 var p = opponents[i];
2560 seen[p.id] = true;
2561 var el = existing[p.id];
2562 if (!el)
2563 {
2564 el = document.createElement('div');
2565 el.className = 'mini';
2566 el.setAttribute('data-player', p.id);
2567 el.innerHTML = '<div class="mini-name"></div>'
2568 + '<canvas class="mini-canvas" width="80" height="104"></canvas>'
2569 + '<div class="mini-meta"></div>';
2570 container.appendChild(el);
2571 }
2572 el.classList.toggle('eliminated', !!p.eliminated);
2573 el.querySelector('.mini-name').textContent = p.name + (p.is_host ? ' (host)' : '');
2574 el.querySelector('.mini-meta').textContent = p.eliminated
2575 ? ('Uit' + (p.place ? ' · ' + p.place + 'e' : ''))
2576 : ('Punten ' + (p.score || 0));
2577 this._drawMini(el.querySelector('canvas'), p.snapshot);
2578 }
2579 for (var id in existing)
2580 {
2581 if (!seen[id])
2582 { existing[id].remove(); }
2583 }
2584 };
2585
2586 var MINI_COLORS = ['#d4553a', '#3a9ad4', '#4caf6a', '#e6c04a', '#b86ad4'];
2587
2588 Online._drawMini = function (canvas, snapshot)
2589 {
2590 if (!canvas)
2591 { return; }
2592 var ctx = canvas.getContext('2d');
2593 var w = 10;
2594 var h = 13;
2595 var tw = canvas.width / w;
2596 var th = canvas.height / h;
2597 ctx.fillStyle = '#0c1020';
2598 ctx.fillRect(0, 0, canvas.width, canvas.height);
2599 ctx.strokeStyle = 'rgba(255,255,255,0.06)';
2600 ctx.lineWidth = 1;
2601 for (var c = 0; c <= w; c++)
2602 {
2603 ctx.beginPath();
2604 ctx.moveTo(c * tw + 0.5, 0);
2605 ctx.lineTo(c * tw + 0.5, canvas.height);
2606 ctx.stroke();
2607 }
2608 for (var r = 0; r <= h; r++)
2609 {
2610 ctx.beginPath();
2611 ctx.moveTo(0, r * th + 0.5);
2612 ctx.lineTo(canvas.width, r * th + 0.5);
2613 ctx.stroke();
2614 }
2615 if (!snapshot || !snapshot.blocks)
2616 { return; }
2617 var blocks = snapshot.blocks;
2618 for (var i = 0; i < blocks.length; i++)
2619 {
2620 var b = blocks[i];
2621 var x = b.col * tw;
2622 var y = canvas.height - (b.y + 1) * th;
2623 if (b.state === 'locked')
2624 { ctx.fillStyle = '#3a3d4a'; }
2625 else if (b.color < 0)
2626 { ctx.fillStyle = '#5a5d66'; }
2627 else
2628 { ctx.fillStyle = MINI_COLORS[b.color] || '#888'; }
2629 ctx.fillRect(x + 0.5, y + 0.5, tw - 1, th - 1);
2630 }
2631 };
2632
2633 Online.miniElement = function (playerId)
2634 {
2635 return document.querySelector('#minis .mini[data-player="' + CSS.escape(playerId) + '"]');
2636 };
2637
2638 /* ---------- flight tweens ------------------------------------------ */
2639
2640 function colorSpriteUrl (color)
2641 {
2642 if (color < 0)
2643 { return 'images/block-gray.png'; }
2644 var names = ['ember', 'aqua', 'leaf', 'sun', 'orchid'];
2645 return 'images/block-' + (names[color] || 'gray') + '.png';
2646 }
2647
2648 /**
2649 * Animate shot results. `locals` is a map of client_id → {col, y, color,
2650 * startX, startY} in viewport pixels, filled by the view just after
2651 * consumeOutgoingShots.
2652 */
2653 Online.spawnFlights = function (results, locals)
2654 {
2655 locals = locals || this._flightLocals || {};
2656 var layer = document.getElementById('flights');
2657 if (!layer)
2658 { return; }
2659 for (var i = 0; i < results.length; i++)
2660 {
2661 var r = results[i];
2662 var meta = locals[r.client_id] || {};
2663 var start = this._flightStart(meta.col);
2664 var end;
2665 var miss = !!r.miss;
2666 if (miss)
2667 { end = this._missEnd(start); }
2668 else
2669 { end = this._targetEnd(r.target_id, start); }
2670 var el = document.createElement('img');
2671 el.src = colorSpriteUrl(r.color != null ? r.color : meta.color);
2672 el.alt = '';
2673 el.className = 'flight';
2674 layer.appendChild(el);
2675 var spin = (Math.random() * 2 - 1) * 720;
2676 var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000;
2677 this._flights.push({
2678 el: el,
2679 start: start,
2680 end: end,
2681 ctrl: miss ? this._missCtrl(start, end) : this._hitCtrl(start, end),
2682 t0: performance.now(),
2683 duration: duration,
2684 spin: spin,
2685 miss: miss,
2686 angle: Math.random() * 360
2687 });
2688 }
2689 this._flightLocals = {};
2690 };
2691
2692 Online.rememberFlightLocal = function (shot, startX, startY)
2693 {
2694 if (!this._flightLocals)
2695 { this._flightLocals = {}; }
2696 this._flightLocals[String(shot.id)] = {
2697 col: shot.col,
2698 y: shot.y,
2699 color: shot.color,
2700 startX: startX,
2701 startY: startY
2702 };
2703 };
2704
2705 Online._flightStart = function (col)
2706 {
2707 var field = document.querySelector('canvas');
2708 var appRef = typeof app !== 'undefined' ? app : null;
2709 if (appRef && appRef.scene && appRef.scene.canvas)
2710 {
2711 var canvas = appRef.scene.canvas;
2712 var rect = canvas.getBoundingClientRect();
2713 var c = col == null ? 4.5 : col;
2714 return {
2715 x: rect.left + (c + 0.5) * (rect.width / 10),
2716 y: rect.top + 4
2717 };
2718 }
2719 if (field)
2720 {
2721 var rect = field.getBoundingClientRect();
2722 return { x: rect.left + rect.width / 2, y: rect.top };
2723 }
2724 return { x: window.innerWidth / 2, y: window.innerHeight * 0.3 };
2725 };
2726
2727 Online._targetEnd = function (targetId, start)
2728 {
2729 var el = targetId && this.miniElement(targetId);
2730 if (el)
2731 {
2732 var r = el.getBoundingClientRect();
2733 return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
2734 }
2735 return { x: start.x + (Math.random() - 0.5) * 80, y: 40 };
2736 };
2737
2738 Online._missEnd = function (start)
2739 {
2740 var dx = (Math.random() * 2 - 1) * window.innerWidth * 0.35;
2741 return {
2742 x: start.x + dx,
2743 y: start.y - (120 + Math.random() * 220)
2744 };
2745 };
2746
2747 Online._missCtrl = function (start, end)
2748 {
2749 return {
2750 x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 160,
2751 y: Math.min(start.y, end.y) - 40 - Math.random() * 80
2752 };
2753 };
2754
2755 Online._hitCtrl = function (start, end)
2756 {
2757 return {
2758 x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 40,
2759 y: (start.y + end.y) / 2 - 30
2760 };
2761 };
2762
2763 Online.tickFlights = function (now)
2764 {
2765 now = now || performance.now();
2766 var leftover = [];
2767 for (var i = 0; i < this._flights.length; i++)
2768 {
2769 var f = this._flights[i];
2770 var u = (now - f.t0) / f.duration;
2771 if (u >= 1)
2772 {
2773 if (f.el && f.el.parentNode)
2774 { f.el.parentNode.removeChild(f.el); }
2775 continue;
2776 }
2777 // Quadratic bezier, ease-in so they feel like they recede.
2778 var e = u * u;
2779 var mt = 1 - e;
2780 var x = mt * mt * f.start.x + 2 * mt * e * f.ctrl.x + e * e * f.end.x;
2781 var y = mt * mt * f.start.y + 2 * mt * e * f.ctrl.y + e * e * f.end.y;
2782 var scale = f.miss ? (1 - e) : (1 - 0.85 * e);
2783 var angle = f.angle + f.spin * u;
2784 f.el.style.transform = 'translate(' + x + 'px,' + y + 'px) translate(-50%,-50%) rotate('
2785 + angle + 'deg) scale(' + scale + ')';
2786 f.el.style.opacity = f.miss ? String(1 - e) : '1';
2787 leftover.push(f);
2788 }
2789 this._flights = leftover;
2790 };
2791
2792 Online.clearFlights = function ()
2793 {
2794 for (var i = 0; i < this._flights.length; i++)
2795 {
2796 var el = this._flights[i].el;
2797 if (el && el.parentNode)
2798 { el.parentNode.removeChild(el); }
2799 }
2800 this._flights = [];
2801 this._flightLocals = {};
2802 };
2803
2804 if (typeof globalThis !== 'undefined')
2805 { globalThis.Online = Online; }
2806 if (typeof module !== 'undefined' && module.exports)
2807 { module.exports = Online; }
2808
2809 /*
2810 * End File:
2811 * /workspace/meteors/src/online.js
2812 */
2813
2191 2814 /*
2192 2815 * Start File:
2193 2816 * /workspace/meteors/src/main.js
@@ -2197,8 +2820,8 @@ else if (typeof globalThis !== 'undefined')
2197 2820 /**
2198 2821 * View and input for Meteors. The simulation lives in GameCore; this file
2199 2822 * only draws it, scales it to the viewport, and translates pointer events
2200 * into beginDrag / moveDrag / endDrag. Ready for a later multiplayer view
2201 * that reuses the same core.
2823 * into beginDrag / moveDrag / endDrag. Online play (stage 2) is wired
2824 * through Online (src/online.js) and the same GameCore.
2202 2825 */
2203 2826
2204 2827 var IMAGES = [
@@ -2236,7 +2859,11 @@ var app = {
2236 2859 cells: [],
2237 2860 pointerId: null,
2238 2861 gameOverShown: false,
2239 selectTween: null
2862 selectTween: null,
2863 online: false,
2864 eliminatedReported: false,
2865 spectating: false,
2866 miniH: 0
2240 2867 };
2241 2868
2242 2869 window.onload = function ()
@@ -2259,6 +2886,8 @@ window.onload = function ()
2259 2886 if (game.images.flame && game.images.flame.addAnimationCycle)
2260 2887 { game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); }
2261 2888 });
2889
2890 bindOnlineUi();
2262 2891 };
2263 2892
2264 2893 function onPlay ()
@@ -2268,16 +2897,27 @@ function onPlay ()
2268 2897 startPlay();
2269 2898 }
2270 2899
2271 function startPlay ()
2900 function startPlay (opts)
2272 2901 {
2902 opts = opts || {};
2273 2903 hideEl('menu');
2274 2904 hideEl('game-over');
2905 hideEl('online-panel');
2906 hideEl('spectator');
2907 hideEl('podium');
2275 2908 showEl('hud');
2276 2909
2277 2910 app.planet = (typeof Planet !== 'undefined' ? Planet.defaultPlanet() : PlanetMod.defaultPlanet());
2278 app.core = new GameCore(app.planet, Math.random);
2911 var miss = opts.missChance;
2912 if (typeof miss === 'number' && isFinite(miss))
2913 { app.core = new GameCore(app.planet, Math.random, miss); }
2914 else
2915 { app.core = new GameCore(app.planet, Math.random); }
2279 2916 app.mode = 'playing';
2917 app.online = !!opts.online;
2280 2918 app.gameOverShown = false;
2919 app.eliminatedReported = false;
2920 app.spectating = false;
2281 2921 app.sprites = Object.create(null);
2282 2922 app.flames = Object.create(null);
2283 2923 app.cells = [];
@@ -2285,6 +2925,11 @@ function startPlay ()
2285 2925 app.selectTween = null;
2286 2926
2287 2927 layout();
2928 if (app.scene)
2929 {
2930 app.scene.destroy();
2931 app.scene = null;
2932 }
2288 2933 app.scene = new Scene(app.fieldX, app.fieldY, app.fieldW, app.fieldH);
2289 2934 app.scene.backgroundColor = { r: 12, g: 16, b: 32 };
2290 2935 app.scene.renderBackground = true;
@@ -2292,11 +2937,16 @@ function startPlay ()
2292 2937
2293 2938 buildCells();
2294 2939 app.manager = app.scene.addObject(makeManager());
2295 bindPointer(app.scene.canvas);
2940 if (!app.spectating)
2941 { bindPointer(app.scene.canvas); }
2296 2942 refreshHud();
2943 if (app.online)
2944 { showEl('minis'); }
2945 else
2946 { hideEl('minis'); }
2297 2947 }
2298 2948
2299 function returnToMenu ()
2949 function teardownPlay ()
2300 2950 {
2301 2951 unbindPointer();
2302 2952 if (app.scene)
@@ -2306,14 +2956,31 @@ function returnToMenu ()
2306 2956 }
2307 2957 app.manager = null;
2308 2958 app.core = null;
2309 app.mode = 'menu';
2310 2959 app.sprites = Object.create(null);
2311 2960 app.flames = Object.create(null);
2312 2961 app.cells = [];
2313 2962 app.selectTween = null;
2314
2963 app.pointerId = null;
2964 app.gameOverShown = false;
2315 2965 hideEl('hud');
2316 2966 hideEl('game-over');
2967 hideEl('spectator');
2968 hideEl('minis');
2969 if (typeof Online !== 'undefined')
2970 { Online.clearFlights(); }
2971 }
2972
2973 function returnToMenu ()
2974 {
2975 if (app.online && typeof Online !== 'undefined')
2976 {
2977 // Online matches do not dump you back to the solo menu:
2978 // elimination becomes spectating; a finished match shows the podium.
2979 return;
2980 }
2981 teardownPlay();
2982 app.mode = 'menu';
2983 app.online = false;
2317 2984 showEl('menu');
2318 2985 var last = document.getElementById('last-score');
2319 2986 if (app.lastScore > 0)
@@ -2361,16 +3028,26 @@ function layout ()
2361 3028 }
2362 3029 catch (e) { /* ignore */ }
2363 3030 app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop);
3031 app.miniH = 0;
3032 if (app.online)
3033 { app.miniH = Math.min(150, Math.max(86, Math.round(vh * 0.20))); }
2364 3034 var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015));
2365 3035 var availW = Math.max(80, vw - margin * 2);
2366 var availH = Math.max(80, vh - app.hudH - margin);
3036 var availH = Math.max(80, vh - app.hudH - app.miniH - margin);
2367 3037 app.tile = Math.max(14, Math.floor(Math.min(availW / 10, availH / 13)));
2368 3038 app.fieldW = app.tile * 10;
2369 3039 app.fieldH = app.tile * 13;
2370 3040 app.fieldX = Math.floor((vw - app.fieldW) / 2);
2371 app.fieldY = app.hudH + Math.floor((vh - app.hudH - app.fieldH - margin / 2) / 2);
2372 if (app.fieldY < app.hudH)
2373 { app.fieldY = app.hudH; }
3041 var topBand = app.hudH + app.miniH;
3042 app.fieldY = topBand + Math.floor((vh - topBand - app.fieldH - margin / 2) / 2);
3043 if (app.fieldY < topBand)
3044 { app.fieldY = topBand; }
3045 var minis = document.getElementById('minis');
3046 if (minis)
3047 {
3048 minis.style.top = app.hudH + 'px';
3049 minis.style.maxHeight = app.miniH + 'px';
3050 }
2374 3051
2375 3052 if (app.scene)
2376 3053 {
@@ -2582,15 +3259,19 @@ function tickView (dt)
2582 3259 updateSelectTween(dt);
2583 3260 syncSprites();
2584 3261 refreshHud();
3262 tickOnline(dt);
2585 3263
2586 3264 if (app.core.state === 'gameover' && !app.gameOverShown)
2587 3265 {
2588 3266 app.gameOverShown = true;
2589 3267 app.lastScore = app.core.score;
2590 3268 document.getElementById('go-score').textContent = String(app.lastScore);
2591 showEl('game-over');
3269 if (app.online)
3270 { onOnlineEliminated(); }
3271 else
3272 { showEl('game-over'); }
2592 3273 }
2593 if (app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY)
3274 if (!app.online && app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY)
2594 3275 { returnToMenu(); }
2595 3276 }
2596 3277
@@ -2739,6 +3420,388 @@ window.addEventListener('orientationchange', function ()
2739 3420 }, 120);
2740 3421 });
2741 3422
3423 /* ---------- online play (stage 2) ---------------------------------- */
3424
3425 function tickOnline (dt)
3426 {
3427 if (!app.online || typeof Online === 'undefined')
3428 { return; }
3429 if (app.core)
3430 {
3431 var shots = app.core.consumeOutgoingShots();
3432 for (var i = 0; i < shots.length; i++)
3433 {
3434 var s = shots[i];
3435 var start = fieldToViewport(s.col, s.y + 1);
3436 Online.rememberFlightLocal(s, start.x, start.y);
3437 }
3438 Online.queueShots(shots);
3439 }
3440 Online.tickFlights();
3441 Online.renderMinis(document.getElementById('minis'));
3442 }
3443
3444 function fieldToViewport (col, fieldY)
3445 {
3446 var canvas = app.scene && app.scene.canvas;
3447 if (!canvas)
3448 { return { x: window.innerWidth / 2, y: 40 }; }
3449 var rect = canvas.getBoundingClientRect();
3450 var x = rect.left + ((col + 0.5) / 10) * rect.width;
3451 var y = rect.top + (1 - (fieldY / 13)) * rect.height;
3452 return { x: x, y: y };
3453 }
3454
3455 function onlinePayload ()
3456 {
3457 if (!app.online || !app.core)
3458 { return {}; }
3459 return {
3460 snapshot: app.core.fieldSnapshot(),
3461 score: app.core.score,
3462 eliminated: app.core.state === 'gameover' || app.spectating || app.eliminatedReported
3463 };
3464 }
3465
3466 function onOnlineEliminated ()
3467 {
3468 app.eliminatedReported = true;
3469 app.spectating = true;
3470 unbindPointer();
3471 hideEl('game-over');
3472 var lobby = typeof Online !== 'undefined' && Online.lobby;
3473 if (lobby && lobby.status === 'finished')
3474 {
3475 showPodium(lobby);
3476 return;
3477 }
3478 showEl('spectator');
3479 }
3480
3481 function showPodium (lobby)
3482 {
3483 hideEl('spectator');
3484 hideEl('game-over');
3485 hideEl('online-panel');
3486 showEl('podium');
3487 var list = document.getElementById('podium-list');
3488 list.innerHTML = '';
3489 var ranks = (lobby && lobby.rankings) || [];
3490 for (var i = 0; i < ranks.length; i++)
3491 {
3492 var r = ranks[i];
3493 var li = document.createElement('li');
3494 var medal = r.place === 1 ? '1e' : (r.place === 2 ? '2e' : (r.place === 3 ? '3e' : r.place + 'e'));
3495 li.textContent = medal + ' ' + r.name + ' · ' + r.score + ' punten';
3496 list.appendChild(li);
3497 }
3498 var hint = document.getElementById('podium-hint');
3499 var secs = (lobby && lobby.podium_seconds) || 5;
3500 hint.textContent = 'Over ' + secs + ' seconden teruggaan naar de lobby…';
3501 }
3502
3503 function startOnlineMatch ()
3504 {
3505 if (app.mode === 'playing' && app.online)
3506 { return; }
3507 var miss = (typeof Online !== 'undefined' && Online.lobby && Online.lobby.miss_chance != null)
3508 ? Online.lobby.miss_chance
3509 : (typeof Online !== 'undefined' ? Online.DEFAULT_MISS_CHANCE : 0.30);
3510 startPlay({ online: true, missChance: miss });
3511 if (typeof Online !== 'undefined')
3512 { Online.startPolling(onlinePayload); }
3513 }
3514
3515 function leaveOnlineMatch (goMenu)
3516 {
3517 if (typeof Online !== 'undefined')
3518 {
3519 Online.stopPolling();
3520 Online.leaveLobby();
3521 Online.clearFlights();
3522 }
3523 teardownPlay();
3524 app.online = false;
3525 if (goMenu)
3526 {
3527 app.mode = 'menu';
3528 showEl('menu');
3529 }
3530 else
3531 {
3532 app.mode = 'online';
3533 openOnlinePanel();
3534 }
3535 }
3536
3537 function bindOnlineUi ()
3538 {
3539 var onlineBtn = document.getElementById('btn-online');
3540 if (!onlineBtn)
3541 { return; }
3542 onlineBtn.addEventListener('click', function ()
3543 { openOnlinePanel(); });
3544
3545 var backs = document.querySelectorAll('[data-back-menu]');
3546 for (var i = 0; i < backs.length; i++)
3547 {
3548 backs[i].addEventListener('click', function ()
3549 {
3550 if (typeof Online !== 'undefined')
3551 { Online.stopPolling(); }
3552 hideEl('online-panel');
3553 app.mode = 'menu';
3554 app.online = false;
3555 showEl('menu');
3556 });
3557 }
3558
3559 document.getElementById('btn-create').addEventListener('click', function ()
3560 {
3561 Online.createLobby().then(function (data)
3562 {
3563 if (data && data.ok)
3564 {
3565 renderOnline();
3566 Online.startPolling(onlinePayload);
3567 }
3568 else
3569 { renderOnline(); }
3570 });
3571 });
3572
3573 document.getElementById('join-form').addEventListener('submit', function (e)
3574 {
3575 e.preventDefault();
3576 var code = (document.getElementById('join-code').value || '').trim();
3577 if (!code)
3578 { return; }
3579 Online.joinLobby(code).then(function ()
3580 {
3581 renderOnline();
3582 if (Online.lobby)
3583 { Online.startPolling(onlinePayload); }
3584 });
3585 });
3586
3587 document.getElementById('btn-ready').addEventListener('click', function ()
3588 {
3589 var me = Online.mePlayer();
3590 Online.setReady(!(me && me.ready)).then(renderOnline);
3591 });
3592
3593 document.getElementById('btn-start').addEventListener('click', function ()
3594 {
3595 Online.startGame().then(function (data)
3596 {
3597 if (data && data.ok)
3598 { startOnlineMatch(); }
3599 else
3600 { renderOnline(); }
3601 });
3602 });
3603
3604 document.getElementById('btn-leave-lobby').addEventListener('click', function ()
3605 {
3606 Online.leaveLobby().then(function ()
3607 {
3608 Online.stopPolling();
3609 renderOnline();
3610 });
3611 });
3612
3613 document.getElementById('btn-copy-code').addEventListener('click', function ()
3614 {
3615 var code = document.getElementById('lobby-code').textContent;
3616 if (navigator.clipboard && navigator.clipboard.writeText)
3617 { navigator.clipboard.writeText(code); }
3618 });
3619
3620 document.getElementById('btn-spectate').addEventListener('click', function ()
3621 {
3622 hideEl('spectator');
3623 app.spectating = true;
3624 });
3625
3626 document.getElementById('btn-leave-game').addEventListener('click', function ()
3627 { leaveOnlineMatch(false); });
3628
3629 if (typeof Online !== 'undefined')
3630 {
3631 Online.onChange = function ()
3632 { renderOnline(); };
3633 Online.onGameStart = function ()
3634 { startOnlineMatch(); };
3635 Online.onIncoming = function (incoming)
3636 {
3637 if (!app.core || app.core.state !== 'playing')
3638 { return; }
3639 for (var i = 0; i < incoming.length; i++)
3640 { app.core.ingestGarbage(); }
3641 };
3642 Online.onFinished = function (lobby)
3643 { showPodium(lobby); };
3644 Online.onLobbyReturn = function (lobby)
3645 {
3646 teardownPlay();
3647 app.online = false;
3648 app.mode = 'online';
3649 hideEl('podium');
3650 showEl('online-panel');
3651 renderOnline();
3652 Online.startPolling(onlinePayload);
3653 };
3654 }
3655
3656 var params = new URLSearchParams(window.location.search);
3657 if (params.get('online') === '1' || params.get('auth') === 'unconfigured')
3658 { openOnlinePanel(); }
3659 }
3660
3661 function openOnlinePanel ()
3662 {
3663 hideEl('menu');
3664 hideEl('game-over');
3665 hideEl('podium');
3666 hideEl('spectator');
3667 showEl('online-panel');
3668 app.mode = 'online';
3669 setOnlineStatus('Even kijken of online spelen beschikbaar is…');
3670 if (typeof Online === 'undefined')
3671 {
3672 showOnlineError('Online spelen is in deze build niet geladen. Je kunt wel alleen spelen.');
3673 showOnly('online-unconfigured');
3674 return;
3675 }
3676 Online.refresh().then(function (data)
3677 {
3678 if (!data || data.ok === false)
3679 {
3680 var msg = (data && data.error) || 'Geen verbinding met de server.';
3681 showOnlineError(msg + ' Je kunt wel alleen spelen.');
3682 if (data && data.configured === false)
3683 { showOnly('online-unconfigured'); }
3684 else
3685 { showOnly('online-login'); }
3686 document.getElementById('btn-login').style.display = 'none';
3687 return;
3688 }
3689 renderOnline();
3690 if (Online.lobby)
3691 { Online.startPolling(onlinePayload); }
3692 });
3693 }
3694
3695 function setOnlineStatus (text)
3696 {
3697 var el = document.getElementById('online-status');
3698 if (el)
3699 { el.textContent = text; }
3700 }
3701
3702 function showOnlineError (text)
3703 {
3704 var el = document.getElementById('online-error');
3705 if (!el)
3706 { return; }
3707 if (!text)
3708 {
3709 el.hidden = true;
3710 el.textContent = '';
3711 return;
3712 }
3713 el.hidden = false;
3714 el.textContent = text;
3715 }
3716
3717 function showOnly (id)
3718 {
3719 var ids = ['online-unconfigured', 'online-login', 'online-home', 'online-lobby'];
3720 for (var i = 0; i < ids.length; i++)
3721 { document.getElementById(ids[i]).hidden = (ids[i] !== id); }
3722 }
3723
3724 function renderOnline ()
3725 {
3726 if (typeof Online === 'undefined')
3727 { return; }
3728 if (app.mode === 'playing' && app.online)
3729 {
3730 Online.renderMinis(document.getElementById('minis'));
3731 if (Online.lobby && Online.lobby.status === 'finished')
3732 { showPodium(Online.lobby); }
3733 return;
3734 }
3735 showOnlineError(Online.error);
3736 if (!Online.configured && !Online.me && !Online.local)
3737 {
3738 setOnlineStatus('Online spelen is nog niet ingesteld.');
3739 showOnly('online-unconfigured');
3740 return;
3741 }
3742 if (!Online.me)
3743 {
3744 setOnlineStatus('Log in om een lobby te maken of eraan deel te nemen.');
3745 showOnly('online-login');
3746 document.getElementById('btn-login').style.display = '';
3747 document.getElementById('btn-login').href = Online.loginUrl();
3748 document.getElementById('local-login').hidden = !Online.local;
3749 return;
3750 }
3751 if (Online.lobby)
3752 {
3753 setOnlineStatus('Lobby');
3754 showOnly('online-lobby');
3755 document.getElementById('lobby-me-name').textContent = Online.me.name;
3756 document.getElementById('lobby-code').textContent = Online.lobby.code;
3757 var list = document.getElementById('lobby-players');
3758 list.innerHTML = '';
3759 var players = Online.lobby.players || [];
3760 for (var i = 0; i < players.length; i++)
3761 {
3762 var p = players[i];
3763 var li = document.createElement('li');
3764 if (p.is_me)
3765 { li.classList.add('you'); }
3766 var label = p.name + (p.is_host ? ' (host)' : '') + (p.is_me ? ' (jij)' : '');
3767 var state = p.ready ? 'Gereed' : 'Wacht…';
3768 li.innerHTML = '<span>' + escapeText(label) + '</span><span class="'
3769 + (p.ready ? 'ready' : 'waiting') + '">' + state + '</span>';
3770 list.appendChild(li);
3771 }
3772 var me = Online.mePlayer();
3773 document.getElementById('btn-ready').textContent = (me && me.ready) ? 'Niet gereed' : 'Gereed';
3774 var start = document.getElementById('btn-start');
3775 start.hidden = !(Online.lobby && Online.me && Online.lobby.host_id === Online.me.id);
3776 start.disabled = !Online.lobby.can_start;
3777 var hint = document.getElementById('lobby-hint');
3778 if (Online.lobby.status === 'playing')
3779 { hint.textContent = 'Het spel start…'; }
3780 else if (players.length < 2)
3781 { hint.textContent = 'Wacht op minstens één andere speler. Deel de code.'; }
3782 else if (!Online.lobby.all_ready)
3783 { hint.textContent = 'Iedereen moet op Gereed drukken. De host start daarna.'; }
3784 else if (Online.lobby.can_start)
3785 { hint.textContent = 'Iedereen is gereed. Druk op Starten.'; }
3786 else
3787 { hint.textContent = 'Wachten tot de host start.'; }
3788 return;
3789 }
3790 setOnlineStatus('Hoi ' + Online.me.name + '. Maak een lobby of val in met een code.');
3791 showOnly('online-home');
3792 document.getElementById('me-name').textContent = Online.me.name;
3793 document.getElementById('local-login').hidden = !Online.local;
3794 }
3795
3796 function escapeText (s)
3797 {
3798 return String(s)
3799 .replace(/&/g, '&amp;')
3800 .replace(/</g, '&lt;')
3801 .replace(/>/g, '&gt;')
3802 .replace(/"/g, '&quot;');
3803 }
3804
2742 3805 /*
2743 3806 * End File:
2744 3807 * /workspace/meteors/src/main.js
@@ -443,6 +443,17 @@ function GameCore (planet, rng)
443 this.state = 'playing';
443 this.state = 'playing';
444 this.drag = null;
444 this.drag = null;
445 this.gameOverTime = 0;
445 this.gameOverTime = 0;
446 this.outgoingShots = [];
447 // Stage-2 default; stage 3 replaces this with Planet.missChance (Power).
448 this.missChance = optsMissChance(arguments);
449}
450
451function optsMissChance (args)
452{
453 // GameCore(planet, rng, missChance) — third arg is optional.
454 if (args.length >= 3 && typeof args[2] === 'number' && isFinite(args[2]))
455 { return Math.max(0, Math.min(1, args[2])); }
456 return GameCore.DEFAULT_MISS_CHANCE;
446}
457}
447
458
448GameCore.COLOR_GRAY = COLOR_GRAY;
459GameCore.COLOR_GRAY = COLOR_GRAY;
@@ -450,6 +461,7 @@ GameCore.LAUNCH_PULL = LAUNCH_PULL;
450GameCore.SWAP_DISTANCE = SWAP_DISTANCE;
461GameCore.SWAP_DISTANCE = SWAP_DISTANCE;
451GameCore.SNAP_Y = SNAP_Y;
462GameCore.SNAP_Y = SNAP_Y;
452GameCore.HORIZONTAL_SLOP = HORIZONTAL_SLOP;
463GameCore.HORIZONTAL_SLOP = HORIZONTAL_SLOP;
464GameCore.DEFAULT_MISS_CHANCE = 0.30;
453GameCore.STATE_STILL = STATE_STILL;
465GameCore.STATE_STILL = STATE_STILL;
454GameCore.STATE_FALLING = STATE_FALLING;
466GameCore.STATE_FALLING = STATE_FALLING;
455GameCore.STATE_FLYING = STATE_FLYING;
467GameCore.STATE_FLYING = STATE_FLYING;
@@ -1508,9 +1520,88 @@ GameCore.prototype.cullOffTop = function ()
1508 }
1520 }
1509 for (var i = 0; i < gone.length; i++)
1521 for (var i = 0; i < gone.length; i++)
1510 {
1522 {
1523 var block = gone[i];
1524 this.outgoingShots.push({
1525 id: block.id,
1526 color: block.color,
1527 col: block.col,
1528 y: block.y
1529 });
1511 this.score += 1;
1530 this.score += 1;
1512 this.removeBlock(gone[i]);
1531 this.removeBlock(block);
1532 }
1533};
1534
1535GameCore.prototype.consumeOutgoingShots = function ()
1536{
1537 var shots = this.outgoingShots;
1538 this.outgoingShots = [];
1539 return shots;
1540};
1541
1542/**
1543 * A compact field picture for the multiplayer snapshot (miniatures).
1544 * Includes every block's col, y, color, state and flame.
1545 */
1546GameCore.prototype.fieldSnapshot = function ()
1547{
1548 var blocks = [];
1549 for (var i = 0; i < this.blocks.length; i++)
1550 {
1551 var b = this.blocks[i];
1552 blocks.push({
1553 id: b.id,
1554 col: b.col,
1555 y: Math.round(b.y * 1000) / 1000,
1556 color: b.color,
1557 state: b.state,
1558 flame: !!b.flame
1559 });
1560 }
1561 return {
1562 score: this.score,
1563 state: this.state,
1564 width: this.width,
1565 height: this.height,
1566 locked: this.lockedColumnCount(),
1567 blocks: blocks
1568 };
1569};
1570
1571/**
1572 * Incoming garbage from another player: a dark-grey block that falls
1573 * normally from the top of an open column. After landing it uses the
1574 * usual 3s settle and then a random colour (landFallingBlock).
1575 * `col` is optional; a random eligible column is used otherwise.
1576 * Returns the new block, or null if every column is locked or full.
1577 */
1578GameCore.prototype.ingestGarbage = function (col)
1579{
1580 if (this.state !== 'playing')
1581 { return null; }
1582 var chosen = null;
1583 if (col != null && col >= 0 && col < this.width
1584 && !this.isColumnLocked(col) && this.groundedCount(col) < this.height)
1585 { chosen = col | 0; }
1586 else
1587 {
1588 var eligible = [];
1589 for (var c = 0; c < this.width; c++)
1590 {
1591 if (this.isColumnLocked(c))
1592 { continue; }
1593 if (this.groundedCount(c) >= this.height)
1594 { continue; }
1595 eligible.push(c);
1596 }
1597 if (!eligible.length)
1598 { return null; }
1599 chosen = eligible[Math.floor(this.rng() * eligible.length) % eligible.length];
1513 }
1600 }
1601 var block = this.createBlock(chosen, this.height, COLOR_GRAY, STATE_FALLING);
1602 block.vy = -this.planet.fallSpeed;
1603 block.flame = false;
1604 return block;
1514};
1605};
1515
1606
1516GameCore.prototype.advanceSettle = function (dt)
1607GameCore.prototype.advanceSettle = function (dt)
@@ -2188,6 +2279,538 @@ else if (typeof globalThis !== 'undefined')
2188 * /workspace/meteors/src/gameCore.js
2279 * /workspace/meteors/src/gameCore.js
2189 */
2280 */
2190
2281
2282/*
2283 * Start File:
2284 * /workspace/meteors/src/online.js
2285 */
2286'use strict';
2287
2288/**
2289 * Online play: talks to api.php (cookie session), polls lobby and game
2290 * state, and draws opponent miniatures plus flying-block tweens.
2291 * Real-time sync is not required; a 0.75 s poll is enough.
2292 */
2293
2294var Online = {
2295 POLL_MS: 750,
2296 DEFAULT_MISS_CHANCE: 0.30,
2297 FLIGHT_DURATION: 1.2,
2298 configured: false,
2299 local: false,
2300 csrf: '',
2301 me: null,
2302 lobby: null,
2303 incoming: [],
2304 shotResults: [],
2305 error: '',
2306 _timer: null,
2307 _pendingShots: [],
2308 _flights: [],
2309 _lastStatus: null,
2310 onChange: null,
2311 onGameStart: null,
2312 onIncoming: null,
2313 onFinished: null,
2314 onLobbyReturn: null
2315};
2316
2317Online._headers = function (json)
2318{
2319 var h = { 'Accept': 'application/json' };
2320 if (json)
2321 { h['Content-Type'] = 'application/json'; }
2322 if (this.csrf)
2323 { h['X-CSRF-Token'] = this.csrf; }
2324 return h;
2325};
2326
2327Online._apply = function (data)
2328{
2329 if (!data)
2330 { return; }
2331 if (typeof data.configured === 'boolean')
2332 { this.configured = data.configured; }
2333 if (typeof data.local === 'boolean')
2334 { this.local = data.local; }
2335 if (data.csrf)
2336 { this.csrf = data.csrf; }
2337 if (data.me !== undefined)
2338 { this.me = data.me; }
2339 if (data.lobby !== undefined)
2340 { this.lobby = data.lobby; }
2341 if (data.incoming)
2342 { this.incoming = data.incoming; }
2343 if (data.shot_results)
2344 { this.shotResults = data.shot_results; }
2345 if (data.miss_chance_default != null)
2346 { this.DEFAULT_MISS_CHANCE = data.miss_chance_default; }
2347 if (data.flight_duration != null)
2348 { this.FLIGHT_DURATION = data.flight_duration; }
2349 if (data.error)
2350 { this.error = data.error; }
2351 else if (data.ok)
2352 { this.error = ''; }
2353};
2354
2355Online.request = function (action, body)
2356{
2357 var self = this;
2358 var isGet = action === 'me' || action === '';
2359 var url = 'api.php?action=' + encodeURIComponent(action || 'me');
2360 var opts = {
2361 method: isGet && !body ? 'GET' : 'POST',
2362 credentials: 'same-origin',
2363 headers: this._headers(!!body || !isGet)
2364 };
2365 if (opts.method === 'POST')
2366 {
2367 var payload = body ? Object.assign({ action: action }, body) : { action: action };
2368 opts.body = JSON.stringify(payload);
2369 }
2370 return fetch(url, opts).then(function (res)
2371 {
2372 return res.json().then(function (data)
2373 {
2374 data = data || {};
2375 if (!res.ok && !data.error)
2376 { data.error = 'De server gaf ' + res.status; data.ok = false; }
2377 self._apply(data);
2378 return data;
2379 }, function ()
2380 {
2381 var fail = { ok: false, error: 'Geen geldig antwoord van de server.' };
2382 self.error = fail.error;
2383 return fail;
2384 });
2385 }).catch(function (err)
2386 {
2387 var fail = { ok: false, error: 'Geen verbinding met de server.' };
2388 self.error = fail.error;
2389 return fail;
2390 });
2391};
2392
2393Online.refresh = function ()
2394{
2395 return this.request('me');
2396};
2397
2398Online.testLogin = function (who)
2399{
2400 return this.request('test_login', { user: who });
2401};
2402
2403Online.createLobby = function ()
2404{
2405 return this.request('lobby_create', { miss_chance: this.DEFAULT_MISS_CHANCE });
2406};
2407
2408Online.joinLobby = function (code)
2409{
2410 return this.request('lobby_join', { code: code });
2411};
2412
2413Online.leaveLobby = function ()
2414{
2415 return this.request('lobby_leave');
2416};
2417
2418Online.setReady = function (ready)
2419{
2420 return this.request('lobby_ready', { ready: !!ready });
2421};
2422
2423Online.startGame = function ()
2424{
2425 var self = this;
2426 var prev = this.lobby && this.lobby.status;
2427 return this.request('lobby_start').then(function (data)
2428 {
2429 self._handleTransitions(prev, data);
2430 return data;
2431 });
2432};
2433
2434Online.queueShots = function (shots)
2435{
2436 for (var i = 0; i < shots.length; i++)
2437 {
2438 this._pendingShots.push({
2439 client_id: String(shots[i].id),
2440 color: shots[i].color,
2441 col: shots[i].col,
2442 y: shots[i].y
2443 });
2444 }
2445};
2446
2447Online.poll = function (opts)
2448{
2449 opts = opts || {};
2450 var body = {};
2451 if (opts.snapshot)
2452 { body.snapshot = opts.snapshot; }
2453 if (opts.score != null)
2454 { body.score = opts.score; }
2455 if (opts.eliminated)
2456 { body.eliminated = true; }
2457 if (this._pendingShots.length)
2458 {
2459 body.outgoing_shots = this._pendingShots.splice(0, this._pendingShots.length);
2460 }
2461 var self = this;
2462 var prevStatus = this.lobby && this.lobby.status;
2463 return this.request('poll', body).then(function (data)
2464 {
2465 self._handleTransitions(prevStatus, data);
2466 if (self.onChange)
2467 { self.onChange(self); }
2468 return data;
2469 });
2470};
2471
2472Online._handleTransitions = function (prevStatus, data)
2473{
2474 var lobby = this.lobby;
2475 var status = lobby && lobby.status;
2476 if (status === 'playing' && prevStatus !== 'playing' && this.onGameStart)
2477 { this.onGameStart(lobby); }
2478 if (data && data.incoming && data.incoming.length && this.onIncoming)
2479 { this.onIncoming(data.incoming); }
2480 if (data && data.shot_results && data.shot_results.length)
2481 { this.spawnFlights(data.shot_results, this._lastQueuedMeta); }
2482 if (status === 'finished' && prevStatus !== 'finished' && this.onFinished)
2483 { this.onFinished(lobby); }
2484 if (status === 'waiting' && prevStatus === 'finished' && this.onLobbyReturn)
2485 { this.onLobbyReturn(lobby); }
2486};
2487
2488Online.startPolling = function (getPayload)
2489{
2490 this.stopPolling();
2491 var self = this;
2492 var tick = function ()
2493 {
2494 var payload = getPayload ? getPayload() : {};
2495 self.poll(payload);
2496 };
2497 tick();
2498 this._timer = setInterval(tick, this.POLL_MS);
2499};
2500
2501Online.stopPolling = function ()
2502{
2503 if (this._timer)
2504 {
2505 clearInterval(this._timer);
2506 this._timer = null;
2507 }
2508};
2509
2510Online.loginUrl = function ()
2511{
2512 return 'auth.php';
2513};
2514
2515Online.logoutUrl = function ()
2516{
2517 return 'logout.php';
2518};
2519
2520Online.opponents = function ()
2521{
2522 if (!this.lobby || !this.lobby.players)
2523 { return []; }
2524 return this.lobby.players.filter(function (p) { return !p.is_me; });
2525};
2526
2527Online.aliveOpponents = function ()
2528{
2529 return this.opponents().filter(function (p) { return !p.eliminated; });
2530};
2531
2532Online.mePlayer = function ()
2533{
2534 if (!this.lobby || !this.lobby.players)
2535 { return null; }
2536 for (var i = 0; i < this.lobby.players.length; i++)
2537 {
2538 if (this.lobby.players[i].is_me)
2539 { return this.lobby.players[i]; }
2540 }
2541 return null;
2542};
2543
2544/* ---------- miniatures --------------------------------------------- */
2545
2546Online.renderMinis = function (container)
2547{
2548 if (!container)
2549 { return; }
2550 var opponents = this.opponents();
2551 var existing = {};
2552 var kids = container.querySelectorAll('[data-player]');
2553 for (var i = 0; i < kids.length; i++)
2554 { existing[kids[i].getAttribute('data-player')] = kids[i]; }
2555
2556 var seen = Object.create(null);
2557 for (var i = 0; i < opponents.length; i++)
2558 {
2559 var p = opponents[i];
2560 seen[p.id] = true;
2561 var el = existing[p.id];
2562 if (!el)
2563 {
2564 el = document.createElement('div');
2565 el.className = 'mini';
2566 el.setAttribute('data-player', p.id);
2567 el.innerHTML = '<div class="mini-name"></div>'
2568 + '<canvas class="mini-canvas" width="80" height="104"></canvas>'
2569 + '<div class="mini-meta"></div>';
2570 container.appendChild(el);
2571 }
2572 el.classList.toggle('eliminated', !!p.eliminated);
2573 el.querySelector('.mini-name').textContent = p.name + (p.is_host ? ' (host)' : '');
2574 el.querySelector('.mini-meta').textContent = p.eliminated
2575 ? ('Uit' + (p.place ? ' · ' + p.place + 'e' : ''))
2576 : ('Punten ' + (p.score || 0));
2577 this._drawMini(el.querySelector('canvas'), p.snapshot);
2578 }
2579 for (var id in existing)
2580 {
2581 if (!seen[id])
2582 { existing[id].remove(); }
2583 }
2584};
2585
2586var MINI_COLORS = ['#d4553a', '#3a9ad4', '#4caf6a', '#e6c04a', '#b86ad4'];
2587
2588Online._drawMini = function (canvas, snapshot)
2589{
2590 if (!canvas)
2591 { return; }
2592 var ctx = canvas.getContext('2d');
2593 var w = 10;
2594 var h = 13;
2595 var tw = canvas.width / w;
2596 var th = canvas.height / h;
2597 ctx.fillStyle = '#0c1020';
2598 ctx.fillRect(0, 0, canvas.width, canvas.height);
2599 ctx.strokeStyle = 'rgba(255,255,255,0.06)';
2600 ctx.lineWidth = 1;
2601 for (var c = 0; c <= w; c++)
2602 {
2603 ctx.beginPath();
2604 ctx.moveTo(c * tw + 0.5, 0);
2605 ctx.lineTo(c * tw + 0.5, canvas.height);
2606 ctx.stroke();
2607 }
2608 for (var r = 0; r <= h; r++)
2609 {
2610 ctx.beginPath();
2611 ctx.moveTo(0, r * th + 0.5);
2612 ctx.lineTo(canvas.width, r * th + 0.5);
2613 ctx.stroke();
2614 }
2615 if (!snapshot || !snapshot.blocks)
2616 { return; }
2617 var blocks = snapshot.blocks;
2618 for (var i = 0; i < blocks.length; i++)
2619 {
2620 var b = blocks[i];
2621 var x = b.col * tw;
2622 var y = canvas.height - (b.y + 1) * th;
2623 if (b.state === 'locked')
2624 { ctx.fillStyle = '#3a3d4a'; }
2625 else if (b.color < 0)
2626 { ctx.fillStyle = '#5a5d66'; }
2627 else
2628 { ctx.fillStyle = MINI_COLORS[b.color] || '#888'; }
2629 ctx.fillRect(x + 0.5, y + 0.5, tw - 1, th - 1);
2630 }
2631};
2632
2633Online.miniElement = function (playerId)
2634{
2635 return document.querySelector('#minis .mini[data-player="' + CSS.escape(playerId) + '"]');
2636};
2637
2638/* ---------- flight tweens ------------------------------------------ */
2639
2640function colorSpriteUrl (color)
2641{
2642 if (color < 0)
2643 { return 'images/block-gray.png'; }
2644 var names = ['ember', 'aqua', 'leaf', 'sun', 'orchid'];
2645 return 'images/block-' + (names[color] || 'gray') + '.png';
2646}
2647
2648/**
2649 * Animate shot results. `locals` is a map of client_id → {col, y, color,
2650 * startX, startY} in viewport pixels, filled by the view just after
2651 * consumeOutgoingShots.
2652 */
2653Online.spawnFlights = function (results, locals)
2654{
2655 locals = locals || this._flightLocals || {};
2656 var layer = document.getElementById('flights');
2657 if (!layer)
2658 { return; }
2659 for (var i = 0; i < results.length; i++)
2660 {
2661 var r = results[i];
2662 var meta = locals[r.client_id] || {};
2663 var start = this._flightStart(meta.col);
2664 var end;
2665 var miss = !!r.miss;
2666 if (miss)
2667 { end = this._missEnd(start); }
2668 else
2669 { end = this._targetEnd(r.target_id, start); }
2670 var el = document.createElement('img');
2671 el.src = colorSpriteUrl(r.color != null ? r.color : meta.color);
2672 el.alt = '';
2673 el.className = 'flight';
2674 layer.appendChild(el);
2675 var spin = (Math.random() * 2 - 1) * 720;
2676 var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000;
2677 this._flights.push({
2678 el: el,
2679 start: start,
2680 end: end,
2681 ctrl: miss ? this._missCtrl(start, end) : this._hitCtrl(start, end),
2682 t0: performance.now(),
2683 duration: duration,
2684 spin: spin,
2685 miss: miss,
2686 angle: Math.random() * 360
2687 });
2688 }
2689 this._flightLocals = {};
2690};
2691
2692Online.rememberFlightLocal = function (shot, startX, startY)
2693{
2694 if (!this._flightLocals)
2695 { this._flightLocals = {}; }
2696 this._flightLocals[String(shot.id)] = {
2697 col: shot.col,
2698 y: shot.y,
2699 color: shot.color,
2700 startX: startX,
2701 startY: startY
2702 };
2703};
2704
2705Online._flightStart = function (col)
2706{
2707 var field = document.querySelector('canvas');
2708 var appRef = typeof app !== 'undefined' ? app : null;
2709 if (appRef && appRef.scene && appRef.scene.canvas)
2710 {
2711 var canvas = appRef.scene.canvas;
2712 var rect = canvas.getBoundingClientRect();
2713 var c = col == null ? 4.5 : col;
2714 return {
2715 x: rect.left + (c + 0.5) * (rect.width / 10),
2716 y: rect.top + 4
2717 };
2718 }
2719 if (field)
2720 {
2721 var rect = field.getBoundingClientRect();
2722 return { x: rect.left + rect.width / 2, y: rect.top };
2723 }
2724 return { x: window.innerWidth / 2, y: window.innerHeight * 0.3 };
2725};
2726
2727Online._targetEnd = function (targetId, start)
2728{
2729 var el = targetId && this.miniElement(targetId);
2730 if (el)
2731 {
2732 var r = el.getBoundingClientRect();
2733 return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
2734 }
2735 return { x: start.x + (Math.random() - 0.5) * 80, y: 40 };
2736};
2737
2738Online._missEnd = function (start)
2739{
2740 var dx = (Math.random() * 2 - 1) * window.innerWidth * 0.35;
2741 return {
2742 x: start.x + dx,
2743 y: start.y - (120 + Math.random() * 220)
2744 };
2745};
2746
2747Online._missCtrl = function (start, end)
2748{
2749 return {
2750 x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 160,
2751 y: Math.min(start.y, end.y) - 40 - Math.random() * 80
2752 };
2753};
2754
2755Online._hitCtrl = function (start, end)
2756{
2757 return {
2758 x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 40,
2759 y: (start.y + end.y) / 2 - 30
2760 };
2761};
2762
2763Online.tickFlights = function (now)
2764{
2765 now = now || performance.now();
2766 var leftover = [];
2767 for (var i = 0; i < this._flights.length; i++)
2768 {
2769 var f = this._flights[i];
2770 var u = (now - f.t0) / f.duration;
2771 if (u >= 1)
2772 {
2773 if (f.el && f.el.parentNode)
2774 { f.el.parentNode.removeChild(f.el); }
2775 continue;
2776 }
2777 // Quadratic bezier, ease-in so they feel like they recede.
2778 var e = u * u;
2779 var mt = 1 - e;
2780 var x = mt * mt * f.start.x + 2 * mt * e * f.ctrl.x + e * e * f.end.x;
2781 var y = mt * mt * f.start.y + 2 * mt * e * f.ctrl.y + e * e * f.end.y;
2782 var scale = f.miss ? (1 - e) : (1 - 0.85 * e);
2783 var angle = f.angle + f.spin * u;
2784 f.el.style.transform = 'translate(' + x + 'px,' + y + 'px) translate(-50%,-50%) rotate('
2785 + angle + 'deg) scale(' + scale + ')';
2786 f.el.style.opacity = f.miss ? String(1 - e) : '1';
2787 leftover.push(f);
2788 }
2789 this._flights = leftover;
2790};
2791
2792Online.clearFlights = function ()
2793{
2794 for (var i = 0; i < this._flights.length; i++)
2795 {
2796 var el = this._flights[i].el;
2797 if (el && el.parentNode)
2798 { el.parentNode.removeChild(el); }
2799 }
2800 this._flights = [];
2801 this._flightLocals = {};
2802};
2803
2804if (typeof globalThis !== 'undefined')
2805{ globalThis.Online = Online; }
2806if (typeof module !== 'undefined' && module.exports)
2807{ module.exports = Online; }
2808
2809/*
2810 * End File:
2811 * /workspace/meteors/src/online.js
2812 */
2813
2191/*
2814/*
2192 * Start File:
2815 * Start File:
2193 * /workspace/meteors/src/main.js
2816 * /workspace/meteors/src/main.js
@@ -2197,8 +2820,8 @@ else if (typeof globalThis !== 'undefined')
2197/**
2820/**
2198 * View and input for Meteors. The simulation lives in GameCore; this file
2821 * View and input for Meteors. The simulation lives in GameCore; this file
2199 * only draws it, scales it to the viewport, and translates pointer events
2822 * only draws it, scales it to the viewport, and translates pointer events
2200 * into beginDrag / moveDrag / endDrag. Ready for a later multiplayer view
2823 * into beginDrag / moveDrag / endDrag. Online play (stage 2) is wired
2201 * that reuses the same core.
2824 * through Online (src/online.js) and the same GameCore.
2202 */
2825 */
2203
2826
2204var IMAGES = [
2827var IMAGES = [
@@ -2236,7 +2859,11 @@ var app = {
2236 cells: [],
2859 cells: [],
2237 pointerId: null,
2860 pointerId: null,
2238 gameOverShown: false,
2861 gameOverShown: false,
2239 selectTween: null
2862 selectTween: null,
2863 online: false,
2864 eliminatedReported: false,
2865 spectating: false,
2866 miniH: 0
2240};
2867};
2241
2868
2242window.onload = function ()
2869window.onload = function ()
@@ -2259,6 +2886,8 @@ window.onload = function ()
2259 if (game.images.flame && game.images.flame.addAnimationCycle)
2886 if (game.images.flame && game.images.flame.addAnimationCycle)
2260 { game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); }
2887 { game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); }
2261 });
2888 });
2889
2890 bindOnlineUi();
2262};
2891};
2263
2892
2264function onPlay ()
2893function onPlay ()
@@ -2268,16 +2897,27 @@ function onPlay ()
2268 startPlay();
2897 startPlay();
2269}
2898}
2270
2899
2271function startPlay ()
2900function startPlay (opts)
2272{
2901{
2902 opts = opts || {};
2273 hideEl('menu');
2903 hideEl('menu');
2274 hideEl('game-over');
2904 hideEl('game-over');
2905 hideEl('online-panel');
2906 hideEl('spectator');
2907 hideEl('podium');
2275 showEl('hud');
2908 showEl('hud');
2276
2909
2277 app.planet = (typeof Planet !== 'undefined' ? Planet.defaultPlanet() : PlanetMod.defaultPlanet());
2910 app.planet = (typeof Planet !== 'undefined' ? Planet.defaultPlanet() : PlanetMod.defaultPlanet());
2278 app.core = new GameCore(app.planet, Math.random);
2911 var miss = opts.missChance;
2912 if (typeof miss === 'number' && isFinite(miss))
2913 { app.core = new GameCore(app.planet, Math.random, miss); }
2914 else
2915 { app.core = new GameCore(app.planet, Math.random); }
2279 app.mode = 'playing';
2916 app.mode = 'playing';
2917 app.online = !!opts.online;
2280 app.gameOverShown = false;
2918 app.gameOverShown = false;
2919 app.eliminatedReported = false;
2920 app.spectating = false;
2281 app.sprites = Object.create(null);
2921 app.sprites = Object.create(null);
2282 app.flames = Object.create(null);
2922 app.flames = Object.create(null);
2283 app.cells = [];
2923 app.cells = [];
@@ -2285,6 +2925,11 @@ function startPlay ()
2285 app.selectTween = null;
2925 app.selectTween = null;
2286
2926
2287 layout();
2927 layout();
2928 if (app.scene)
2929 {
2930 app.scene.destroy();
2931 app.scene = null;
2932 }
2288 app.scene = new Scene(app.fieldX, app.fieldY, app.fieldW, app.fieldH);
2933 app.scene = new Scene(app.fieldX, app.fieldY, app.fieldW, app.fieldH);
2289 app.scene.backgroundColor = { r: 12, g: 16, b: 32 };
2934 app.scene.backgroundColor = { r: 12, g: 16, b: 32 };
2290 app.scene.renderBackground = true;
2935 app.scene.renderBackground = true;
@@ -2292,11 +2937,16 @@ function startPlay ()
2292
2937
2293 buildCells();
2938 buildCells();
2294 app.manager = app.scene.addObject(makeManager());
2939 app.manager = app.scene.addObject(makeManager());
2295 bindPointer(app.scene.canvas);
2940 if (!app.spectating)
2941 { bindPointer(app.scene.canvas); }
2296 refreshHud();
2942 refreshHud();
2943 if (app.online)
2944 { showEl('minis'); }
2945 else
2946 { hideEl('minis'); }
2297}
2947}
2298
2948
2299function returnToMenu ()
2949function teardownPlay ()
2300{
2950{
2301 unbindPointer();
2951 unbindPointer();
2302 if (app.scene)
2952 if (app.scene)
@@ -2306,14 +2956,31 @@ function returnToMenu ()
2306 }
2956 }
2307 app.manager = null;
2957 app.manager = null;
2308 app.core = null;
2958 app.core = null;
2309 app.mode = 'menu';
2310 app.sprites = Object.create(null);
2959 app.sprites = Object.create(null);
2311 app.flames = Object.create(null);
2960 app.flames = Object.create(null);
2312 app.cells = [];
2961 app.cells = [];
2313 app.selectTween = null;
2962 app.selectTween = null;
2314
2963 app.pointerId = null;
2964 app.gameOverShown = false;
2315 hideEl('hud');
2965 hideEl('hud');
2316 hideEl('game-over');
2966 hideEl('game-over');
2967 hideEl('spectator');
2968 hideEl('minis');
2969 if (typeof Online !== 'undefined')
2970 { Online.clearFlights(); }
2971}
2972
2973function returnToMenu ()
2974{
2975 if (app.online && typeof Online !== 'undefined')
2976 {
2977 // Online matches do not dump you back to the solo menu:
2978 // elimination becomes spectating; a finished match shows the podium.
2979 return;
2980 }
2981 teardownPlay();
2982 app.mode = 'menu';
2983 app.online = false;
2317 showEl('menu');
2984 showEl('menu');
2318 var last = document.getElementById('last-score');
2985 var last = document.getElementById('last-score');
2319 if (app.lastScore > 0)
2986 if (app.lastScore > 0)
@@ -2361,16 +3028,26 @@ function layout ()
2361 }
3028 }
2362 catch (e) { /* ignore */ }
3029 catch (e) { /* ignore */ }
2363 app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop);
3030 app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop);
3031 app.miniH = 0;
3032 if (app.online)
3033 { app.miniH = Math.min(150, Math.max(86, Math.round(vh * 0.20))); }
2364 var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015));
3034 var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015));
2365 var availW = Math.max(80, vw - margin * 2);
3035 var availW = Math.max(80, vw - margin * 2);
2366 var availH = Math.max(80, vh - app.hudH - margin);
3036 var availH = Math.max(80, vh - app.hudH - app.miniH - margin);
2367 app.tile = Math.max(14, Math.floor(Math.min(availW / 10, availH / 13)));
3037 app.tile = Math.max(14, Math.floor(Math.min(availW / 10, availH / 13)));
2368 app.fieldW = app.tile * 10;
3038 app.fieldW = app.tile * 10;
2369 app.fieldH = app.tile * 13;
3039 app.fieldH = app.tile * 13;
2370 app.fieldX = Math.floor((vw - app.fieldW) / 2);
3040 app.fieldX = Math.floor((vw - app.fieldW) / 2);
2371 app.fieldY = app.hudH + Math.floor((vh - app.hudH - app.fieldH - margin / 2) / 2);
3041 var topBand = app.hudH + app.miniH;
2372 if (app.fieldY < app.hudH)
3042 app.fieldY = topBand + Math.floor((vh - topBand - app.fieldH - margin / 2) / 2);
2373 { app.fieldY = app.hudH; }
3043 if (app.fieldY < topBand)
3044 { app.fieldY = topBand; }
3045 var minis = document.getElementById('minis');
3046 if (minis)
3047 {
3048 minis.style.top = app.hudH + 'px';
3049 minis.style.maxHeight = app.miniH + 'px';
3050 }
2374
3051
2375 if (app.scene)
3052 if (app.scene)
2376 {
3053 {
@@ -2582,15 +3259,19 @@ function tickView (dt)
2582 updateSelectTween(dt);
3259 updateSelectTween(dt);
2583 syncSprites();
3260 syncSprites();
2584 refreshHud();
3261 refreshHud();
3262 tickOnline(dt);
2585
3263
2586 if (app.core.state === 'gameover' && !app.gameOverShown)
3264 if (app.core.state === 'gameover' && !app.gameOverShown)
2587 {
3265 {
2588 app.gameOverShown = true;
3266 app.gameOverShown = true;
2589 app.lastScore = app.core.score;
3267 app.lastScore = app.core.score;
2590 document.getElementById('go-score').textContent = String(app.lastScore);
3268 document.getElementById('go-score').textContent = String(app.lastScore);
2591 showEl('game-over');
3269 if (app.online)
3270 { onOnlineEliminated(); }
3271 else
3272 { showEl('game-over'); }
2592 }
3273 }
2593 if (app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY)
3274 if (!app.online && app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY)
2594 { returnToMenu(); }
3275 { returnToMenu(); }
2595}
3276}
2596
3277
@@ -2739,6 +3420,388 @@ window.addEventListener('orientationchange', function ()
2739 }, 120);
3420 }, 120);
2740});
3421});
2741
3422
3423/* ---------- online play (stage 2) ---------------------------------- */
3424
3425function tickOnline (dt)
3426{
3427 if (!app.online || typeof Online === 'undefined')
3428 { return; }
3429 if (app.core)
3430 {
3431 var shots = app.core.consumeOutgoingShots();
3432 for (var i = 0; i < shots.length; i++)
3433 {
3434 var s = shots[i];
3435 var start = fieldToViewport(s.col, s.y + 1);
3436 Online.rememberFlightLocal(s, start.x, start.y);
3437 }
3438 Online.queueShots(shots);
3439 }
3440 Online.tickFlights();
3441 Online.renderMinis(document.getElementById('minis'));
3442}
3443
3444function fieldToViewport (col, fieldY)
3445{
3446 var canvas = app.scene && app.scene.canvas;
3447 if (!canvas)
3448 { return { x: window.innerWidth / 2, y: 40 }; }
3449 var rect = canvas.getBoundingClientRect();
3450 var x = rect.left + ((col + 0.5) / 10) * rect.width;
3451 var y = rect.top + (1 - (fieldY / 13)) * rect.height;
3452 return { x: x, y: y };
3453}
3454
3455function onlinePayload ()
3456{
3457 if (!app.online || !app.core)
3458 { return {}; }
3459 return {
3460 snapshot: app.core.fieldSnapshot(),
3461 score: app.core.score,
3462 eliminated: app.core.state === 'gameover' || app.spectating || app.eliminatedReported
3463 };
3464}
3465
3466function onOnlineEliminated ()
3467{
3468 app.eliminatedReported = true;
3469 app.spectating = true;
3470 unbindPointer();
3471 hideEl('game-over');
3472 var lobby = typeof Online !== 'undefined' && Online.lobby;
3473 if (lobby && lobby.status === 'finished')
3474 {
3475 showPodium(lobby);
3476 return;
3477 }
3478 showEl('spectator');
3479}
3480
3481function showPodium (lobby)
3482{
3483 hideEl('spectator');
3484 hideEl('game-over');
3485 hideEl('online-panel');
3486 showEl('podium');
3487 var list = document.getElementById('podium-list');
3488 list.innerHTML = '';
3489 var ranks = (lobby && lobby.rankings) || [];
3490 for (var i = 0; i < ranks.length; i++)
3491 {
3492 var r = ranks[i];
3493 var li = document.createElement('li');
3494 var medal = r.place === 1 ? '1e' : (r.place === 2 ? '2e' : (r.place === 3 ? '3e' : r.place + 'e'));
3495 li.textContent = medal + ' ' + r.name + ' · ' + r.score + ' punten';
3496 list.appendChild(li);
3497 }
3498 var hint = document.getElementById('podium-hint');
3499 var secs = (lobby && lobby.podium_seconds) || 5;
3500 hint.textContent = 'Over ' + secs + ' seconden teruggaan naar de lobby…';
3501}
3502
3503function startOnlineMatch ()
3504{
3505 if (app.mode === 'playing' && app.online)
3506 { return; }
3507 var miss = (typeof Online !== 'undefined' && Online.lobby && Online.lobby.miss_chance != null)
3508 ? Online.lobby.miss_chance
3509 : (typeof Online !== 'undefined' ? Online.DEFAULT_MISS_CHANCE : 0.30);
3510 startPlay({ online: true, missChance: miss });
3511 if (typeof Online !== 'undefined')
3512 { Online.startPolling(onlinePayload); }
3513}
3514
3515function leaveOnlineMatch (goMenu)
3516{
3517 if (typeof Online !== 'undefined')
3518 {
3519 Online.stopPolling();
3520 Online.leaveLobby();
3521 Online.clearFlights();
3522 }
3523 teardownPlay();
3524 app.online = false;
3525 if (goMenu)
3526 {
3527 app.mode = 'menu';
3528 showEl('menu');
3529 }
3530 else
3531 {
3532 app.mode = 'online';
3533 openOnlinePanel();
3534 }
3535}
3536
3537function bindOnlineUi ()
3538{
3539 var onlineBtn = document.getElementById('btn-online');
3540 if (!onlineBtn)
3541 { return; }
3542 onlineBtn.addEventListener('click', function ()
3543 { openOnlinePanel(); });
3544
3545 var backs = document.querySelectorAll('[data-back-menu]');
3546 for (var i = 0; i < backs.length; i++)
3547 {
3548 backs[i].addEventListener('click', function ()
3549 {
3550 if (typeof Online !== 'undefined')
3551 { Online.stopPolling(); }
3552 hideEl('online-panel');
3553 app.mode = 'menu';
3554 app.online = false;
3555 showEl('menu');
3556 });
3557 }
3558
3559 document.getElementById('btn-create').addEventListener('click', function ()
3560 {
3561 Online.createLobby().then(function (data)
3562 {
3563 if (data && data.ok)
3564 {
3565 renderOnline();
3566 Online.startPolling(onlinePayload);
3567 }
3568 else
3569 { renderOnline(); }
3570 });
3571 });
3572
3573 document.getElementById('join-form').addEventListener('submit', function (e)
3574 {
3575 e.preventDefault();
3576 var code = (document.getElementById('join-code').value || '').trim();
3577 if (!code)
3578 { return; }
3579 Online.joinLobby(code).then(function ()
3580 {
3581 renderOnline();
3582 if (Online.lobby)
3583 { Online.startPolling(onlinePayload); }
3584 });
3585 });
3586
3587 document.getElementById('btn-ready').addEventListener('click', function ()
3588 {
3589 var me = Online.mePlayer();
3590 Online.setReady(!(me && me.ready)).then(renderOnline);
3591 });
3592
3593 document.getElementById('btn-start').addEventListener('click', function ()
3594 {
3595 Online.startGame().then(function (data)
3596 {
3597 if (data && data.ok)
3598 { startOnlineMatch(); }
3599 else
3600 { renderOnline(); }
3601 });
3602 });
3603
3604 document.getElementById('btn-leave-lobby').addEventListener('click', function ()
3605 {
3606 Online.leaveLobby().then(function ()
3607 {
3608 Online.stopPolling();
3609 renderOnline();
3610 });
3611 });
3612
3613 document.getElementById('btn-copy-code').addEventListener('click', function ()
3614 {
3615 var code = document.getElementById('lobby-code').textContent;
3616 if (navigator.clipboard && navigator.clipboard.writeText)
3617 { navigator.clipboard.writeText(code); }
3618 });
3619
3620 document.getElementById('btn-spectate').addEventListener('click', function ()
3621 {
3622 hideEl('spectator');
3623 app.spectating = true;
3624 });
3625
3626 document.getElementById('btn-leave-game').addEventListener('click', function ()
3627 { leaveOnlineMatch(false); });
3628
3629 if (typeof Online !== 'undefined')
3630 {
3631 Online.onChange = function ()
3632 { renderOnline(); };
3633 Online.onGameStart = function ()
3634 { startOnlineMatch(); };
3635 Online.onIncoming = function (incoming)
3636 {
3637 if (!app.core || app.core.state !== 'playing')
3638 { return; }
3639 for (var i = 0; i < incoming.length; i++)
3640 { app.core.ingestGarbage(); }
3641 };
3642 Online.onFinished = function (lobby)
3643 { showPodium(lobby); };
3644 Online.onLobbyReturn = function (lobby)
3645 {
3646 teardownPlay();
3647 app.online = false;
3648 app.mode = 'online';
3649 hideEl('podium');
3650 showEl('online-panel');
3651 renderOnline();
3652 Online.startPolling(onlinePayload);
3653 };
3654 }
3655
3656 var params = new URLSearchParams(window.location.search);
3657 if (params.get('online') === '1' || params.get('auth') === 'unconfigured')
3658 { openOnlinePanel(); }
3659}
3660
3661function openOnlinePanel ()
3662{
3663 hideEl('menu');
3664 hideEl('game-over');
3665 hideEl('podium');
3666 hideEl('spectator');
3667 showEl('online-panel');
3668 app.mode = 'online';
3669 setOnlineStatus('Even kijken of online spelen beschikbaar is…');
3670 if (typeof Online === 'undefined')
3671 {
3672 showOnlineError('Online spelen is in deze build niet geladen. Je kunt wel alleen spelen.');
3673 showOnly('online-unconfigured');
3674 return;
3675 }
3676 Online.refresh().then(function (data)
3677 {
3678 if (!data || data.ok === false)
3679 {
3680 var msg = (data && data.error) || 'Geen verbinding met de server.';
3681 showOnlineError(msg + ' Je kunt wel alleen spelen.');
3682 if (data && data.configured === false)
3683 { showOnly('online-unconfigured'); }
3684 else
3685 { showOnly('online-login'); }
3686 document.getElementById('btn-login').style.display = 'none';
3687 return;
3688 }
3689 renderOnline();
3690 if (Online.lobby)
3691 { Online.startPolling(onlinePayload); }
3692 });
3693}
3694
3695function setOnlineStatus (text)
3696{
3697 var el = document.getElementById('online-status');
3698 if (el)
3699 { el.textContent = text; }
3700}
3701
3702function showOnlineError (text)
3703{
3704 var el = document.getElementById('online-error');
3705 if (!el)
3706 { return; }
3707 if (!text)
3708 {
3709 el.hidden = true;
3710 el.textContent = '';
3711 return;
3712 }
3713 el.hidden = false;
3714 el.textContent = text;
3715}
3716
3717function showOnly (id)
3718{
3719 var ids = ['online-unconfigured', 'online-login', 'online-home', 'online-lobby'];
3720 for (var i = 0; i < ids.length; i++)
3721 { document.getElementById(ids[i]).hidden = (ids[i] !== id); }
3722}
3723
3724function renderOnline ()
3725{
3726 if (typeof Online === 'undefined')
3727 { return; }
3728 if (app.mode === 'playing' && app.online)
3729 {
3730 Online.renderMinis(document.getElementById('minis'));
3731 if (Online.lobby && Online.lobby.status === 'finished')
3732 { showPodium(Online.lobby); }
3733 return;
3734 }
3735 showOnlineError(Online.error);
3736 if (!Online.configured && !Online.me && !Online.local)
3737 {
3738 setOnlineStatus('Online spelen is nog niet ingesteld.');
3739 showOnly('online-unconfigured');
3740 return;
3741 }
3742 if (!Online.me)
3743 {
3744 setOnlineStatus('Log in om een lobby te maken of eraan deel te nemen.');
3745 showOnly('online-login');
3746 document.getElementById('btn-login').style.display = '';
3747 document.getElementById('btn-login').href = Online.loginUrl();
3748 document.getElementById('local-login').hidden = !Online.local;
3749 return;
3750 }
3751 if (Online.lobby)
3752 {
3753 setOnlineStatus('Lobby');
3754 showOnly('online-lobby');
3755 document.getElementById('lobby-me-name').textContent = Online.me.name;
3756 document.getElementById('lobby-code').textContent = Online.lobby.code;
3757 var list = document.getElementById('lobby-players');
3758 list.innerHTML = '';
3759 var players = Online.lobby.players || [];
3760 for (var i = 0; i < players.length; i++)
3761 {
3762 var p = players[i];
3763 var li = document.createElement('li');
3764 if (p.is_me)
3765 { li.classList.add('you'); }
3766 var label = p.name + (p.is_host ? ' (host)' : '') + (p.is_me ? ' (jij)' : '');
3767 var state = p.ready ? 'Gereed' : 'Wacht…';
3768 li.innerHTML = '<span>' + escapeText(label) + '</span><span class="'
3769 + (p.ready ? 'ready' : 'waiting') + '">' + state + '</span>';
3770 list.appendChild(li);
3771 }
3772 var me = Online.mePlayer();
3773 document.getElementById('btn-ready').textContent = (me && me.ready) ? 'Niet gereed' : 'Gereed';
3774 var start = document.getElementById('btn-start');
3775 start.hidden = !(Online.lobby && Online.me && Online.lobby.host_id === Online.me.id);
3776 start.disabled = !Online.lobby.can_start;
3777 var hint = document.getElementById('lobby-hint');
3778 if (Online.lobby.status === 'playing')
3779 { hint.textContent = 'Het spel start…'; }
3780 else if (players.length < 2)
3781 { hint.textContent = 'Wacht op minstens één andere speler. Deel de code.'; }
3782 else if (!Online.lobby.all_ready)
3783 { hint.textContent = 'Iedereen moet op Gereed drukken. De host start daarna.'; }
3784 else if (Online.lobby.can_start)
3785 { hint.textContent = 'Iedereen is gereed. Druk op Starten.'; }
3786 else
3787 { hint.textContent = 'Wachten tot de host start.'; }
3788 return;
3789 }
3790 setOnlineStatus('Hoi ' + Online.me.name + '. Maak een lobby of val in met een code.');
3791 showOnly('online-home');
3792 document.getElementById('me-name').textContent = Online.me.name;
3793 document.getElementById('local-login').hidden = !Online.local;
3794}
3795
3796function escapeText (s)
3797{
3798 return String(s)
3799 .replace(/&/g, '&amp;')
3800 .replace(/</g, '&lt;')
3801 .replace(/>/g, '&gt;')
3802 .replace(/"/g, '&quot;');
3803}
3804
2742/*
3805/*
2743 * End File:
3806 * End File:
2744 * /workspace/meteors/src/main.js
3807 * /workspace/meteors/src/main.js
src/build.sh +18 −0
@@ -1,5 +1,7 @@
1 1 #!/usr/bin/env bash
2 2 # Concatenate game sources into build/game.js, same pattern as raytracer / frameworkv3.
3 # Also copies the PHP API into build/ so a local `php -S` and the FTP deploy
4 # serve the same tree. data/config.php and any sqlite are NEVER copied.
3 5 set -euo pipefail
4 6 ROOT="$(cd "$(dirname "$0")/.." && pwd)"
5 7 BUILD_FILE="$ROOT/build/game.js"
@@ -15,6 +17,7 @@ FILES=(
15 17 "$SRC_DIR/planet.js"
16 18 "$SRC_DIR/easing.js"
17 19 "$SRC_DIR/gameCore.js"
20 "$SRC_DIR/online.js"
18 21 "$SRC_DIR/main.js"
19 22 )
20 23
@@ -38,4 +41,19 @@ do
38 41 printf "\n/*\n * End File:\n * %s\n */ \n" "$file" >> "$BUILD_FILE"
39 42 done
40 43
44 # PHP API lives next to the static game so api.php, auth.php and callback.php
45 # share a cookie path. Never copy secrets or the database.
46 SERVER="$ROOT/server"
47 cp -f "$SERVER/api.php" "$SERVER/auth.php" "$SERVER/callback.php" \
48 "$SERVER/logout.php" "$SERVER/router.php" "$SERVER/.htaccess" \
49 "$ROOT/build/"
50 mkdir -p "$ROOT/build/lib"
51 cp -f "$SERVER/lib/bootstrap.php" "$SERVER/lib/Store.php" "$ROOT/build/lib/"
52 mkdir -p "$ROOT/build/data"
53 cp -f "$SERVER/data/.htaccess" "$ROOT/build/data/.htaccess"
54 # Belt and braces: a leftover local config or db must never enter build/.
55 rm -f "$ROOT/build/data/config.php" "$ROOT/build/data/config.lock"
56 rm -f "$ROOT/build/data/"*.sqlite "$ROOT/build/data/"*.sqlite-journal
57 rm -rf "$ROOT/build/data/sessions"
58
41 59 printf "DONE\n"
@@ -1,5 +1,7 @@
1#!/usr/bin/env bash
1#!/usr/bin/env bash
2# Concatenate game sources into build/game.js, same pattern as raytracer / frameworkv3.
2# Concatenate game sources into build/game.js, same pattern as raytracer / frameworkv3.
3# Also copies the PHP API into build/ so a local `php -S` and the FTP deploy
4# serve the same tree. data/config.php and any sqlite are NEVER copied.
3set -euo pipefail
5set -euo pipefail
4ROOT="$(cd "$(dirname "$0")/.." && pwd)"
6ROOT="$(cd "$(dirname "$0")/.." && pwd)"
5BUILD_FILE="$ROOT/build/game.js"
7BUILD_FILE="$ROOT/build/game.js"
@@ -15,6 +17,7 @@ FILES=(
15 "$SRC_DIR/planet.js"
17 "$SRC_DIR/planet.js"
16 "$SRC_DIR/easing.js"
18 "$SRC_DIR/easing.js"
17 "$SRC_DIR/gameCore.js"
19 "$SRC_DIR/gameCore.js"
20 "$SRC_DIR/online.js"
18 "$SRC_DIR/main.js"
21 "$SRC_DIR/main.js"
19)
22)
20
23
@@ -38,4 +41,19 @@ do
38 printf "\n/*\n * End File:\n * %s\n */ \n" "$file" >> "$BUILD_FILE"
41 printf "\n/*\n * End File:\n * %s\n */ \n" "$file" >> "$BUILD_FILE"
39done
42done
40
43
44# PHP API lives next to the static game so api.php, auth.php and callback.php
45# share a cookie path. Never copy secrets or the database.
46SERVER="$ROOT/server"
47cp -f "$SERVER/api.php" "$SERVER/auth.php" "$SERVER/callback.php" \
48 "$SERVER/logout.php" "$SERVER/router.php" "$SERVER/.htaccess" \
49 "$ROOT/build/"
50mkdir -p "$ROOT/build/lib"
51cp -f "$SERVER/lib/bootstrap.php" "$SERVER/lib/Store.php" "$ROOT/build/lib/"
52mkdir -p "$ROOT/build/data"
53cp -f "$SERVER/data/.htaccess" "$ROOT/build/data/.htaccess"
54# Belt and braces: a leftover local config or db must never enter build/.
55rm -f "$ROOT/build/data/config.php" "$ROOT/build/data/config.lock"
56rm -f "$ROOT/build/data/"*.sqlite "$ROOT/build/data/"*.sqlite-journal
57rm -rf "$ROOT/build/data/sessions"
58
41printf "DONE\n"
59printf "DONE\n"
src/main.js +455 −15
@@ -3,8 +3,8 @@
3 3 /**
4 4 * View and input for Meteors. The simulation lives in GameCore; this file
5 5 * only draws it, scales it to the viewport, and translates pointer events
6 * into beginDrag / moveDrag / endDrag. Ready for a later multiplayer view
7 * that reuses the same core.
6 * into beginDrag / moveDrag / endDrag. Online play (stage 2) is wired
7 * through Online (src/online.js) and the same GameCore.
8 8 */
9 9
10 10 var IMAGES = [
@@ -42,7 +42,11 @@ var app = {
42 42 cells: [],
43 43 pointerId: null,
44 44 gameOverShown: false,
45 selectTween: null
45 selectTween: null,
46 online: false,
47 eliminatedReported: false,
48 spectating: false,
49 miniH: 0
46 50 };
47 51
48 52 window.onload = function ()
@@ -65,6 +69,8 @@ window.onload = function ()
65 69 if (game.images.flame && game.images.flame.addAnimationCycle)
66 70 { game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); }
67 71 });
72
73 bindOnlineUi();
68 74 };
69 75
70 76 function onPlay ()
@@ -74,16 +80,27 @@ function onPlay ()
74 80 startPlay();
75 81 }
76 82
77 function startPlay ()
83 function startPlay (opts)
78 84 {
85 opts = opts || {};
79 86 hideEl('menu');
80 87 hideEl('game-over');
88 hideEl('online-panel');
89 hideEl('spectator');
90 hideEl('podium');
81 91 showEl('hud');
82 92
83 93 app.planet = (typeof Planet !== 'undefined' ? Planet.defaultPlanet() : PlanetMod.defaultPlanet());
84 app.core = new GameCore(app.planet, Math.random);
94 var miss = opts.missChance;
95 if (typeof miss === 'number' && isFinite(miss))
96 { app.core = new GameCore(app.planet, Math.random, miss); }
97 else
98 { app.core = new GameCore(app.planet, Math.random); }
85 99 app.mode = 'playing';
100 app.online = !!opts.online;
86 101 app.gameOverShown = false;
102 app.eliminatedReported = false;
103 app.spectating = false;
87 104 app.sprites = Object.create(null);
88 105 app.flames = Object.create(null);
89 106 app.cells = [];
@@ -91,6 +108,11 @@ function startPlay ()
91 108 app.selectTween = null;
92 109
93 110 layout();
111 if (app.scene)
112 {
113 app.scene.destroy();
114 app.scene = null;
115 }
94 116 app.scene = new Scene(app.fieldX, app.fieldY, app.fieldW, app.fieldH);
95 117 app.scene.backgroundColor = { r: 12, g: 16, b: 32 };
96 118 app.scene.renderBackground = true;
@@ -98,11 +120,16 @@ function startPlay ()
98 120
99 121 buildCells();
100 122 app.manager = app.scene.addObject(makeManager());
101 bindPointer(app.scene.canvas);
123 if (!app.spectating)
124 { bindPointer(app.scene.canvas); }
102 125 refreshHud();
126 if (app.online)
127 { showEl('minis'); }
128 else
129 { hideEl('minis'); }
103 130 }
104 131
105 function returnToMenu ()
132 function teardownPlay ()
106 133 {
107 134 unbindPointer();
108 135 if (app.scene)
@@ -112,14 +139,31 @@ function returnToMenu ()
112 139 }
113 140 app.manager = null;
114 141 app.core = null;
115 app.mode = 'menu';
116 142 app.sprites = Object.create(null);
117 143 app.flames = Object.create(null);
118 144 app.cells = [];
119 145 app.selectTween = null;
120
146 app.pointerId = null;
147 app.gameOverShown = false;
121 148 hideEl('hud');
122 149 hideEl('game-over');
150 hideEl('spectator');
151 hideEl('minis');
152 if (typeof Online !== 'undefined')
153 { Online.clearFlights(); }
154 }
155
156 function returnToMenu ()
157 {
158 if (app.online && typeof Online !== 'undefined')
159 {
160 // Online matches do not dump you back to the solo menu:
161 // elimination becomes spectating; a finished match shows the podium.
162 return;
163 }
164 teardownPlay();
165 app.mode = 'menu';
166 app.online = false;
123 167 showEl('menu');
124 168 var last = document.getElementById('last-score');
125 169 if (app.lastScore > 0)
@@ -167,16 +211,26 @@ function layout ()
167 211 }
168 212 catch (e) { /* ignore */ }
169 213 app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop);
214 app.miniH = 0;
215 if (app.online)
216 { app.miniH = Math.min(150, Math.max(86, Math.round(vh * 0.20))); }
170 217 var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015));
171 218 var availW = Math.max(80, vw - margin * 2);
172 var availH = Math.max(80, vh - app.hudH - margin);
219 var availH = Math.max(80, vh - app.hudH - app.miniH - margin);
173 220 app.tile = Math.max(14, Math.floor(Math.min(availW / 10, availH / 13)));
174 221 app.fieldW = app.tile * 10;
175 222 app.fieldH = app.tile * 13;
176 223 app.fieldX = Math.floor((vw - app.fieldW) / 2);
177 app.fieldY = app.hudH + Math.floor((vh - app.hudH - app.fieldH - margin / 2) / 2);
178 if (app.fieldY < app.hudH)
179 { app.fieldY = app.hudH; }
224 var topBand = app.hudH + app.miniH;
225 app.fieldY = topBand + Math.floor((vh - topBand - app.fieldH - margin / 2) / 2);
226 if (app.fieldY < topBand)
227 { app.fieldY = topBand; }
228 var minis = document.getElementById('minis');
229 if (minis)
230 {
231 minis.style.top = app.hudH + 'px';
232 minis.style.maxHeight = app.miniH + 'px';
233 }
180 234
181 235 if (app.scene)
182 236 {
@@ -388,15 +442,19 @@ function tickView (dt)
388 442 updateSelectTween(dt);
389 443 syncSprites();
390 444 refreshHud();
445 tickOnline(dt);
391 446
392 447 if (app.core.state === 'gameover' && !app.gameOverShown)
393 448 {
394 449 app.gameOverShown = true;
395 450 app.lastScore = app.core.score;
396 451 document.getElementById('go-score').textContent = String(app.lastScore);
397 showEl('game-over');
452 if (app.online)
453 { onOnlineEliminated(); }
454 else
455 { showEl('game-over'); }
398 456 }
399 if (app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY)
457 if (!app.online && app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY)
400 458 { returnToMenu(); }
401 459 }
402 460
@@ -544,3 +602,385 @@ window.addEventListener('orientationchange', function ()
544 602 { layout(); }
545 603 }, 120);
546 604 });
605
606 /* ---------- online play (stage 2) ---------------------------------- */
607
608 function tickOnline (dt)
609 {
610 if (!app.online || typeof Online === 'undefined')
611 { return; }
612 if (app.core)
613 {
614 var shots = app.core.consumeOutgoingShots();
615 for (var i = 0; i < shots.length; i++)
616 {
617 var s = shots[i];
618 var start = fieldToViewport(s.col, s.y + 1);
619 Online.rememberFlightLocal(s, start.x, start.y);
620 }
621 Online.queueShots(shots);
622 }
623 Online.tickFlights();
624 Online.renderMinis(document.getElementById('minis'));
625 }
626
627 function fieldToViewport (col, fieldY)
628 {
629 var canvas = app.scene && app.scene.canvas;
630 if (!canvas)
631 { return { x: window.innerWidth / 2, y: 40 }; }
632 var rect = canvas.getBoundingClientRect();
633 var x = rect.left + ((col + 0.5) / 10) * rect.width;
634 var y = rect.top + (1 - (fieldY / 13)) * rect.height;
635 return { x: x, y: y };
636 }
637
638 function onlinePayload ()
639 {
640 if (!app.online || !app.core)
641 { return {}; }
642 return {
643 snapshot: app.core.fieldSnapshot(),
644 score: app.core.score,
645 eliminated: app.core.state === 'gameover' || app.spectating || app.eliminatedReported
646 };
647 }
648
649 function onOnlineEliminated ()
650 {
651 app.eliminatedReported = true;
652 app.spectating = true;
653 unbindPointer();
654 hideEl('game-over');
655 var lobby = typeof Online !== 'undefined' && Online.lobby;
656 if (lobby && lobby.status === 'finished')
657 {
658 showPodium(lobby);
659 return;
660 }
661 showEl('spectator');
662 }
663
664 function showPodium (lobby)
665 {
666 hideEl('spectator');
667 hideEl('game-over');
668 hideEl('online-panel');
669 showEl('podium');
670 var list = document.getElementById('podium-list');
671 list.innerHTML = '';
672 var ranks = (lobby && lobby.rankings) || [];
673 for (var i = 0; i < ranks.length; i++)
674 {
675 var r = ranks[i];
676 var li = document.createElement('li');
677 var medal = r.place === 1 ? '1e' : (r.place === 2 ? '2e' : (r.place === 3 ? '3e' : r.place + 'e'));
678 li.textContent = medal + ' ' + r.name + ' · ' + r.score + ' punten';
679 list.appendChild(li);
680 }
681 var hint = document.getElementById('podium-hint');
682 var secs = (lobby && lobby.podium_seconds) || 5;
683 hint.textContent = 'Over ' + secs + ' seconden teruggaan naar de lobby…';
684 }
685
686 function startOnlineMatch ()
687 {
688 if (app.mode === 'playing' && app.online)
689 { return; }
690 var miss = (typeof Online !== 'undefined' && Online.lobby && Online.lobby.miss_chance != null)
691 ? Online.lobby.miss_chance
692 : (typeof Online !== 'undefined' ? Online.DEFAULT_MISS_CHANCE : 0.30);
693 startPlay({ online: true, missChance: miss });
694 if (typeof Online !== 'undefined')
695 { Online.startPolling(onlinePayload); }
696 }
697
698 function leaveOnlineMatch (goMenu)
699 {
700 if (typeof Online !== 'undefined')
701 {
702 Online.stopPolling();
703 Online.leaveLobby();
704 Online.clearFlights();
705 }
706 teardownPlay();
707 app.online = false;
708 if (goMenu)
709 {
710 app.mode = 'menu';
711 showEl('menu');
712 }
713 else
714 {
715 app.mode = 'online';
716 openOnlinePanel();
717 }
718 }
719
720 function bindOnlineUi ()
721 {
722 var onlineBtn = document.getElementById('btn-online');
723 if (!onlineBtn)
724 { return; }
725 onlineBtn.addEventListener('click', function ()
726 { openOnlinePanel(); });
727
728 var backs = document.querySelectorAll('[data-back-menu]');
729 for (var i = 0; i < backs.length; i++)
730 {
731 backs[i].addEventListener('click', function ()
732 {
733 if (typeof Online !== 'undefined')
734 { Online.stopPolling(); }
735 hideEl('online-panel');
736 app.mode = 'menu';
737 app.online = false;
738 showEl('menu');
739 });
740 }
741
742 document.getElementById('btn-create').addEventListener('click', function ()
743 {
744 Online.createLobby().then(function (data)
745 {
746 if (data && data.ok)
747 {
748 renderOnline();
749 Online.startPolling(onlinePayload);
750 }
751 else
752 { renderOnline(); }
753 });
754 });
755
756 document.getElementById('join-form').addEventListener('submit', function (e)
757 {
758 e.preventDefault();
759 var code = (document.getElementById('join-code').value || '').trim();
760 if (!code)
761 { return; }
762 Online.joinLobby(code).then(function ()
763 {
764 renderOnline();
765 if (Online.lobby)
766 { Online.startPolling(onlinePayload); }
767 });
768 });
769
770 document.getElementById('btn-ready').addEventListener('click', function ()
771 {
772 var me = Online.mePlayer();
773 Online.setReady(!(me && me.ready)).then(renderOnline);
774 });
775
776 document.getElementById('btn-start').addEventListener('click', function ()
777 {
778 Online.startGame().then(function (data)
779 {
780 if (data && data.ok)
781 { startOnlineMatch(); }
782 else
783 { renderOnline(); }
784 });
785 });
786
787 document.getElementById('btn-leave-lobby').addEventListener('click', function ()
788 {
789 Online.leaveLobby().then(function ()
790 {
791 Online.stopPolling();
792 renderOnline();
793 });
794 });
795
796 document.getElementById('btn-copy-code').addEventListener('click', function ()
797 {
798 var code = document.getElementById('lobby-code').textContent;
799 if (navigator.clipboard && navigator.clipboard.writeText)
800 { navigator.clipboard.writeText(code); }
801 });
802
803 document.getElementById('btn-spectate').addEventListener('click', function ()
804 {
805 hideEl('spectator');
806 app.spectating = true;
807 });
808
809 document.getElementById('btn-leave-game').addEventListener('click', function ()
810 { leaveOnlineMatch(false); });
811
812 if (typeof Online !== 'undefined')
813 {
814 Online.onChange = function ()
815 { renderOnline(); };
816 Online.onGameStart = function ()
817 { startOnlineMatch(); };
818 Online.onIncoming = function (incoming)
819 {
820 if (!app.core || app.core.state !== 'playing')
821 { return; }
822 for (var i = 0; i < incoming.length; i++)
823 { app.core.ingestGarbage(); }
824 };
825 Online.onFinished = function (lobby)
826 { showPodium(lobby); };
827 Online.onLobbyReturn = function (lobby)
828 {
829 teardownPlay();
830 app.online = false;
831 app.mode = 'online';
832 hideEl('podium');
833 showEl('online-panel');
834 renderOnline();
835 Online.startPolling(onlinePayload);
836 };
837 }
838
839 var params = new URLSearchParams(window.location.search);
840 if (params.get('online') === '1' || params.get('auth') === 'unconfigured')
841 { openOnlinePanel(); }
842 }
843
844 function openOnlinePanel ()
845 {
846 hideEl('menu');
847 hideEl('game-over');
848 hideEl('podium');
849 hideEl('spectator');
850 showEl('online-panel');
851 app.mode = 'online';
852 setOnlineStatus('Even kijken of online spelen beschikbaar is…');
853 if (typeof Online === 'undefined')
854 {
855 showOnlineError('Online spelen is in deze build niet geladen. Je kunt wel alleen spelen.');
856 showOnly('online-unconfigured');
857 return;
858 }
859 Online.refresh().then(function (data)
860 {
861 if (!data || data.ok === false)
862 {
863 var msg = (data && data.error) || 'Geen verbinding met de server.';
864 showOnlineError(msg + ' Je kunt wel alleen spelen.');
865 if (data && data.configured === false)
866 { showOnly('online-unconfigured'); }
867 else
868 { showOnly('online-login'); }
869 document.getElementById('btn-login').style.display = 'none';
870 return;
871 }
872 renderOnline();
873 if (Online.lobby)
874 { Online.startPolling(onlinePayload); }
875 });
876 }
877
878 function setOnlineStatus (text)
879 {
880 var el = document.getElementById('online-status');
881 if (el)
882 { el.textContent = text; }
883 }
884
885 function showOnlineError (text)
886 {
887 var el = document.getElementById('online-error');
888 if (!el)
889 { return; }
890 if (!text)
891 {
892 el.hidden = true;
893 el.textContent = '';
894 return;
895 }
896 el.hidden = false;
897 el.textContent = text;
898 }
899
900 function showOnly (id)
901 {
902 var ids = ['online-unconfigured', 'online-login', 'online-home', 'online-lobby'];
903 for (var i = 0; i < ids.length; i++)
904 { document.getElementById(ids[i]).hidden = (ids[i] !== id); }
905 }
906
907 function renderOnline ()
908 {
909 if (typeof Online === 'undefined')
910 { return; }
911 if (app.mode === 'playing' && app.online)
912 {
913 Online.renderMinis(document.getElementById('minis'));
914 if (Online.lobby && Online.lobby.status === 'finished')
915 { showPodium(Online.lobby); }
916 return;
917 }
918 showOnlineError(Online.error);
919 if (!Online.configured && !Online.me && !Online.local)
920 {
921 setOnlineStatus('Online spelen is nog niet ingesteld.');
922 showOnly('online-unconfigured');
923 return;
924 }
925 if (!Online.me)
926 {
927 setOnlineStatus('Log in om een lobby te maken of eraan deel te nemen.');
928 showOnly('online-login');
929 document.getElementById('btn-login').style.display = '';
930 document.getElementById('btn-login').href = Online.loginUrl();
931 document.getElementById('local-login').hidden = !Online.local;
932 return;
933 }
934 if (Online.lobby)
935 {
936 setOnlineStatus('Lobby');
937 showOnly('online-lobby');
938 document.getElementById('lobby-me-name').textContent = Online.me.name;
939 document.getElementById('lobby-code').textContent = Online.lobby.code;
940 var list = document.getElementById('lobby-players');
941 list.innerHTML = '';
942 var players = Online.lobby.players || [];
943 for (var i = 0; i < players.length; i++)
944 {
945 var p = players[i];
946 var li = document.createElement('li');
947 if (p.is_me)
948 { li.classList.add('you'); }
949 var label = p.name + (p.is_host ? ' (host)' : '') + (p.is_me ? ' (jij)' : '');
950 var state = p.ready ? 'Gereed' : 'Wacht…';
951 li.innerHTML = '<span>' + escapeText(label) + '</span><span class="'
952 + (p.ready ? 'ready' : 'waiting') + '">' + state + '</span>';
953 list.appendChild(li);
954 }
955 var me = Online.mePlayer();
956 document.getElementById('btn-ready').textContent = (me && me.ready) ? 'Niet gereed' : 'Gereed';
957 var start = document.getElementById('btn-start');
958 start.hidden = !(Online.lobby && Online.me && Online.lobby.host_id === Online.me.id);
959 start.disabled = !Online.lobby.can_start;
960 var hint = document.getElementById('lobby-hint');
961 if (Online.lobby.status === 'playing')
962 { hint.textContent = 'Het spel start…'; }
963 else if (players.length < 2)
964 { hint.textContent = 'Wacht op minstens één andere speler. Deel de code.'; }
965 else if (!Online.lobby.all_ready)
966 { hint.textContent = 'Iedereen moet op Gereed drukken. De host start daarna.'; }
967 else if (Online.lobby.can_start)
968 { hint.textContent = 'Iedereen is gereed. Druk op Starten.'; }
969 else
970 { hint.textContent = 'Wachten tot de host start.'; }
971 return;
972 }
973 setOnlineStatus('Hoi ' + Online.me.name + '. Maak een lobby of val in met een code.');
974 showOnly('online-home');
975 document.getElementById('me-name').textContent = Online.me.name;
976 document.getElementById('local-login').hidden = !Online.local;
977 }
978
979 function escapeText (s)
980 {
981 return String(s)
982 .replace(/&/g, '&amp;')
983 .replace(/</g, '&lt;')
984 .replace(/>/g, '&gt;')
985 .replace(/"/g, '&quot;');
986 }
@@ -3,8 +3,8 @@
3/**
3/**
4 * View and input for Meteors. The simulation lives in GameCore; this file
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
5 * only draws it, scales it to the viewport, and translates pointer events
6 * into beginDrag / moveDrag / endDrag. Ready for a later multiplayer view
6 * into beginDrag / moveDrag / endDrag. Online play (stage 2) is wired
7 * that reuses the same core.
7 * through Online (src/online.js) and the same GameCore.
8 */
8 */
9
9
10var IMAGES = [
10var IMAGES = [
@@ -42,7 +42,11 @@ var app = {
42 cells: [],
42 cells: [],
43 pointerId: null,
43 pointerId: null,
44 gameOverShown: false,
44 gameOverShown: false,
45 selectTween: null
45 selectTween: null,
46 online: false,
47 eliminatedReported: false,
48 spectating: false,
49 miniH: 0
46};
50};
47
51
48window.onload = function ()
52window.onload = function ()
@@ -65,6 +69,8 @@ window.onload = function ()
65 if (game.images.flame && game.images.flame.addAnimationCycle)
69 if (game.images.flame && game.images.flame.addAnimationCycle)
66 { game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); }
70 { game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); }
67 });
71 });
72
73 bindOnlineUi();
68};
74};
69
75
70function onPlay ()
76function onPlay ()
@@ -74,16 +80,27 @@ function onPlay ()
74 startPlay();
80 startPlay();
75}
81}
76
82
77function startPlay ()
83function startPlay (opts)
78{
84{
85 opts = opts || {};
79 hideEl('menu');
86 hideEl('menu');
80 hideEl('game-over');
87 hideEl('game-over');
88 hideEl('online-panel');
89 hideEl('spectator');
90 hideEl('podium');
81 showEl('hud');
91 showEl('hud');
82
92
83 app.planet = (typeof Planet !== 'undefined' ? Planet.defaultPlanet() : PlanetMod.defaultPlanet());
93 app.planet = (typeof Planet !== 'undefined' ? Planet.defaultPlanet() : PlanetMod.defaultPlanet());
84 app.core = new GameCore(app.planet, Math.random);
94 var miss = opts.missChance;
95 if (typeof miss === 'number' && isFinite(miss))
96 { app.core = new GameCore(app.planet, Math.random, miss); }
97 else
98 { app.core = new GameCore(app.planet, Math.random); }
85 app.mode = 'playing';
99 app.mode = 'playing';
100 app.online = !!opts.online;
86 app.gameOverShown = false;
101 app.gameOverShown = false;
102 app.eliminatedReported = false;
103 app.spectating = false;
87 app.sprites = Object.create(null);
104 app.sprites = Object.create(null);
88 app.flames = Object.create(null);
105 app.flames = Object.create(null);
89 app.cells = [];
106 app.cells = [];
@@ -91,6 +108,11 @@ function startPlay ()
91 app.selectTween = null;
108 app.selectTween = null;
92
109
93 layout();
110 layout();
111 if (app.scene)
112 {
113 app.scene.destroy();
114 app.scene = null;
115 }
94 app.scene = new Scene(app.fieldX, app.fieldY, app.fieldW, app.fieldH);
116 app.scene = new Scene(app.fieldX, app.fieldY, app.fieldW, app.fieldH);
95 app.scene.backgroundColor = { r: 12, g: 16, b: 32 };
117 app.scene.backgroundColor = { r: 12, g: 16, b: 32 };
96 app.scene.renderBackground = true;
118 app.scene.renderBackground = true;
@@ -98,11 +120,16 @@ function startPlay ()
98
120
99 buildCells();
121 buildCells();
100 app.manager = app.scene.addObject(makeManager());
122 app.manager = app.scene.addObject(makeManager());
101 bindPointer(app.scene.canvas);
123 if (!app.spectating)
124 { bindPointer(app.scene.canvas); }
102 refreshHud();
125 refreshHud();
126 if (app.online)
127 { showEl('minis'); }
128 else
129 { hideEl('minis'); }
103}
130}
104
131
105function returnToMenu ()
132function teardownPlay ()
106{
133{
107 unbindPointer();
134 unbindPointer();
108 if (app.scene)
135 if (app.scene)
@@ -112,14 +139,31 @@ function returnToMenu ()
112 }
139 }
113 app.manager = null;
140 app.manager = null;
114 app.core = null;
141 app.core = null;
115 app.mode = 'menu';
116 app.sprites = Object.create(null);
142 app.sprites = Object.create(null);
117 app.flames = Object.create(null);
143 app.flames = Object.create(null);
118 app.cells = [];
144 app.cells = [];
119 app.selectTween = null;
145 app.selectTween = null;
120
146 app.pointerId = null;
147 app.gameOverShown = false;
121 hideEl('hud');
148 hideEl('hud');
122 hideEl('game-over');
149 hideEl('game-over');
150 hideEl('spectator');
151 hideEl('minis');
152 if (typeof Online !== 'undefined')
153 { Online.clearFlights(); }
154}
155
156function returnToMenu ()
157{
158 if (app.online && typeof Online !== 'undefined')
159 {
160 // Online matches do not dump you back to the solo menu:
161 // elimination becomes spectating; a finished match shows the podium.
162 return;
163 }
164 teardownPlay();
165 app.mode = 'menu';
166 app.online = false;
123 showEl('menu');
167 showEl('menu');
124 var last = document.getElementById('last-score');
168 var last = document.getElementById('last-score');
125 if (app.lastScore > 0)
169 if (app.lastScore > 0)
@@ -167,16 +211,26 @@ function layout ()
167 }
211 }
168 catch (e) { /* ignore */ }
212 catch (e) { /* ignore */ }
169 app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop);
213 app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop);
214 app.miniH = 0;
215 if (app.online)
216 { app.miniH = Math.min(150, Math.max(86, Math.round(vh * 0.20))); }
170 var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015));
217 var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015));
171 var availW = Math.max(80, vw - margin * 2);
218 var availW = Math.max(80, vw - margin * 2);
172 var availH = Math.max(80, vh - app.hudH - margin);
219 var availH = Math.max(80, vh - app.hudH - app.miniH - margin);
173 app.tile = Math.max(14, Math.floor(Math.min(availW / 10, availH / 13)));
220 app.tile = Math.max(14, Math.floor(Math.min(availW / 10, availH / 13)));
174 app.fieldW = app.tile * 10;
221 app.fieldW = app.tile * 10;
175 app.fieldH = app.tile * 13;
222 app.fieldH = app.tile * 13;
176 app.fieldX = Math.floor((vw - app.fieldW) / 2);
223 app.fieldX = Math.floor((vw - app.fieldW) / 2);
177 app.fieldY = app.hudH + Math.floor((vh - app.hudH - app.fieldH - margin / 2) / 2);
224 var topBand = app.hudH + app.miniH;
178 if (app.fieldY < app.hudH)
225 app.fieldY = topBand + Math.floor((vh - topBand - app.fieldH - margin / 2) / 2);
179 { app.fieldY = app.hudH; }
226 if (app.fieldY < topBand)
227 { app.fieldY = topBand; }
228 var minis = document.getElementById('minis');
229 if (minis)
230 {
231 minis.style.top = app.hudH + 'px';
232 minis.style.maxHeight = app.miniH + 'px';
233 }
180
234
181 if (app.scene)
235 if (app.scene)
182 {
236 {
@@ -388,15 +442,19 @@ function tickView (dt)
388 updateSelectTween(dt);
442 updateSelectTween(dt);
389 syncSprites();
443 syncSprites();
390 refreshHud();
444 refreshHud();
445 tickOnline(dt);
391
446
392 if (app.core.state === 'gameover' && !app.gameOverShown)
447 if (app.core.state === 'gameover' && !app.gameOverShown)
393 {
448 {
394 app.gameOverShown = true;
449 app.gameOverShown = true;
395 app.lastScore = app.core.score;
450 app.lastScore = app.core.score;
396 document.getElementById('go-score').textContent = String(app.lastScore);
451 document.getElementById('go-score').textContent = String(app.lastScore);
397 showEl('game-over');
452 if (app.online)
453 { onOnlineEliminated(); }
454 else
455 { showEl('game-over'); }
398 }
456 }
399 if (app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY)
457 if (!app.online && app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY)
400 { returnToMenu(); }
458 { returnToMenu(); }
401}
459}
402
460
@@ -544,3 +602,385 @@ window.addEventListener('orientationchange', function ()
544 { layout(); }
602 { layout(); }
545 }, 120);
603 }, 120);
546});
604});
605
606/* ---------- online play (stage 2) ---------------------------------- */
607
608function tickOnline (dt)
609{
610 if (!app.online || typeof Online === 'undefined')
611 { return; }
612 if (app.core)
613 {
614 var shots = app.core.consumeOutgoingShots();
615 for (var i = 0; i < shots.length; i++)
616 {
617 var s = shots[i];
618 var start = fieldToViewport(s.col, s.y + 1);
619 Online.rememberFlightLocal(s, start.x, start.y);
620 }
621 Online.queueShots(shots);
622 }
623 Online.tickFlights();
624 Online.renderMinis(document.getElementById('minis'));
625}
626
627function fieldToViewport (col, fieldY)
628{
629 var canvas = app.scene && app.scene.canvas;
630 if (!canvas)
631 { return { x: window.innerWidth / 2, y: 40 }; }
632 var rect = canvas.getBoundingClientRect();
633 var x = rect.left + ((col + 0.5) / 10) * rect.width;
634 var y = rect.top + (1 - (fieldY / 13)) * rect.height;
635 return { x: x, y: y };
636}
637
638function onlinePayload ()
639{
640 if (!app.online || !app.core)
641 { return {}; }
642 return {
643 snapshot: app.core.fieldSnapshot(),
644 score: app.core.score,
645 eliminated: app.core.state === 'gameover' || app.spectating || app.eliminatedReported
646 };
647}
648
649function onOnlineEliminated ()
650{
651 app.eliminatedReported = true;
652 app.spectating = true;
653 unbindPointer();
654 hideEl('game-over');
655 var lobby = typeof Online !== 'undefined' && Online.lobby;
656 if (lobby && lobby.status === 'finished')
657 {
658 showPodium(lobby);
659 return;
660 }
661 showEl('spectator');
662}
663
664function showPodium (lobby)
665{
666 hideEl('spectator');
667 hideEl('game-over');
668 hideEl('online-panel');
669 showEl('podium');
670 var list = document.getElementById('podium-list');
671 list.innerHTML = '';
672 var ranks = (lobby && lobby.rankings) || [];
673 for (var i = 0; i < ranks.length; i++)
674 {
675 var r = ranks[i];
676 var li = document.createElement('li');
677 var medal = r.place === 1 ? '1e' : (r.place === 2 ? '2e' : (r.place === 3 ? '3e' : r.place + 'e'));
678 li.textContent = medal + ' ' + r.name + ' · ' + r.score + ' punten';
679 list.appendChild(li);
680 }
681 var hint = document.getElementById('podium-hint');
682 var secs = (lobby && lobby.podium_seconds) || 5;
683 hint.textContent = 'Over ' + secs + ' seconden teruggaan naar de lobby…';
684}
685
686function startOnlineMatch ()
687{
688 if (app.mode === 'playing' && app.online)
689 { return; }
690 var miss = (typeof Online !== 'undefined' && Online.lobby && Online.lobby.miss_chance != null)
691 ? Online.lobby.miss_chance
692 : (typeof Online !== 'undefined' ? Online.DEFAULT_MISS_CHANCE : 0.30);
693 startPlay({ online: true, missChance: miss });
694 if (typeof Online !== 'undefined')
695 { Online.startPolling(onlinePayload); }
696}
697
698function leaveOnlineMatch (goMenu)
699{
700 if (typeof Online !== 'undefined')
701 {
702 Online.stopPolling();
703 Online.leaveLobby();
704 Online.clearFlights();
705 }
706 teardownPlay();
707 app.online = false;
708 if (goMenu)
709 {
710 app.mode = 'menu';
711 showEl('menu');
712 }
713 else
714 {
715 app.mode = 'online';
716 openOnlinePanel();
717 }
718}
719
720function bindOnlineUi ()
721{
722 var onlineBtn = document.getElementById('btn-online');
723 if (!onlineBtn)
724 { return; }
725 onlineBtn.addEventListener('click', function ()
726 { openOnlinePanel(); });
727
728 var backs = document.querySelectorAll('[data-back-menu]');
729 for (var i = 0; i < backs.length; i++)
730 {
731 backs[i].addEventListener('click', function ()
732 {
733 if (typeof Online !== 'undefined')
734 { Online.stopPolling(); }
735 hideEl('online-panel');
736 app.mode = 'menu';
737 app.online = false;
738 showEl('menu');
739 });
740 }
741
742 document.getElementById('btn-create').addEventListener('click', function ()
743 {
744 Online.createLobby().then(function (data)
745 {
746 if (data && data.ok)
747 {
748 renderOnline();
749 Online.startPolling(onlinePayload);
750 }
751 else
752 { renderOnline(); }
753 });
754 });
755
756 document.getElementById('join-form').addEventListener('submit', function (e)
757 {
758 e.preventDefault();
759 var code = (document.getElementById('join-code').value || '').trim();
760 if (!code)
761 { return; }
762 Online.joinLobby(code).then(function ()
763 {
764 renderOnline();
765 if (Online.lobby)
766 { Online.startPolling(onlinePayload); }
767 });
768 });
769
770 document.getElementById('btn-ready').addEventListener('click', function ()
771 {
772 var me = Online.mePlayer();
773 Online.setReady(!(me && me.ready)).then(renderOnline);
774 });
775
776 document.getElementById('btn-start').addEventListener('click', function ()
777 {
778 Online.startGame().then(function (data)
779 {
780 if (data && data.ok)
781 { startOnlineMatch(); }
782 else
783 { renderOnline(); }
784 });
785 });
786
787 document.getElementById('btn-leave-lobby').addEventListener('click', function ()
788 {
789 Online.leaveLobby().then(function ()
790 {
791 Online.stopPolling();
792 renderOnline();
793 });
794 });
795
796 document.getElementById('btn-copy-code').addEventListener('click', function ()
797 {
798 var code = document.getElementById('lobby-code').textContent;
799 if (navigator.clipboard && navigator.clipboard.writeText)
800 { navigator.clipboard.writeText(code); }
801 });
802
803 document.getElementById('btn-spectate').addEventListener('click', function ()
804 {
805 hideEl('spectator');
806 app.spectating = true;
807 });
808
809 document.getElementById('btn-leave-game').addEventListener('click', function ()
810 { leaveOnlineMatch(false); });
811
812 if (typeof Online !== 'undefined')
813 {
814 Online.onChange = function ()
815 { renderOnline(); };
816 Online.onGameStart = function ()
817 { startOnlineMatch(); };
818 Online.onIncoming = function (incoming)
819 {
820 if (!app.core || app.core.state !== 'playing')
821 { return; }
822 for (var i = 0; i < incoming.length; i++)
823 { app.core.ingestGarbage(); }
824 };
825 Online.onFinished = function (lobby)
826 { showPodium(lobby); };
827 Online.onLobbyReturn = function (lobby)
828 {
829 teardownPlay();
830 app.online = false;
831 app.mode = 'online';
832 hideEl('podium');
833 showEl('online-panel');
834 renderOnline();
835 Online.startPolling(onlinePayload);
836 };
837 }
838
839 var params = new URLSearchParams(window.location.search);
840 if (params.get('online') === '1' || params.get('auth') === 'unconfigured')
841 { openOnlinePanel(); }
842}
843
844function openOnlinePanel ()
845{
846 hideEl('menu');
847 hideEl('game-over');
848 hideEl('podium');
849 hideEl('spectator');
850 showEl('online-panel');
851 app.mode = 'online';
852 setOnlineStatus('Even kijken of online spelen beschikbaar is…');
853 if (typeof Online === 'undefined')
854 {
855 showOnlineError('Online spelen is in deze build niet geladen. Je kunt wel alleen spelen.');
856 showOnly('online-unconfigured');
857 return;
858 }
859 Online.refresh().then(function (data)
860 {
861 if (!data || data.ok === false)
862 {
863 var msg = (data && data.error) || 'Geen verbinding met de server.';
864 showOnlineError(msg + ' Je kunt wel alleen spelen.');
865 if (data && data.configured === false)
866 { showOnly('online-unconfigured'); }
867 else
868 { showOnly('online-login'); }
869 document.getElementById('btn-login').style.display = 'none';
870 return;
871 }
872 renderOnline();
873 if (Online.lobby)
874 { Online.startPolling(onlinePayload); }
875 });
876}
877
878function setOnlineStatus (text)
879{
880 var el = document.getElementById('online-status');
881 if (el)
882 { el.textContent = text; }
883}
884
885function showOnlineError (text)
886{
887 var el = document.getElementById('online-error');
888 if (!el)
889 { return; }
890 if (!text)
891 {
892 el.hidden = true;
893 el.textContent = '';
894 return;
895 }
896 el.hidden = false;
897 el.textContent = text;
898}
899
900function showOnly (id)
901{
902 var ids = ['online-unconfigured', 'online-login', 'online-home', 'online-lobby'];
903 for (var i = 0; i < ids.length; i++)
904 { document.getElementById(ids[i]).hidden = (ids[i] !== id); }
905}
906
907function renderOnline ()
908{
909 if (typeof Online === 'undefined')
910 { return; }
911 if (app.mode === 'playing' && app.online)
912 {
913 Online.renderMinis(document.getElementById('minis'));
914 if (Online.lobby && Online.lobby.status === 'finished')
915 { showPodium(Online.lobby); }
916 return;
917 }
918 showOnlineError(Online.error);
919 if (!Online.configured && !Online.me && !Online.local)
920 {
921 setOnlineStatus('Online spelen is nog niet ingesteld.');
922 showOnly('online-unconfigured');
923 return;
924 }
925 if (!Online.me)
926 {
927 setOnlineStatus('Log in om een lobby te maken of eraan deel te nemen.');
928 showOnly('online-login');
929 document.getElementById('btn-login').style.display = '';
930 document.getElementById('btn-login').href = Online.loginUrl();
931 document.getElementById('local-login').hidden = !Online.local;
932 return;
933 }
934 if (Online.lobby)
935 {
936 setOnlineStatus('Lobby');
937 showOnly('online-lobby');
938 document.getElementById('lobby-me-name').textContent = Online.me.name;
939 document.getElementById('lobby-code').textContent = Online.lobby.code;
940 var list = document.getElementById('lobby-players');
941 list.innerHTML = '';
942 var players = Online.lobby.players || [];
943 for (var i = 0; i < players.length; i++)
944 {
945 var p = players[i];
946 var li = document.createElement('li');
947 if (p.is_me)
948 { li.classList.add('you'); }
949 var label = p.name + (p.is_host ? ' (host)' : '') + (p.is_me ? ' (jij)' : '');
950 var state = p.ready ? 'Gereed' : 'Wacht…';
951 li.innerHTML = '<span>' + escapeText(label) + '</span><span class="'
952 + (p.ready ? 'ready' : 'waiting') + '">' + state + '</span>';
953 list.appendChild(li);
954 }
955 var me = Online.mePlayer();
956 document.getElementById('btn-ready').textContent = (me && me.ready) ? 'Niet gereed' : 'Gereed';
957 var start = document.getElementById('btn-start');
958 start.hidden = !(Online.lobby && Online.me && Online.lobby.host_id === Online.me.id);
959 start.disabled = !Online.lobby.can_start;
960 var hint = document.getElementById('lobby-hint');
961 if (Online.lobby.status === 'playing')
962 { hint.textContent = 'Het spel start…'; }
963 else if (players.length < 2)
964 { hint.textContent = 'Wacht op minstens één andere speler. Deel de code.'; }
965 else if (!Online.lobby.all_ready)
966 { hint.textContent = 'Iedereen moet op Gereed drukken. De host start daarna.'; }
967 else if (Online.lobby.can_start)
968 { hint.textContent = 'Iedereen is gereed. Druk op Starten.'; }
969 else
970 { hint.textContent = 'Wachten tot de host start.'; }
971 return;
972 }
973 setOnlineStatus('Hoi ' + Online.me.name + '. Maak een lobby of val in met een code.');
974 showOnly('online-home');
975 document.getElementById('me-name').textContent = Online.me.name;
976 document.getElementById('local-login').hidden = !Online.local;
977}
978
979function escapeText (s)
980{
981 return String(s)
982 .replace(/&/g, '&amp;')
983 .replace(/</g, '&lt;')
984 .replace(/>/g, '&gt;')
985 .replace(/"/g, '&quot;');
986}
src/online.js +7 −1
@@ -137,7 +137,13 @@ Online.setReady = function (ready)
137 137
138 138 Online.startGame = function ()
139 139 {
140 return this.request('lobby_start');
140 var self = this;
141 var prev = this.lobby && this.lobby.status;
142 return this.request('lobby_start').then(function (data)
143 {
144 self._handleTransitions(prev, data);
145 return data;
146 });
141 147 };
142 148
143 149 Online.queueShots = function (shots)
@@ -137,7 +137,13 @@ Online.setReady = function (ready)
137
137
138Online.startGame = function ()
138Online.startGame = function ()
139{
139{
140 return this.request('lobby_start');
140 var self = this;
141 var prev = this.lobby && this.lobby.status;
142 return this.request('lobby_start').then(function (data)
143 {
144 self._handleTransitions(prev, data);
145 return data;
146 });
141};
147};
142
148
143Online.queueShots = function (shots)
149Online.queueShots = function (shots)