BlueGit

projects-timfalken-com meteors

Merge branch 'feature/t1173-reward-screen'

timfa Grok Bot · pushed by timfa

Authored 2026-11-14 · 3 days ago

Hash
443a53208de578187ef71c388cf5f7563893450d
Pipeline
Passed
11 files changed +2072 −39
README.md +15 −0
@@ -66,6 +66,7 @@ De spelkern is deterministisch en staat los van tekenen en invoer, zodat stage 2
66 66 | `src/gameCore.js` | Simulatie: vallen, wisselen, match-3, raketsprong, linken, push-up + her-sprong, landen als starre groep + 3 s wachten, kolom-slot, game over, punten; stage 2: `outgoingShots`, `ingestGarbage`, `missChance`, `fieldSnapshot` |
67 67 | `src/main.js` | Menu, HUD, frameworkv3-scene, muis/touch, schaal naar het scherm, landing-bounce, selectie-tween, online-lobby |
68 68 | `src/offline.js` | Offline Strijd: progressie, bot-AI, lokale 'multiplayer'-schoten |
69 | `src/reward.js` | Puntenscherm na een spel/ronde (t1173): timing (5 + t blokjes/s) en de overlay |
69 70 | `src/online.js` | API-client, polling, opponent-miniaturen, vlucht-tweens van afgeschoten blokjes |
70 71 | `server/` | PHP API: OAuth, lobby, shots, SQLite in `data/` (niet gedeployed) |
71 72 | `server/lib/planets.json` | Catalogus van 12 planeten (JS en PHP delen dit bestand) |
@@ -140,6 +141,20 @@ Lokaal inloggen: `auth.php?test=1`. Op de live site blijft de
140 141 ontwerper verborgen tot OAuth (`callback.php` + CI-geheim
141 142 `auth_client_secret`) is ingesteld.
142 143
144 ## Puntenscherm (ingelogd)
145
146 Na een spel in **Spelen**, na elke ronde van **Offline Strijd** en na
147 een **Online**-wedstrijd zie je als ingelogde speler eerst midden in
148 beeld “You won!” of “You lost...” (in de gekozen taal). Na een seconde
149 schuift die tekst naar boven en vliegen blokjes van jouw planeet (ook
150 eigen planeten) in boogjes naar het getal onderaan: je profieltotaal.
151 Elk blokje is één nieuw verdiend punt, dus het getal loopt van het
152 totaal vóór de ronde naar het nieuwe totaal dat de server bevestigt.
153 Het tempo begint op 5 blokjes per seconde en wordt elke seconde 1
154 blokje/s sneller (253 punten ≈ 18 s). Daarna ga je, net als voorheen,
155 naar het menu, de volgende ronde, het resultaatscherm of de lobby.
156 Uitgelogd verandert er niets. Zie `docs/ASSUMPTIONS.md` (t1173).
157
143 158 ## Taalkeuze
144 159
145 160 Het spel is standaard Engels. Rechtsonder op het hoofdmenu staat de
@@ -66,6 +66,7 @@ De spelkern is deterministisch en staat los van tekenen en invoer, zodat stage 2
66| `src/gameCore.js` | Simulatie: vallen, wisselen, match-3, raketsprong, linken, push-up + her-sprong, landen als starre groep + 3 s wachten, kolom-slot, game over, punten; stage 2: `outgoingShots`, `ingestGarbage`, `missChance`, `fieldSnapshot` |
66| `src/gameCore.js` | Simulatie: vallen, wisselen, match-3, raketsprong, linken, push-up + her-sprong, landen als starre groep + 3 s wachten, kolom-slot, game over, punten; stage 2: `outgoingShots`, `ingestGarbage`, `missChance`, `fieldSnapshot` |
67| `src/main.js` | Menu, HUD, frameworkv3-scene, muis/touch, schaal naar het scherm, landing-bounce, selectie-tween, online-lobby |
67| `src/main.js` | Menu, HUD, frameworkv3-scene, muis/touch, schaal naar het scherm, landing-bounce, selectie-tween, online-lobby |
68| `src/offline.js` | Offline Strijd: progressie, bot-AI, lokale 'multiplayer'-schoten |
68| `src/offline.js` | Offline Strijd: progressie, bot-AI, lokale 'multiplayer'-schoten |
69| `src/reward.js` | Puntenscherm na een spel/ronde (t1173): timing (5 + t blokjes/s) en de overlay |
69| `src/online.js` | API-client, polling, opponent-miniaturen, vlucht-tweens van afgeschoten blokjes |
70| `src/online.js` | API-client, polling, opponent-miniaturen, vlucht-tweens van afgeschoten blokjes |
70| `server/` | PHP API: OAuth, lobby, shots, SQLite in `data/` (niet gedeployed) |
71| `server/` | PHP API: OAuth, lobby, shots, SQLite in `data/` (niet gedeployed) |
71| `server/lib/planets.json` | Catalogus van 12 planeten (JS en PHP delen dit bestand) |
72| `server/lib/planets.json` | Catalogus van 12 planeten (JS en PHP delen dit bestand) |
@@ -140,6 +141,20 @@ Lokaal inloggen: `auth.php?test=1`. Op de live site blijft de
140ontwerper verborgen tot OAuth (`callback.php` + CI-geheim
141ontwerper verborgen tot OAuth (`callback.php` + CI-geheim
141`auth_client_secret`) is ingesteld.
142`auth_client_secret`) is ingesteld.
142
143
144## Puntenscherm (ingelogd)
145
146Na een spel in **Spelen**, na elke ronde van **Offline Strijd** en na
147een **Online**-wedstrijd zie je als ingelogde speler eerst midden in
148beeld “You won!” of “You lost...” (in de gekozen taal). Na een seconde
149schuift die tekst naar boven en vliegen blokjes van jouw planeet (ook
150eigen planeten) in boogjes naar het getal onderaan: je profieltotaal.
151Elk blokje is één nieuw verdiend punt, dus het getal loopt van het
152totaal vóór de ronde naar het nieuwe totaal dat de server bevestigt.
153Het tempo begint op 5 blokjes per seconde en wordt elke seconde 1
154blokje/s sneller (253 punten ≈ 18 s). Daarna ga je, net als voorheen,
155naar het menu, de volgende ronde, het resultaatscherm of de lobby.
156Uitgelogd verandert er niets. Zie `docs/ASSUMPTIONS.md` (t1173).
157
143## Taalkeuze
158## Taalkeuze
144
159
145Het spel is standaard Engels. Rechtsonder op het hoofdmenu staat de
160Het spel is standaard Engels. Rechtsonder op het hoofdmenu staat de
build/game.js +696 −19
@@ -1301,7 +1301,11 @@ var I18N_CATALOG = {
1301 1301 "block.forge-brass": "Forge brass",
1302 1302 "block.forge-soot": "Forge soot",
1303 1303 "error.webgl": "This game needs WebGL. Please try another browser, or turn on hardware acceleration.",
1304 "error.startFailed": "Could not start the game."
1304 "error.startFailed": "Could not start the game.",
1305 "reward.won": "You won!",
1306 "reward.lost": "You lost...",
1307 "reward.total": "Total points",
1308 "reward.continue": "Tap to continue"
1305 1309 },
1306 1310 "nl": {
1307 1311 "menu.tagline": "Drie op een rij, en je blokjes krijgen raketmotoren.",
@@ -1582,7 +1586,11 @@ var I18N_CATALOG = {
1582 1586 "block.forge-brass": "Forge-messing",
1583 1587 "block.forge-soot": "Forge-roet",
1584 1588 "error.webgl": "Dit spel heeft WebGL nodig. Probeer een andere browser, of zet hardwareversnelling aan.",
1585 "error.startFailed": "Het spel kon niet worden gestart."
1589 "error.startFailed": "Het spel kon niet worden gestart.",
1590 "reward.won": "Gewonnen!",
1591 "reward.lost": "Verloren...",
1592 "reward.total": "Totaal punten",
1593 "reward.continue": "Tik om verder te gaan"
1586 1594 },
1587 1595 "de": {
1588 1596 "menu.tagline": "Drei in einer Reihe — und deine Blöcke bekommen Raketenantrieb.",
@@ -1863,7 +1871,11 @@ var I18N_CATALOG = {
1863 1871 "block.forge-brass": "Forge-Messing",
1864 1872 "block.forge-soot": "Forge-Ruß",
1865 1873 "error.webgl": "Dieses Spiel benötigt WebGL. Bitte verwende einen anderen Browser oder aktiviere die Hardwarebeschleunigung.",
1866 "error.startFailed": "Das Spiel konnte nicht gestartet werden."
1874 "error.startFailed": "Das Spiel konnte nicht gestartet werden.",
1875 "reward.won": "Gewonnen!",
1876 "reward.lost": "Verloren...",
1877 "reward.total": "Punkte gesamt",
1878 "reward.continue": "Tippen zum Fortfahren"
1867 1879 },
1868 1880 "fr": {
1869 1881 "menu.tagline": "Trois d’affilée, et tes blocs s’équipent de propulseurs.",
@@ -2144,7 +2156,11 @@ var I18N_CATALOG = {
2144 2156 "block.forge-brass": "Forge laiton",
2145 2157 "block.forge-soot": "Forge suie",
2146 2158 "error.webgl": "Ce jeu a besoin de WebGL. Essayez un autre navigateur, ou activez l’accélération matérielle.",
2147 "error.startFailed": "Impossible de lancer le jeu."
2159 "error.startFailed": "Impossible de lancer le jeu.",
2160 "reward.won": "Victoire !",
2161 "reward.lost": "Perdu...",
2162 "reward.total": "Total des points",
2163 "reward.continue": "Touchez pour continuer"
2148 2164 },
2149 2165 "ja": {
2150 2166 "menu.tagline": "三つ揃えると、ブロックにロケットが点火します。",
@@ -2425,7 +2441,11 @@ var I18N_CATALOG = {
2425 2441 "block.forge-brass": "フォージの真鍮",
2426 2442 "block.forge-soot": "フォージの煤",
2427 2443 "error.webgl": "このゲームにはWebGLが必要です。別のブラウザを使うか、ハードウェアアクセラレーションを有効にしてください。",
2428 "error.startFailed": "ゲームを開始できませんでした。"
2444 "error.startFailed": "ゲームを開始できませんでした。",
2445 "reward.won": "勝利!",
2446 "reward.lost": "敗北...",
2447 "reward.total": "合計ポイント",
2448 "reward.continue": "タップして続ける"
2429 2449 },
2430 2450 "zh": {
2431 2451 "menu.tagline": "三个一排,你的方块就会装上火箭。",
@@ -2706,7 +2726,11 @@ var I18N_CATALOG = {
2706 2726 "block.forge-brass": "Forge黄铜",
2707 2727 "block.forge-soot": "Forge煤烟",
2708 2728 "error.webgl": "本游戏需要 WebGL。请尝试其他浏览器,或开启硬件加速。",
2709 "error.startFailed": "无法开始游戏。"
2729 "error.startFailed": "无法开始游戏。",
2730 "reward.won": "你赢了!",
2731 "reward.lost": "你输了...",
2732 "reward.total": "总积分",
2733 "reward.continue": "点击继续"
2710 2734 },
2711 2735 "ko": {
2712 2736 "menu.tagline": "세 개를 나란히 맞추면 블록에 로켓이 점화됩니다.",
@@ -2987,7 +3011,11 @@ var I18N_CATALOG = {
2987 3011 "block.forge-brass": "Forge 황동",
2988 3012 "block.forge-soot": "Forge 그을음",
2989 3013 "error.webgl": "이 게임은 WebGL이 필요합니다. 다른 브라우저를 사용하거나 하드웨어 가속을 켜 주세요.",
2990 "error.startFailed": "게임을 시작할 수 없습니다."
3014 "error.startFailed": "게임을 시작할 수 없습니다.",
3015 "reward.won": "승리!",
3016 "reward.lost": "패배...",
3017 "reward.total": "총 포인트",
3018 "reward.continue": "탭하여 계속"
2991 3019 },
2992 3020 "pl": {
2993 3021 "menu.tagline": "Trzy w rzędzie, a twoje klocki dostają napęd rakietowy.",
@@ -3268,7 +3296,11 @@ var I18N_CATALOG = {
3268 3296 "block.forge-brass": "Forge mosiądz",
3269 3297 "block.forge-soot": "Forge sadza",
3270 3298 "error.webgl": "Ta gra wymaga WebGL. Spróbuj innej przeglądarki albo włącz akcelerację sprzętową.",
3271 "error.startFailed": "Nie udało się uruchomić gry."
3299 "error.startFailed": "Nie udało się uruchomić gry.",
3300 "reward.won": "Wygrana!",
3301 "reward.lost": "Przegrana...",
3302 "reward.total": "Suma punktów",
3303 "reward.continue": "Dotknij, aby kontynuować"
3272 3304 },
3273 3305 "ru": {
3274 3306 "menu.tagline": "Три в ряд — и твои блоки получают ракетные двигатели.",
@@ -3549,7 +3581,11 @@ var I18N_CATALOG = {
3549 3581 "block.forge-brass": "Forge (латунь)",
3550 3582 "block.forge-soot": "Forge (сажа)",
3551 3583 "error.webgl": "Этой игре нужен WebGL. Попробуйте другой браузер или включите аппаратное ускорение.",
3552 "error.startFailed": "Не удалось начать игру."
3584 "error.startFailed": "Не удалось начать игру.",
3585 "reward.won": "Победа!",
3586 "reward.lost": "Поражение...",
3587 "reward.total": "Всего очков",
3588 "reward.continue": "Нажмите, чтобы продолжить"
3553 3589 },
3554 3590 "es": {
3555 3591 "menu.tagline": "Tres en raya, y tus bloques ganan motores cohete.",
@@ -3830,7 +3866,11 @@ var I18N_CATALOG = {
3830 3866 "block.forge-brass": "Forge latón",
3831 3867 "block.forge-soot": "Forge hollín",
3832 3868 "error.webgl": "Este juego necesita WebGL. Prueba con otro navegador o activa la aceleración por hardware.",
3833 "error.startFailed": "No se pudo iniciar el juego."
3869 "error.startFailed": "No se pudo iniciar el juego.",
3870 "reward.won": "¡Has ganado!",
3871 "reward.lost": "Has perdido...",
3872 "reward.total": "Puntos totales",
3873 "reward.continue": "Toca para continuar"
3834 3874 }
3835 3875 },
3836 3876 "errors": {
@@ -11195,6 +11235,530 @@ if (typeof module !== 'undefined' && module.exports && typeof Offline !== 'undef
11195 11235 * /workspace/meteors/src/offline.js
11196 11236 */
11197 11237
11238 /*
11239 * Start File:
11240 * /workspace/meteors/src/reward.js
11241 */
11242 /*
11243 * End-of-round reward screen (t1173 / t1174).
11244 *
11245 * Logged-in only. Sequence: a centred "You won!" / "You lost..." for
11246 * INTRO seconds, then it tweens to the top (RISE seconds). Once the
11247 * server has confirmed the new profile total, blocks of the player's
11248 * planet arc from the top of the screen into a counter at the bottom
11249 * centre, one block per newly earned point. Each arrival adds 1.
11250 *
11251 * Spawn rate accelerates: rate(t) = RATE0 + ACCEL·t blocks/s, so the
11252 * number spawned after t seconds is N(t) = RATE0·t + ACCEL·t²/2, and
11253 * block i (0-based) leaves at T(i) = the t where N(t) = i.
11254 * 253 points → the last block leaves at exactly 18 s.
11255 *
11256 * The pure timing / sequencing part (Reward.spawnTime, Reward.createSequence)
11257 * has no DOM and is unit-tested. Reward.play wires it to an overlay.
11258 */
11259 (function (root)
11260 {
11261 'use strict';
11262
11263 var RATE0 = 5; // blocks per second at t = 0
11264 var ACCEL = 1; // +1 block/s every second
11265 var INTRO = 1.0; // centred title before it rises
11266 var RISE = 0.6; // title tween to the top
11267 var FLIGHT = 0.7; // one block's arc duration
11268 var HOLD = 1.5; // final total shown before continuing
11269 var HOLD_ZERO = 1.5; // earned 0: show the number briefly
11270 var WAIT_MAX = 8; // give up waiting for the server after this
11271
11272 /** Seconds after the start of counting when block i (0-based) leaves. */
11273 function spawnTime (i)
11274 {
11275 if (!(i > 0))
11276 { return 0; }
11277 if (ACCEL === 0)
11278 { return i / RATE0; }
11279 return (-RATE0 + Math.sqrt(RATE0 * RATE0 + 2 * ACCEL * i)) / ACCEL;
11280 }
11281
11282 /** Blocks spawned (left the top) by time t, capped at n. */
11283 function spawnedBy (t, n)
11284 {
11285 if (!(t >= 0) || !(n > 0))
11286 { return 0; }
11287 // Block i has left when T(i) <= t, i.e. i <= N(t).
11288 var k = Math.floor(RATE0 * t + ACCEL * t * t / 2 + 1e-9) + 1;
11289 return Math.min(n, Math.max(0, k));
11290 }
11291
11292 /** Blocks that have arrived in the counter by time t. */
11293 function arrivedBy (t, n, flight)
11294 {
11295 flight = flight == null ? FLIGHT : flight;
11296 return spawnedBy(t - flight, n);
11297 }
11298
11299 /** Total seconds from the first spawn until the last block arrives. */
11300 function countDuration (n, flight)
11301 {
11302 flight = flight == null ? FLIGHT : flight;
11303 if (!(n > 0))
11304 { return 0; }
11305 return spawnTime(n - 1) + flight;
11306 }
11307
11308 /**
11309 * A pure, dt-driven sequence. Phases: intro → rise → wait → count →
11310 * hold → done. `setResult({ before, after })` supplies the confirmed
11311 * totals (earned = after − before, never negative); `setResult(null)`
11312 * means the server did not confirm, so nothing is counted and the
11313 * title is held briefly. tick(dt) returns
11314 * { phase, counter, spawn: [indices], arrived, done }.
11315 */
11316 function createSequence (opts)
11317 {
11318 opts = opts || {};
11319 var s = {
11320 phase: 'intro',
11321 t: 0, // time inside the current phase
11322 countT: 0,
11323 won: !!opts.won,
11324 flight: opts.flight == null ? FLIGHT : opts.flight,
11325 intro: opts.intro == null ? INTRO : opts.intro,
11326 rise: opts.rise == null ? RISE : opts.rise,
11327 hold: opts.hold == null ? HOLD : opts.hold,
11328 holdZero: opts.holdZero == null ? HOLD_ZERO : opts.holdZero,
11329 waitMax: opts.waitMax == null ? WAIT_MAX : opts.waitMax,
11330 hasResult: false,
11331 failed: false,
11332 before: 0,
11333 after: 0,
11334 earned: 0,
11335 spawned: 0,
11336 arrived: 0,
11337 counter: 0
11338 };
11339
11340 s.setResult = function (res)
11341 {
11342 if (s.hasResult)
11343 { return; }
11344 s.hasResult = true;
11345 if (!res || typeof res.after !== 'number' || !isFinite(res.after))
11346 {
11347 s.failed = true;
11348 return;
11349 }
11350 var after = Math.max(0, Math.floor(res.after));
11351 var before = typeof res.before === 'number' && isFinite(res.before)
11352 ? Math.max(0, Math.floor(res.before)) : after;
11353 if (before > after)
11354 { before = after; }
11355 s.before = before;
11356 s.after = after;
11357 s.earned = after - before;
11358 s.counter = before;
11359 };
11360
11361 s.finish = function ()
11362 {
11363 if (s.phase !== 'hold')
11364 { return false; }
11365 s.phase = 'done';
11366 return true;
11367 };
11368
11369 function enter (phase)
11370 {
11371 s.phase = phase;
11372 s.t = 0;
11373 }
11374
11375 s.tick = function (dt)
11376 {
11377 var out = { phase: s.phase, counter: s.counter, spawn: [], arrived: 0, done: false };
11378 if (s.phase === 'done')
11379 {
11380 out.done = true;
11381 return out;
11382 }
11383 dt = Math.max(0, Number(dt) || 0);
11384 var left = dt;
11385 // Allow several phase changes inside one large dt.
11386 for (var guard = 0; guard < 8 && left >= 0; guard++)
11387 {
11388 if (s.phase === 'intro')
11389 {
11390 if (s.t + left < s.intro)
11391 { s.t += left; left = -1; break; }
11392 left -= (s.intro - s.t);
11393 enter('rise');
11394 }
11395 else if (s.phase === 'rise')
11396 {
11397 if (s.t + left < s.rise)
11398 { s.t += left; left = -1; break; }
11399 left -= (s.rise - s.t);
11400 enter('wait');
11401 }
11402 else if (s.phase === 'wait')
11403 {
11404 if (!s.hasResult)
11405 {
11406 s.t += left;
11407 if (s.t >= s.waitMax)
11408 {
11409 s.hasResult = true;
11410 s.failed = true;
11411 enter('hold');
11412 continue;
11413 }
11414 left = -1;
11415 break;
11416 }
11417 if (s.failed || s.earned <= 0)
11418 { enter('hold'); continue; }
11419 enter('count');
11420 s.countT = 0;
11421 }
11422 else if (s.phase === 'count')
11423 {
11424 s.countT += left;
11425 left = -1;
11426 var sp = spawnedBy(s.countT, s.earned);
11427 for (var i = s.spawned; i < sp; i++)
11428 { out.spawn.push(i); }
11429 s.spawned = sp;
11430 var ar = arrivedBy(s.countT, s.earned, s.flight);
11431 out.arrived = ar - s.arrived;
11432 s.arrived = ar;
11433 s.counter = s.before + ar;
11434 if (ar >= s.earned)
11435 {
11436 s.counter = s.after;
11437 enter('hold');
11438 }
11439 break;
11440 }
11441 else if (s.phase === 'hold')
11442 {
11443 var need = (s.failed || s.earned <= 0) ? s.holdZero : s.hold;
11444 if (s.t + left < need)
11445 { s.t += left; left = -1; break; }
11446 enter('done');
11447 break;
11448 }
11449 else
11450 { break; }
11451 }
11452 out.phase = s.phase;
11453 out.counter = s.counter;
11454 out.done = s.phase === 'done';
11455 return out;
11456 };
11457
11458 return s;
11459 }
11460
11461 /* ---------------- DOM / canvas player (browser only) ---------------- */
11462
11463 var active = null;
11464
11465 function reducedMotion ()
11466 {
11467 try
11468 {
11469 return !!(root.matchMedia && root.matchMedia('(prefers-reduced-motion: reduce)').matches);
11470 }
11471 catch (e) { return false; }
11472 }
11473
11474 function tr (key, fallback)
11475 {
11476 if (typeof I18n !== 'undefined' && I18n.t)
11477 {
11478 var v = I18n.t(key);
11479 if (v && v !== key)
11480 { return v; }
11481 }
11482 return fallback;
11483 }
11484
11485 function planetImages (planet)
11486 {
11487 var list = [];
11488 var colors = (planet && planet.colors) || [];
11489 for (var i = 0; i < colors.length; i++)
11490 {
11491 if (!colors[i] || !colors[i].image)
11492 { continue; }
11493 var img = new Image();
11494 img.decoding = 'async';
11495 img.src = colors[i].image;
11496 list.push({ img: img, hex: colors[i].hex || '#ffffff' });
11497 }
11498 if (!list.length)
11499 { list.push({ img: null, hex: '#ffffff' }); }
11500 return list;
11501 }
11502
11503 /**
11504 * Show the reward overlay. opts: { won, planet, result: Promise<{before,
11505 * after}|null>, onDone }. Returns a handle with .active and .cancel().
11506 */
11507 function play (opts)
11508 {
11509 opts = opts || {};
11510 if (active)
11511 { active.cancel(); }
11512 var doc = root.document;
11513 var overlay = doc.getElementById('reward');
11514 var title = doc.getElementById('reward-title');
11515 var counter = doc.getElementById('reward-total');
11516 var label = doc.getElementById('reward-label');
11517 var canvas = doc.getElementById('reward-canvas');
11518 var hint = doc.getElementById('reward-hint');
11519 if (!overlay || !title || !counter || !canvas)
11520 {
11521 if (opts.onDone)
11522 { opts.onDone(); }
11523 return null;
11524 }
11525 var still = reducedMotion();
11526 var seq = createSequence({ won: opts.won, rise: still ? 0 : RISE });
11527 var imgs = planetImages(opts.planet);
11528 var flying = [];
11529 var last = 0;
11530 var raf = 0;
11531 var pop = 0;
11532 var ctx = canvas.getContext('2d');
11533 var dpr = Math.min(2, root.devicePixelRatio || 1);
11534 var W = 0;
11535 var H = 0;
11536
11537 title.textContent = opts.won ? tr('reward.won', 'You won!') : tr('reward.lost', 'You lost...');
11538 title.className = 'reward-title' + (opts.won ? ' won' : ' lost');
11539 if (label)
11540 { label.textContent = tr('reward.total', 'Total points'); }
11541 counter.textContent = '';
11542 counter.parentNode.hidden = true;
11543 if (hint)
11544 { hint.hidden = true; hint.textContent = tr('reward.continue', 'Tap to continue'); }
11545 overlay.classList.toggle('reduced', still);
11546 overlay.hidden = false;
11547
11548 function resize ()
11549 {
11550 W = root.innerWidth || 360;
11551 H = root.innerHeight || 640;
11552 canvas.width = Math.round(W * dpr);
11553 canvas.height = Math.round(H * dpr);
11554 canvas.style.width = W + 'px';
11555 canvas.style.height = H + 'px';
11556 if (ctx)
11557 { ctx.setTransform(dpr, 0, 0, dpr, 0, 0); }
11558 }
11559 resize();
11560 root.addEventListener('resize', resize);
11561
11562 function target ()
11563 {
11564 var r = counter.getBoundingClientRect();
11565 if (r.width > 0)
11566 { return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; }
11567 return { x: W / 2, y: H - 80 };
11568 }
11569
11570 function spawn ()
11571 {
11572 var size = Math.max(28, Math.min(56, Math.round(Math.min(W, H) * 0.075)));
11573 var sx = size + Math.random() * Math.max(1, W - 2 * size);
11574 var sy = -size;
11575 var tg = target();
11576 // Random arc: control point pushed sideways and up.
11577 var mx = (sx + tg.x) / 2 + (Math.random() - 0.5) * W * 0.9;
11578 var my = Math.min(sy, tg.y) + (Math.random() * 0.5) * H;
11579 flying.push({
11580 t: 0,
11581 sx: sx, sy: sy, cx: mx, cy: my,
11582 pick: imgs[Math.floor(Math.random() * imgs.length)],
11583 size: size,
11584 rot: (Math.random() - 0.5) * 6
11585 });
11586 }
11587
11588 function draw (dt)
11589 {
11590 if (!ctx)
11591 { return; }
11592 ctx.clearRect(0, 0, W, H);
11593 var tg = target();
11594 for (var i = flying.length - 1; i >= 0; i--)
11595 {
11596 var f = flying[i];
11597 f.t += dt / FLIGHT;
11598 if (f.t >= 1)
11599 {
11600 flying.splice(i, 1);
11601 continue;
11602 }
11603 var u = f.t;
11604 // Ease in a little so blocks accelerate into the counter.
11605 var e = u * u * (3 - 2 * u) * 0.35 + u * 0.65;
11606 var a = 1 - e;
11607 var x = a * a * f.sx + 2 * a * e * f.cx + e * e * tg.x;
11608 var y = a * a * f.sy + 2 * a * e * f.cy + e * e * tg.y;
11609 var s = f.size * (1 - 0.45 * e);
11610 ctx.save();
11611 ctx.translate(x, y);
11612 ctx.rotate(f.rot * e);
11613 if (f.pick.img && f.pick.img.complete && f.pick.img.naturalWidth)
11614 { ctx.drawImage(f.pick.img, -s / 2, -s / 2, s, s); }
11615 else
11616 {
11617 ctx.fillStyle = f.pick.hex;
11618 ctx.fillRect(-s / 2, -s / 2, s, s);
11619 }
11620 ctx.restore();
11621 }
11622 }
11623
11624 function setCounter (v)
11625 {
11626 counter.textContent = String(v);
11627 }
11628
11629 var handle = {
11630 active: true,
11631 seq: seq,
11632 flyingCount: function () { return flying.length; },
11633 cancel: function ()
11634 { cleanup(false); }
11635 };
11636
11637 function onTap (e)
11638 {
11639 if (seq.phase !== 'hold')
11640 { return; }
11641 if (e && e.type === 'keydown' && e.key !== ' ' && e.key !== 'Enter' && e.key !== 'Spacebar')
11642 { return; }
11643 if (e && e.preventDefault)
11644 { e.preventDefault(); }
11645 seq.finish();
11646 }
11647 overlay.addEventListener('pointerup', onTap);
11648 doc.addEventListener('keydown', onTap);
11649
11650 function cleanup (callDone)
11651 {
11652 if (!handle.active)
11653 { return; }
11654 handle.active = false;
11655 if (raf && root.cancelAnimationFrame)
11656 { root.cancelAnimationFrame(raf); }
11657 root.removeEventListener('resize', resize);
11658 overlay.removeEventListener('pointerup', onTap);
11659 doc.removeEventListener('keydown', onTap);
11660 overlay.hidden = true;
11661 overlay.classList.remove('risen');
11662 if (ctx)
11663 { ctx.clearRect(0, 0, W, H); }
11664 if (active === handle)
11665 { active = null; }
11666 if (callDone && opts.onDone)
11667 { opts.onDone(); }
11668 }
11669
11670 Promise.resolve(opts.result).then(function (res)
11671 { seq.setResult(res); }, function ()
11672 { seq.setResult(null); });
11673
11674 function frame (now)
11675 {
11676 if (!handle.active)
11677 { return; }
11678 var dt = last ? Math.min(0.1, (now - last) / 1000) : 0;
11679 last = now;
11680 var prev = seq.phase;
11681 var out = seq.tick(dt);
11682 if (prev === 'intro' && out.phase !== 'intro')
11683 { overlay.classList.add('risen'); }
11684 if ((out.phase === 'count' || out.phase === 'hold' || out.phase === 'done')
11685 && counter.parentNode.hidden && seq.hasResult && !seq.failed)
11686 {
11687 counter.parentNode.hidden = false;
11688 setCounter(seq.before);
11689 }
11690 if (!still)
11691 {
11692 for (var i = 0; i < out.spawn.length; i++)
11693 { spawn(); }
11694 }
11695 if (out.arrived > 0)
11696 {
11697 pop = 1;
11698 setCounter(out.counter);
11699 }
11700 if (out.phase === 'hold' && !seq.failed)
11701 { setCounter(seq.after); }
11702 if (out.phase === 'hold' && hint && hint.hidden)
11703 { hint.hidden = false; }
11704 if (pop > 0)
11705 {
11706 pop = Math.max(0, pop - dt * 6);
11707 counter.style.transform = 'scale(' + (1 + 0.18 * pop).toFixed(3) + ')';
11708 }
11709 draw(dt);
11710 if (out.done)
11711 {
11712 cleanup(true);
11713 return;
11714 }
11715 raf = root.requestAnimationFrame(frame);
11716 }
11717 raf = root.requestAnimationFrame(frame);
11718 active = handle;
11719 return handle;
11720 }
11721
11722 var Reward = {
11723 RATE0: RATE0,
11724 ACCEL: ACCEL,
11725 INTRO: INTRO,
11726 RISE: RISE,
11727 FLIGHT: FLIGHT,
11728 HOLD: HOLD,
11729 HOLD_ZERO: HOLD_ZERO,
11730 WAIT_MAX: WAIT_MAX,
11731 spawnTime: spawnTime,
11732 spawnedBy: spawnedBy,
11733 arrivedBy: arrivedBy,
11734 countDuration: countDuration,
11735 createSequence: createSequence,
11736 play: play,
11737 isActive: function () { return !!(active && active.active); },
11738 /** Read-only snapshot for tests and debugging. */
11739 debugState: function ()
11740 {
11741 if (!active)
11742 { return null; }
11743 var q = active.seq;
11744 return {
11745 phase: q.phase, counter: q.counter, before: q.before, after: q.after,
11746 earned: q.earned, spawned: q.spawned, arrived: q.arrived,
11747 failed: q.failed, won: q.won, flying: active.flyingCount()
11748 };
11749 }
11750 };
11751
11752 if (typeof module !== 'undefined' && module.exports)
11753 { module.exports = Reward; }
11754 root.Reward = Reward;
11755 })(typeof globalThis !== 'undefined' ? globalThis : this);
11756
11757 /*
11758 * End File:
11759 * /workspace/meteors/src/reward.js
11760 */
11761
11198 11762 /*
11199 11763 * Start File:
11200 11764 * /workspace/meteors/src/designer.js
@@ -11829,7 +12393,10 @@ var app = {
11829 12393 miniAcc: 0,
11830 12394 offlineResultShown: false,
11831 12395 roundWonDelay: 0,
11832 roundWonHandled: false
12396 roundWonHandled: false,
12397 rewardActive: false,
12398 onlineBefore: 0,
12399 pendingLobbyReturn: null
11833 12400 };
11834 12401
11835 12402 window.onload = function ()
@@ -12641,13 +13208,15 @@ function tickView (dt)
12641 13208 { onOnlineEliminated(); }
12642 13209 else if (app.offline)
12643 13210 { /* Offline result is shown from tickOffline. */ }
13211 else if (rewardEnabled())
13212 { showReward(false, finishPlaySession(app.lastScore), returnToMenu); }
12644 13213 else
12645 13214 {
12646 13215 showEl('game-over');
12647 13216 finishPlaySession(app.lastScore);
12648 13217 }
12649 13218 }
12650 if (!app.online && !app.offline && app.core.state === 'gameover'
13219 if (!app.online && !app.offline && !app.rewardActive && app.core.state === 'gameover'
12651 13220 && app.core.gameOverTime >= GAME_OVER_DELAY)
12652 13221 { returnToMenu(); }
12653 13222 }
@@ -13201,6 +13770,13 @@ function tickOffline (dt)
13201 13770 {
13202 13771 app.roundWonHandled = true;
13203 13772 app.roundWonDelay = Offline.ROUND_WON_DELAY || 1.5;
13773 if (rewardEnabled())
13774 { showReward(true, finishPlaySession(app.core.score), startNextOfflineRound); }
13775 }
13776 if (app.rewardActive)
13777 {
13778 updateOfflineMinis(dt, true);
13779 return;
13204 13780 }
13205 13781 app.roundWonDelay -= dt;
13206 13782 if (app.roundWonDelay <= 0)
@@ -13242,7 +13818,17 @@ function tickOffline (dt)
13242 13818 updateOfflineMinis(dt, false);
13243 13819
13244 13820 if (app.battle.state === 'lost' && !app.offlineResultShown)
13245 { showOfflineResult(); }
13821 {
13822 if (rewardEnabled())
13823 {
13824 // Guard against starting the reward twice; showOfflineResult
13825 // sets the flag again when it runs afterwards.
13826 app.offlineResultShown = true;
13827 showReward(false, finishPlaySession(app.core ? app.core.score : 0), showOfflineResult);
13828 }
13829 else
13830 { showOfflineResult(); }
13831 }
13246 13832 }
13247 13833
13248 13834 function startNextOfflineRound ()
@@ -13593,6 +14179,8 @@ function onOnlineEliminated ()
13593 14179 app.spectating = true;
13594 14180 unbindPointer();
13595 14181 hideEl('game-over');
14182 if (app.rewardActive)
14183 { return; }
13596 14184 var lobby = typeof Online !== 'undefined' && Online.lobby;
13597 14185 if (lobby && lobby.status === 'finished')
13598 14186 {
@@ -13648,6 +14236,8 @@ function startOnlineMatch ()
13648 14236 if (typeof me.planet.miss_chance === 'number')
13649 14237 { miss = me.planet.miss_chance; }
13650 14238 }
14239 app.onlineBefore = (typeof Online !== 'undefined' && Online.lifetimePoints) || 0;
14240 app.pendingLobbyReturn = null;
13651 14241 startPlay({ online: true, planet: planet, missChance: miss });
13652 14242 if (typeof Online !== 'undefined')
13653 14243 { Online.startPolling(onlinePayload); }
@@ -13797,9 +14387,32 @@ function bindOnlineUi ()
13797 14387 }
13798 14388 };
13799 14389 Online.onFinished = function (lobby)
13800 { showPodium(lobby); };
14390 {
14391 if (app.mode === 'playing' && app.online && rewardEnabled() && !app.rewardActive)
14392 {
14393 // Lifetime points in this same poll already include the
14394 // server's online award (maybeAwardOnlineLobby).
14395 var result = { before: app.onlineBefore || 0, after: Online.lifetimePoints || 0 };
14396 showReward(myOnlinePlace(lobby) === 1, Promise.resolve(result), function ()
14397 {
14398 var pending = app.pendingLobbyReturn;
14399 app.pendingLobbyReturn = null;
14400 if (pending || !(Online.lobby && Online.lobby.status === 'finished'))
14401 { Online.onLobbyReturn(pending || Online.lobby); }
14402 else
14403 { showPodium(Online.lobby); }
14404 });
14405 return;
14406 }
14407 showPodium(lobby);
14408 };
13801 14409 Online.onLobbyReturn = function (lobby)
13802 14410 {
14411 if (app.rewardActive)
14412 {
14413 app.pendingLobbyReturn = lobby;
14414 return;
14415 }
13803 14416 teardownPlay();
13804 14417 app.online = false;
13805 14418 app.mode = 'online';
@@ -13888,7 +14501,7 @@ function renderOnline ()
13888 14501 if (app.mode === 'playing' && app.online)
13889 14502 {
13890 14503 Online.renderMinis(document.getElementById('minis'));
13891 if (Online.lobby && Online.lobby.status === 'finished')
14504 if (Online.lobby && Online.lobby.status === 'finished' && !app.rewardActive)
13892 14505 { showPodium(Online.lobby); }
13893 14506 return;
13894 14507 }
@@ -14178,14 +14791,78 @@ function beginPlaySession (mode)
14178 14791 });
14179 14792 }
14180 14793
14794 /**
14795 * Ends the solo/offline play session. Resolves to the server-confirmed
14796 * { before, after } profile totals (t1173), or null when there is no
14797 * logged-in user or the server did not confirm. Without a token (e.g.
14798 * play_begin failed) a logged-in player gets { before = after = current }.
14799 */
14181 14800 function finishPlaySession (score)
14182 14801 {
14183 14802 var token = app.playToken;
14184 14803 app.playToken = null;
14185 if (!token || typeof Online === 'undefined' || !Online.playFinish)
14186 { return; }
14187 Online.playFinish(token, score || 0).then(function ()
14188 { refreshMenuAccount(); });
14804 var hasOnline = typeof Online !== 'undefined';
14805 var current = hasOnline ? (Online.lifetimePoints || 0) : 0;
14806 if (!token || !hasOnline || !Online.playFinish)
14807 {
14808 return Promise.resolve(hasOnline && Online.me ? { before: current, after: current } : null);
14809 }
14810 return Promise.resolve(Online.playFinish(token, score || 0)).then(function (data)
14811 {
14812 refreshMenuAccount();
14813 if (data && data.ok !== false && typeof data.lifetime_points === 'number')
14814 {
14815 var awarded = Math.max(0, Number(data.awarded) || 0);
14816 return { before: data.lifetime_points - awarded, after: data.lifetime_points };
14817 }
14818 return null;
14819 }, function ()
14820 { return null; });
14821 }
14822
14823 /* ---------- t1173 reward screen (logged in only) ------------------- */
14824
14825 function rewardEnabled ()
14826 {
14827 return typeof Reward !== 'undefined' && typeof Online !== 'undefined' && !!Online.me;
14828 }
14829
14830 /**
14831 * Shows "You won!" / "You lost..." and the points fly-in, then calls
14832 * next() — the same destination the mode used before (menu, next
14833 * offline round, offline result, or the online lobby/podium).
14834 */
14835 function showReward (won, resultPromise, next)
14836 {
14837 app.rewardActive = true;
14838 hideEl('game-over');
14839 hideEl('spectator');
14840 hideEl('podium');
14841 var handle = Reward.play({
14842 won: won,
14843 planet: app.planet,
14844 result: resultPromise,
14845 onDone: function ()
14846 {
14847 app.rewardActive = false;
14848 if (next)
14849 { next(); }
14850 }
14851 });
14852 if (!handle)
14853 { app.rewardActive = false; }
14854 }
14855
14856 function myOnlinePlace (lobby)
14857 {
14858 var me = typeof Online !== 'undefined' ? Online.me : null;
14859 var ranks = (lobby && lobby.rankings) || [];
14860 for (var i = 0; i < ranks.length; i++)
14861 {
14862 if (me && ranks[i].id === me.id)
14863 { return ranks[i].place; }
14864 }
14865 return null;
14189 14866 }
14190 14867
14191 14868
@@ -1301,7 +1301,11 @@ var I18N_CATALOG = {
1301 "block.forge-brass": "Forge brass",
1301 "block.forge-brass": "Forge brass",
1302 "block.forge-soot": "Forge soot",
1302 "block.forge-soot": "Forge soot",
1303 "error.webgl": "This game needs WebGL. Please try another browser, or turn on hardware acceleration.",
1303 "error.webgl": "This game needs WebGL. Please try another browser, or turn on hardware acceleration.",
1304 "error.startFailed": "Could not start the game."
1304 "error.startFailed": "Could not start the game.",
1305 "reward.won": "You won!",
1306 "reward.lost": "You lost...",
1307 "reward.total": "Total points",
1308 "reward.continue": "Tap to continue"
1305 },
1309 },
1306 "nl": {
1310 "nl": {
1307 "menu.tagline": "Drie op een rij, en je blokjes krijgen raketmotoren.",
1311 "menu.tagline": "Drie op een rij, en je blokjes krijgen raketmotoren.",
@@ -1582,7 +1586,11 @@ var I18N_CATALOG = {
1582 "block.forge-brass": "Forge-messing",
1586 "block.forge-brass": "Forge-messing",
1583 "block.forge-soot": "Forge-roet",
1587 "block.forge-soot": "Forge-roet",
1584 "error.webgl": "Dit spel heeft WebGL nodig. Probeer een andere browser, of zet hardwareversnelling aan.",
1588 "error.webgl": "Dit spel heeft WebGL nodig. Probeer een andere browser, of zet hardwareversnelling aan.",
1585 "error.startFailed": "Het spel kon niet worden gestart."
1589 "error.startFailed": "Het spel kon niet worden gestart.",
1590 "reward.won": "Gewonnen!",
1591 "reward.lost": "Verloren...",
1592 "reward.total": "Totaal punten",
1593 "reward.continue": "Tik om verder te gaan"
1586 },
1594 },
1587 "de": {
1595 "de": {
1588 "menu.tagline": "Drei in einer Reihe — und deine Blöcke bekommen Raketenantrieb.",
1596 "menu.tagline": "Drei in einer Reihe — und deine Blöcke bekommen Raketenantrieb.",
@@ -1863,7 +1871,11 @@ var I18N_CATALOG = {
1863 "block.forge-brass": "Forge-Messing",
1871 "block.forge-brass": "Forge-Messing",
1864 "block.forge-soot": "Forge-Ruß",
1872 "block.forge-soot": "Forge-Ruß",
1865 "error.webgl": "Dieses Spiel benötigt WebGL. Bitte verwende einen anderen Browser oder aktiviere die Hardwarebeschleunigung.",
1873 "error.webgl": "Dieses Spiel benötigt WebGL. Bitte verwende einen anderen Browser oder aktiviere die Hardwarebeschleunigung.",
1866 "error.startFailed": "Das Spiel konnte nicht gestartet werden."
1874 "error.startFailed": "Das Spiel konnte nicht gestartet werden.",
1875 "reward.won": "Gewonnen!",
1876 "reward.lost": "Verloren...",
1877 "reward.total": "Punkte gesamt",
1878 "reward.continue": "Tippen zum Fortfahren"
1867 },
1879 },
1868 "fr": {
1880 "fr": {
1869 "menu.tagline": "Trois d’affilée, et tes blocs s’équipent de propulseurs.",
1881 "menu.tagline": "Trois d’affilée, et tes blocs s’équipent de propulseurs.",
@@ -2144,7 +2156,11 @@ var I18N_CATALOG = {
2144 "block.forge-brass": "Forge laiton",
2156 "block.forge-brass": "Forge laiton",
2145 "block.forge-soot": "Forge suie",
2157 "block.forge-soot": "Forge suie",
2146 "error.webgl": "Ce jeu a besoin de WebGL. Essayez un autre navigateur, ou activez l’accélération matérielle.",
2158 "error.webgl": "Ce jeu a besoin de WebGL. Essayez un autre navigateur, ou activez l’accélération matérielle.",
2147 "error.startFailed": "Impossible de lancer le jeu."
2159 "error.startFailed": "Impossible de lancer le jeu.",
2160 "reward.won": "Victoire !",
2161 "reward.lost": "Perdu...",
2162 "reward.total": "Total des points",
2163 "reward.continue": "Touchez pour continuer"
2148 },
2164 },
2149 "ja": {
2165 "ja": {
2150 "menu.tagline": "三つ揃えると、ブロックにロケットが点火します。",
2166 "menu.tagline": "三つ揃えると、ブロックにロケットが点火します。",
@@ -2425,7 +2441,11 @@ var I18N_CATALOG = {
2425 "block.forge-brass": "フォージの真鍮",
2441 "block.forge-brass": "フォージの真鍮",
2426 "block.forge-soot": "フォージの煤",
2442 "block.forge-soot": "フォージの煤",
2427 "error.webgl": "このゲームにはWebGLが必要です。別のブラウザを使うか、ハードウェアアクセラレーションを有効にしてください。",
2443 "error.webgl": "このゲームにはWebGLが必要です。別のブラウザを使うか、ハードウェアアクセラレーションを有効にしてください。",
2428 "error.startFailed": "ゲームを開始できませんでした。"
2444 "error.startFailed": "ゲームを開始できませんでした。",
2445 "reward.won": "勝利!",
2446 "reward.lost": "敗北...",
2447 "reward.total": "合計ポイント",
2448 "reward.continue": "タップして続ける"
2429 },
2449 },
2430 "zh": {
2450 "zh": {
2431 "menu.tagline": "三个一排,你的方块就会装上火箭。",
2451 "menu.tagline": "三个一排,你的方块就会装上火箭。",
@@ -2706,7 +2726,11 @@ var I18N_CATALOG = {
2706 "block.forge-brass": "Forge黄铜",
2726 "block.forge-brass": "Forge黄铜",
2707 "block.forge-soot": "Forge煤烟",
2727 "block.forge-soot": "Forge煤烟",
2708 "error.webgl": "本游戏需要 WebGL。请尝试其他浏览器,或开启硬件加速。",
2728 "error.webgl": "本游戏需要 WebGL。请尝试其他浏览器,或开启硬件加速。",
2709 "error.startFailed": "无法开始游戏。"
2729 "error.startFailed": "无法开始游戏。",
2730 "reward.won": "你赢了!",
2731 "reward.lost": "你输了...",
2732 "reward.total": "总积分",
2733 "reward.continue": "点击继续"
2710 },
2734 },
2711 "ko": {
2735 "ko": {
2712 "menu.tagline": "세 개를 나란히 맞추면 블록에 로켓이 점화됩니다.",
2736 "menu.tagline": "세 개를 나란히 맞추면 블록에 로켓이 점화됩니다.",
@@ -2987,7 +3011,11 @@ var I18N_CATALOG = {
2987 "block.forge-brass": "Forge 황동",
3011 "block.forge-brass": "Forge 황동",
2988 "block.forge-soot": "Forge 그을음",
3012 "block.forge-soot": "Forge 그을음",
2989 "error.webgl": "이 게임은 WebGL이 필요합니다. 다른 브라우저를 사용하거나 하드웨어 가속을 켜 주세요.",
3013 "error.webgl": "이 게임은 WebGL이 필요합니다. 다른 브라우저를 사용하거나 하드웨어 가속을 켜 주세요.",
2990 "error.startFailed": "게임을 시작할 수 없습니다."
3014 "error.startFailed": "게임을 시작할 수 없습니다.",
3015 "reward.won": "승리!",
3016 "reward.lost": "패배...",
3017 "reward.total": "총 포인트",
3018 "reward.continue": "탭하여 계속"
2991 },
3019 },
2992 "pl": {
3020 "pl": {
2993 "menu.tagline": "Trzy w rzędzie, a twoje klocki dostają napęd rakietowy.",
3021 "menu.tagline": "Trzy w rzędzie, a twoje klocki dostają napęd rakietowy.",
@@ -3268,7 +3296,11 @@ var I18N_CATALOG = {
3268 "block.forge-brass": "Forge mosiądz",
3296 "block.forge-brass": "Forge mosiądz",
3269 "block.forge-soot": "Forge sadza",
3297 "block.forge-soot": "Forge sadza",
3270 "error.webgl": "Ta gra wymaga WebGL. Spróbuj innej przeglądarki albo włącz akcelerację sprzętową.",
3298 "error.webgl": "Ta gra wymaga WebGL. Spróbuj innej przeglądarki albo włącz akcelerację sprzętową.",
3271 "error.startFailed": "Nie udało się uruchomić gry."
3299 "error.startFailed": "Nie udało się uruchomić gry.",
3300 "reward.won": "Wygrana!",
3301 "reward.lost": "Przegrana...",
3302 "reward.total": "Suma punktów",
3303 "reward.continue": "Dotknij, aby kontynuować"
3272 },
3304 },
3273 "ru": {
3305 "ru": {
3274 "menu.tagline": "Три в ряд — и твои блоки получают ракетные двигатели.",
3306 "menu.tagline": "Три в ряд — и твои блоки получают ракетные двигатели.",
@@ -3549,7 +3581,11 @@ var I18N_CATALOG = {
3549 "block.forge-brass": "Forge (латунь)",
3581 "block.forge-brass": "Forge (латунь)",
3550 "block.forge-soot": "Forge (сажа)",
3582 "block.forge-soot": "Forge (сажа)",
3551 "error.webgl": "Этой игре нужен WebGL. Попробуйте другой браузер или включите аппаратное ускорение.",
3583 "error.webgl": "Этой игре нужен WebGL. Попробуйте другой браузер или включите аппаратное ускорение.",
3552 "error.startFailed": "Не удалось начать игру."
3584 "error.startFailed": "Не удалось начать игру.",
3585 "reward.won": "Победа!",
3586 "reward.lost": "Поражение...",
3587 "reward.total": "Всего очков",
3588 "reward.continue": "Нажмите, чтобы продолжить"
3553 },
3589 },
3554 "es": {
3590 "es": {
3555 "menu.tagline": "Tres en raya, y tus bloques ganan motores cohete.",
3591 "menu.tagline": "Tres en raya, y tus bloques ganan motores cohete.",
@@ -3830,7 +3866,11 @@ var I18N_CATALOG = {
3830 "block.forge-brass": "Forge latón",
3866 "block.forge-brass": "Forge latón",
3831 "block.forge-soot": "Forge hollín",
3867 "block.forge-soot": "Forge hollín",
3832 "error.webgl": "Este juego necesita WebGL. Prueba con otro navegador o activa la aceleración por hardware.",
3868 "error.webgl": "Este juego necesita WebGL. Prueba con otro navegador o activa la aceleración por hardware.",
3833 "error.startFailed": "No se pudo iniciar el juego."
3869 "error.startFailed": "No se pudo iniciar el juego.",
3870 "reward.won": "¡Has ganado!",
3871 "reward.lost": "Has perdido...",
3872 "reward.total": "Puntos totales",
3873 "reward.continue": "Toca para continuar"
3834 }
3874 }
3835 },
3875 },
3836 "errors": {
3876 "errors": {
@@ -11195,6 +11235,530 @@ if (typeof module !== 'undefined' && module.exports && typeof Offline !== 'undef
11195 * /workspace/meteors/src/offline.js
11235 * /workspace/meteors/src/offline.js
11196 */
11236 */
11197
11237
11238/*
11239 * Start File:
11240 * /workspace/meteors/src/reward.js
11241 */
11242/*
11243 * End-of-round reward screen (t1173 / t1174).
11244 *
11245 * Logged-in only. Sequence: a centred "You won!" / "You lost..." for
11246 * INTRO seconds, then it tweens to the top (RISE seconds). Once the
11247 * server has confirmed the new profile total, blocks of the player's
11248 * planet arc from the top of the screen into a counter at the bottom
11249 * centre, one block per newly earned point. Each arrival adds 1.
11250 *
11251 * Spawn rate accelerates: rate(t) = RATE0 + ACCEL·t blocks/s, so the
11252 * number spawned after t seconds is N(t) = RATE0·t + ACCEL·t²/2, and
11253 * block i (0-based) leaves at T(i) = the t where N(t) = i.
11254 * 253 points → the last block leaves at exactly 18 s.
11255 *
11256 * The pure timing / sequencing part (Reward.spawnTime, Reward.createSequence)
11257 * has no DOM and is unit-tested. Reward.play wires it to an overlay.
11258 */
11259(function (root)
11260{
11261'use strict';
11262
11263var RATE0 = 5; // blocks per second at t = 0
11264var ACCEL = 1; // +1 block/s every second
11265var INTRO = 1.0; // centred title before it rises
11266var RISE = 0.6; // title tween to the top
11267var FLIGHT = 0.7; // one block's arc duration
11268var HOLD = 1.5; // final total shown before continuing
11269var HOLD_ZERO = 1.5; // earned 0: show the number briefly
11270var WAIT_MAX = 8; // give up waiting for the server after this
11271
11272/** Seconds after the start of counting when block i (0-based) leaves. */
11273function spawnTime (i)
11274{
11275 if (!(i > 0))
11276 { return 0; }
11277 if (ACCEL === 0)
11278 { return i / RATE0; }
11279 return (-RATE0 + Math.sqrt(RATE0 * RATE0 + 2 * ACCEL * i)) / ACCEL;
11280}
11281
11282/** Blocks spawned (left the top) by time t, capped at n. */
11283function spawnedBy (t, n)
11284{
11285 if (!(t >= 0) || !(n > 0))
11286 { return 0; }
11287 // Block i has left when T(i) <= t, i.e. i <= N(t).
11288 var k = Math.floor(RATE0 * t + ACCEL * t * t / 2 + 1e-9) + 1;
11289 return Math.min(n, Math.max(0, k));
11290}
11291
11292/** Blocks that have arrived in the counter by time t. */
11293function arrivedBy (t, n, flight)
11294{
11295 flight = flight == null ? FLIGHT : flight;
11296 return spawnedBy(t - flight, n);
11297}
11298
11299/** Total seconds from the first spawn until the last block arrives. */
11300function countDuration (n, flight)
11301{
11302 flight = flight == null ? FLIGHT : flight;
11303 if (!(n > 0))
11304 { return 0; }
11305 return spawnTime(n - 1) + flight;
11306}
11307
11308/**
11309 * A pure, dt-driven sequence. Phases: intro → rise → wait → count →
11310 * hold → done. `setResult({ before, after })` supplies the confirmed
11311 * totals (earned = after − before, never negative); `setResult(null)`
11312 * means the server did not confirm, so nothing is counted and the
11313 * title is held briefly. tick(dt) returns
11314 * { phase, counter, spawn: [indices], arrived, done }.
11315 */
11316function createSequence (opts)
11317{
11318 opts = opts || {};
11319 var s = {
11320 phase: 'intro',
11321 t: 0, // time inside the current phase
11322 countT: 0,
11323 won: !!opts.won,
11324 flight: opts.flight == null ? FLIGHT : opts.flight,
11325 intro: opts.intro == null ? INTRO : opts.intro,
11326 rise: opts.rise == null ? RISE : opts.rise,
11327 hold: opts.hold == null ? HOLD : opts.hold,
11328 holdZero: opts.holdZero == null ? HOLD_ZERO : opts.holdZero,
11329 waitMax: opts.waitMax == null ? WAIT_MAX : opts.waitMax,
11330 hasResult: false,
11331 failed: false,
11332 before: 0,
11333 after: 0,
11334 earned: 0,
11335 spawned: 0,
11336 arrived: 0,
11337 counter: 0
11338 };
11339
11340 s.setResult = function (res)
11341 {
11342 if (s.hasResult)
11343 { return; }
11344 s.hasResult = true;
11345 if (!res || typeof res.after !== 'number' || !isFinite(res.after))
11346 {
11347 s.failed = true;
11348 return;
11349 }
11350 var after = Math.max(0, Math.floor(res.after));
11351 var before = typeof res.before === 'number' && isFinite(res.before)
11352 ? Math.max(0, Math.floor(res.before)) : after;
11353 if (before > after)
11354 { before = after; }
11355 s.before = before;
11356 s.after = after;
11357 s.earned = after - before;
11358 s.counter = before;
11359 };
11360
11361 s.finish = function ()
11362 {
11363 if (s.phase !== 'hold')
11364 { return false; }
11365 s.phase = 'done';
11366 return true;
11367 };
11368
11369 function enter (phase)
11370 {
11371 s.phase = phase;
11372 s.t = 0;
11373 }
11374
11375 s.tick = function (dt)
11376 {
11377 var out = { phase: s.phase, counter: s.counter, spawn: [], arrived: 0, done: false };
11378 if (s.phase === 'done')
11379 {
11380 out.done = true;
11381 return out;
11382 }
11383 dt = Math.max(0, Number(dt) || 0);
11384 var left = dt;
11385 // Allow several phase changes inside one large dt.
11386 for (var guard = 0; guard < 8 && left >= 0; guard++)
11387 {
11388 if (s.phase === 'intro')
11389 {
11390 if (s.t + left < s.intro)
11391 { s.t += left; left = -1; break; }
11392 left -= (s.intro - s.t);
11393 enter('rise');
11394 }
11395 else if (s.phase === 'rise')
11396 {
11397 if (s.t + left < s.rise)
11398 { s.t += left; left = -1; break; }
11399 left -= (s.rise - s.t);
11400 enter('wait');
11401 }
11402 else if (s.phase === 'wait')
11403 {
11404 if (!s.hasResult)
11405 {
11406 s.t += left;
11407 if (s.t >= s.waitMax)
11408 {
11409 s.hasResult = true;
11410 s.failed = true;
11411 enter('hold');
11412 continue;
11413 }
11414 left = -1;
11415 break;
11416 }
11417 if (s.failed || s.earned <= 0)
11418 { enter('hold'); continue; }
11419 enter('count');
11420 s.countT = 0;
11421 }
11422 else if (s.phase === 'count')
11423 {
11424 s.countT += left;
11425 left = -1;
11426 var sp = spawnedBy(s.countT, s.earned);
11427 for (var i = s.spawned; i < sp; i++)
11428 { out.spawn.push(i); }
11429 s.spawned = sp;
11430 var ar = arrivedBy(s.countT, s.earned, s.flight);
11431 out.arrived = ar - s.arrived;
11432 s.arrived = ar;
11433 s.counter = s.before + ar;
11434 if (ar >= s.earned)
11435 {
11436 s.counter = s.after;
11437 enter('hold');
11438 }
11439 break;
11440 }
11441 else if (s.phase === 'hold')
11442 {
11443 var need = (s.failed || s.earned <= 0) ? s.holdZero : s.hold;
11444 if (s.t + left < need)
11445 { s.t += left; left = -1; break; }
11446 enter('done');
11447 break;
11448 }
11449 else
11450 { break; }
11451 }
11452 out.phase = s.phase;
11453 out.counter = s.counter;
11454 out.done = s.phase === 'done';
11455 return out;
11456 };
11457
11458 return s;
11459}
11460
11461/* ---------------- DOM / canvas player (browser only) ---------------- */
11462
11463var active = null;
11464
11465function reducedMotion ()
11466{
11467 try
11468 {
11469 return !!(root.matchMedia && root.matchMedia('(prefers-reduced-motion: reduce)').matches);
11470 }
11471 catch (e) { return false; }
11472}
11473
11474function tr (key, fallback)
11475{
11476 if (typeof I18n !== 'undefined' && I18n.t)
11477 {
11478 var v = I18n.t(key);
11479 if (v && v !== key)
11480 { return v; }
11481 }
11482 return fallback;
11483}
11484
11485function planetImages (planet)
11486{
11487 var list = [];
11488 var colors = (planet && planet.colors) || [];
11489 for (var i = 0; i < colors.length; i++)
11490 {
11491 if (!colors[i] || !colors[i].image)
11492 { continue; }
11493 var img = new Image();
11494 img.decoding = 'async';
11495 img.src = colors[i].image;
11496 list.push({ img: img, hex: colors[i].hex || '#ffffff' });
11497 }
11498 if (!list.length)
11499 { list.push({ img: null, hex: '#ffffff' }); }
11500 return list;
11501}
11502
11503/**
11504 * Show the reward overlay. opts: { won, planet, result: Promise<{before,
11505 * after}|null>, onDone }. Returns a handle with .active and .cancel().
11506 */
11507function play (opts)
11508{
11509 opts = opts || {};
11510 if (active)
11511 { active.cancel(); }
11512 var doc = root.document;
11513 var overlay = doc.getElementById('reward');
11514 var title = doc.getElementById('reward-title');
11515 var counter = doc.getElementById('reward-total');
11516 var label = doc.getElementById('reward-label');
11517 var canvas = doc.getElementById('reward-canvas');
11518 var hint = doc.getElementById('reward-hint');
11519 if (!overlay || !title || !counter || !canvas)
11520 {
11521 if (opts.onDone)
11522 { opts.onDone(); }
11523 return null;
11524 }
11525 var still = reducedMotion();
11526 var seq = createSequence({ won: opts.won, rise: still ? 0 : RISE });
11527 var imgs = planetImages(opts.planet);
11528 var flying = [];
11529 var last = 0;
11530 var raf = 0;
11531 var pop = 0;
11532 var ctx = canvas.getContext('2d');
11533 var dpr = Math.min(2, root.devicePixelRatio || 1);
11534 var W = 0;
11535 var H = 0;
11536
11537 title.textContent = opts.won ? tr('reward.won', 'You won!') : tr('reward.lost', 'You lost...');
11538 title.className = 'reward-title' + (opts.won ? ' won' : ' lost');
11539 if (label)
11540 { label.textContent = tr('reward.total', 'Total points'); }
11541 counter.textContent = '';
11542 counter.parentNode.hidden = true;
11543 if (hint)
11544 { hint.hidden = true; hint.textContent = tr('reward.continue', 'Tap to continue'); }
11545 overlay.classList.toggle('reduced', still);
11546 overlay.hidden = false;
11547
11548 function resize ()
11549 {
11550 W = root.innerWidth || 360;
11551 H = root.innerHeight || 640;
11552 canvas.width = Math.round(W * dpr);
11553 canvas.height = Math.round(H * dpr);
11554 canvas.style.width = W + 'px';
11555 canvas.style.height = H + 'px';
11556 if (ctx)
11557 { ctx.setTransform(dpr, 0, 0, dpr, 0, 0); }
11558 }
11559 resize();
11560 root.addEventListener('resize', resize);
11561
11562 function target ()
11563 {
11564 var r = counter.getBoundingClientRect();
11565 if (r.width > 0)
11566 { return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; }
11567 return { x: W / 2, y: H - 80 };
11568 }
11569
11570 function spawn ()
11571 {
11572 var size = Math.max(28, Math.min(56, Math.round(Math.min(W, H) * 0.075)));
11573 var sx = size + Math.random() * Math.max(1, W - 2 * size);
11574 var sy = -size;
11575 var tg = target();
11576 // Random arc: control point pushed sideways and up.
11577 var mx = (sx + tg.x) / 2 + (Math.random() - 0.5) * W * 0.9;
11578 var my = Math.min(sy, tg.y) + (Math.random() * 0.5) * H;
11579 flying.push({
11580 t: 0,
11581 sx: sx, sy: sy, cx: mx, cy: my,
11582 pick: imgs[Math.floor(Math.random() * imgs.length)],
11583 size: size,
11584 rot: (Math.random() - 0.5) * 6
11585 });
11586 }
11587
11588 function draw (dt)
11589 {
11590 if (!ctx)
11591 { return; }
11592 ctx.clearRect(0, 0, W, H);
11593 var tg = target();
11594 for (var i = flying.length - 1; i >= 0; i--)
11595 {
11596 var f = flying[i];
11597 f.t += dt / FLIGHT;
11598 if (f.t >= 1)
11599 {
11600 flying.splice(i, 1);
11601 continue;
11602 }
11603 var u = f.t;
11604 // Ease in a little so blocks accelerate into the counter.
11605 var e = u * u * (3 - 2 * u) * 0.35 + u * 0.65;
11606 var a = 1 - e;
11607 var x = a * a * f.sx + 2 * a * e * f.cx + e * e * tg.x;
11608 var y = a * a * f.sy + 2 * a * e * f.cy + e * e * tg.y;
11609 var s = f.size * (1 - 0.45 * e);
11610 ctx.save();
11611 ctx.translate(x, y);
11612 ctx.rotate(f.rot * e);
11613 if (f.pick.img && f.pick.img.complete && f.pick.img.naturalWidth)
11614 { ctx.drawImage(f.pick.img, -s / 2, -s / 2, s, s); }
11615 else
11616 {
11617 ctx.fillStyle = f.pick.hex;
11618 ctx.fillRect(-s / 2, -s / 2, s, s);
11619 }
11620 ctx.restore();
11621 }
11622 }
11623
11624 function setCounter (v)
11625 {
11626 counter.textContent = String(v);
11627 }
11628
11629 var handle = {
11630 active: true,
11631 seq: seq,
11632 flyingCount: function () { return flying.length; },
11633 cancel: function ()
11634 { cleanup(false); }
11635 };
11636
11637 function onTap (e)
11638 {
11639 if (seq.phase !== 'hold')
11640 { return; }
11641 if (e && e.type === 'keydown' && e.key !== ' ' && e.key !== 'Enter' && e.key !== 'Spacebar')
11642 { return; }
11643 if (e && e.preventDefault)
11644 { e.preventDefault(); }
11645 seq.finish();
11646 }
11647 overlay.addEventListener('pointerup', onTap);
11648 doc.addEventListener('keydown', onTap);
11649
11650 function cleanup (callDone)
11651 {
11652 if (!handle.active)
11653 { return; }
11654 handle.active = false;
11655 if (raf && root.cancelAnimationFrame)
11656 { root.cancelAnimationFrame(raf); }
11657 root.removeEventListener('resize', resize);
11658 overlay.removeEventListener('pointerup', onTap);
11659 doc.removeEventListener('keydown', onTap);
11660 overlay.hidden = true;
11661 overlay.classList.remove('risen');
11662 if (ctx)
11663 { ctx.clearRect(0, 0, W, H); }
11664 if (active === handle)
11665 { active = null; }
11666 if (callDone && opts.onDone)
11667 { opts.onDone(); }
11668 }
11669
11670 Promise.resolve(opts.result).then(function (res)
11671 { seq.setResult(res); }, function ()
11672 { seq.setResult(null); });
11673
11674 function frame (now)
11675 {
11676 if (!handle.active)
11677 { return; }
11678 var dt = last ? Math.min(0.1, (now - last) / 1000) : 0;
11679 last = now;
11680 var prev = seq.phase;
11681 var out = seq.tick(dt);
11682 if (prev === 'intro' && out.phase !== 'intro')
11683 { overlay.classList.add('risen'); }
11684 if ((out.phase === 'count' || out.phase === 'hold' || out.phase === 'done')
11685 && counter.parentNode.hidden && seq.hasResult && !seq.failed)
11686 {
11687 counter.parentNode.hidden = false;
11688 setCounter(seq.before);
11689 }
11690 if (!still)
11691 {
11692 for (var i = 0; i < out.spawn.length; i++)
11693 { spawn(); }
11694 }
11695 if (out.arrived > 0)
11696 {
11697 pop = 1;
11698 setCounter(out.counter);
11699 }
11700 if (out.phase === 'hold' && !seq.failed)
11701 { setCounter(seq.after); }
11702 if (out.phase === 'hold' && hint && hint.hidden)
11703 { hint.hidden = false; }
11704 if (pop > 0)
11705 {
11706 pop = Math.max(0, pop - dt * 6);
11707 counter.style.transform = 'scale(' + (1 + 0.18 * pop).toFixed(3) + ')';
11708 }
11709 draw(dt);
11710 if (out.done)
11711 {
11712 cleanup(true);
11713 return;
11714 }
11715 raf = root.requestAnimationFrame(frame);
11716 }
11717 raf = root.requestAnimationFrame(frame);
11718 active = handle;
11719 return handle;
11720}
11721
11722var Reward = {
11723 RATE0: RATE0,
11724 ACCEL: ACCEL,
11725 INTRO: INTRO,
11726 RISE: RISE,
11727 FLIGHT: FLIGHT,
11728 HOLD: HOLD,
11729 HOLD_ZERO: HOLD_ZERO,
11730 WAIT_MAX: WAIT_MAX,
11731 spawnTime: spawnTime,
11732 spawnedBy: spawnedBy,
11733 arrivedBy: arrivedBy,
11734 countDuration: countDuration,
11735 createSequence: createSequence,
11736 play: play,
11737 isActive: function () { return !!(active && active.active); },
11738 /** Read-only snapshot for tests and debugging. */
11739 debugState: function ()
11740 {
11741 if (!active)
11742 { return null; }
11743 var q = active.seq;
11744 return {
11745 phase: q.phase, counter: q.counter, before: q.before, after: q.after,
11746 earned: q.earned, spawned: q.spawned, arrived: q.arrived,
11747 failed: q.failed, won: q.won, flying: active.flyingCount()
11748 };
11749 }
11750};
11751
11752if (typeof module !== 'undefined' && module.exports)
11753{ module.exports = Reward; }
11754root.Reward = Reward;
11755})(typeof globalThis !== 'undefined' ? globalThis : this);
11756
11757/*
11758 * End File:
11759 * /workspace/meteors/src/reward.js
11760 */
11761
11198/*
11762/*
11199 * Start File:
11763 * Start File:
11200 * /workspace/meteors/src/designer.js
11764 * /workspace/meteors/src/designer.js
@@ -11829,7 +12393,10 @@ var app = {
11829 miniAcc: 0,
12393 miniAcc: 0,
11830 offlineResultShown: false,
12394 offlineResultShown: false,
11831 roundWonDelay: 0,
12395 roundWonDelay: 0,
11832 roundWonHandled: false
12396 roundWonHandled: false,
12397 rewardActive: false,
12398 onlineBefore: 0,
12399 pendingLobbyReturn: null
11833};
12400};
11834
12401
11835window.onload = function ()
12402window.onload = function ()
@@ -12641,13 +13208,15 @@ function tickView (dt)
12641 { onOnlineEliminated(); }
13208 { onOnlineEliminated(); }
12642 else if (app.offline)
13209 else if (app.offline)
12643 { /* Offline result is shown from tickOffline. */ }
13210 { /* Offline result is shown from tickOffline. */ }
13211 else if (rewardEnabled())
13212 { showReward(false, finishPlaySession(app.lastScore), returnToMenu); }
12644 else
13213 else
12645 {
13214 {
12646 showEl('game-over');
13215 showEl('game-over');
12647 finishPlaySession(app.lastScore);
13216 finishPlaySession(app.lastScore);
12648 }
13217 }
12649 }
13218 }
12650 if (!app.online && !app.offline && app.core.state === 'gameover'
13219 if (!app.online && !app.offline && !app.rewardActive && app.core.state === 'gameover'
12651 && app.core.gameOverTime >= GAME_OVER_DELAY)
13220 && app.core.gameOverTime >= GAME_OVER_DELAY)
12652 { returnToMenu(); }
13221 { returnToMenu(); }
12653}
13222}
@@ -13201,6 +13770,13 @@ function tickOffline (dt)
13201 {
13770 {
13202 app.roundWonHandled = true;
13771 app.roundWonHandled = true;
13203 app.roundWonDelay = Offline.ROUND_WON_DELAY || 1.5;
13772 app.roundWonDelay = Offline.ROUND_WON_DELAY || 1.5;
13773 if (rewardEnabled())
13774 { showReward(true, finishPlaySession(app.core.score), startNextOfflineRound); }
13775 }
13776 if (app.rewardActive)
13777 {
13778 updateOfflineMinis(dt, true);
13779 return;
13204 }
13780 }
13205 app.roundWonDelay -= dt;
13781 app.roundWonDelay -= dt;
13206 if (app.roundWonDelay <= 0)
13782 if (app.roundWonDelay <= 0)
@@ -13242,7 +13818,17 @@ function tickOffline (dt)
13242 updateOfflineMinis(dt, false);
13818 updateOfflineMinis(dt, false);
13243
13819
13244 if (app.battle.state === 'lost' && !app.offlineResultShown)
13820 if (app.battle.state === 'lost' && !app.offlineResultShown)
13245 { showOfflineResult(); }
13821 {
13822 if (rewardEnabled())
13823 {
13824 // Guard against starting the reward twice; showOfflineResult
13825 // sets the flag again when it runs afterwards.
13826 app.offlineResultShown = true;
13827 showReward(false, finishPlaySession(app.core ? app.core.score : 0), showOfflineResult);
13828 }
13829 else
13830 { showOfflineResult(); }
13831 }
13246}
13832}
13247
13833
13248function startNextOfflineRound ()
13834function startNextOfflineRound ()
@@ -13593,6 +14179,8 @@ function onOnlineEliminated ()
13593 app.spectating = true;
14179 app.spectating = true;
13594 unbindPointer();
14180 unbindPointer();
13595 hideEl('game-over');
14181 hideEl('game-over');
14182 if (app.rewardActive)
14183 { return; }
13596 var lobby = typeof Online !== 'undefined' && Online.lobby;
14184 var lobby = typeof Online !== 'undefined' && Online.lobby;
13597 if (lobby && lobby.status === 'finished')
14185 if (lobby && lobby.status === 'finished')
13598 {
14186 {
@@ -13648,6 +14236,8 @@ function startOnlineMatch ()
13648 if (typeof me.planet.miss_chance === 'number')
14236 if (typeof me.planet.miss_chance === 'number')
13649 { miss = me.planet.miss_chance; }
14237 { miss = me.planet.miss_chance; }
13650 }
14238 }
14239 app.onlineBefore = (typeof Online !== 'undefined' && Online.lifetimePoints) || 0;
14240 app.pendingLobbyReturn = null;
13651 startPlay({ online: true, planet: planet, missChance: miss });
14241 startPlay({ online: true, planet: planet, missChance: miss });
13652 if (typeof Online !== 'undefined')
14242 if (typeof Online !== 'undefined')
13653 { Online.startPolling(onlinePayload); }
14243 { Online.startPolling(onlinePayload); }
@@ -13797,9 +14387,32 @@ function bindOnlineUi ()
13797 }
14387 }
13798 };
14388 };
13799 Online.onFinished = function (lobby)
14389 Online.onFinished = function (lobby)
13800 { showPodium(lobby); };
14390 {
14391 if (app.mode === 'playing' && app.online && rewardEnabled() && !app.rewardActive)
14392 {
14393 // Lifetime points in this same poll already include the
14394 // server's online award (maybeAwardOnlineLobby).
14395 var result = { before: app.onlineBefore || 0, after: Online.lifetimePoints || 0 };
14396 showReward(myOnlinePlace(lobby) === 1, Promise.resolve(result), function ()
14397 {
14398 var pending = app.pendingLobbyReturn;
14399 app.pendingLobbyReturn = null;
14400 if (pending || !(Online.lobby && Online.lobby.status === 'finished'))
14401 { Online.onLobbyReturn(pending || Online.lobby); }
14402 else
14403 { showPodium(Online.lobby); }
14404 });
14405 return;
14406 }
14407 showPodium(lobby);
14408 };
13801 Online.onLobbyReturn = function (lobby)
14409 Online.onLobbyReturn = function (lobby)
13802 {
14410 {
14411 if (app.rewardActive)
14412 {
14413 app.pendingLobbyReturn = lobby;
14414 return;
14415 }
13803 teardownPlay();
14416 teardownPlay();
13804 app.online = false;
14417 app.online = false;
13805 app.mode = 'online';
14418 app.mode = 'online';
@@ -13888,7 +14501,7 @@ function renderOnline ()
13888 if (app.mode === 'playing' && app.online)
14501 if (app.mode === 'playing' && app.online)
13889 {
14502 {
13890 Online.renderMinis(document.getElementById('minis'));
14503 Online.renderMinis(document.getElementById('minis'));
13891 if (Online.lobby && Online.lobby.status === 'finished')
14504 if (Online.lobby && Online.lobby.status === 'finished' && !app.rewardActive)
13892 { showPodium(Online.lobby); }
14505 { showPodium(Online.lobby); }
13893 return;
14506 return;
13894 }
14507 }
@@ -14178,14 +14791,78 @@ function beginPlaySession (mode)
14178 });
14791 });
14179}
14792}
14180
14793
14794/**
14795 * Ends the solo/offline play session. Resolves to the server-confirmed
14796 * { before, after } profile totals (t1173), or null when there is no
14797 * logged-in user or the server did not confirm. Without a token (e.g.
14798 * play_begin failed) a logged-in player gets { before = after = current }.
14799 */
14181function finishPlaySession (score)
14800function finishPlaySession (score)
14182{
14801{
14183 var token = app.playToken;
14802 var token = app.playToken;
14184 app.playToken = null;
14803 app.playToken = null;
14185 if (!token || typeof Online === 'undefined' || !Online.playFinish)
14804 var hasOnline = typeof Online !== 'undefined';
14186 { return; }
14805 var current = hasOnline ? (Online.lifetimePoints || 0) : 0;
14187 Online.playFinish(token, score || 0).then(function ()
14806 if (!token || !hasOnline || !Online.playFinish)
14188 { refreshMenuAccount(); });
14807 {
14808 return Promise.resolve(hasOnline && Online.me ? { before: current, after: current } : null);
14809 }
14810 return Promise.resolve(Online.playFinish(token, score || 0)).then(function (data)
14811 {
14812 refreshMenuAccount();
14813 if (data && data.ok !== false && typeof data.lifetime_points === 'number')
14814 {
14815 var awarded = Math.max(0, Number(data.awarded) || 0);
14816 return { before: data.lifetime_points - awarded, after: data.lifetime_points };
14817 }
14818 return null;
14819 }, function ()
14820 { return null; });
14821}
14822
14823/* ---------- t1173 reward screen (logged in only) ------------------- */
14824
14825function rewardEnabled ()
14826{
14827 return typeof Reward !== 'undefined' && typeof Online !== 'undefined' && !!Online.me;
14828}
14829
14830/**
14831 * Shows "You won!" / "You lost..." and the points fly-in, then calls
14832 * next() — the same destination the mode used before (menu, next
14833 * offline round, offline result, or the online lobby/podium).
14834 */
14835function showReward (won, resultPromise, next)
14836{
14837 app.rewardActive = true;
14838 hideEl('game-over');
14839 hideEl('spectator');
14840 hideEl('podium');
14841 var handle = Reward.play({
14842 won: won,
14843 planet: app.planet,
14844 result: resultPromise,
14845 onDone: function ()
14846 {
14847 app.rewardActive = false;
14848 if (next)
14849 { next(); }
14850 }
14851 });
14852 if (!handle)
14853 { app.rewardActive = false; }
14854}
14855
14856function myOnlinePlace (lobby)
14857{
14858 var me = typeof Online !== 'undefined' ? Online.me : null;
14859 var ranks = (lobby && lobby.rankings) || [];
14860 for (var i = 0; i < ranks.length; i++)
14861 {
14862 if (me && ranks[i].id === me.id)
14863 { return ranks[i].place; }
14864 }
14865 return null;
14189}
14866}
14190
14867
14191
14868
build/index.html +10 −0
@@ -215,6 +215,16 @@
215 215 <p class="hint" id="podium-hint">Returning to the lobby in 5 seconds…</p>
216 216 </div>
217 217
218 <div id="reward" class="reward" hidden aria-live="polite">
219 <canvas id="reward-canvas" class="reward-canvas" aria-hidden="true"></canvas>
220 <h2 id="reward-title" class="reward-title">You won!</h2>
221 <div class="reward-counter" hidden>
222 <div id="reward-label" class="reward-label" data-i18n="reward.total">Total points</div>
223 <div id="reward-total" class="reward-total">0</div>
224 </div>
225 <p id="reward-hint" class="reward-hint" hidden data-i18n="reward.continue">Tap to continue</p>
226 </div>
227
218 228 <script src="framework.js"></script>
219 229 <script src="game.js"></script>
220 230 </body>
@@ -215,6 +215,16 @@
215 <p class="hint" id="podium-hint">Returning to the lobby in 5 seconds…</p>
215 <p class="hint" id="podium-hint">Returning to the lobby in 5 seconds…</p>
216 </div>
216 </div>
217
217
218 <div id="reward" class="reward" hidden aria-live="polite">
219 <canvas id="reward-canvas" class="reward-canvas" aria-hidden="true"></canvas>
220 <h2 id="reward-title" class="reward-title">You won!</h2>
221 <div class="reward-counter" hidden>
222 <div id="reward-label" class="reward-label" data-i18n="reward.total">Total points</div>
223 <div id="reward-total" class="reward-total">0</div>
224 </div>
225 <p id="reward-hint" class="reward-hint" hidden data-i18n="reward.continue">Tap to continue</p>
226 </div>
227
218 <script src="framework.js"></script>
228 <script src="framework.js"></script>
219 <script src="game.js"></script>
229 <script src="game.js"></script>
220</body>
230</body>
build/style.css +79 −1
@@ -46,7 +46,7 @@ html, body {
46 46 text-align: center;
47 47 }
48 48
49 .screen[hidden], #hud[hidden], #game-over[hidden], #online-panel[hidden], #minis[hidden], #spectator[hidden], #podium[hidden], #flights[hidden], #flights-back[hidden], #planet-select[hidden], #offline-result[hidden], #offline-hud[hidden], #chain-indicator[hidden], #designer[hidden], #designer-edit[hidden] { display: none !important; }
49 .screen[hidden], #hud[hidden], #game-over[hidden], #online-panel[hidden], #minis[hidden], #spectator[hidden], #podium[hidden], #flights[hidden], #flights-back[hidden], #planet-select[hidden], #offline-result[hidden], #offline-hud[hidden], #chain-indicator[hidden], #designer[hidden], #designer-edit[hidden], #reward[hidden] { display: none !important; }
50 50
51 51 h1 {
52 52 font-size: clamp(48px, 14vw, 96px);
@@ -985,3 +985,81 @@ html[lang="ja"], html[lang="zh-Hans"], html[lang="ko"] {
985 985 font-size: 0.95rem;
986 986 line-height: 1.45;
987 987 }
988
989 /* ---------- t1173 reward screen ---------- */
990 .reward {
991 position: fixed;
992 inset: 0;
993 z-index: 70;
994 background: rgba(8, 10, 22, 0.82);
995 overflow: hidden;
996 touch-action: none;
997 user-select: none;
998 -webkit-user-select: none;
999 }
1000 .reward-canvas {
1001 position: absolute;
1002 inset: 0;
1003 width: 100%;
1004 height: 100%;
1005 pointer-events: none;
1006 z-index: 1;
1007 }
1008 .reward-title {
1009 position: absolute;
1010 left: 0;
1011 right: 0;
1012 top: 50%;
1013 margin: 0;
1014 padding: 0 16px;
1015 text-align: center;
1016 font-size: clamp(36px, 11vw, 72px);
1017 font-weight: 800;
1018 transform: translateY(-50%);
1019 transition: top 0.6s cubic-bezier(0.22, 1, 0.36, 1), transform 0.6s cubic-bezier(0.22, 1, 0.36, 1), font-size 0.6s ease;
1020 z-index: 2;
1021 text-shadow: 0 2px 18px rgba(0, 0, 0, 0.6);
1022 }
1023 .reward-title.won { color: #ffe27a; }
1024 .reward-title.lost { color: #ffb0a0; }
1025 .reward.risen .reward-title {
1026 top: max(18px, env(safe-area-inset-top));
1027 transform: translateY(0);
1028 font-size: clamp(28px, 8vw, 52px);
1029 }
1030 .reward.reduced .reward-title { transition: none; }
1031 .reward-counter {
1032 position: absolute;
1033 left: 50%;
1034 bottom: max(28px, calc(env(safe-area-inset-bottom) + 20px));
1035 transform: translateX(-50%);
1036 text-align: center;
1037 z-index: 3;
1038 }
1039 .reward-counter[hidden] { display: none !important; }
1040 .reward-label {
1041 font-size: clamp(12px, 3.2vw, 15px);
1042 letter-spacing: 0.12em;
1043 text-transform: uppercase;
1044 color: #b7bdd4;
1045 }
1046 .reward-total {
1047 display: inline-block;
1048 font-size: clamp(40px, 12vw, 72px);
1049 font-weight: 800;
1050 color: #ffe27a;
1051 font-variant-numeric: tabular-nums;
1052 text-shadow: 0 0 18px rgba(255, 200, 80, 0.45);
1053 transform-origin: 50% 60%;
1054 will-change: transform;
1055 }
1056 .reward-hint {
1057 position: absolute;
1058 left: 0;
1059 right: 0;
1060 bottom: max(4px, env(safe-area-inset-bottom));
1061 margin: 0;
1062 font-size: 13px;
1063 color: #8f96b2;
1064 z-index: 3;
1065 }
@@ -46,7 +46,7 @@ html, body {
46 text-align: center;
46 text-align: center;
47}
47}
48
48
49.screen[hidden], #hud[hidden], #game-over[hidden], #online-panel[hidden], #minis[hidden], #spectator[hidden], #podium[hidden], #flights[hidden], #flights-back[hidden], #planet-select[hidden], #offline-result[hidden], #offline-hud[hidden], #chain-indicator[hidden], #designer[hidden], #designer-edit[hidden] { display: none !important; }
49.screen[hidden], #hud[hidden], #game-over[hidden], #online-panel[hidden], #minis[hidden], #spectator[hidden], #podium[hidden], #flights[hidden], #flights-back[hidden], #planet-select[hidden], #offline-result[hidden], #offline-hud[hidden], #chain-indicator[hidden], #designer[hidden], #designer-edit[hidden], #reward[hidden] { display: none !important; }
50
50
51h1 {
51h1 {
52 font-size: clamp(48px, 14vw, 96px);
52 font-size: clamp(48px, 14vw, 96px);
@@ -985,3 +985,81 @@ html[lang="ja"], html[lang="zh-Hans"], html[lang="ko"] {
985 font-size: 0.95rem;
985 font-size: 0.95rem;
986 line-height: 1.45;
986 line-height: 1.45;
987}
987}
988
989/* ---------- t1173 reward screen ---------- */
990.reward {
991 position: fixed;
992 inset: 0;
993 z-index: 70;
994 background: rgba(8, 10, 22, 0.82);
995 overflow: hidden;
996 touch-action: none;
997 user-select: none;
998 -webkit-user-select: none;
999}
1000.reward-canvas {
1001 position: absolute;
1002 inset: 0;
1003 width: 100%;
1004 height: 100%;
1005 pointer-events: none;
1006 z-index: 1;
1007}
1008.reward-title {
1009 position: absolute;
1010 left: 0;
1011 right: 0;
1012 top: 50%;
1013 margin: 0;
1014 padding: 0 16px;
1015 text-align: center;
1016 font-size: clamp(36px, 11vw, 72px);
1017 font-weight: 800;
1018 transform: translateY(-50%);
1019 transition: top 0.6s cubic-bezier(0.22, 1, 0.36, 1), transform 0.6s cubic-bezier(0.22, 1, 0.36, 1), font-size 0.6s ease;
1020 z-index: 2;
1021 text-shadow: 0 2px 18px rgba(0, 0, 0, 0.6);
1022}
1023.reward-title.won { color: #ffe27a; }
1024.reward-title.lost { color: #ffb0a0; }
1025.reward.risen .reward-title {
1026 top: max(18px, env(safe-area-inset-top));
1027 transform: translateY(0);
1028 font-size: clamp(28px, 8vw, 52px);
1029}
1030.reward.reduced .reward-title { transition: none; }
1031.reward-counter {
1032 position: absolute;
1033 left: 50%;
1034 bottom: max(28px, calc(env(safe-area-inset-bottom) + 20px));
1035 transform: translateX(-50%);
1036 text-align: center;
1037 z-index: 3;
1038}
1039.reward-counter[hidden] { display: none !important; }
1040.reward-label {
1041 font-size: clamp(12px, 3.2vw, 15px);
1042 letter-spacing: 0.12em;
1043 text-transform: uppercase;
1044 color: #b7bdd4;
1045}
1046.reward-total {
1047 display: inline-block;
1048 font-size: clamp(40px, 12vw, 72px);
1049 font-weight: 800;
1050 color: #ffe27a;
1051 font-variant-numeric: tabular-nums;
1052 text-shadow: 0 0 18px rgba(255, 200, 80, 0.45);
1053 transform-origin: 50% 60%;
1054 will-change: transform;
1055}
1056.reward-hint {
1057 position: absolute;
1058 left: 0;
1059 right: 0;
1060 bottom: max(4px, env(safe-area-inset-bottom));
1061 margin: 0;
1062 font-size: 13px;
1063 color: #8f96b2;
1064 z-index: 3;
1065}
docs/ASSUMPTIONS.md +49 −0
@@ -894,3 +894,52 @@ Aanname:
894 894 1+1-plan (dat is door de sorteervolgorde al de winnaar), en een
895 895 plafond van **4000** bord-evaluaties per tick. Als dat plafond wordt
896 896 bereikt kan een zeldzame langere setup worden gemist.
897
898
899 ## t1173 / t1174 — puntenscherm na een spel of ronde
900
901 - Alleen voor **ingelogde** spelers. Uitgelogd blijft alles zoals het
902 was (game-over-overlay in solo, de oude vertraging tussen
903 Offline-rondes, podium in Online).
904 - **Gewonnen of verloren:** Spelen (solo) eindigt altijd doordat je
905 veld vol loopt, dus daar staat “You lost...”. Offline Strijd: een
906 gewonnen ronde (alle bots uit) → “You won!”, verlies → “You lost...”.
907 Online: plek 1 → “You won!”, anders “You lost...”. Teksten staan in
908 alle tien talen (`reward.won` / `reward.lost`).
909 - **Volgorde:** de titel staat 1 s gecentreerd en schuift dan in 0,6 s
910 naar boven. Pas als de server het nieuwe totaal heeft bevestigd
911 begint het tellen: het getal onderaan start op het totaal vóór de
912 ronde en elk aankomend blokje telt er 1 bij op, tot het nieuwe
913 totaal. Bij 0 verdiende punten staat het getal kort (1,5 s) in beeld
914 zonder blokjes. Aan het eind blijft het eindtotaal 1,5 s staan.
915 - **Tempo (t1174, i.p.v. een overslaanknop):** `rate = 5 + t` blokjes/s.
916 Na t seconden zijn er `5t + t²/2` vertrokken; blokje i vertrekt op
917 `t = −5 + √(25 + 2i)`. 253 punten: het laatste blokje vertrekt na
918 precies 18 s, plus 0,7 s vlucht. Er is **geen** overslaan-knop en
919 geen sneltoets om meteen naar het eindtotaal te springen. Wel mag je
920 tijdens die laatste 1,5 s (eindtotaal staat al) tikken/klikken of
921 Spatie/Enter drukken om meteen door te gaan.
922 - **Bron van de getallen:** solo en Offline gebruiken het antwoord van
923 `play_finish`: nieuw totaal = `lifetime_points`, start =
924 `lifetime_points − awarded`. Online is er geen `play_finish`; de
925 server kent de punten zelf toe bij uitschakeling/einde. Het start-
926 getal is het profieltotaal bij de start van de wedstrijd, het
927 eindgetal het totaal uit de poll die de wedstrijd als afgelopen meldt
928 (de toekenning gebeurt in dezelfde transactie, vóór het antwoord).
929 Antwoordt de server niet binnen 8 s of met een fout, dan wordt niets
930 geteld en gaat het scherm na 1,5 s verder.
931 - **Blokjes:** willekeurig gekozen uit de vijf blokjes (plaatjes) van
932 de planeet waarmee je die ronde speelde, ook bij eigen planeten. Ze
933 starten op een willekeurige x net boven het scherm en volgen een
934 kwadratische boog met een willekeurig controlepunt naar het getal.
935 - **Daarna:** solo → menu; Offline gewonnen → volgende ronde; Offline
936 verloren → het bestaande resultaatscherm; Online → de lobby. Omdat
937 de server de lobby na 5 s podium al terugzet, wacht de client met
938 teruggaan tot het puntenscherm klaar is. Is de lobby dan nog niet
939 terug, dan zie je de rest van het podium.
940 - **Techniek:** een DOM-overlay met één 2D-canvas voor de vliegende
941 blokjes (geen extra WebGL-context), ~20 tegelijk in beeld, getekend
942 via `requestAnimationFrame` (frames worden afgekapt op 0,1 s, dus een
943 achtergrondtab springt niet). Werkt op desktop en mobiel. Bij
944 `prefers-reduced-motion` vliegen er geen blokjes en springt de titel
945 zonder animatie naar boven; het getal telt in hetzelfde tempo op.
@@ -894,3 +894,52 @@ Aanname:
894 1+1-plan (dat is door de sorteervolgorde al de winnaar), en een
894 1+1-plan (dat is door de sorteervolgorde al de winnaar), en een
895 plafond van **4000** bord-evaluaties per tick. Als dat plafond wordt
895 plafond van **4000** bord-evaluaties per tick. Als dat plafond wordt
896 bereikt kan een zeldzame langere setup worden gemist.
896 bereikt kan een zeldzame langere setup worden gemist.
897
898
899## t1173 / t1174 — puntenscherm na een spel of ronde
900
901- Alleen voor **ingelogde** spelers. Uitgelogd blijft alles zoals het
902 was (game-over-overlay in solo, de oude vertraging tussen
903 Offline-rondes, podium in Online).
904- **Gewonnen of verloren:** Spelen (solo) eindigt altijd doordat je
905 veld vol loopt, dus daar staat “You lost...”. Offline Strijd: een
906 gewonnen ronde (alle bots uit) → “You won!”, verlies → “You lost...”.
907 Online: plek 1 → “You won!”, anders “You lost...”. Teksten staan in
908 alle tien talen (`reward.won` / `reward.lost`).
909- **Volgorde:** de titel staat 1 s gecentreerd en schuift dan in 0,6 s
910 naar boven. Pas als de server het nieuwe totaal heeft bevestigd
911 begint het tellen: het getal onderaan start op het totaal vóór de
912 ronde en elk aankomend blokje telt er 1 bij op, tot het nieuwe
913 totaal. Bij 0 verdiende punten staat het getal kort (1,5 s) in beeld
914 zonder blokjes. Aan het eind blijft het eindtotaal 1,5 s staan.
915- **Tempo (t1174, i.p.v. een overslaanknop):** `rate = 5 + t` blokjes/s.
916 Na t seconden zijn er `5t + t²/2` vertrokken; blokje i vertrekt op
917 `t = −5 + √(25 + 2i)`. 253 punten: het laatste blokje vertrekt na
918 precies 18 s, plus 0,7 s vlucht. Er is **geen** overslaan-knop en
919 geen sneltoets om meteen naar het eindtotaal te springen. Wel mag je
920 tijdens die laatste 1,5 s (eindtotaal staat al) tikken/klikken of
921 Spatie/Enter drukken om meteen door te gaan.
922- **Bron van de getallen:** solo en Offline gebruiken het antwoord van
923 `play_finish`: nieuw totaal = `lifetime_points`, start =
924 `lifetime_points − awarded`. Online is er geen `play_finish`; de
925 server kent de punten zelf toe bij uitschakeling/einde. Het start-
926 getal is het profieltotaal bij de start van de wedstrijd, het
927 eindgetal het totaal uit de poll die de wedstrijd als afgelopen meldt
928 (de toekenning gebeurt in dezelfde transactie, vóór het antwoord).
929 Antwoordt de server niet binnen 8 s of met een fout, dan wordt niets
930 geteld en gaat het scherm na 1,5 s verder.
931- **Blokjes:** willekeurig gekozen uit de vijf blokjes (plaatjes) van
932 de planeet waarmee je die ronde speelde, ook bij eigen planeten. Ze
933 starten op een willekeurige x net boven het scherm en volgen een
934 kwadratische boog met een willekeurig controlepunt naar het getal.
935- **Daarna:** solo → menu; Offline gewonnen → volgende ronde; Offline
936 verloren → het bestaande resultaatscherm; Online → de lobby. Omdat
937 de server de lobby na 5 s podium al terugzet, wacht de client met
938 teruggaan tot het puntenscherm klaar is. Is de lobby dan nog niet
939 terug, dan zie je de rest van het podium.
940- **Techniek:** een DOM-overlay met één 2D-canvas voor de vliegende
941 blokjes (geen extra WebGL-context), ~20 tegelijk in beeld, getekend
942 via `requestAnimationFrame` (frames worden afgekapt op 0,1 s, dus een
943 achtergrondtab springt niet). Werkt op desktop en mobiel. Bij
944 `prefers-reduced-motion` vliegen er geen blokjes en springt de titel
945 zonder animatie naar boven; het getal telt in hetzelfde tempo op.
server/lib/i18n.json +50 −10
@@ -279,7 +279,11 @@
279 279 "block.forge-brass": "Forge brass",
280 280 "block.forge-soot": "Forge soot",
281 281 "error.webgl": "This game needs WebGL. Please try another browser, or turn on hardware acceleration.",
282 "error.startFailed": "Could not start the game."
282 "error.startFailed": "Could not start the game.",
283 "reward.won": "You won!",
284 "reward.lost": "You lost...",
285 "reward.total": "Total points",
286 "reward.continue": "Tap to continue"
283 287 },
284 288 "nl": {
285 289 "menu.tagline": "Drie op een rij, en je blokjes krijgen raketmotoren.",
@@ -560,7 +564,11 @@
560 564 "block.forge-brass": "Forge-messing",
561 565 "block.forge-soot": "Forge-roet",
562 566 "error.webgl": "Dit spel heeft WebGL nodig. Probeer een andere browser, of zet hardwareversnelling aan.",
563 "error.startFailed": "Het spel kon niet worden gestart."
567 "error.startFailed": "Het spel kon niet worden gestart.",
568 "reward.won": "Gewonnen!",
569 "reward.lost": "Verloren...",
570 "reward.total": "Totaal punten",
571 "reward.continue": "Tik om verder te gaan"
564 572 },
565 573 "de": {
566 574 "menu.tagline": "Drei in einer Reihe — und deine Blöcke bekommen Raketenantrieb.",
@@ -841,7 +849,11 @@
841 849 "block.forge-brass": "Forge-Messing",
842 850 "block.forge-soot": "Forge-Ruß",
843 851 "error.webgl": "Dieses Spiel benötigt WebGL. Bitte verwende einen anderen Browser oder aktiviere die Hardwarebeschleunigung.",
844 "error.startFailed": "Das Spiel konnte nicht gestartet werden."
852 "error.startFailed": "Das Spiel konnte nicht gestartet werden.",
853 "reward.won": "Gewonnen!",
854 "reward.lost": "Verloren...",
855 "reward.total": "Punkte gesamt",
856 "reward.continue": "Tippen zum Fortfahren"
845 857 },
846 858 "fr": {
847 859 "menu.tagline": "Trois d’affilée, et tes blocs s’équipent de propulseurs.",
@@ -1122,7 +1134,11 @@
1122 1134 "block.forge-brass": "Forge laiton",
1123 1135 "block.forge-soot": "Forge suie",
1124 1136 "error.webgl": "Ce jeu a besoin de WebGL. Essayez un autre navigateur, ou activez l’accélération matérielle.",
1125 "error.startFailed": "Impossible de lancer le jeu."
1137 "error.startFailed": "Impossible de lancer le jeu.",
1138 "reward.won": "Victoire !",
1139 "reward.lost": "Perdu...",
1140 "reward.total": "Total des points",
1141 "reward.continue": "Touchez pour continuer"
1126 1142 },
1127 1143 "ja": {
1128 1144 "menu.tagline": "三つ揃えると、ブロックにロケットが点火します。",
@@ -1403,7 +1419,11 @@
1403 1419 "block.forge-brass": "フォージの真鍮",
1404 1420 "block.forge-soot": "フォージの煤",
1405 1421 "error.webgl": "このゲームにはWebGLが必要です。別のブラウザを使うか、ハードウェアアクセラレーションを有効にしてください。",
1406 "error.startFailed": "ゲームを開始できませんでした。"
1422 "error.startFailed": "ゲームを開始できませんでした。",
1423 "reward.won": "勝利!",
1424 "reward.lost": "敗北...",
1425 "reward.total": "合計ポイント",
1426 "reward.continue": "タップして続ける"
1407 1427 },
1408 1428 "zh": {
1409 1429 "menu.tagline": "三个一排,你的方块就会装上火箭。",
@@ -1684,7 +1704,11 @@
1684 1704 "block.forge-brass": "Forge黄铜",
1685 1705 "block.forge-soot": "Forge煤烟",
1686 1706 "error.webgl": "本游戏需要 WebGL。请尝试其他浏览器,或开启硬件加速。",
1687 "error.startFailed": "无法开始游戏。"
1707 "error.startFailed": "无法开始游戏。",
1708 "reward.won": "你赢了!",
1709 "reward.lost": "你输了...",
1710 "reward.total": "总积分",
1711 "reward.continue": "点击继续"
1688 1712 },
1689 1713 "ko": {
1690 1714 "menu.tagline": "세 개를 나란히 맞추면 블록에 로켓이 점화됩니다.",
@@ -1965,7 +1989,11 @@
1965 1989 "block.forge-brass": "Forge 황동",
1966 1990 "block.forge-soot": "Forge 그을음",
1967 1991 "error.webgl": "이 게임은 WebGL이 필요합니다. 다른 브라우저를 사용하거나 하드웨어 가속을 켜 주세요.",
1968 "error.startFailed": "게임을 시작할 수 없습니다."
1992 "error.startFailed": "게임을 시작할 수 없습니다.",
1993 "reward.won": "승리!",
1994 "reward.lost": "패배...",
1995 "reward.total": "총 포인트",
1996 "reward.continue": "탭하여 계속"
1969 1997 },
1970 1998 "pl": {
1971 1999 "menu.tagline": "Trzy w rzędzie, a twoje klocki dostają napęd rakietowy.",
@@ -2246,7 +2274,11 @@
2246 2274 "block.forge-brass": "Forge mosiądz",
2247 2275 "block.forge-soot": "Forge sadza",
2248 2276 "error.webgl": "Ta gra wymaga WebGL. Spróbuj innej przeglądarki albo włącz akcelerację sprzętową.",
2249 "error.startFailed": "Nie udało się uruchomić gry."
2277 "error.startFailed": "Nie udało się uruchomić gry.",
2278 "reward.won": "Wygrana!",
2279 "reward.lost": "Przegrana...",
2280 "reward.total": "Suma punktów",
2281 "reward.continue": "Dotknij, aby kontynuować"
2250 2282 },
2251 2283 "ru": {
2252 2284 "menu.tagline": "Три в ряд — и твои блоки получают ракетные двигатели.",
@@ -2527,7 +2559,11 @@
2527 2559 "block.forge-brass": "Forge (латунь)",
2528 2560 "block.forge-soot": "Forge (сажа)",
2529 2561 "error.webgl": "Этой игре нужен WebGL. Попробуйте другой браузер или включите аппаратное ускорение.",
2530 "error.startFailed": "Не удалось начать игру."
2562 "error.startFailed": "Не удалось начать игру.",
2563 "reward.won": "Победа!",
2564 "reward.lost": "Поражение...",
2565 "reward.total": "Всего очков",
2566 "reward.continue": "Нажмите, чтобы продолжить"
2531 2567 },
2532 2568 "es": {
2533 2569 "menu.tagline": "Tres en raya, y tus bloques ganan motores cohete.",
@@ -2808,7 +2844,11 @@
2808 2844 "block.forge-brass": "Forge latón",
2809 2845 "block.forge-soot": "Forge hollín",
2810 2846 "error.webgl": "Este juego necesita WebGL. Prueba con otro navegador o activa la aceleración por hardware.",
2811 "error.startFailed": "No se pudo iniciar el juego."
2847 "error.startFailed": "No se pudo iniciar el juego.",
2848 "reward.won": "¡Has ganado!",
2849 "reward.lost": "Has perdido...",
2850 "reward.total": "Puntos totales",
2851 "reward.continue": "Toca para continuar"
2812 2852 }
2813 2853 },
2814 2854 "errors": {
@@ -279,7 +279,11 @@
279 "block.forge-brass": "Forge brass",
279 "block.forge-brass": "Forge brass",
280 "block.forge-soot": "Forge soot",
280 "block.forge-soot": "Forge soot",
281 "error.webgl": "This game needs WebGL. Please try another browser, or turn on hardware acceleration.",
281 "error.webgl": "This game needs WebGL. Please try another browser, or turn on hardware acceleration.",
282 "error.startFailed": "Could not start the game."
282 "error.startFailed": "Could not start the game.",
283 "reward.won": "You won!",
284 "reward.lost": "You lost...",
285 "reward.total": "Total points",
286 "reward.continue": "Tap to continue"
283 },
287 },
284 "nl": {
288 "nl": {
285 "menu.tagline": "Drie op een rij, en je blokjes krijgen raketmotoren.",
289 "menu.tagline": "Drie op een rij, en je blokjes krijgen raketmotoren.",
@@ -560,7 +564,11 @@
560 "block.forge-brass": "Forge-messing",
564 "block.forge-brass": "Forge-messing",
561 "block.forge-soot": "Forge-roet",
565 "block.forge-soot": "Forge-roet",
562 "error.webgl": "Dit spel heeft WebGL nodig. Probeer een andere browser, of zet hardwareversnelling aan.",
566 "error.webgl": "Dit spel heeft WebGL nodig. Probeer een andere browser, of zet hardwareversnelling aan.",
563 "error.startFailed": "Het spel kon niet worden gestart."
567 "error.startFailed": "Het spel kon niet worden gestart.",
568 "reward.won": "Gewonnen!",
569 "reward.lost": "Verloren...",
570 "reward.total": "Totaal punten",
571 "reward.continue": "Tik om verder te gaan"
564 },
572 },
565 "de": {
573 "de": {
566 "menu.tagline": "Drei in einer Reihe — und deine Blöcke bekommen Raketenantrieb.",
574 "menu.tagline": "Drei in einer Reihe — und deine Blöcke bekommen Raketenantrieb.",
@@ -841,7 +849,11 @@
841 "block.forge-brass": "Forge-Messing",
849 "block.forge-brass": "Forge-Messing",
842 "block.forge-soot": "Forge-Ruß",
850 "block.forge-soot": "Forge-Ruß",
843 "error.webgl": "Dieses Spiel benötigt WebGL. Bitte verwende einen anderen Browser oder aktiviere die Hardwarebeschleunigung.",
851 "error.webgl": "Dieses Spiel benötigt WebGL. Bitte verwende einen anderen Browser oder aktiviere die Hardwarebeschleunigung.",
844 "error.startFailed": "Das Spiel konnte nicht gestartet werden."
852 "error.startFailed": "Das Spiel konnte nicht gestartet werden.",
853 "reward.won": "Gewonnen!",
854 "reward.lost": "Verloren...",
855 "reward.total": "Punkte gesamt",
856 "reward.continue": "Tippen zum Fortfahren"
845 },
857 },
846 "fr": {
858 "fr": {
847 "menu.tagline": "Trois d’affilée, et tes blocs s’équipent de propulseurs.",
859 "menu.tagline": "Trois d’affilée, et tes blocs s’équipent de propulseurs.",
@@ -1122,7 +1134,11 @@
1122 "block.forge-brass": "Forge laiton",
1134 "block.forge-brass": "Forge laiton",
1123 "block.forge-soot": "Forge suie",
1135 "block.forge-soot": "Forge suie",
1124 "error.webgl": "Ce jeu a besoin de WebGL. Essayez un autre navigateur, ou activez l’accélération matérielle.",
1136 "error.webgl": "Ce jeu a besoin de WebGL. Essayez un autre navigateur, ou activez l’accélération matérielle.",
1125 "error.startFailed": "Impossible de lancer le jeu."
1137 "error.startFailed": "Impossible de lancer le jeu.",
1138 "reward.won": "Victoire !",
1139 "reward.lost": "Perdu...",
1140 "reward.total": "Total des points",
1141 "reward.continue": "Touchez pour continuer"
1126 },
1142 },
1127 "ja": {
1143 "ja": {
1128 "menu.tagline": "三つ揃えると、ブロックにロケットが点火します。",
1144 "menu.tagline": "三つ揃えると、ブロックにロケットが点火します。",
@@ -1403,7 +1419,11 @@
1403 "block.forge-brass": "フォージの真鍮",
1419 "block.forge-brass": "フォージの真鍮",
1404 "block.forge-soot": "フォージの煤",
1420 "block.forge-soot": "フォージの煤",
1405 "error.webgl": "このゲームにはWebGLが必要です。別のブラウザを使うか、ハードウェアアクセラレーションを有効にしてください。",
1421 "error.webgl": "このゲームにはWebGLが必要です。別のブラウザを使うか、ハードウェアアクセラレーションを有効にしてください。",
1406 "error.startFailed": "ゲームを開始できませんでした。"
1422 "error.startFailed": "ゲームを開始できませんでした。",
1423 "reward.won": "勝利!",
1424 "reward.lost": "敗北...",
1425 "reward.total": "合計ポイント",
1426 "reward.continue": "タップして続ける"
1407 },
1427 },
1408 "zh": {
1428 "zh": {
1409 "menu.tagline": "三个一排,你的方块就会装上火箭。",
1429 "menu.tagline": "三个一排,你的方块就会装上火箭。",
@@ -1684,7 +1704,11 @@
1684 "block.forge-brass": "Forge黄铜",
1704 "block.forge-brass": "Forge黄铜",
1685 "block.forge-soot": "Forge煤烟",
1705 "block.forge-soot": "Forge煤烟",
1686 "error.webgl": "本游戏需要 WebGL。请尝试其他浏览器,或开启硬件加速。",
1706 "error.webgl": "本游戏需要 WebGL。请尝试其他浏览器,或开启硬件加速。",
1687 "error.startFailed": "无法开始游戏。"
1707 "error.startFailed": "无法开始游戏。",
1708 "reward.won": "你赢了!",
1709 "reward.lost": "你输了...",
1710 "reward.total": "总积分",
1711 "reward.continue": "点击继续"
1688 },
1712 },
1689 "ko": {
1713 "ko": {
1690 "menu.tagline": "세 개를 나란히 맞추면 블록에 로켓이 점화됩니다.",
1714 "menu.tagline": "세 개를 나란히 맞추면 블록에 로켓이 점화됩니다.",
@@ -1965,7 +1989,11 @@
1965 "block.forge-brass": "Forge 황동",
1989 "block.forge-brass": "Forge 황동",
1966 "block.forge-soot": "Forge 그을음",
1990 "block.forge-soot": "Forge 그을음",
1967 "error.webgl": "이 게임은 WebGL이 필요합니다. 다른 브라우저를 사용하거나 하드웨어 가속을 켜 주세요.",
1991 "error.webgl": "이 게임은 WebGL이 필요합니다. 다른 브라우저를 사용하거나 하드웨어 가속을 켜 주세요.",
1968 "error.startFailed": "게임을 시작할 수 없습니다."
1992 "error.startFailed": "게임을 시작할 수 없습니다.",
1993 "reward.won": "승리!",
1994 "reward.lost": "패배...",
1995 "reward.total": "총 포인트",
1996 "reward.continue": "탭하여 계속"
1969 },
1997 },
1970 "pl": {
1998 "pl": {
1971 "menu.tagline": "Trzy w rzędzie, a twoje klocki dostają napęd rakietowy.",
1999 "menu.tagline": "Trzy w rzędzie, a twoje klocki dostają napęd rakietowy.",
@@ -2246,7 +2274,11 @@
2246 "block.forge-brass": "Forge mosiądz",
2274 "block.forge-brass": "Forge mosiądz",
2247 "block.forge-soot": "Forge sadza",
2275 "block.forge-soot": "Forge sadza",
2248 "error.webgl": "Ta gra wymaga WebGL. Spróbuj innej przeglądarki albo włącz akcelerację sprzętową.",
2276 "error.webgl": "Ta gra wymaga WebGL. Spróbuj innej przeglądarki albo włącz akcelerację sprzętową.",
2249 "error.startFailed": "Nie udało się uruchomić gry."
2277 "error.startFailed": "Nie udało się uruchomić gry.",
2278 "reward.won": "Wygrana!",
2279 "reward.lost": "Przegrana...",
2280 "reward.total": "Suma punktów",
2281 "reward.continue": "Dotknij, aby kontynuować"
2250 },
2282 },
2251 "ru": {
2283 "ru": {
2252 "menu.tagline": "Три в ряд — и твои блоки получают ракетные двигатели.",
2284 "menu.tagline": "Три в ряд — и твои блоки получают ракетные двигатели.",
@@ -2527,7 +2559,11 @@
2527 "block.forge-brass": "Forge (латунь)",
2559 "block.forge-brass": "Forge (латунь)",
2528 "block.forge-soot": "Forge (сажа)",
2560 "block.forge-soot": "Forge (сажа)",
2529 "error.webgl": "Этой игре нужен WebGL. Попробуйте другой браузер или включите аппаратное ускорение.",
2561 "error.webgl": "Этой игре нужен WebGL. Попробуйте другой браузер или включите аппаратное ускорение.",
2530 "error.startFailed": "Не удалось начать игру."
2562 "error.startFailed": "Не удалось начать игру.",
2563 "reward.won": "Победа!",
2564 "reward.lost": "Поражение...",
2565 "reward.total": "Всего очков",
2566 "reward.continue": "Нажмите, чтобы продолжить"
2531 },
2567 },
2532 "es": {
2568 "es": {
2533 "menu.tagline": "Tres en raya, y tus bloques ganan motores cohete.",
2569 "menu.tagline": "Tres en raya, y tus bloques ganan motores cohete.",
@@ -2808,7 +2844,11 @@
2808 "block.forge-brass": "Forge latón",
2844 "block.forge-brass": "Forge latón",
2809 "block.forge-soot": "Forge hollín",
2845 "block.forge-soot": "Forge hollín",
2810 "error.webgl": "Este juego necesita WebGL. Prueba con otro navegador o activa la aceleración por hardware.",
2846 "error.webgl": "Este juego necesita WebGL. Prueba con otro navegador o activa la aceleración por hardware.",
2811 "error.startFailed": "No se pudo iniciar el juego."
2847 "error.startFailed": "No se pudo iniciar el juego.",
2848 "reward.won": "¡Has ganado!",
2849 "reward.lost": "Has perdido...",
2850 "reward.total": "Puntos totales",
2851 "reward.continue": "Toca para continuar"
2812 }
2852 }
2813 },
2853 },
2814 "errors": {
2854 "errors": {
src/build.sh +1 −0
@@ -22,6 +22,7 @@ FILES=(
22 22 "$SRC_DIR/miniLayout.js"
23 23 "$SRC_DIR/online.js"
24 24 "$SRC_DIR/offline.js"
25 "$SRC_DIR/reward.js"
25 26 "$SRC_DIR/designer.js"
26 27 "$SRC_DIR/main.js"
27 28 )
@@ -22,6 +22,7 @@ FILES=(
22 "$SRC_DIR/miniLayout.js"
22 "$SRC_DIR/miniLayout.js"
23 "$SRC_DIR/online.js"
23 "$SRC_DIR/online.js"
24 "$SRC_DIR/offline.js"
24 "$SRC_DIR/offline.js"
25 "$SRC_DIR/reward.js"
25 "$SRC_DIR/designer.js"
26 "$SRC_DIR/designer.js"
26 "$SRC_DIR/main.js"
27 "$SRC_DIR/main.js"
27)
28)
src/main.js +122 −9
@@ -86,7 +86,10 @@ var app = {
86 86 miniAcc: 0,
87 87 offlineResultShown: false,
88 88 roundWonDelay: 0,
89 roundWonHandled: false
89 roundWonHandled: false,
90 rewardActive: false,
91 onlineBefore: 0,
92 pendingLobbyReturn: null
90 93 };
91 94
92 95 window.onload = function ()
@@ -898,13 +901,15 @@ function tickView (dt)
898 901 { onOnlineEliminated(); }
899 902 else if (app.offline)
900 903 { /* Offline result is shown from tickOffline. */ }
904 else if (rewardEnabled())
905 { showReward(false, finishPlaySession(app.lastScore), returnToMenu); }
901 906 else
902 907 {
903 908 showEl('game-over');
904 909 finishPlaySession(app.lastScore);
905 910 }
906 911 }
907 if (!app.online && !app.offline && app.core.state === 'gameover'
912 if (!app.online && !app.offline && !app.rewardActive && app.core.state === 'gameover'
908 913 && app.core.gameOverTime >= GAME_OVER_DELAY)
909 914 { returnToMenu(); }
910 915 }
@@ -1458,6 +1463,13 @@ function tickOffline (dt)
1458 1463 {
1459 1464 app.roundWonHandled = true;
1460 1465 app.roundWonDelay = Offline.ROUND_WON_DELAY || 1.5;
1466 if (rewardEnabled())
1467 { showReward(true, finishPlaySession(app.core.score), startNextOfflineRound); }
1468 }
1469 if (app.rewardActive)
1470 {
1471 updateOfflineMinis(dt, true);
1472 return;
1461 1473 }
1462 1474 app.roundWonDelay -= dt;
1463 1475 if (app.roundWonDelay <= 0)
@@ -1499,7 +1511,17 @@ function tickOffline (dt)
1499 1511 updateOfflineMinis(dt, false);
1500 1512
1501 1513 if (app.battle.state === 'lost' && !app.offlineResultShown)
1502 { showOfflineResult(); }
1514 {
1515 if (rewardEnabled())
1516 {
1517 // Guard against starting the reward twice; showOfflineResult
1518 // sets the flag again when it runs afterwards.
1519 app.offlineResultShown = true;
1520 showReward(false, finishPlaySession(app.core ? app.core.score : 0), showOfflineResult);
1521 }
1522 else
1523 { showOfflineResult(); }
1524 }
1503 1525 }
1504 1526
1505 1527 function startNextOfflineRound ()
@@ -1850,6 +1872,8 @@ function onOnlineEliminated ()
1850 1872 app.spectating = true;
1851 1873 unbindPointer();
1852 1874 hideEl('game-over');
1875 if (app.rewardActive)
1876 { return; }
1853 1877 var lobby = typeof Online !== 'undefined' && Online.lobby;
1854 1878 if (lobby && lobby.status === 'finished')
1855 1879 {
@@ -1905,6 +1929,8 @@ function startOnlineMatch ()
1905 1929 if (typeof me.planet.miss_chance === 'number')
1906 1930 { miss = me.planet.miss_chance; }
1907 1931 }
1932 app.onlineBefore = (typeof Online !== 'undefined' && Online.lifetimePoints) || 0;
1933 app.pendingLobbyReturn = null;
1908 1934 startPlay({ online: true, planet: planet, missChance: miss });
1909 1935 if (typeof Online !== 'undefined')
1910 1936 { Online.startPolling(onlinePayload); }
@@ -2054,9 +2080,32 @@ function bindOnlineUi ()
2054 2080 }
2055 2081 };
2056 2082 Online.onFinished = function (lobby)
2057 { showPodium(lobby); };
2083 {
2084 if (app.mode === 'playing' && app.online && rewardEnabled() && !app.rewardActive)
2085 {
2086 // Lifetime points in this same poll already include the
2087 // server's online award (maybeAwardOnlineLobby).
2088 var result = { before: app.onlineBefore || 0, after: Online.lifetimePoints || 0 };
2089 showReward(myOnlinePlace(lobby) === 1, Promise.resolve(result), function ()
2090 {
2091 var pending = app.pendingLobbyReturn;
2092 app.pendingLobbyReturn = null;
2093 if (pending || !(Online.lobby && Online.lobby.status === 'finished'))
2094 { Online.onLobbyReturn(pending || Online.lobby); }
2095 else
2096 { showPodium(Online.lobby); }
2097 });
2098 return;
2099 }
2100 showPodium(lobby);
2101 };
2058 2102 Online.onLobbyReturn = function (lobby)
2059 2103 {
2104 if (app.rewardActive)
2105 {
2106 app.pendingLobbyReturn = lobby;
2107 return;
2108 }
2060 2109 teardownPlay();
2061 2110 app.online = false;
2062 2111 app.mode = 'online';
@@ -2145,7 +2194,7 @@ function renderOnline ()
2145 2194 if (app.mode === 'playing' && app.online)
2146 2195 {
2147 2196 Online.renderMinis(document.getElementById('minis'));
2148 if (Online.lobby && Online.lobby.status === 'finished')
2197 if (Online.lobby && Online.lobby.status === 'finished' && !app.rewardActive)
2149 2198 { showPodium(Online.lobby); }
2150 2199 return;
2151 2200 }
@@ -2435,14 +2484,78 @@ function beginPlaySession (mode)
2435 2484 });
2436 2485 }
2437 2486
2487 /**
2488 * Ends the solo/offline play session. Resolves to the server-confirmed
2489 * { before, after } profile totals (t1173), or null when there is no
2490 * logged-in user or the server did not confirm. Without a token (e.g.
2491 * play_begin failed) a logged-in player gets { before = after = current }.
2492 */
2438 2493 function finishPlaySession (score)
2439 2494 {
2440 2495 var token = app.playToken;
2441 2496 app.playToken = null;
2442 if (!token || typeof Online === 'undefined' || !Online.playFinish)
2443 { return; }
2444 Online.playFinish(token, score || 0).then(function ()
2445 { refreshMenuAccount(); });
2497 var hasOnline = typeof Online !== 'undefined';
2498 var current = hasOnline ? (Online.lifetimePoints || 0) : 0;
2499 if (!token || !hasOnline || !Online.playFinish)
2500 {
2501 return Promise.resolve(hasOnline && Online.me ? { before: current, after: current } : null);
2502 }
2503 return Promise.resolve(Online.playFinish(token, score || 0)).then(function (data)
2504 {
2505 refreshMenuAccount();
2506 if (data && data.ok !== false && typeof data.lifetime_points === 'number')
2507 {
2508 var awarded = Math.max(0, Number(data.awarded) || 0);
2509 return { before: data.lifetime_points - awarded, after: data.lifetime_points };
2510 }
2511 return null;
2512 }, function ()
2513 { return null; });
2514 }
2515
2516 /* ---------- t1173 reward screen (logged in only) ------------------- */
2517
2518 function rewardEnabled ()
2519 {
2520 return typeof Reward !== 'undefined' && typeof Online !== 'undefined' && !!Online.me;
2521 }
2522
2523 /**
2524 * Shows "You won!" / "You lost..." and the points fly-in, then calls
2525 * next() — the same destination the mode used before (menu, next
2526 * offline round, offline result, or the online lobby/podium).
2527 */
2528 function showReward (won, resultPromise, next)
2529 {
2530 app.rewardActive = true;
2531 hideEl('game-over');
2532 hideEl('spectator');
2533 hideEl('podium');
2534 var handle = Reward.play({
2535 won: won,
2536 planet: app.planet,
2537 result: resultPromise,
2538 onDone: function ()
2539 {
2540 app.rewardActive = false;
2541 if (next)
2542 { next(); }
2543 }
2544 });
2545 if (!handle)
2546 { app.rewardActive = false; }
2547 }
2548
2549 function myOnlinePlace (lobby)
2550 {
2551 var me = typeof Online !== 'undefined' ? Online.me : null;
2552 var ranks = (lobby && lobby.rankings) || [];
2553 for (var i = 0; i < ranks.length; i++)
2554 {
2555 if (me && ranks[i].id === me.id)
2556 { return ranks[i].place; }
2557 }
2558 return null;
2446 2559 }
2447 2560
2448 2561
@@ -86,7 +86,10 @@ var app = {
86 miniAcc: 0,
86 miniAcc: 0,
87 offlineResultShown: false,
87 offlineResultShown: false,
88 roundWonDelay: 0,
88 roundWonDelay: 0,
89 roundWonHandled: false
89 roundWonHandled: false,
90 rewardActive: false,
91 onlineBefore: 0,
92 pendingLobbyReturn: null
90};
93};
91
94
92window.onload = function ()
95window.onload = function ()
@@ -898,13 +901,15 @@ function tickView (dt)
898 { onOnlineEliminated(); }
901 { onOnlineEliminated(); }
899 else if (app.offline)
902 else if (app.offline)
900 { /* Offline result is shown from tickOffline. */ }
903 { /* Offline result is shown from tickOffline. */ }
904 else if (rewardEnabled())
905 { showReward(false, finishPlaySession(app.lastScore), returnToMenu); }
901 else
906 else
902 {
907 {
903 showEl('game-over');
908 showEl('game-over');
904 finishPlaySession(app.lastScore);
909 finishPlaySession(app.lastScore);
905 }
910 }
906 }
911 }
907 if (!app.online && !app.offline && app.core.state === 'gameover'
912 if (!app.online && !app.offline && !app.rewardActive && app.core.state === 'gameover'
908 && app.core.gameOverTime >= GAME_OVER_DELAY)
913 && app.core.gameOverTime >= GAME_OVER_DELAY)
909 { returnToMenu(); }
914 { returnToMenu(); }
910}
915}
@@ -1458,6 +1463,13 @@ function tickOffline (dt)
1458 {
1463 {
1459 app.roundWonHandled = true;
1464 app.roundWonHandled = true;
1460 app.roundWonDelay = Offline.ROUND_WON_DELAY || 1.5;
1465 app.roundWonDelay = Offline.ROUND_WON_DELAY || 1.5;
1466 if (rewardEnabled())
1467 { showReward(true, finishPlaySession(app.core.score), startNextOfflineRound); }
1468 }
1469 if (app.rewardActive)
1470 {
1471 updateOfflineMinis(dt, true);
1472 return;
1461 }
1473 }
1462 app.roundWonDelay -= dt;
1474 app.roundWonDelay -= dt;
1463 if (app.roundWonDelay <= 0)
1475 if (app.roundWonDelay <= 0)
@@ -1499,7 +1511,17 @@ function tickOffline (dt)
1499 updateOfflineMinis(dt, false);
1511 updateOfflineMinis(dt, false);
1500
1512
1501 if (app.battle.state === 'lost' && !app.offlineResultShown)
1513 if (app.battle.state === 'lost' && !app.offlineResultShown)
1502 { showOfflineResult(); }
1514 {
1515 if (rewardEnabled())
1516 {
1517 // Guard against starting the reward twice; showOfflineResult
1518 // sets the flag again when it runs afterwards.
1519 app.offlineResultShown = true;
1520 showReward(false, finishPlaySession(app.core ? app.core.score : 0), showOfflineResult);
1521 }
1522 else
1523 { showOfflineResult(); }
1524 }
1503}
1525}
1504
1526
1505function startNextOfflineRound ()
1527function startNextOfflineRound ()
@@ -1850,6 +1872,8 @@ function onOnlineEliminated ()
1850 app.spectating = true;
1872 app.spectating = true;
1851 unbindPointer();
1873 unbindPointer();
1852 hideEl('game-over');
1874 hideEl('game-over');
1875 if (app.rewardActive)
1876 { return; }
1853 var lobby = typeof Online !== 'undefined' && Online.lobby;
1877 var lobby = typeof Online !== 'undefined' && Online.lobby;
1854 if (lobby && lobby.status === 'finished')
1878 if (lobby && lobby.status === 'finished')
1855 {
1879 {
@@ -1905,6 +1929,8 @@ function startOnlineMatch ()
1905 if (typeof me.planet.miss_chance === 'number')
1929 if (typeof me.planet.miss_chance === 'number')
1906 { miss = me.planet.miss_chance; }
1930 { miss = me.planet.miss_chance; }
1907 }
1931 }
1932 app.onlineBefore = (typeof Online !== 'undefined' && Online.lifetimePoints) || 0;
1933 app.pendingLobbyReturn = null;
1908 startPlay({ online: true, planet: planet, missChance: miss });
1934 startPlay({ online: true, planet: planet, missChance: miss });
1909 if (typeof Online !== 'undefined')
1935 if (typeof Online !== 'undefined')
1910 { Online.startPolling(onlinePayload); }
1936 { Online.startPolling(onlinePayload); }
@@ -2054,9 +2080,32 @@ function bindOnlineUi ()
2054 }
2080 }
2055 };
2081 };
2056 Online.onFinished = function (lobby)
2082 Online.onFinished = function (lobby)
2057 { showPodium(lobby); };
2083 {
2084 if (app.mode === 'playing' && app.online && rewardEnabled() && !app.rewardActive)
2085 {
2086 // Lifetime points in this same poll already include the
2087 // server's online award (maybeAwardOnlineLobby).
2088 var result = { before: app.onlineBefore || 0, after: Online.lifetimePoints || 0 };
2089 showReward(myOnlinePlace(lobby) === 1, Promise.resolve(result), function ()
2090 {
2091 var pending = app.pendingLobbyReturn;
2092 app.pendingLobbyReturn = null;
2093 if (pending || !(Online.lobby && Online.lobby.status === 'finished'))
2094 { Online.onLobbyReturn(pending || Online.lobby); }
2095 else
2096 { showPodium(Online.lobby); }
2097 });
2098 return;
2099 }
2100 showPodium(lobby);
2101 };
2058 Online.onLobbyReturn = function (lobby)
2102 Online.onLobbyReturn = function (lobby)
2059 {
2103 {
2104 if (app.rewardActive)
2105 {
2106 app.pendingLobbyReturn = lobby;
2107 return;
2108 }
2060 teardownPlay();
2109 teardownPlay();
2061 app.online = false;
2110 app.online = false;
2062 app.mode = 'online';
2111 app.mode = 'online';
@@ -2145,7 +2194,7 @@ function renderOnline ()
2145 if (app.mode === 'playing' && app.online)
2194 if (app.mode === 'playing' && app.online)
2146 {
2195 {
2147 Online.renderMinis(document.getElementById('minis'));
2196 Online.renderMinis(document.getElementById('minis'));
2148 if (Online.lobby && Online.lobby.status === 'finished')
2197 if (Online.lobby && Online.lobby.status === 'finished' && !app.rewardActive)
2149 { showPodium(Online.lobby); }
2198 { showPodium(Online.lobby); }
2150 return;
2199 return;
2151 }
2200 }
@@ -2435,14 +2484,78 @@ function beginPlaySession (mode)
2435 });
2484 });
2436}
2485}
2437
2486
2487/**
2488 * Ends the solo/offline play session. Resolves to the server-confirmed
2489 * { before, after } profile totals (t1173), or null when there is no
2490 * logged-in user or the server did not confirm. Without a token (e.g.
2491 * play_begin failed) a logged-in player gets { before = after = current }.
2492 */
2438function finishPlaySession (score)
2493function finishPlaySession (score)
2439{
2494{
2440 var token = app.playToken;
2495 var token = app.playToken;
2441 app.playToken = null;
2496 app.playToken = null;
2442 if (!token || typeof Online === 'undefined' || !Online.playFinish)
2497 var hasOnline = typeof Online !== 'undefined';
2443 { return; }
2498 var current = hasOnline ? (Online.lifetimePoints || 0) : 0;
2444 Online.playFinish(token, score || 0).then(function ()
2499 if (!token || !hasOnline || !Online.playFinish)
2445 { refreshMenuAccount(); });
2500 {
2501 return Promise.resolve(hasOnline && Online.me ? { before: current, after: current } : null);
2502 }
2503 return Promise.resolve(Online.playFinish(token, score || 0)).then(function (data)
2504 {
2505 refreshMenuAccount();
2506 if (data && data.ok !== false && typeof data.lifetime_points === 'number')
2507 {
2508 var awarded = Math.max(0, Number(data.awarded) || 0);
2509 return { before: data.lifetime_points - awarded, after: data.lifetime_points };
2510 }
2511 return null;
2512 }, function ()
2513 { return null; });
2514}
2515
2516/* ---------- t1173 reward screen (logged in only) ------------------- */
2517
2518function rewardEnabled ()
2519{
2520 return typeof Reward !== 'undefined' && typeof Online !== 'undefined' && !!Online.me;
2521}
2522
2523/**
2524 * Shows "You won!" / "You lost..." and the points fly-in, then calls
2525 * next() — the same destination the mode used before (menu, next
2526 * offline round, offline result, or the online lobby/podium).
2527 */
2528function showReward (won, resultPromise, next)
2529{
2530 app.rewardActive = true;
2531 hideEl('game-over');
2532 hideEl('spectator');
2533 hideEl('podium');
2534 var handle = Reward.play({
2535 won: won,
2536 planet: app.planet,
2537 result: resultPromise,
2538 onDone: function ()
2539 {
2540 app.rewardActive = false;
2541 if (next)
2542 { next(); }
2543 }
2544 });
2545 if (!handle)
2546 { app.rewardActive = false; }
2547}
2548
2549function myOnlinePlace (lobby)
2550{
2551 var me = typeof Online !== 'undefined' ? Online.me : null;
2552 var ranks = (lobby && lobby.rankings) || [];
2553 for (var i = 0; i < ranks.length; i++)
2554 {
2555 if (me && ranks[i].id === me.id)
2556 { return ranks[i].place; }
2557 }
2558 return null;
2446}
2559}
2447
2560
2448
2561
src/reward.js added +514 −0
@@ -0,0 +1,514 @@
1 /*
2 * End-of-round reward screen (t1173 / t1174).
3 *
4 * Logged-in only. Sequence: a centred "You won!" / "You lost..." for
5 * INTRO seconds, then it tweens to the top (RISE seconds). Once the
6 * server has confirmed the new profile total, blocks of the player's
7 * planet arc from the top of the screen into a counter at the bottom
8 * centre, one block per newly earned point. Each arrival adds 1.
9 *
10 * Spawn rate accelerates: rate(t) = RATE0 + ACCEL·t blocks/s, so the
11 * number spawned after t seconds is N(t) = RATE0·t + ACCEL·t²/2, and
12 * block i (0-based) leaves at T(i) = the t where N(t) = i.
13 * 253 points → the last block leaves at exactly 18 s.
14 *
15 * The pure timing / sequencing part (Reward.spawnTime, Reward.createSequence)
16 * has no DOM and is unit-tested. Reward.play wires it to an overlay.
17 */
18 (function (root)
19 {
20 'use strict';
21
22 var RATE0 = 5; // blocks per second at t = 0
23 var ACCEL = 1; // +1 block/s every second
24 var INTRO = 1.0; // centred title before it rises
25 var RISE = 0.6; // title tween to the top
26 var FLIGHT = 0.7; // one block's arc duration
27 var HOLD = 1.5; // final total shown before continuing
28 var HOLD_ZERO = 1.5; // earned 0: show the number briefly
29 var WAIT_MAX = 8; // give up waiting for the server after this
30
31 /** Seconds after the start of counting when block i (0-based) leaves. */
32 function spawnTime (i)
33 {
34 if (!(i > 0))
35 { return 0; }
36 if (ACCEL === 0)
37 { return i / RATE0; }
38 return (-RATE0 + Math.sqrt(RATE0 * RATE0 + 2 * ACCEL * i)) / ACCEL;
39 }
40
41 /** Blocks spawned (left the top) by time t, capped at n. */
42 function spawnedBy (t, n)
43 {
44 if (!(t >= 0) || !(n > 0))
45 { return 0; }
46 // Block i has left when T(i) <= t, i.e. i <= N(t).
47 var k = Math.floor(RATE0 * t + ACCEL * t * t / 2 + 1e-9) + 1;
48 return Math.min(n, Math.max(0, k));
49 }
50
51 /** Blocks that have arrived in the counter by time t. */
52 function arrivedBy (t, n, flight)
53 {
54 flight = flight == null ? FLIGHT : flight;
55 return spawnedBy(t - flight, n);
56 }
57
58 /** Total seconds from the first spawn until the last block arrives. */
59 function countDuration (n, flight)
60 {
61 flight = flight == null ? FLIGHT : flight;
62 if (!(n > 0))
63 { return 0; }
64 return spawnTime(n - 1) + flight;
65 }
66
67 /**
68 * A pure, dt-driven sequence. Phases: intro → rise → wait → count →
69 * hold → done. `setResult({ before, after })` supplies the confirmed
70 * totals (earned = after − before, never negative); `setResult(null)`
71 * means the server did not confirm, so nothing is counted and the
72 * title is held briefly. tick(dt) returns
73 * { phase, counter, spawn: [indices], arrived, done }.
74 */
75 function createSequence (opts)
76 {
77 opts = opts || {};
78 var s = {
79 phase: 'intro',
80 t: 0, // time inside the current phase
81 countT: 0,
82 won: !!opts.won,
83 flight: opts.flight == null ? FLIGHT : opts.flight,
84 intro: opts.intro == null ? INTRO : opts.intro,
85 rise: opts.rise == null ? RISE : opts.rise,
86 hold: opts.hold == null ? HOLD : opts.hold,
87 holdZero: opts.holdZero == null ? HOLD_ZERO : opts.holdZero,
88 waitMax: opts.waitMax == null ? WAIT_MAX : opts.waitMax,
89 hasResult: false,
90 failed: false,
91 before: 0,
92 after: 0,
93 earned: 0,
94 spawned: 0,
95 arrived: 0,
96 counter: 0
97 };
98
99 s.setResult = function (res)
100 {
101 if (s.hasResult)
102 { return; }
103 s.hasResult = true;
104 if (!res || typeof res.after !== 'number' || !isFinite(res.after))
105 {
106 s.failed = true;
107 return;
108 }
109 var after = Math.max(0, Math.floor(res.after));
110 var before = typeof res.before === 'number' && isFinite(res.before)
111 ? Math.max(0, Math.floor(res.before)) : after;
112 if (before > after)
113 { before = after; }
114 s.before = before;
115 s.after = after;
116 s.earned = after - before;
117 s.counter = before;
118 };
119
120 s.finish = function ()
121 {
122 if (s.phase !== 'hold')
123 { return false; }
124 s.phase = 'done';
125 return true;
126 };
127
128 function enter (phase)
129 {
130 s.phase = phase;
131 s.t = 0;
132 }
133
134 s.tick = function (dt)
135 {
136 var out = { phase: s.phase, counter: s.counter, spawn: [], arrived: 0, done: false };
137 if (s.phase === 'done')
138 {
139 out.done = true;
140 return out;
141 }
142 dt = Math.max(0, Number(dt) || 0);
143 var left = dt;
144 // Allow several phase changes inside one large dt.
145 for (var guard = 0; guard < 8 && left >= 0; guard++)
146 {
147 if (s.phase === 'intro')
148 {
149 if (s.t + left < s.intro)
150 { s.t += left; left = -1; break; }
151 left -= (s.intro - s.t);
152 enter('rise');
153 }
154 else if (s.phase === 'rise')
155 {
156 if (s.t + left < s.rise)
157 { s.t += left; left = -1; break; }
158 left -= (s.rise - s.t);
159 enter('wait');
160 }
161 else if (s.phase === 'wait')
162 {
163 if (!s.hasResult)
164 {
165 s.t += left;
166 if (s.t >= s.waitMax)
167 {
168 s.hasResult = true;
169 s.failed = true;
170 enter('hold');
171 continue;
172 }
173 left = -1;
174 break;
175 }
176 if (s.failed || s.earned <= 0)
177 { enter('hold'); continue; }
178 enter('count');
179 s.countT = 0;
180 }
181 else if (s.phase === 'count')
182 {
183 s.countT += left;
184 left = -1;
185 var sp = spawnedBy(s.countT, s.earned);
186 for (var i = s.spawned; i < sp; i++)
187 { out.spawn.push(i); }
188 s.spawned = sp;
189 var ar = arrivedBy(s.countT, s.earned, s.flight);
190 out.arrived = ar - s.arrived;
191 s.arrived = ar;
192 s.counter = s.before + ar;
193 if (ar >= s.earned)
194 {
195 s.counter = s.after;
196 enter('hold');
197 }
198 break;
199 }
200 else if (s.phase === 'hold')
201 {
202 var need = (s.failed || s.earned <= 0) ? s.holdZero : s.hold;
203 if (s.t + left < need)
204 { s.t += left; left = -1; break; }
205 enter('done');
206 break;
207 }
208 else
209 { break; }
210 }
211 out.phase = s.phase;
212 out.counter = s.counter;
213 out.done = s.phase === 'done';
214 return out;
215 };
216
217 return s;
218 }
219
220 /* ---------------- DOM / canvas player (browser only) ---------------- */
221
222 var active = null;
223
224 function reducedMotion ()
225 {
226 try
227 {
228 return !!(root.matchMedia && root.matchMedia('(prefers-reduced-motion: reduce)').matches);
229 }
230 catch (e) { return false; }
231 }
232
233 function tr (key, fallback)
234 {
235 if (typeof I18n !== 'undefined' && I18n.t)
236 {
237 var v = I18n.t(key);
238 if (v && v !== key)
239 { return v; }
240 }
241 return fallback;
242 }
243
244 function planetImages (planet)
245 {
246 var list = [];
247 var colors = (planet && planet.colors) || [];
248 for (var i = 0; i < colors.length; i++)
249 {
250 if (!colors[i] || !colors[i].image)
251 { continue; }
252 var img = new Image();
253 img.decoding = 'async';
254 img.src = colors[i].image;
255 list.push({ img: img, hex: colors[i].hex || '#ffffff' });
256 }
257 if (!list.length)
258 { list.push({ img: null, hex: '#ffffff' }); }
259 return list;
260 }
261
262 /**
263 * Show the reward overlay. opts: { won, planet, result: Promise<{before,
264 * after}|null>, onDone }. Returns a handle with .active and .cancel().
265 */
266 function play (opts)
267 {
268 opts = opts || {};
269 if (active)
270 { active.cancel(); }
271 var doc = root.document;
272 var overlay = doc.getElementById('reward');
273 var title = doc.getElementById('reward-title');
274 var counter = doc.getElementById('reward-total');
275 var label = doc.getElementById('reward-label');
276 var canvas = doc.getElementById('reward-canvas');
277 var hint = doc.getElementById('reward-hint');
278 if (!overlay || !title || !counter || !canvas)
279 {
280 if (opts.onDone)
281 { opts.onDone(); }
282 return null;
283 }
284 var still = reducedMotion();
285 var seq = createSequence({ won: opts.won, rise: still ? 0 : RISE });
286 var imgs = planetImages(opts.planet);
287 var flying = [];
288 var last = 0;
289 var raf = 0;
290 var pop = 0;
291 var ctx = canvas.getContext('2d');
292 var dpr = Math.min(2, root.devicePixelRatio || 1);
293 var W = 0;
294 var H = 0;
295
296 title.textContent = opts.won ? tr('reward.won', 'You won!') : tr('reward.lost', 'You lost...');
297 title.className = 'reward-title' + (opts.won ? ' won' : ' lost');
298 if (label)
299 { label.textContent = tr('reward.total', 'Total points'); }
300 counter.textContent = '';
301 counter.parentNode.hidden = true;
302 if (hint)
303 { hint.hidden = true; hint.textContent = tr('reward.continue', 'Tap to continue'); }
304 overlay.classList.toggle('reduced', still);
305 overlay.hidden = false;
306
307 function resize ()
308 {
309 W = root.innerWidth || 360;
310 H = root.innerHeight || 640;
311 canvas.width = Math.round(W * dpr);
312 canvas.height = Math.round(H * dpr);
313 canvas.style.width = W + 'px';
314 canvas.style.height = H + 'px';
315 if (ctx)
316 { ctx.setTransform(dpr, 0, 0, dpr, 0, 0); }
317 }
318 resize();
319 root.addEventListener('resize', resize);
320
321 function target ()
322 {
323 var r = counter.getBoundingClientRect();
324 if (r.width > 0)
325 { return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; }
326 return { x: W / 2, y: H - 80 };
327 }
328
329 function spawn ()
330 {
331 var size = Math.max(28, Math.min(56, Math.round(Math.min(W, H) * 0.075)));
332 var sx = size + Math.random() * Math.max(1, W - 2 * size);
333 var sy = -size;
334 var tg = target();
335 // Random arc: control point pushed sideways and up.
336 var mx = (sx + tg.x) / 2 + (Math.random() - 0.5) * W * 0.9;
337 var my = Math.min(sy, tg.y) + (Math.random() * 0.5) * H;
338 flying.push({
339 t: 0,
340 sx: sx, sy: sy, cx: mx, cy: my,
341 pick: imgs[Math.floor(Math.random() * imgs.length)],
342 size: size,
343 rot: (Math.random() - 0.5) * 6
344 });
345 }
346
347 function draw (dt)
348 {
349 if (!ctx)
350 { return; }
351 ctx.clearRect(0, 0, W, H);
352 var tg = target();
353 for (var i = flying.length - 1; i >= 0; i--)
354 {
355 var f = flying[i];
356 f.t += dt / FLIGHT;
357 if (f.t >= 1)
358 {
359 flying.splice(i, 1);
360 continue;
361 }
362 var u = f.t;
363 // Ease in a little so blocks accelerate into the counter.
364 var e = u * u * (3 - 2 * u) * 0.35 + u * 0.65;
365 var a = 1 - e;
366 var x = a * a * f.sx + 2 * a * e * f.cx + e * e * tg.x;
367 var y = a * a * f.sy + 2 * a * e * f.cy + e * e * tg.y;
368 var s = f.size * (1 - 0.45 * e);
369 ctx.save();
370 ctx.translate(x, y);
371 ctx.rotate(f.rot * e);
372 if (f.pick.img && f.pick.img.complete && f.pick.img.naturalWidth)
373 { ctx.drawImage(f.pick.img, -s / 2, -s / 2, s, s); }
374 else
375 {
376 ctx.fillStyle = f.pick.hex;
377 ctx.fillRect(-s / 2, -s / 2, s, s);
378 }
379 ctx.restore();
380 }
381 }
382
383 function setCounter (v)
384 {
385 counter.textContent = String(v);
386 }
387
388 var handle = {
389 active: true,
390 seq: seq,
391 flyingCount: function () { return flying.length; },
392 cancel: function ()
393 { cleanup(false); }
394 };
395
396 function onTap (e)
397 {
398 if (seq.phase !== 'hold')
399 { return; }
400 if (e && e.type === 'keydown' && e.key !== ' ' && e.key !== 'Enter' && e.key !== 'Spacebar')
401 { return; }
402 if (e && e.preventDefault)
403 { e.preventDefault(); }
404 seq.finish();
405 }
406 overlay.addEventListener('pointerup', onTap);
407 doc.addEventListener('keydown', onTap);
408
409 function cleanup (callDone)
410 {
411 if (!handle.active)
412 { return; }
413 handle.active = false;
414 if (raf && root.cancelAnimationFrame)
415 { root.cancelAnimationFrame(raf); }
416 root.removeEventListener('resize', resize);
417 overlay.removeEventListener('pointerup', onTap);
418 doc.removeEventListener('keydown', onTap);
419 overlay.hidden = true;
420 overlay.classList.remove('risen');
421 if (ctx)
422 { ctx.clearRect(0, 0, W, H); }
423 if (active === handle)
424 { active = null; }
425 if (callDone && opts.onDone)
426 { opts.onDone(); }
427 }
428
429 Promise.resolve(opts.result).then(function (res)
430 { seq.setResult(res); }, function ()
431 { seq.setResult(null); });
432
433 function frame (now)
434 {
435 if (!handle.active)
436 { return; }
437 var dt = last ? Math.min(0.1, (now - last) / 1000) : 0;
438 last = now;
439 var prev = seq.phase;
440 var out = seq.tick(dt);
441 if (prev === 'intro' && out.phase !== 'intro')
442 { overlay.classList.add('risen'); }
443 if ((out.phase === 'count' || out.phase === 'hold' || out.phase === 'done')
444 && counter.parentNode.hidden && seq.hasResult && !seq.failed)
445 {
446 counter.parentNode.hidden = false;
447 setCounter(seq.before);
448 }
449 if (!still)
450 {
451 for (var i = 0; i < out.spawn.length; i++)
452 { spawn(); }
453 }
454 if (out.arrived > 0)
455 {
456 pop = 1;
457 setCounter(out.counter);
458 }
459 if (out.phase === 'hold' && !seq.failed)
460 { setCounter(seq.after); }
461 if (out.phase === 'hold' && hint && hint.hidden)
462 { hint.hidden = false; }
463 if (pop > 0)
464 {
465 pop = Math.max(0, pop - dt * 6);
466 counter.style.transform = 'scale(' + (1 + 0.18 * pop).toFixed(3) + ')';
467 }
468 draw(dt);
469 if (out.done)
470 {
471 cleanup(true);
472 return;
473 }
474 raf = root.requestAnimationFrame(frame);
475 }
476 raf = root.requestAnimationFrame(frame);
477 active = handle;
478 return handle;
479 }
480
481 var Reward = {
482 RATE0: RATE0,
483 ACCEL: ACCEL,
484 INTRO: INTRO,
485 RISE: RISE,
486 FLIGHT: FLIGHT,
487 HOLD: HOLD,
488 HOLD_ZERO: HOLD_ZERO,
489 WAIT_MAX: WAIT_MAX,
490 spawnTime: spawnTime,
491 spawnedBy: spawnedBy,
492 arrivedBy: arrivedBy,
493 countDuration: countDuration,
494 createSequence: createSequence,
495 play: play,
496 isActive: function () { return !!(active && active.active); },
497 /** Read-only snapshot for tests and debugging. */
498 debugState: function ()
499 {
500 if (!active)
501 { return null; }
502 var q = active.seq;
503 return {
504 phase: q.phase, counter: q.counter, before: q.before, after: q.after,
505 earned: q.earned, spawned: q.spawned, arrived: q.arrived,
506 failed: q.failed, won: q.won, flying: active.flyingCount()
507 };
508 }
509 };
510
511 if (typeof module !== 'undefined' && module.exports)
512 { module.exports = Reward; }
513 root.Reward = Reward;
514 })(typeof globalThis !== 'undefined' ? globalThis : this);
@@ -0,0 +1,514 @@
1/*
2 * End-of-round reward screen (t1173 / t1174).
3 *
4 * Logged-in only. Sequence: a centred "You won!" / "You lost..." for
5 * INTRO seconds, then it tweens to the top (RISE seconds). Once the
6 * server has confirmed the new profile total, blocks of the player's
7 * planet arc from the top of the screen into a counter at the bottom
8 * centre, one block per newly earned point. Each arrival adds 1.
9 *
10 * Spawn rate accelerates: rate(t) = RATE0 + ACCEL·t blocks/s, so the
11 * number spawned after t seconds is N(t) = RATE0·t + ACCEL·t²/2, and
12 * block i (0-based) leaves at T(i) = the t where N(t) = i.
13 * 253 points → the last block leaves at exactly 18 s.
14 *
15 * The pure timing / sequencing part (Reward.spawnTime, Reward.createSequence)
16 * has no DOM and is unit-tested. Reward.play wires it to an overlay.
17 */
18(function (root)
19{
20'use strict';
21
22var RATE0 = 5; // blocks per second at t = 0
23var ACCEL = 1; // +1 block/s every second
24var INTRO = 1.0; // centred title before it rises
25var RISE = 0.6; // title tween to the top
26var FLIGHT = 0.7; // one block's arc duration
27var HOLD = 1.5; // final total shown before continuing
28var HOLD_ZERO = 1.5; // earned 0: show the number briefly
29var WAIT_MAX = 8; // give up waiting for the server after this
30
31/** Seconds after the start of counting when block i (0-based) leaves. */
32function spawnTime (i)
33{
34 if (!(i > 0))
35 { return 0; }
36 if (ACCEL === 0)
37 { return i / RATE0; }
38 return (-RATE0 + Math.sqrt(RATE0 * RATE0 + 2 * ACCEL * i)) / ACCEL;
39}
40
41/** Blocks spawned (left the top) by time t, capped at n. */
42function spawnedBy (t, n)
43{
44 if (!(t >= 0) || !(n > 0))
45 { return 0; }
46 // Block i has left when T(i) <= t, i.e. i <= N(t).
47 var k = Math.floor(RATE0 * t + ACCEL * t * t / 2 + 1e-9) + 1;
48 return Math.min(n, Math.max(0, k));
49}
50
51/** Blocks that have arrived in the counter by time t. */
52function arrivedBy (t, n, flight)
53{
54 flight = flight == null ? FLIGHT : flight;
55 return spawnedBy(t - flight, n);
56}
57
58/** Total seconds from the first spawn until the last block arrives. */
59function countDuration (n, flight)
60{
61 flight = flight == null ? FLIGHT : flight;
62 if (!(n > 0))
63 { return 0; }
64 return spawnTime(n - 1) + flight;
65}
66
67/**
68 * A pure, dt-driven sequence. Phases: intro → rise → wait → count →
69 * hold → done. `setResult({ before, after })` supplies the confirmed
70 * totals (earned = after − before, never negative); `setResult(null)`
71 * means the server did not confirm, so nothing is counted and the
72 * title is held briefly. tick(dt) returns
73 * { phase, counter, spawn: [indices], arrived, done }.
74 */
75function createSequence (opts)
76{
77 opts = opts || {};
78 var s = {
79 phase: 'intro',
80 t: 0, // time inside the current phase
81 countT: 0,
82 won: !!opts.won,
83 flight: opts.flight == null ? FLIGHT : opts.flight,
84 intro: opts.intro == null ? INTRO : opts.intro,
85 rise: opts.rise == null ? RISE : opts.rise,
86 hold: opts.hold == null ? HOLD : opts.hold,
87 holdZero: opts.holdZero == null ? HOLD_ZERO : opts.holdZero,
88 waitMax: opts.waitMax == null ? WAIT_MAX : opts.waitMax,
89 hasResult: false,
90 failed: false,
91 before: 0,
92 after: 0,
93 earned: 0,
94 spawned: 0,
95 arrived: 0,
96 counter: 0
97 };
98
99 s.setResult = function (res)
100 {
101 if (s.hasResult)
102 { return; }
103 s.hasResult = true;
104 if (!res || typeof res.after !== 'number' || !isFinite(res.after))
105 {
106 s.failed = true;
107 return;
108 }
109 var after = Math.max(0, Math.floor(res.after));
110 var before = typeof res.before === 'number' && isFinite(res.before)
111 ? Math.max(0, Math.floor(res.before)) : after;
112 if (before > after)
113 { before = after; }
114 s.before = before;
115 s.after = after;
116 s.earned = after - before;
117 s.counter = before;
118 };
119
120 s.finish = function ()
121 {
122 if (s.phase !== 'hold')
123 { return false; }
124 s.phase = 'done';
125 return true;
126 };
127
128 function enter (phase)
129 {
130 s.phase = phase;
131 s.t = 0;
132 }
133
134 s.tick = function (dt)
135 {
136 var out = { phase: s.phase, counter: s.counter, spawn: [], arrived: 0, done: false };
137 if (s.phase === 'done')
138 {
139 out.done = true;
140 return out;
141 }
142 dt = Math.max(0, Number(dt) || 0);
143 var left = dt;
144 // Allow several phase changes inside one large dt.
145 for (var guard = 0; guard < 8 && left >= 0; guard++)
146 {
147 if (s.phase === 'intro')
148 {
149 if (s.t + left < s.intro)
150 { s.t += left; left = -1; break; }
151 left -= (s.intro - s.t);
152 enter('rise');
153 }
154 else if (s.phase === 'rise')
155 {
156 if (s.t + left < s.rise)
157 { s.t += left; left = -1; break; }
158 left -= (s.rise - s.t);
159 enter('wait');
160 }
161 else if (s.phase === 'wait')
162 {
163 if (!s.hasResult)
164 {
165 s.t += left;
166 if (s.t >= s.waitMax)
167 {
168 s.hasResult = true;
169 s.failed = true;
170 enter('hold');
171 continue;
172 }
173 left = -1;
174 break;
175 }
176 if (s.failed || s.earned <= 0)
177 { enter('hold'); continue; }
178 enter('count');
179 s.countT = 0;
180 }
181 else if (s.phase === 'count')
182 {
183 s.countT += left;
184 left = -1;
185 var sp = spawnedBy(s.countT, s.earned);
186 for (var i = s.spawned; i < sp; i++)
187 { out.spawn.push(i); }
188 s.spawned = sp;
189 var ar = arrivedBy(s.countT, s.earned, s.flight);
190 out.arrived = ar - s.arrived;
191 s.arrived = ar;
192 s.counter = s.before + ar;
193 if (ar >= s.earned)
194 {
195 s.counter = s.after;
196 enter('hold');
197 }
198 break;
199 }
200 else if (s.phase === 'hold')
201 {
202 var need = (s.failed || s.earned <= 0) ? s.holdZero : s.hold;
203 if (s.t + left < need)
204 { s.t += left; left = -1; break; }
205 enter('done');
206 break;
207 }
208 else
209 { break; }
210 }
211 out.phase = s.phase;
212 out.counter = s.counter;
213 out.done = s.phase === 'done';
214 return out;
215 };
216
217 return s;
218}
219
220/* ---------------- DOM / canvas player (browser only) ---------------- */
221
222var active = null;
223
224function reducedMotion ()
225{
226 try
227 {
228 return !!(root.matchMedia && root.matchMedia('(prefers-reduced-motion: reduce)').matches);
229 }
230 catch (e) { return false; }
231}
232
233function tr (key, fallback)
234{
235 if (typeof I18n !== 'undefined' && I18n.t)
236 {
237 var v = I18n.t(key);
238 if (v && v !== key)
239 { return v; }
240 }
241 return fallback;
242}
243
244function planetImages (planet)
245{
246 var list = [];
247 var colors = (planet && planet.colors) || [];
248 for (var i = 0; i < colors.length; i++)
249 {
250 if (!colors[i] || !colors[i].image)
251 { continue; }
252 var img = new Image();
253 img.decoding = 'async';
254 img.src = colors[i].image;
255 list.push({ img: img, hex: colors[i].hex || '#ffffff' });
256 }
257 if (!list.length)
258 { list.push({ img: null, hex: '#ffffff' }); }
259 return list;
260}
261
262/**
263 * Show the reward overlay. opts: { won, planet, result: Promise<{before,
264 * after}|null>, onDone }. Returns a handle with .active and .cancel().
265 */
266function play (opts)
267{
268 opts = opts || {};
269 if (active)
270 { active.cancel(); }
271 var doc = root.document;
272 var overlay = doc.getElementById('reward');
273 var title = doc.getElementById('reward-title');
274 var counter = doc.getElementById('reward-total');
275 var label = doc.getElementById('reward-label');
276 var canvas = doc.getElementById('reward-canvas');
277 var hint = doc.getElementById('reward-hint');
278 if (!overlay || !title || !counter || !canvas)
279 {
280 if (opts.onDone)
281 { opts.onDone(); }
282 return null;
283 }
284 var still = reducedMotion();
285 var seq = createSequence({ won: opts.won, rise: still ? 0 : RISE });
286 var imgs = planetImages(opts.planet);
287 var flying = [];
288 var last = 0;
289 var raf = 0;
290 var pop = 0;
291 var ctx = canvas.getContext('2d');
292 var dpr = Math.min(2, root.devicePixelRatio || 1);
293 var W = 0;
294 var H = 0;
295
296 title.textContent = opts.won ? tr('reward.won', 'You won!') : tr('reward.lost', 'You lost...');
297 title.className = 'reward-title' + (opts.won ? ' won' : ' lost');
298 if (label)
299 { label.textContent = tr('reward.total', 'Total points'); }
300 counter.textContent = '';
301 counter.parentNode.hidden = true;
302 if (hint)
303 { hint.hidden = true; hint.textContent = tr('reward.continue', 'Tap to continue'); }
304 overlay.classList.toggle('reduced', still);
305 overlay.hidden = false;
306
307 function resize ()
308 {
309 W = root.innerWidth || 360;
310 H = root.innerHeight || 640;
311 canvas.width = Math.round(W * dpr);
312 canvas.height = Math.round(H * dpr);
313 canvas.style.width = W + 'px';
314 canvas.style.height = H + 'px';
315 if (ctx)
316 { ctx.setTransform(dpr, 0, 0, dpr, 0, 0); }
317 }
318 resize();
319 root.addEventListener('resize', resize);
320
321 function target ()
322 {
323 var r = counter.getBoundingClientRect();
324 if (r.width > 0)
325 { return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; }
326 return { x: W / 2, y: H - 80 };
327 }
328
329 function spawn ()
330 {
331 var size = Math.max(28, Math.min(56, Math.round(Math.min(W, H) * 0.075)));
332 var sx = size + Math.random() * Math.max(1, W - 2 * size);
333 var sy = -size;
334 var tg = target();
335 // Random arc: control point pushed sideways and up.
336 var mx = (sx + tg.x) / 2 + (Math.random() - 0.5) * W * 0.9;
337 var my = Math.min(sy, tg.y) + (Math.random() * 0.5) * H;
338 flying.push({
339 t: 0,
340 sx: sx, sy: sy, cx: mx, cy: my,
341 pick: imgs[Math.floor(Math.random() * imgs.length)],
342 size: size,
343 rot: (Math.random() - 0.5) * 6
344 });
345 }
346
347 function draw (dt)
348 {
349 if (!ctx)
350 { return; }
351 ctx.clearRect(0, 0, W, H);
352 var tg = target();
353 for (var i = flying.length - 1; i >= 0; i--)
354 {
355 var f = flying[i];
356 f.t += dt / FLIGHT;
357 if (f.t >= 1)
358 {
359 flying.splice(i, 1);
360 continue;
361 }
362 var u = f.t;
363 // Ease in a little so blocks accelerate into the counter.
364 var e = u * u * (3 - 2 * u) * 0.35 + u * 0.65;
365 var a = 1 - e;
366 var x = a * a * f.sx + 2 * a * e * f.cx + e * e * tg.x;
367 var y = a * a * f.sy + 2 * a * e * f.cy + e * e * tg.y;
368 var s = f.size * (1 - 0.45 * e);
369 ctx.save();
370 ctx.translate(x, y);
371 ctx.rotate(f.rot * e);
372 if (f.pick.img && f.pick.img.complete && f.pick.img.naturalWidth)
373 { ctx.drawImage(f.pick.img, -s / 2, -s / 2, s, s); }
374 else
375 {
376 ctx.fillStyle = f.pick.hex;
377 ctx.fillRect(-s / 2, -s / 2, s, s);
378 }
379 ctx.restore();
380 }
381 }
382
383 function setCounter (v)
384 {
385 counter.textContent = String(v);
386 }
387
388 var handle = {
389 active: true,
390 seq: seq,
391 flyingCount: function () { return flying.length; },
392 cancel: function ()
393 { cleanup(false); }
394 };
395
396 function onTap (e)
397 {
398 if (seq.phase !== 'hold')
399 { return; }
400 if (e && e.type === 'keydown' && e.key !== ' ' && e.key !== 'Enter' && e.key !== 'Spacebar')
401 { return; }
402 if (e && e.preventDefault)
403 { e.preventDefault(); }
404 seq.finish();
405 }
406 overlay.addEventListener('pointerup', onTap);
407 doc.addEventListener('keydown', onTap);
408
409 function cleanup (callDone)
410 {
411 if (!handle.active)
412 { return; }
413 handle.active = false;
414 if (raf && root.cancelAnimationFrame)
415 { root.cancelAnimationFrame(raf); }
416 root.removeEventListener('resize', resize);
417 overlay.removeEventListener('pointerup', onTap);
418 doc.removeEventListener('keydown', onTap);
419 overlay.hidden = true;
420 overlay.classList.remove('risen');
421 if (ctx)
422 { ctx.clearRect(0, 0, W, H); }
423 if (active === handle)
424 { active = null; }
425 if (callDone && opts.onDone)
426 { opts.onDone(); }
427 }
428
429 Promise.resolve(opts.result).then(function (res)
430 { seq.setResult(res); }, function ()
431 { seq.setResult(null); });
432
433 function frame (now)
434 {
435 if (!handle.active)
436 { return; }
437 var dt = last ? Math.min(0.1, (now - last) / 1000) : 0;
438 last = now;
439 var prev = seq.phase;
440 var out = seq.tick(dt);
441 if (prev === 'intro' && out.phase !== 'intro')
442 { overlay.classList.add('risen'); }
443 if ((out.phase === 'count' || out.phase === 'hold' || out.phase === 'done')
444 && counter.parentNode.hidden && seq.hasResult && !seq.failed)
445 {
446 counter.parentNode.hidden = false;
447 setCounter(seq.before);
448 }
449 if (!still)
450 {
451 for (var i = 0; i < out.spawn.length; i++)
452 { spawn(); }
453 }
454 if (out.arrived > 0)
455 {
456 pop = 1;
457 setCounter(out.counter);
458 }
459 if (out.phase === 'hold' && !seq.failed)
460 { setCounter(seq.after); }
461 if (out.phase === 'hold' && hint && hint.hidden)
462 { hint.hidden = false; }
463 if (pop > 0)
464 {
465 pop = Math.max(0, pop - dt * 6);
466 counter.style.transform = 'scale(' + (1 + 0.18 * pop).toFixed(3) + ')';
467 }
468 draw(dt);
469 if (out.done)
470 {
471 cleanup(true);
472 return;
473 }
474 raf = root.requestAnimationFrame(frame);
475 }
476 raf = root.requestAnimationFrame(frame);
477 active = handle;
478 return handle;
479}
480
481var Reward = {
482 RATE0: RATE0,
483 ACCEL: ACCEL,
484 INTRO: INTRO,
485 RISE: RISE,
486 FLIGHT: FLIGHT,
487 HOLD: HOLD,
488 HOLD_ZERO: HOLD_ZERO,
489 WAIT_MAX: WAIT_MAX,
490 spawnTime: spawnTime,
491 spawnedBy: spawnedBy,
492 arrivedBy: arrivedBy,
493 countDuration: countDuration,
494 createSequence: createSequence,
495 play: play,
496 isActive: function () { return !!(active && active.active); },
497 /** Read-only snapshot for tests and debugging. */
498 debugState: function ()
499 {
500 if (!active)
501 { return null; }
502 var q = active.seq;
503 return {
504 phase: q.phase, counter: q.counter, before: q.before, after: q.after,
505 earned: q.earned, spawned: q.spawned, arrived: q.arrived,
506 failed: q.failed, won: q.won, flying: active.flyingCount()
507 };
508 }
509};
510
511if (typeof module !== 'undefined' && module.exports)
512{ module.exports = Reward; }
513root.Reward = Reward;
514})(typeof globalThis !== 'undefined' ? globalThis : this);
test/reward.test.js added +204 −0
@@ -0,0 +1,204 @@
1 'use strict';
2
3 const { describe, it } = require('node:test');
4 const assert = require('node:assert/strict');
5 const Reward = require('../src/reward.js');
6
7 function runToEnd (seq, dt, maxT)
8 {
9 const events = [];
10 let t = 0;
11 let spawned = 0;
12 let arrived = 0;
13 let lastCounter = null;
14 let monotonic = true;
15 while (t < maxT)
16 {
17 const out = seq.tick(dt);
18 t += dt;
19 spawned += out.spawn.length;
20 arrived += out.arrived;
21 if (lastCounter != null && out.counter < lastCounter)
22 { monotonic = false; }
23 lastCounter = out.counter;
24 events.push({ t, phase: out.phase, counter: out.counter });
25 if (out.done)
26 { break; }
27 }
28 return { events, t, spawned, arrived, monotonic, last: events[events.length - 1] };
29 }
30
31 describe('Reward spawn schedule (t1174: 5 + t blocks/s)', () =>
32 {
33 it('block i leaves when 5t + t²/2 = i', () =>
34 {
35 assert.equal(Reward.RATE0, 5);
36 assert.equal(Reward.ACCEL, 1);
37 assert.equal(Reward.spawnTime(0), 0);
38 for (const i of [1, 5, 10, 50, 100, 252, 1000])
39 {
40 const t = Reward.spawnTime(i);
41 assert.ok(Math.abs(5 * t + t * t / 2 - i) < 1e-9, 'i=' + i + ' t=' + t);
42 }
43 // spawn times strictly increase, gaps shrink (accelerating)
44 let prevGap = Infinity;
45 for (let i = 1; i < 300; i++)
46 {
47 const gap = Reward.spawnTime(i) - Reward.spawnTime(i - 1);
48 assert.ok(gap > 0);
49 assert.ok(gap <= prevGap + 1e-12, 'gap grew at ' + i);
50 prevGap = gap;
51 }
52 });
53
54 it('starts at 5/s and the 253rd block leaves at 18 s (Tim\'s example)', () =>
55 {
56 // 1/5 s between the first two blocks.
57 assert.ok(Math.abs(Reward.spawnTime(1) - (-5 + Math.sqrt(27))) < 1e-12);
58 assert.ok(Reward.spawnTime(1) > 0.19 && Reward.spawnTime(1) < 0.2);
59 assert.ok(Math.abs(Reward.spawnTime(252) - 18) < 1e-9);
60 assert.equal(Reward.spawnedBy(18, 253), 253);
61 assert.equal(Reward.spawnedBy(17.99, 253), 252);
62 assert.ok(Math.abs(Reward.countDuration(253) - (18 + Reward.FLIGHT)) < 1e-9);
63 });
64
65 it('spawnedBy matches floor(5t + t²/2) + 1, capped by n', () =>
66 {
67 for (let t = 0; t <= 20; t += 0.37)
68 {
69 const expect = Math.min(253, Math.floor(5 * t + t * t / 2 + 1e-9) + 1);
70 assert.equal(Reward.spawnedBy(t, 253), expect, 't=' + t);
71 }
72 assert.equal(Reward.spawnedBy(-1, 10), 0);
73 assert.equal(Reward.spawnedBy(5, 0), 0);
74 assert.equal(Reward.spawnedBy(100, 7), 7);
75 assert.equal(Reward.arrivedBy(Reward.FLIGHT - 0.01, 10), 0);
76 assert.equal(Reward.arrivedBy(Reward.FLIGHT, 10), 1);
77 });
78 });
79
80 describe('Reward sequence (t1173)', () =>
81 {
82 it('500 + 253 → counts every point from 500 up to 753 in ~18.7 s', () =>
83 {
84 const seq = Reward.createSequence({ won: true });
85 seq.setResult({ before: 500, after: 753 });
86 const r = runToEnd(seq, 1 / 60, 60);
87 assert.equal(r.last.phase, 'done');
88 assert.equal(r.spawned, 253);
89 assert.equal(r.arrived, 253);
90 assert.ok(r.monotonic, 'counter never goes down');
91 assert.equal(seq.counter, 753);
92 const counting = r.events.filter((e) => e.phase === 'count');
93 assert.ok(counting.length > 0);
94 assert.ok(counting[0].counter >= 500 && counting[0].counter < 510);
95 // intro + rise + count + hold
96 const expected = Reward.INTRO + Reward.RISE + Reward.countDuration(253) + Reward.HOLD;
97 assert.ok(Math.abs(r.t - expected) < 0.1, 't=' + r.t + ' expected ' + expected);
98 });
99
100 it('phases run intro → rise → wait → count → hold → done', () =>
101 {
102 const seq = Reward.createSequence({});
103 const phases = [];
104 const push = (p) => { if (phases[phases.length - 1] !== p) { phases.push(p); } };
105 push(seq.phase);
106 for (let i = 0; i < 60; i++) { push(seq.tick(0.05).phase); } // 3 s, no result yet
107 assert.deepEqual(phases, ['intro', 'rise', 'wait']);
108 assert.equal(seq.counter, 0);
109 seq.setResult({ before: 10, after: 13 });
110 for (let i = 0; i < 200; i++) { push(seq.tick(0.05).phase); }
111 assert.deepEqual(phases, ['intro', 'rise', 'wait', 'count', 'hold', 'done']);
112 assert.equal(seq.counter, 13);
113 });
114
115 it('title stays centred for one second before rising', () =>
116 {
117 const seq = Reward.createSequence({});
118 assert.equal(seq.tick(0.99).phase, 'intro');
119 assert.equal(seq.tick(0.02).phase, 'rise');
120 });
121
122 it('nothing is counted before the server result arrives', () =>
123 {
124 const seq = Reward.createSequence({ waitMax: 100 });
125 let spawned = 0;
126 for (let i = 0; i < 100; i++) { spawned += seq.tick(0.05).spawn.length; }
127 assert.equal(spawned, 0);
128 assert.equal(seq.phase, 'wait');
129 });
130
131 it('earned 0 shows the number briefly, no blocks', () =>
132 {
133 const seq = Reward.createSequence({});
134 seq.setResult({ before: 42, after: 42 });
135 const r = runToEnd(seq, 0.05, 30);
136 assert.equal(r.spawned, 0);
137 assert.equal(seq.counter, 42);
138 assert.ok(r.events.some((e) => e.phase === 'hold' && e.counter === 42));
139 assert.equal(r.last.phase, 'done');
140 const expected = Reward.INTRO + Reward.RISE + Reward.HOLD_ZERO;
141 assert.ok(Math.abs(r.t - expected) < 0.11);
142 });
143
144 it('server failure: no count, still continues', () =>
145 {
146 const seq = Reward.createSequence({});
147 seq.setResult(null);
148 const r = runToEnd(seq, 0.05, 30);
149 assert.equal(r.spawned, 0);
150 assert.equal(seq.failed, true);
151 assert.equal(r.last.phase, 'done');
152 });
153
154 it('no answer at all times out and continues', () =>
155 {
156 const seq = Reward.createSequence({ waitMax: 2 });
157 const r = runToEnd(seq, 0.05, 30);
158 assert.equal(r.last.phase, 'done');
159 assert.equal(seq.failed, true);
160 });
161
162 it('before > after or a missing before is clamped (never counts down)', () =>
163 {
164 const a = Reward.createSequence({});
165 a.setResult({ before: 900, after: 800 });
166 assert.equal(a.earned, 0);
167 assert.equal(a.counter, 800);
168 const b = Reward.createSequence({});
169 b.setResult({ after: 77 });
170 assert.equal(b.earned, 0);
171 assert.equal(b.before, 77);
172 });
173
174 it('a huge frame (tab in background) still lands exactly on the total', () =>
175 {
176 const seq = Reward.createSequence({});
177 seq.setResult({ before: 0, after: 40 });
178 let spawned = 0;
179 let out;
180 for (let i = 0; i < 10; i++)
181 {
182 out = seq.tick(5);
183 spawned += out.spawn.length;
184 }
185 assert.equal(spawned, 40);
186 assert.equal(seq.counter, 40);
187 assert.equal(out.done, true);
188 });
189
190 it('only the hold phase can be finished early (tap to continue), not the count', () =>
191 {
192 const seq = Reward.createSequence({});
193 seq.setResult({ before: 0, after: 100 });
194 seq.tick(2);
195 assert.equal(seq.phase, 'count');
196 assert.equal(seq.finish(), false);
197 assert.equal(seq.phase, 'count');
198 while (seq.phase === 'count') { seq.tick(0.1); }
199 assert.equal(seq.phase, 'hold');
200 assert.equal(seq.counter, 100);
201 assert.equal(seq.finish(), true);
202 assert.equal(seq.tick(0.01).done, true);
203 });
204 });
@@ -0,0 +1,204 @@
1'use strict';
2
3const { describe, it } = require('node:test');
4const assert = require('node:assert/strict');
5const Reward = require('../src/reward.js');
6
7function runToEnd (seq, dt, maxT)
8{
9 const events = [];
10 let t = 0;
11 let spawned = 0;
12 let arrived = 0;
13 let lastCounter = null;
14 let monotonic = true;
15 while (t < maxT)
16 {
17 const out = seq.tick(dt);
18 t += dt;
19 spawned += out.spawn.length;
20 arrived += out.arrived;
21 if (lastCounter != null && out.counter < lastCounter)
22 { monotonic = false; }
23 lastCounter = out.counter;
24 events.push({ t, phase: out.phase, counter: out.counter });
25 if (out.done)
26 { break; }
27 }
28 return { events, t, spawned, arrived, monotonic, last: events[events.length - 1] };
29}
30
31describe('Reward spawn schedule (t1174: 5 + t blocks/s)', () =>
32{
33 it('block i leaves when 5t + t²/2 = i', () =>
34 {
35 assert.equal(Reward.RATE0, 5);
36 assert.equal(Reward.ACCEL, 1);
37 assert.equal(Reward.spawnTime(0), 0);
38 for (const i of [1, 5, 10, 50, 100, 252, 1000])
39 {
40 const t = Reward.spawnTime(i);
41 assert.ok(Math.abs(5 * t + t * t / 2 - i) < 1e-9, 'i=' + i + ' t=' + t);
42 }
43 // spawn times strictly increase, gaps shrink (accelerating)
44 let prevGap = Infinity;
45 for (let i = 1; i < 300; i++)
46 {
47 const gap = Reward.spawnTime(i) - Reward.spawnTime(i - 1);
48 assert.ok(gap > 0);
49 assert.ok(gap <= prevGap + 1e-12, 'gap grew at ' + i);
50 prevGap = gap;
51 }
52 });
53
54 it('starts at 5/s and the 253rd block leaves at 18 s (Tim\'s example)', () =>
55 {
56 // 1/5 s between the first two blocks.
57 assert.ok(Math.abs(Reward.spawnTime(1) - (-5 + Math.sqrt(27))) < 1e-12);
58 assert.ok(Reward.spawnTime(1) > 0.19 && Reward.spawnTime(1) < 0.2);
59 assert.ok(Math.abs(Reward.spawnTime(252) - 18) < 1e-9);
60 assert.equal(Reward.spawnedBy(18, 253), 253);
61 assert.equal(Reward.spawnedBy(17.99, 253), 252);
62 assert.ok(Math.abs(Reward.countDuration(253) - (18 + Reward.FLIGHT)) < 1e-9);
63 });
64
65 it('spawnedBy matches floor(5t + t²/2) + 1, capped by n', () =>
66 {
67 for (let t = 0; t <= 20; t += 0.37)
68 {
69 const expect = Math.min(253, Math.floor(5 * t + t * t / 2 + 1e-9) + 1);
70 assert.equal(Reward.spawnedBy(t, 253), expect, 't=' + t);
71 }
72 assert.equal(Reward.spawnedBy(-1, 10), 0);
73 assert.equal(Reward.spawnedBy(5, 0), 0);
74 assert.equal(Reward.spawnedBy(100, 7), 7);
75 assert.equal(Reward.arrivedBy(Reward.FLIGHT - 0.01, 10), 0);
76 assert.equal(Reward.arrivedBy(Reward.FLIGHT, 10), 1);
77 });
78});
79
80describe('Reward sequence (t1173)', () =>
81{
82 it('500 + 253 → counts every point from 500 up to 753 in ~18.7 s', () =>
83 {
84 const seq = Reward.createSequence({ won: true });
85 seq.setResult({ before: 500, after: 753 });
86 const r = runToEnd(seq, 1 / 60, 60);
87 assert.equal(r.last.phase, 'done');
88 assert.equal(r.spawned, 253);
89 assert.equal(r.arrived, 253);
90 assert.ok(r.monotonic, 'counter never goes down');
91 assert.equal(seq.counter, 753);
92 const counting = r.events.filter((e) => e.phase === 'count');
93 assert.ok(counting.length > 0);
94 assert.ok(counting[0].counter >= 500 && counting[0].counter < 510);
95 // intro + rise + count + hold
96 const expected = Reward.INTRO + Reward.RISE + Reward.countDuration(253) + Reward.HOLD;
97 assert.ok(Math.abs(r.t - expected) < 0.1, 't=' + r.t + ' expected ' + expected);
98 });
99
100 it('phases run intro → rise → wait → count → hold → done', () =>
101 {
102 const seq = Reward.createSequence({});
103 const phases = [];
104 const push = (p) => { if (phases[phases.length - 1] !== p) { phases.push(p); } };
105 push(seq.phase);
106 for (let i = 0; i < 60; i++) { push(seq.tick(0.05).phase); } // 3 s, no result yet
107 assert.deepEqual(phases, ['intro', 'rise', 'wait']);
108 assert.equal(seq.counter, 0);
109 seq.setResult({ before: 10, after: 13 });
110 for (let i = 0; i < 200; i++) { push(seq.tick(0.05).phase); }
111 assert.deepEqual(phases, ['intro', 'rise', 'wait', 'count', 'hold', 'done']);
112 assert.equal(seq.counter, 13);
113 });
114
115 it('title stays centred for one second before rising', () =>
116 {
117 const seq = Reward.createSequence({});
118 assert.equal(seq.tick(0.99).phase, 'intro');
119 assert.equal(seq.tick(0.02).phase, 'rise');
120 });
121
122 it('nothing is counted before the server result arrives', () =>
123 {
124 const seq = Reward.createSequence({ waitMax: 100 });
125 let spawned = 0;
126 for (let i = 0; i < 100; i++) { spawned += seq.tick(0.05).spawn.length; }
127 assert.equal(spawned, 0);
128 assert.equal(seq.phase, 'wait');
129 });
130
131 it('earned 0 shows the number briefly, no blocks', () =>
132 {
133 const seq = Reward.createSequence({});
134 seq.setResult({ before: 42, after: 42 });
135 const r = runToEnd(seq, 0.05, 30);
136 assert.equal(r.spawned, 0);
137 assert.equal(seq.counter, 42);
138 assert.ok(r.events.some((e) => e.phase === 'hold' && e.counter === 42));
139 assert.equal(r.last.phase, 'done');
140 const expected = Reward.INTRO + Reward.RISE + Reward.HOLD_ZERO;
141 assert.ok(Math.abs(r.t - expected) < 0.11);
142 });
143
144 it('server failure: no count, still continues', () =>
145 {
146 const seq = Reward.createSequence({});
147 seq.setResult(null);
148 const r = runToEnd(seq, 0.05, 30);
149 assert.equal(r.spawned, 0);
150 assert.equal(seq.failed, true);
151 assert.equal(r.last.phase, 'done');
152 });
153
154 it('no answer at all times out and continues', () =>
155 {
156 const seq = Reward.createSequence({ waitMax: 2 });
157 const r = runToEnd(seq, 0.05, 30);
158 assert.equal(r.last.phase, 'done');
159 assert.equal(seq.failed, true);
160 });
161
162 it('before > after or a missing before is clamped (never counts down)', () =>
163 {
164 const a = Reward.createSequence({});
165 a.setResult({ before: 900, after: 800 });
166 assert.equal(a.earned, 0);
167 assert.equal(a.counter, 800);
168 const b = Reward.createSequence({});
169 b.setResult({ after: 77 });
170 assert.equal(b.earned, 0);
171 assert.equal(b.before, 77);
172 });
173
174 it('a huge frame (tab in background) still lands exactly on the total', () =>
175 {
176 const seq = Reward.createSequence({});
177 seq.setResult({ before: 0, after: 40 });
178 let spawned = 0;
179 let out;
180 for (let i = 0; i < 10; i++)
181 {
182 out = seq.tick(5);
183 spawned += out.spawn.length;
184 }
185 assert.equal(spawned, 40);
186 assert.equal(seq.counter, 40);
187 assert.equal(out.done, true);
188 });
189
190 it('only the hold phase can be finished early (tap to continue), not the count', () =>
191 {
192 const seq = Reward.createSequence({});
193 seq.setResult({ before: 0, after: 100 });
194 seq.tick(2);
195 assert.equal(seq.phase, 'count');
196 assert.equal(seq.finish(), false);
197 assert.equal(seq.phase, 'count');
198 while (seq.phase === 'count') { seq.tick(0.1); }
199 assert.equal(seq.phase, 'hold');
200 assert.equal(seq.counter, 100);
201 assert.equal(seq.finish(), true);
202 assert.equal(seq.tick(0.01).done, true);
203 });
204});
test/t1173-playwright.py added +332 −0
@@ -0,0 +1,332 @@
1 #!/usr/bin/env python3
2 """t1173/t1174: reward screen after solo, Offline Strijd rounds and online matches.
3
4 Local PHP server with ?test= logins. Screenshots in /workspace/meteors-shots/t1173-local-*.
5 """
6 from __future__ import annotations
7
8 import os
9 import socket
10 import subprocess
11 import sys
12 import tempfile
13 import time
14 from pathlib import Path
15
16 from playwright.sync_api import sync_playwright
17
18 ROOT = Path("/workspace/meteors")
19 SHOTS = Path("/workspace/meteors-shots")
20 SHOTS.mkdir(parents=True, exist_ok=True)
21 PHP = os.environ.get("PHP", "/home/box/.local/bin/php")
22 CHROME = "/usr/bin/google-chrome"
23 CHROME_ARGS = ["--use-gl=angle", "--use-angle=swiftshader", "--no-sandbox", "--disable-dev-shm-usage"]
24 FAILURES = []
25 URL = None
26
27 STATE_JS = """() => {
28 const el = document.getElementById('reward');
29 const t = document.getElementById('reward-title');
30 const r = t ? t.getBoundingClientRect() : null;
31 const c = document.getElementById('reward-total');
32 const cr = c ? c.getBoundingClientRect() : null;
33 return {
34 visible: !!el && !el.hidden,
35 title: t && t.textContent,
36 titleTop: r && r.top, titleH: r && r.height,
37 counter: c && c.textContent,
38 counterVisible: !!c && !c.parentNode.hidden,
39 counterY: cr && (cr.top + cr.height / 2),
40 vh: window.innerHeight,
41 dbg: (typeof Reward !== 'undefined' && Reward.debugState) ? Reward.debugState() : null,
42 mode: window.app && app.mode,
43 menuPoints: (document.getElementById('menu-points') || {}).textContent,
44 lifetime: (typeof Online !== 'undefined') ? Online.lifetimePoints : null,
45 };
46 }"""
47
48
49 def check(cond, msg):
50 print(("OK " if cond else "FAIL") + " " + msg)
51 if not cond:
52 FAILURES.append(msg)
53 return cond
54
55
56 def shot(page, name):
57 path = SHOTS / name
58 page.screenshot(path=str(path), full_page=False)
59 print(f"wrote {path}")
60
61
62 def free_port():
63 s = socket.socket()
64 s.bind(("127.0.0.1", 0))
65 port = s.getsockname()[1]
66 s.close()
67 return port
68
69
70 def start_php(port, data, log_path):
71 env = os.environ.copy()
72 env["METEORS_DATA_DIR"] = str(data)
73 log = open(log_path, "w")
74 proc = subprocess.Popen(
75 [PHP, "-S", f"127.0.0.1:{port}", "-t", str(ROOT / "build"), str(ROOT / "build" / "router.php")],
76 cwd=str(ROOT / "build"), env=env, stdout=log, stderr=log,
77 )
78 time.sleep(0.5)
79 if proc.poll() is not None:
80 raise RuntimeError("php failed: " + Path(log_path).read_text(errors="replace"))
81 return proc
82
83
84 def login(page, n, next_path="index.html"):
85 page.goto(f"{URL}auth.php?test={n}&next=index.html", wait_until="domcontentloaded", timeout=15000)
86 page.wait_for_timeout(300)
87 page.goto(f"{URL}{next_path}", wait_until="domcontentloaded", timeout=15000)
88 page.wait_for_function("() => typeof Online !== 'undefined' && Online.me", timeout=15000)
89 page.wait_for_timeout(400)
90
91
92 def state(page):
93 return page.evaluate(STATE_JS)
94
95
96 def pick_and_play(page, button="#btn-play"):
97 page.locator(button).click()
98 page.wait_for_selector("#planet-select:not([hidden])", timeout=8000)
99 page.wait_for_timeout(200)
100 page.locator("#btn-planet-go").click()
101 page.wait_for_function("() => window.app && app.mode === 'playing' && app.core", timeout=10000)
102 page.wait_for_timeout(300)
103
104
105 def force_gameover(page, score):
106 page.evaluate(
107 """(s) => { app.core.score = s; app.core.state = 'gameover'; app.core.gameOverTime = 0; }""", score
108 )
109
110
111 def watch_reward(page, prefix, expect_title, expect_earned):
112 """Follow one reward run; returns the final debug state."""
113 page.wait_for_function("() => !document.getElementById('reward').hidden", timeout=5000)
114 page.wait_for_timeout(350)
115 st = state(page)
116 print("intro", {k: st[k] for k in ("title", "titleTop", "vh", "counterVisible")})
117 check(st["title"] == expect_title, f"{prefix}: title {st['title']!r} == {expect_title!r}")
118 mid = st["titleTop"] + st["titleH"] / 2
119 check(abs(mid - st["vh"] / 2) < st["vh"] * 0.12, f"{prefix}: title centred first (mid {mid:.0f} / vh {st['vh']})")
120 check(st["dbg"] and st["dbg"]["phase"] == "intro", f"{prefix}: phase intro at 0.35 s ({st['dbg'] and st['dbg']['phase']})")
121 shot(page, f"t1173-local-{prefix}-1-centered.png")
122 # After 1 s + 0.6 s tween: title at the top.
123 page.wait_for_timeout(1500)
124 st = state(page)
125 check(st["titleTop"] < st["vh"] * 0.15, f"{prefix}: title rose to the top ({st['titleTop']:.0f})")
126 if expect_earned > 0:
127 page.wait_for_function(
128 "() => Reward.debugState() && Reward.debugState().phase === 'count' && Reward.debugState().flying >= 2",
129 timeout=6000,
130 )
131 page.wait_for_timeout(250)
132 st = state(page)
133 d = st["dbg"]
134 print("counting", d, st["counter"])
135 check(d["earned"] == expect_earned, f"{prefix}: earned {d['earned']} == {expect_earned}")
136 check(st["counterVisible"], f"{prefix}: counter visible at the bottom")
137 check(st["counterY"] > st["vh"] * 0.7, f"{prefix}: counter near bottom ({st['counterY']:.0f}/{st['vh']})")
138 check(d["before"] <= int(st["counter"]) <= d["after"], f"{prefix}: counter {st['counter']} within [{d['before']}, {d['after']}]")
139 check(d["flying"] >= 1, f"{prefix}: blocks are flying ({d['flying']})")
140 shot(page, f"t1173-local-{prefix}-2-counting.png")
141 page.wait_for_function("() => Reward.debugState() && Reward.debugState().phase === 'hold'", timeout=30000)
142 st = state(page)
143 d = st["dbg"]
144 check(int(st["counter"]) == d["after"], f"{prefix}: final counter {st['counter']} == after {d['after']}")
145 check(d["after"] - d["before"] == expect_earned, f"{prefix}: after-before == {expect_earned}")
146 check(d["after"] == st["lifetime"], f"{prefix}: final == server lifetime ({st['lifetime']})")
147 shot(page, f"t1173-local-{prefix}-3-final.png")
148 page.wait_for_function("() => document.getElementById('reward').hidden", timeout=6000)
149 page.wait_for_timeout(300)
150 return d
151
152
153 def test_logged_out_solo(browser):
154 print("\n== logged-out solo stays as before ==")
155 ctx = browser.new_context(viewport={"width": 1280, "height": 800})
156 page = ctx.new_page()
157 page.goto(f"{URL}index.html", wait_until="networkidle")
158 pick_and_play(page)
159 page.wait_for_timeout(500)
160 force_gameover(page, 7)
161 page.wait_for_timeout(500)
162 st = state(page)
163 go = page.evaluate("() => !document.getElementById('game-over').hidden")
164 check(not st["visible"], "logged out: no reward screen")
165 check(go, "logged out: classic game-over overlay")
166 shot(page, "t1173-local-loggedout-gameover.png")
167 page.wait_for_function("() => !document.getElementById('menu').hidden", timeout=8000)
168 check(True, "logged out: back to menu")
169 ctx.close()
170
171
172 def test_solo(browser):
173 print("\n== logged-in solo ==")
174 ctx = browser.new_context(viewport={"width": 1280, "height": 800})
175 page = ctx.new_page()
176 errs = []
177 page.on("pageerror", lambda e: errs.append(str(e)))
178 login(page, 1)
179 before = int(page.locator("#menu-points").inner_text().strip() or 0)
180 pick_and_play(page)
181 page.wait_for_function("() => app.playToken", timeout=8000)
182 page.wait_for_timeout(3600) # server needs >= 3 s and 4 pts/s → 12 allowed
183 force_gameover(page, 12)
184 d = watch_reward(page, "solo", "You lost...", 12)
185 check(d["before"] == before, f"solo: counter started at the old profile total {before}")
186 page.wait_for_function("() => !document.getElementById('menu').hidden", timeout=6000)
187 page.wait_for_timeout(500)
188 pts = int(page.locator("#menu-points").inner_text().strip())
189 check(pts == before + 12, f"solo: menu shows new total {pts} == {before + 12}")
190 check(not errs, f"solo: no page errors {errs[:3]}")
191 shot(page, "t1173-local-solo-4-menu.png")
192
193 print("\n== logged-in solo, 0 points ==")
194 pick_and_play(page)
195 page.wait_for_timeout(600)
196 force_gameover(page, 0)
197 page.wait_for_function("() => !document.getElementById('reward').hidden", timeout=5000)
198 page.wait_for_function("() => Reward.debugState() && Reward.debugState().phase === 'hold'", timeout=6000)
199 st = state(page)
200 check(st["counterVisible"] and int(st["counter"]) == pts, f"zero: shows total {st['counter']} briefly")
201 check(st["dbg"]["spawned"] == 0, "zero: no blocks")
202 shot(page, "t1173-local-solo-zero.png")
203 page.wait_for_function("() => !document.getElementById('menu').hidden", timeout=6000)
204 ctx.close()
205
206
207 def test_offline(browser):
208 print("\n== logged-in Offline Strijd: win a round, then lose ==")
209 ctx = browser.new_context(viewport={"width": 1280, "height": 800})
210 page = ctx.new_page()
211 login(page, 1)
212 pick_and_play(page, "#btn-offline")
213 page.wait_for_function("() => app.playToken && app.battle", timeout=8000)
214 page.wait_for_timeout(3600)
215 page.evaluate("() => { app.core.score = 8; for (const b of app.battle.bots) b.core.state = 'gameover'; }")
216 watch_reward(page, "offline-won", "You won!", 8)
217 page.wait_for_function("() => app.battle && app.battle.round === 2 && app.mode === 'playing'", timeout=6000)
218 check(True, "offline: continued to round 2 after the reward")
219 shot(page, "t1173-local-offline-round2.png")
220 page.wait_for_function("() => app.playToken", timeout=8000)
221 page.wait_for_timeout(3600)
222 force_gameover(page, 5)
223 watch_reward(page, "offline-lost", "You lost...", 5)
224 page.wait_for_function("() => !document.getElementById('offline-result').hidden", timeout=6000)
225 check(True, "offline: lost → offline result screen (as before)")
226 shot(page, "t1173-local-offline-result.png")
227 ctx.close()
228
229
230 def test_online(browser):
231 print("\n== online two players ==")
232 c1 = browser.new_context(viewport={"width": 1280, "height": 800})
233 c2 = browser.new_context(viewport={"width": 390, "height": 844}, is_mobile=True, has_touch=True, device_scale_factor=2)
234 p1, p2 = c1.new_page(), c2.new_page()
235 login(p1, 1, "index.html?online=1")
236 login(p2, 2, "index.html?online=1")
237 for p in (p1, p2):
238 p.locator("#online-panel").wait_for(state="visible", timeout=8000)
239 if p.locator("#online-lobby").is_visible() and p.locator("#btn-leave-lobby").is_visible():
240 p.locator("#btn-leave-lobby").click()
241 p.wait_for_timeout(400)
242 p1.locator("#btn-create").click()
243 p1.wait_for_function("() => (document.getElementById('lobby-code')||{}).textContent.trim().length >= 4", timeout=8000)
244 code = p1.locator("#lobby-code").inner_text().strip()
245 p2.locator("#join-code").fill(code)
246 p2.locator("#btn-join").click()
247 p2.locator("#online-lobby").wait_for(state="visible", timeout=8000)
248 p1.locator("#btn-ready").click()
249 p2.locator("#btn-ready").click()
250 start = p1.locator("#btn-start")
251 for _ in range(20):
252 if start.is_visible() and start.is_enabled():
253 break
254 p1.wait_for_timeout(400)
255 start.click()
256 for p in (p1, p2):
257 p.wait_for_function("() => app && app.mode === 'playing' && app.online && app.core", timeout=10000)
258 b1 = p1.evaluate("() => app.onlineBefore")
259 b2 = p2.evaluate("() => app.onlineBefore")
260 p1.wait_for_timeout(1500)
261 p1.evaluate("() => { app.core.score = 9; }")
262 p2.evaluate("() => { app.core.score = 6; }")
263 p1.wait_for_timeout(1200) # let the scores reach the server
264 p2.evaluate("() => { app.core.state = 'gameover'; app.core.gameOverTime = 0; }")
265 p1.wait_for_function("() => !document.getElementById('reward').hidden", timeout=12000)
266 p2.wait_for_function("() => !document.getElementById('reward').hidden", timeout=12000)
267 p1.wait_for_timeout(300)
268 s1, s2 = state(p1), state(p2)
269 check(s1["title"] == "You won!", f"online winner sees You won! ({s1['title']!r})")
270 check(s2["title"] == "You lost...", f"online loser sees You lost... ({s2['title']!r})")
271 shot(p1, "t1173-local-online-winner-1-centered.png")
272 shot(p2, "t1173-local-online-mobile-loser-1-centered.png")
273 p1.wait_for_function("() => Reward.debugState() && Reward.debugState().phase === 'count'", timeout=8000)
274 p1.wait_for_timeout(400)
275 shot(p1, "t1173-local-online-winner-2-counting.png")
276 p2.wait_for_function("() => Reward.debugState() && ['count','hold'].includes(Reward.debugState().phase)", timeout=8000)
277 p2.wait_for_timeout(200)
278 shot(p2, "t1173-local-online-mobile-loser-2-counting.png")
279 for p, b, earned, tag in ((p1, b1, 9, "winner"), (p2, b2, 6, "loser")):
280 p.wait_for_function("() => Reward.debugState() && Reward.debugState().phase === 'hold'", timeout=20000)
281 d = state(p)["dbg"]
282 check(d["before"] == b and d["after"] - d["before"] == earned,
283 f"online {tag}: {d['before']} → {d['after']} (+{earned})")
284 shot(p2, "t1173-local-online-mobile-loser-3-final.png")
285 # Mobile: tap during the hold continues.
286 p2.tap("#reward")
287 p2.wait_for_function("() => document.getElementById('reward').hidden", timeout=3000)
288 check(True, "mobile tap in the hold continues")
289 for p, tag in ((p1, "winner"), (p2, "loser")):
290 p.wait_for_function("() => app.mode === 'online' && !document.getElementById('online-lobby').hidden", timeout=15000)
291 check(True, f"online {tag}: back in the lobby afterwards")
292 shot(p1, "t1173-local-online-winner-4-lobby.png")
293 c1.close()
294 c2.close()
295
296
297 def main():
298 global URL
299 port = free_port()
300 URL = f"http://127.0.0.1:{port}/"
301 data = Path(tempfile.mkdtemp(prefix="meteors-t1173-"))
302 proc = start_php(port, data, "/tmp/t1173-php.log")
303 try:
304 with sync_playwright() as p:
305 browser = p.chromium.launch(executable_path=CHROME, args=CHROME_ARGS, headless=True)
306 only = sys.argv[1:] or ["out", "solo", "offline", "online"]
307 if "out" in only:
308 test_logged_out_solo(browser)
309 if "solo" in only:
310 test_solo(browser)
311 if "offline" in only:
312 test_offline(browser)
313 if "online" in only:
314 test_online(browser)
315 browser.close()
316 finally:
317 proc.terminate()
318 try:
319 proc.wait(timeout=3)
320 except Exception:
321 proc.kill()
322 if FAILURES:
323 print("FAILURES:")
324 for f in FAILURES:
325 print(" -", f)
326 return 1
327 print("ALL OK")
328 return 0
329
330
331 if __name__ == "__main__":
332 sys.exit(main())
@@ -0,0 +1,332 @@
1#!/usr/bin/env python3
2"""t1173/t1174: reward screen after solo, Offline Strijd rounds and online matches.
3
4Local PHP server with ?test= logins. Screenshots in /workspace/meteors-shots/t1173-local-*.
5"""
6from __future__ import annotations
7
8import os
9import socket
10import subprocess
11import sys
12import tempfile
13import time
14from pathlib import Path
15
16from playwright.sync_api import sync_playwright
17
18ROOT = Path("/workspace/meteors")
19SHOTS = Path("/workspace/meteors-shots")
20SHOTS.mkdir(parents=True, exist_ok=True)
21PHP = os.environ.get("PHP", "/home/box/.local/bin/php")
22CHROME = "/usr/bin/google-chrome"
23CHROME_ARGS = ["--use-gl=angle", "--use-angle=swiftshader", "--no-sandbox", "--disable-dev-shm-usage"]
24FAILURES = []
25URL = None
26
27STATE_JS = """() => {
28 const el = document.getElementById('reward');
29 const t = document.getElementById('reward-title');
30 const r = t ? t.getBoundingClientRect() : null;
31 const c = document.getElementById('reward-total');
32 const cr = c ? c.getBoundingClientRect() : null;
33 return {
34 visible: !!el && !el.hidden,
35 title: t && t.textContent,
36 titleTop: r && r.top, titleH: r && r.height,
37 counter: c && c.textContent,
38 counterVisible: !!c && !c.parentNode.hidden,
39 counterY: cr && (cr.top + cr.height / 2),
40 vh: window.innerHeight,
41 dbg: (typeof Reward !== 'undefined' && Reward.debugState) ? Reward.debugState() : null,
42 mode: window.app && app.mode,
43 menuPoints: (document.getElementById('menu-points') || {}).textContent,
44 lifetime: (typeof Online !== 'undefined') ? Online.lifetimePoints : null,
45 };
46}"""
47
48
49def check(cond, msg):
50 print(("OK " if cond else "FAIL") + " " + msg)
51 if not cond:
52 FAILURES.append(msg)
53 return cond
54
55
56def shot(page, name):
57 path = SHOTS / name
58 page.screenshot(path=str(path), full_page=False)
59 print(f"wrote {path}")
60
61
62def free_port():
63 s = socket.socket()
64 s.bind(("127.0.0.1", 0))
65 port = s.getsockname()[1]
66 s.close()
67 return port
68
69
70def start_php(port, data, log_path):
71 env = os.environ.copy()
72 env["METEORS_DATA_DIR"] = str(data)
73 log = open(log_path, "w")
74 proc = subprocess.Popen(
75 [PHP, "-S", f"127.0.0.1:{port}", "-t", str(ROOT / "build"), str(ROOT / "build" / "router.php")],
76 cwd=str(ROOT / "build"), env=env, stdout=log, stderr=log,
77 )
78 time.sleep(0.5)
79 if proc.poll() is not None:
80 raise RuntimeError("php failed: " + Path(log_path).read_text(errors="replace"))
81 return proc
82
83
84def login(page, n, next_path="index.html"):
85 page.goto(f"{URL}auth.php?test={n}&next=index.html", wait_until="domcontentloaded", timeout=15000)
86 page.wait_for_timeout(300)
87 page.goto(f"{URL}{next_path}", wait_until="domcontentloaded", timeout=15000)
88 page.wait_for_function("() => typeof Online !== 'undefined' && Online.me", timeout=15000)
89 page.wait_for_timeout(400)
90
91
92def state(page):
93 return page.evaluate(STATE_JS)
94
95
96def pick_and_play(page, button="#btn-play"):
97 page.locator(button).click()
98 page.wait_for_selector("#planet-select:not([hidden])", timeout=8000)
99 page.wait_for_timeout(200)
100 page.locator("#btn-planet-go").click()
101 page.wait_for_function("() => window.app && app.mode === 'playing' && app.core", timeout=10000)
102 page.wait_for_timeout(300)
103
104
105def force_gameover(page, score):
106 page.evaluate(
107 """(s) => { app.core.score = s; app.core.state = 'gameover'; app.core.gameOverTime = 0; }""", score
108 )
109
110
111def watch_reward(page, prefix, expect_title, expect_earned):
112 """Follow one reward run; returns the final debug state."""
113 page.wait_for_function("() => !document.getElementById('reward').hidden", timeout=5000)
114 page.wait_for_timeout(350)
115 st = state(page)
116 print("intro", {k: st[k] for k in ("title", "titleTop", "vh", "counterVisible")})
117 check(st["title"] == expect_title, f"{prefix}: title {st['title']!r} == {expect_title!r}")
118 mid = st["titleTop"] + st["titleH"] / 2
119 check(abs(mid - st["vh"] / 2) < st["vh"] * 0.12, f"{prefix}: title centred first (mid {mid:.0f} / vh {st['vh']})")
120 check(st["dbg"] and st["dbg"]["phase"] == "intro", f"{prefix}: phase intro at 0.35 s ({st['dbg'] and st['dbg']['phase']})")
121 shot(page, f"t1173-local-{prefix}-1-centered.png")
122 # After 1 s + 0.6 s tween: title at the top.
123 page.wait_for_timeout(1500)
124 st = state(page)
125 check(st["titleTop"] < st["vh"] * 0.15, f"{prefix}: title rose to the top ({st['titleTop']:.0f})")
126 if expect_earned > 0:
127 page.wait_for_function(
128 "() => Reward.debugState() && Reward.debugState().phase === 'count' && Reward.debugState().flying >= 2",
129 timeout=6000,
130 )
131 page.wait_for_timeout(250)
132 st = state(page)
133 d = st["dbg"]
134 print("counting", d, st["counter"])
135 check(d["earned"] == expect_earned, f"{prefix}: earned {d['earned']} == {expect_earned}")
136 check(st["counterVisible"], f"{prefix}: counter visible at the bottom")
137 check(st["counterY"] > st["vh"] * 0.7, f"{prefix}: counter near bottom ({st['counterY']:.0f}/{st['vh']})")
138 check(d["before"] <= int(st["counter"]) <= d["after"], f"{prefix}: counter {st['counter']} within [{d['before']}, {d['after']}]")
139 check(d["flying"] >= 1, f"{prefix}: blocks are flying ({d['flying']})")
140 shot(page, f"t1173-local-{prefix}-2-counting.png")
141 page.wait_for_function("() => Reward.debugState() && Reward.debugState().phase === 'hold'", timeout=30000)
142 st = state(page)
143 d = st["dbg"]
144 check(int(st["counter"]) == d["after"], f"{prefix}: final counter {st['counter']} == after {d['after']}")
145 check(d["after"] - d["before"] == expect_earned, f"{prefix}: after-before == {expect_earned}")
146 check(d["after"] == st["lifetime"], f"{prefix}: final == server lifetime ({st['lifetime']})")
147 shot(page, f"t1173-local-{prefix}-3-final.png")
148 page.wait_for_function("() => document.getElementById('reward').hidden", timeout=6000)
149 page.wait_for_timeout(300)
150 return d
151
152
153def test_logged_out_solo(browser):
154 print("\n== logged-out solo stays as before ==")
155 ctx = browser.new_context(viewport={"width": 1280, "height": 800})
156 page = ctx.new_page()
157 page.goto(f"{URL}index.html", wait_until="networkidle")
158 pick_and_play(page)
159 page.wait_for_timeout(500)
160 force_gameover(page, 7)
161 page.wait_for_timeout(500)
162 st = state(page)
163 go = page.evaluate("() => !document.getElementById('game-over').hidden")
164 check(not st["visible"], "logged out: no reward screen")
165 check(go, "logged out: classic game-over overlay")
166 shot(page, "t1173-local-loggedout-gameover.png")
167 page.wait_for_function("() => !document.getElementById('menu').hidden", timeout=8000)
168 check(True, "logged out: back to menu")
169 ctx.close()
170
171
172def test_solo(browser):
173 print("\n== logged-in solo ==")
174 ctx = browser.new_context(viewport={"width": 1280, "height": 800})
175 page = ctx.new_page()
176 errs = []
177 page.on("pageerror", lambda e: errs.append(str(e)))
178 login(page, 1)
179 before = int(page.locator("#menu-points").inner_text().strip() or 0)
180 pick_and_play(page)
181 page.wait_for_function("() => app.playToken", timeout=8000)
182 page.wait_for_timeout(3600) # server needs >= 3 s and 4 pts/s → 12 allowed
183 force_gameover(page, 12)
184 d = watch_reward(page, "solo", "You lost...", 12)
185 check(d["before"] == before, f"solo: counter started at the old profile total {before}")
186 page.wait_for_function("() => !document.getElementById('menu').hidden", timeout=6000)
187 page.wait_for_timeout(500)
188 pts = int(page.locator("#menu-points").inner_text().strip())
189 check(pts == before + 12, f"solo: menu shows new total {pts} == {before + 12}")
190 check(not errs, f"solo: no page errors {errs[:3]}")
191 shot(page, "t1173-local-solo-4-menu.png")
192
193 print("\n== logged-in solo, 0 points ==")
194 pick_and_play(page)
195 page.wait_for_timeout(600)
196 force_gameover(page, 0)
197 page.wait_for_function("() => !document.getElementById('reward').hidden", timeout=5000)
198 page.wait_for_function("() => Reward.debugState() && Reward.debugState().phase === 'hold'", timeout=6000)
199 st = state(page)
200 check(st["counterVisible"] and int(st["counter"]) == pts, f"zero: shows total {st['counter']} briefly")
201 check(st["dbg"]["spawned"] == 0, "zero: no blocks")
202 shot(page, "t1173-local-solo-zero.png")
203 page.wait_for_function("() => !document.getElementById('menu').hidden", timeout=6000)
204 ctx.close()
205
206
207def test_offline(browser):
208 print("\n== logged-in Offline Strijd: win a round, then lose ==")
209 ctx = browser.new_context(viewport={"width": 1280, "height": 800})
210 page = ctx.new_page()
211 login(page, 1)
212 pick_and_play(page, "#btn-offline")
213 page.wait_for_function("() => app.playToken && app.battle", timeout=8000)
214 page.wait_for_timeout(3600)
215 page.evaluate("() => { app.core.score = 8; for (const b of app.battle.bots) b.core.state = 'gameover'; }")
216 watch_reward(page, "offline-won", "You won!", 8)
217 page.wait_for_function("() => app.battle && app.battle.round === 2 && app.mode === 'playing'", timeout=6000)
218 check(True, "offline: continued to round 2 after the reward")
219 shot(page, "t1173-local-offline-round2.png")
220 page.wait_for_function("() => app.playToken", timeout=8000)
221 page.wait_for_timeout(3600)
222 force_gameover(page, 5)
223 watch_reward(page, "offline-lost", "You lost...", 5)
224 page.wait_for_function("() => !document.getElementById('offline-result').hidden", timeout=6000)
225 check(True, "offline: lost → offline result screen (as before)")
226 shot(page, "t1173-local-offline-result.png")
227 ctx.close()
228
229
230def test_online(browser):
231 print("\n== online two players ==")
232 c1 = browser.new_context(viewport={"width": 1280, "height": 800})
233 c2 = browser.new_context(viewport={"width": 390, "height": 844}, is_mobile=True, has_touch=True, device_scale_factor=2)
234 p1, p2 = c1.new_page(), c2.new_page()
235 login(p1, 1, "index.html?online=1")
236 login(p2, 2, "index.html?online=1")
237 for p in (p1, p2):
238 p.locator("#online-panel").wait_for(state="visible", timeout=8000)
239 if p.locator("#online-lobby").is_visible() and p.locator("#btn-leave-lobby").is_visible():
240 p.locator("#btn-leave-lobby").click()
241 p.wait_for_timeout(400)
242 p1.locator("#btn-create").click()
243 p1.wait_for_function("() => (document.getElementById('lobby-code')||{}).textContent.trim().length >= 4", timeout=8000)
244 code = p1.locator("#lobby-code").inner_text().strip()
245 p2.locator("#join-code").fill(code)
246 p2.locator("#btn-join").click()
247 p2.locator("#online-lobby").wait_for(state="visible", timeout=8000)
248 p1.locator("#btn-ready").click()
249 p2.locator("#btn-ready").click()
250 start = p1.locator("#btn-start")
251 for _ in range(20):
252 if start.is_visible() and start.is_enabled():
253 break
254 p1.wait_for_timeout(400)
255 start.click()
256 for p in (p1, p2):
257 p.wait_for_function("() => app && app.mode === 'playing' && app.online && app.core", timeout=10000)
258 b1 = p1.evaluate("() => app.onlineBefore")
259 b2 = p2.evaluate("() => app.onlineBefore")
260 p1.wait_for_timeout(1500)
261 p1.evaluate("() => { app.core.score = 9; }")
262 p2.evaluate("() => { app.core.score = 6; }")
263 p1.wait_for_timeout(1200) # let the scores reach the server
264 p2.evaluate("() => { app.core.state = 'gameover'; app.core.gameOverTime = 0; }")
265 p1.wait_for_function("() => !document.getElementById('reward').hidden", timeout=12000)
266 p2.wait_for_function("() => !document.getElementById('reward').hidden", timeout=12000)
267 p1.wait_for_timeout(300)
268 s1, s2 = state(p1), state(p2)
269 check(s1["title"] == "You won!", f"online winner sees You won! ({s1['title']!r})")
270 check(s2["title"] == "You lost...", f"online loser sees You lost... ({s2['title']!r})")
271 shot(p1, "t1173-local-online-winner-1-centered.png")
272 shot(p2, "t1173-local-online-mobile-loser-1-centered.png")
273 p1.wait_for_function("() => Reward.debugState() && Reward.debugState().phase === 'count'", timeout=8000)
274 p1.wait_for_timeout(400)
275 shot(p1, "t1173-local-online-winner-2-counting.png")
276 p2.wait_for_function("() => Reward.debugState() && ['count','hold'].includes(Reward.debugState().phase)", timeout=8000)
277 p2.wait_for_timeout(200)
278 shot(p2, "t1173-local-online-mobile-loser-2-counting.png")
279 for p, b, earned, tag in ((p1, b1, 9, "winner"), (p2, b2, 6, "loser")):
280 p.wait_for_function("() => Reward.debugState() && Reward.debugState().phase === 'hold'", timeout=20000)
281 d = state(p)["dbg"]
282 check(d["before"] == b and d["after"] - d["before"] == earned,
283 f"online {tag}: {d['before']} → {d['after']} (+{earned})")
284 shot(p2, "t1173-local-online-mobile-loser-3-final.png")
285 # Mobile: tap during the hold continues.
286 p2.tap("#reward")
287 p2.wait_for_function("() => document.getElementById('reward').hidden", timeout=3000)
288 check(True, "mobile tap in the hold continues")
289 for p, tag in ((p1, "winner"), (p2, "loser")):
290 p.wait_for_function("() => app.mode === 'online' && !document.getElementById('online-lobby').hidden", timeout=15000)
291 check(True, f"online {tag}: back in the lobby afterwards")
292 shot(p1, "t1173-local-online-winner-4-lobby.png")
293 c1.close()
294 c2.close()
295
296
297def main():
298 global URL
299 port = free_port()
300 URL = f"http://127.0.0.1:{port}/"
301 data = Path(tempfile.mkdtemp(prefix="meteors-t1173-"))
302 proc = start_php(port, data, "/tmp/t1173-php.log")
303 try:
304 with sync_playwright() as p:
305 browser = p.chromium.launch(executable_path=CHROME, args=CHROME_ARGS, headless=True)
306 only = sys.argv[1:] or ["out", "solo", "offline", "online"]
307 if "out" in only:
308 test_logged_out_solo(browser)
309 if "solo" in only:
310 test_solo(browser)
311 if "offline" in only:
312 test_offline(browser)
313 if "online" in only:
314 test_online(browser)
315 browser.close()
316 finally:
317 proc.terminate()
318 try:
319 proc.wait(timeout=3)
320 except Exception:
321 proc.kill()
322 if FAILURES:
323 print("FAILURES:")
324 for f in FAILURES:
325 print(" -", f)
326 return 1
327 print("ALL OK")
328 return 0
329
330
331if __name__ == "__main__":
332 sys.exit(main())