Merge feature/t1278-mp-reward-tally: award online rematches so the point tally runs (t1278)
@@ -92,7 +92,7 @@ De spelkern is deterministisch en staat los van tekenen en invoer, zodat stage 2
92
92
| `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` |
93
93
| `src/main.js` | Menu, HUD, frameworkv3-scene, muis/touch, schaal naar het scherm, landing-bounce, selectie-tween, online-lobby |
94
94
| `src/offline.js` | Offline Strijd: progressie, bot-AI, lokale 'multiplayer'-schoten |
95
| `src/reward.js` | Puntenscherm na een spel/ronde (t1173): timing (15 + 10·t blokjes/s, t1178) en de overlay |
95
| `src/reward.js` | Puntenscherm na een spel/ronde (t1173): blokjes in 4 s (t1194) naar het profieltotaal; online rematch telt opnieuw (t1278) |
96
96
| `src/online.js` | API-client, polling, opponent-miniaturen, vlucht-tweens van afgeschoten blokjes |
97
97
| `server/` | PHP API: OAuth, lobby, shots, SQLite in `data/` (niet gedeployed) |
98
98
| `server/lib/planets.json` | Catalogus van 12 planeten (JS en PHP delen dit bestand) |
@@ -92,7 +92,7 @@ De spelkern is deterministisch en staat los van tekenen en invoer, zodat stage 292
| `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` |92
| `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` |93
| `src/main.js` | Menu, HUD, frameworkv3-scene, muis/touch, schaal naar het scherm, landing-bounce, selectie-tween, online-lobby |93
| `src/main.js` | Menu, HUD, frameworkv3-scene, muis/touch, schaal naar het scherm, landing-bounce, selectie-tween, online-lobby |94
| `src/offline.js` | Offline Strijd: progressie, bot-AI, lokale 'multiplayer'-schoten |94
| `src/offline.js` | Offline Strijd: progressie, bot-AI, lokale 'multiplayer'-schoten |95
| `src/reward.js` | Puntenscherm na een spel/ronde (t1173): timing (15 + 10·t blokjes/s, t1178) en de overlay |95
| `src/reward.js` | Puntenscherm na een spel/ronde (t1173): blokjes in 4 s (t1194) naar het profieltotaal; online rematch telt opnieuw (t1278) |96
| `src/online.js` | API-client, polling, opponent-miniaturen, vlucht-tweens van afgeschoten blokjes |96
| `src/online.js` | API-client, polling, opponent-miniaturen, vlucht-tweens van afgeschoten blokjes |97
| `server/` | PHP API: OAuth, lobby, shots, SQLite in `data/` (niet gedeployed) |97
| `server/` | PHP API: OAuth, lobby, shots, SQLite in `data/` (niet gedeployed) |98
| `server/lib/planets.json` | Catalogus van 12 planeten (JS en PHP delen dit bestand) |98
| `server/lib/planets.json` | Catalogus van 12 planeten (JS en PHP delen dit bestand) |@@ -9646,6 +9646,7 @@ var Online = {
9646
9646
csrf: '',
9647
9647
me: null,
9648
9648
lifetimePoints: 0,
9649
onlineAwarded: null,
9649
9650
locale: null,
9650
9651
localeExplicit: false,
9651
9652
authLocale: null,
@@ -9708,6 +9709,8 @@ Online._apply = function (data)
9708
9709
{ this.error = ''; }
9709
9710
if (data.lifetime_points != null)
9710
9711
{ this.lifetimePoints = data.lifetime_points; }
9712
if (data.online_awarded !== undefined)
9713
{ this.onlineAwarded = data.online_awarded; }
9711
9714
if (data.locale !== undefined)
9712
9715
{ this.locale = data.locale; }
9713
9716
if (data.locale_explicit !== undefined)
@@ -11655,6 +11658,37 @@ Online.clearFlights = function ()
11655
11658
this._miniPredict = Object.create(null);
11656
11659
};
11657
11660
11661
/**
11662
* Totals for the end-of-match reward (t1173 / t1278). Prefers the
11663
* server's online_awarded (same shape as play_finish: after − awarded)
11664
* so a rematch or a stringy payload still starts the tally. Falls back
11665
* to the snapshot taken at match start.
11666
*/
11667
Online.rewardResult = function (opts)
11668
{
11669
opts = opts || {};
11670
var after = Number(opts.lifetimePoints);
11671
if (!isFinite(after))
11672
{ return null; }
11673
after = Math.max(0, Math.floor(after));
11674
if (opts.awarded != null && opts.awarded !== '')
11675
{
11676
var awarded = Number(opts.awarded);
11677
if (isFinite(awarded))
11678
{
11679
awarded = Math.max(0, Math.floor(awarded));
11680
return { before: Math.max(0, after - awarded), after: after };
11681
}
11682
}
11683
var before = Number(opts.before);
11684
if (!isFinite(before))
11685
{ before = after; }
11686
before = Math.max(0, Math.floor(before));
11687
if (before > after)
11688
{ before = after; }
11689
return { before: before, after: after };
11690
};
11691
11658
11692
if (typeof globalThis !== 'undefined')
11659
11693
{ globalThis.Online = Online; }
11660
11694
if (typeof module !== 'undefined' && module.exports)
@@ -12738,19 +12772,33 @@ function createSequence (opts)
12738
12772
counter: 0
12739
12773
};
12740
12774
12775
function toCount (v)
12776
{
12777
var n = Number(v);
12778
if (!isFinite(n))
12779
{ return null; }
12780
return Math.max(0, Math.floor(n));
12781
}
12782
12741
12783
s.setResult = function (res)
12742
12784
{
12743
12785
if (s.hasResult)
12744
12786
{ return; }
12745
12787
s.hasResult = true;
12746
if (!res || typeof res.after !== 'number' || !isFinite(res.after))
12788
if (!res)
12789
{
12790
s.failed = true;
12791
return;
12792
}
12793
var after = toCount(res.after);
12794
if (after == null)
12747
12795
{
12748
12796
s.failed = true;
12749
12797
return;
12750
12798
}
12751
var after = Math.max(0, Math.floor(res.after));
12752
var before = typeof res.before === 'number' && isFinite(res.before)
12753
? Math.max(0, Math.floor(res.before)) : after;
12799
var before = (res.before != null && res.before !== '') ? toCount(res.before) : after;
12800
if (before == null)
12801
{ before = after; }
12754
12802
if (before > after)
12755
12803
{ before = after; }
12756
12804
s.before = before;
@@ -15947,7 +15995,9 @@ function startOnlineMatch ()
15947
15995
if (typeof me.planet.miss_chance === 'number')
15948
15996
{ miss = me.planet.miss_chance; }
15949
15997
}
15950
app.onlineBefore = (typeof Online !== 'undefined' && Online.lifetimePoints) || 0;
15998
app.onlineBefore = Number((typeof Online !== 'undefined' && Online.lifetimePoints) || 0) || 0;
15999
if (typeof Online !== 'undefined')
16000
{ Online.onlineAwarded = null; }
15951
16001
app.pendingLobbyReturn = null;
15952
16002
startPlay({ online: true, planet: planet, missChance: miss });
15953
16003
if (typeof Online !== 'undefined')
@@ -16101,9 +16151,17 @@ function bindOnlineUi ()
16101
16151
{
16102
16152
if (app.mode === 'playing' && app.online && rewardEnabled() && !app.rewardActive)
16103
16153
{
16104
// Lifetime points in this same poll already include the
16105
// server's online award (maybeAwardOnlineLobby).
16106
var result = { before: app.onlineBefore || 0, after: Online.lifetimePoints || 0 };
16154
// Prefer the poll's online_awarded (t1278): same formula as
16155
// play_finish. Rematches in a reused lobby used to leave
16156
// lifetimePoints unchanged, so before === after and the
16157
// tally never started even though "You won!" still rose.
16158
var result = (typeof Online.rewardResult === 'function')
16159
? Online.rewardResult({
16160
lifetimePoints: Online.lifetimePoints,
16161
awarded: Online.onlineAwarded,
16162
before: app.onlineBefore
16163
})
16164
: { before: app.onlineBefore || 0, after: Online.lifetimePoints || 0 };
16107
16165
showReward(myOnlinePlace(lobby) === 1, Promise.resolve(result), function ()
16108
16166
{
16109
16167
var pending = app.pendingLobbyReturn;
@@ -9646,6 +9646,7 @@ var Online = {9646
csrf: '',9646
csrf: '',9647
me: null,9647
me: null,9648
lifetimePoints: 0,9648
lifetimePoints: 0,9649
onlineAwarded: null,9649
locale: null,9650
locale: null,9650
localeExplicit: false,9651
localeExplicit: false,9651
authLocale: null,9652
authLocale: null,@@ -9708,6 +9709,8 @@ Online._apply = function (data)9708
{ this.error = ''; }9709
{ this.error = ''; }9709
if (data.lifetime_points != null)9710
if (data.lifetime_points != null)9710
{ this.lifetimePoints = data.lifetime_points; }9711
{ this.lifetimePoints = data.lifetime_points; }9712
if (data.online_awarded !== undefined)9713
{ this.onlineAwarded = data.online_awarded; }9711
if (data.locale !== undefined)9714
if (data.locale !== undefined)9712
{ this.locale = data.locale; }9715
{ this.locale = data.locale; }9713
if (data.locale_explicit !== undefined)9716
if (data.locale_explicit !== undefined)@@ -11655,6 +11658,37 @@ Online.clearFlights = function ()11655
this._miniPredict = Object.create(null);11658
this._miniPredict = Object.create(null);11656
};11659
};11657
11660
11661
/**11662
* Totals for the end-of-match reward (t1173 / t1278). Prefers the11663
* server's online_awarded (same shape as play_finish: after − awarded)11664
* so a rematch or a stringy payload still starts the tally. Falls back11665
* to the snapshot taken at match start.11666
*/11667
Online.rewardResult = function (opts)11668
{11669
opts = opts || {};11670
var after = Number(opts.lifetimePoints);11671
if (!isFinite(after))11672
{ return null; }11673
after = Math.max(0, Math.floor(after));11674
if (opts.awarded != null && opts.awarded !== '')11675
{11676
var awarded = Number(opts.awarded);11677
if (isFinite(awarded))11678
{11679
awarded = Math.max(0, Math.floor(awarded));11680
return { before: Math.max(0, after - awarded), after: after };11681
}11682
}11683
var before = Number(opts.before);11684
if (!isFinite(before))11685
{ before = after; }11686
before = Math.max(0, Math.floor(before));11687
if (before > after)11688
{ before = after; }11689
return { before: before, after: after };11690
};11691
11658
if (typeof globalThis !== 'undefined')11692
if (typeof globalThis !== 'undefined')11659
{ globalThis.Online = Online; }11693
{ globalThis.Online = Online; }11660
if (typeof module !== 'undefined' && module.exports)11694
if (typeof module !== 'undefined' && module.exports)@@ -12738,19 +12772,33 @@ function createSequence (opts)12738
counter: 012772
counter: 012739
};12773
};12740
12774
12775
function toCount (v)12776
{12777
var n = Number(v);12778
if (!isFinite(n))12779
{ return null; }12780
return Math.max(0, Math.floor(n));12781
}12782
12741
s.setResult = function (res)12783
s.setResult = function (res)12742
{12784
{12743
if (s.hasResult)12785
if (s.hasResult)12744
{ return; }12786
{ return; }12745
s.hasResult = true;12787
s.hasResult = true;12746
if (!res || typeof res.after !== 'number' || !isFinite(res.after))12788
if (!res)12789
{12790
s.failed = true;12791
return;12792
}12793
var after = toCount(res.after);12794
if (after == null)12747
{12795
{12748
s.failed = true;12796
s.failed = true;12749
return;12797
return;12750
}12798
}12751
var after = Math.max(0, Math.floor(res.after));12799
var before = (res.before != null && res.before !== '') ? toCount(res.before) : after;12752
var before = typeof res.before === 'number' && isFinite(res.before)12800
if (before == null)12753
? Math.max(0, Math.floor(res.before)) : after;12801
{ before = after; }12754
if (before > after)12802
if (before > after)12755
{ before = after; }12803
{ before = after; }12756
s.before = before;12804
s.before = before;@@ -15947,7 +15995,9 @@ function startOnlineMatch ()15947
if (typeof me.planet.miss_chance === 'number')15995
if (typeof me.planet.miss_chance === 'number')15948
{ miss = me.planet.miss_chance; }15996
{ miss = me.planet.miss_chance; }15949
}15997
}15950
app.onlineBefore = (typeof Online !== 'undefined' && Online.lifetimePoints) || 0;15998
app.onlineBefore = Number((typeof Online !== 'undefined' && Online.lifetimePoints) || 0) || 0;15999
if (typeof Online !== 'undefined')16000
{ Online.onlineAwarded = null; }15951
app.pendingLobbyReturn = null;16001
app.pendingLobbyReturn = null;15952
startPlay({ online: true, planet: planet, missChance: miss });16002
startPlay({ online: true, planet: planet, missChance: miss });15953
if (typeof Online !== 'undefined')16003
if (typeof Online !== 'undefined')@@ -16101,9 +16151,17 @@ function bindOnlineUi ()16101
{16151
{16102
if (app.mode === 'playing' && app.online && rewardEnabled() && !app.rewardActive)16152
if (app.mode === 'playing' && app.online && rewardEnabled() && !app.rewardActive)16103
{16153
{16104
// Lifetime points in this same poll already include the16154
// Prefer the poll's online_awarded (t1278): same formula as16105
// server's online award (maybeAwardOnlineLobby).16155
// play_finish. Rematches in a reused lobby used to leave16106
var result = { before: app.onlineBefore || 0, after: Online.lifetimePoints || 0 };16156
// lifetimePoints unchanged, so before === after and the16157
// tally never started even though "You won!" still rose.16158
var result = (typeof Online.rewardResult === 'function')16159
? Online.rewardResult({16160
lifetimePoints: Online.lifetimePoints,16161
awarded: Online.onlineAwarded,16162
before: app.onlineBefore16163
})16164
: { before: app.onlineBefore || 0, after: Online.lifetimePoints || 0 };16107
showReward(myOnlinePlace(lobby) === 1, Promise.resolve(result), function ()16165
showReward(myOnlinePlace(lobby) === 1, Promise.resolve(result), function ()16108
{16166
{16109
var pending = app.pendingLobbyReturn;16167
var pending = app.pendingLobbyReturn;@@ -264,6 +264,6 @@
264
264
</div>
265
265
266
266
<script src="framework.js?v=24498ce42730"></script>
267
<script src="game.js?v=107719dcf338"></script>
267
<script src="game.js?v=ff19c123f41d"></script>
268
268
</body>
269
269
</html>
@@ -264,6 +264,6 @@264
</div>264
</div>265
265
266
<script src="framework.js?v=24498ce42730"></script>266
<script src="framework.js?v=24498ce42730"></script>267
<script src="game.js?v=107719dcf338"></script>267
<script src="game.js?v=ff19c123f41d"></script>268
</body>268
</body>269
</html>269
</html>@@ -1548,3 +1548,30 @@ punten” tonen. Zodra je punten hebt, sta je er gewoon bij, met de
1548
1548
markering `you`.
1549
1549
1550
1550
Tests: `server/tests/run.php` (t1263).
1551
1552
## t1278 — Puntentelling na een online rematch
1553
1554
**Oorzaak.** “You won!” / “You lost...” schoof na een online wedstrijd
1555
wel omhoog, maar de optelling (blokjes naar het puntentotaal) bleef
1556
uit. Solo en Offline Strijd gebruikten `play_finish` (`awarded` +
1557
nieuw totaal). Online kende de server de punten zelf toe met sleutel
1558
`online:{lobbyId}:{userId}`. De lobby wordt na het podium echter
1559
teruggezet naar `waiting` en hergebruikt. De tweede (en volgende)
1560
wedstrijd in dezelfde lobby vond die sleutel al en kende 0 punten
1561
toe. De client vergeleek het profieltotaal bij de start met dat uit
1562
de finished-poll: die waren gelijk, `earned` werd 0, de tel-fase
1563
werd overgeslagen. De titel schuift via CSS, onafhankelijk van die
1564
fase, dus die zag je wél. Een eerste wedstrijd in een verse lobby
1565
werkte; dat is waarom de bestaande Playwright-check groen bleef.
1566
1567
**Oplossing.** De toekenningssleutel is nu
1568
`online:{lobbyId}:{started}:{userId}` (`started` wordt bij elke
1569
`startGame` opnieuw gezet). Een oude sleutel telt alleen mee als hij
1570
bij déze wedstrijd hoort (`created >= started`), zodat een lobby die
1571
tijdens het podium werd uitgerold geen dubbele punten krijgt. De poll
1572
stuurt `online_awarded` mee (zelfde formule als `play_finish`). De
1573
client gebruikt dat voor het puntenscherm.
1574
1575
Tests: `server/tests/run.php` (t1278, inclusief rematch),
1576
`test/online-reward.test.js`, `test/reward.test.js`.
1577
@@ -1548,3 +1548,30 @@ punten” tonen. Zodra je punten hebt, sta je er gewoon bij, met de1548
markering `you`.1548
markering `you`.1549
1549
1550
Tests: `server/tests/run.php` (t1263).1550
Tests: `server/tests/run.php` (t1263).1551
1552
## t1278 — Puntentelling na een online rematch1553
1554
**Oorzaak.** “You won!” / “You lost...” schoof na een online wedstrijd1555
wel omhoog, maar de optelling (blokjes naar het puntentotaal) bleef1556
uit. Solo en Offline Strijd gebruikten `play_finish` (`awarded` +1557
nieuw totaal). Online kende de server de punten zelf toe met sleutel1558
`online:{lobbyId}:{userId}`. De lobby wordt na het podium echter1559
teruggezet naar `waiting` en hergebruikt. De tweede (en volgende)1560
wedstrijd in dezelfde lobby vond die sleutel al en kende 0 punten1561
toe. De client vergeleek het profieltotaal bij de start met dat uit1562
de finished-poll: die waren gelijk, `earned` werd 0, de tel-fase1563
werd overgeslagen. De titel schuift via CSS, onafhankelijk van die1564
fase, dus die zag je wél. Een eerste wedstrijd in een verse lobby1565
werkte; dat is waarom de bestaande Playwright-check groen bleef.1566
1567
**Oplossing.** De toekenningssleutel is nu1568
`online:{lobbyId}:{started}:{userId}` (`started` wordt bij elke1569
`startGame` opnieuw gezet). Een oude sleutel telt alleen mee als hij1570
bij déze wedstrijd hoort (`created >= started`), zodat een lobby die1571
tijdens het podium werd uitgerold geen dubbele punten krijgt. De poll1572
stuurt `online_awarded` mee (zelfde formule als `play_finish`). De1573
client gebruikt dat voor het puntenscherm.1574
1575
Tests: `server/tests/run.php` (t1278, inclusief rematch),1576
`test/online-reward.test.js`, `test/reward.test.js`.1577
@@ -163,6 +163,8 @@ try {
163
163
$outgoing = isset($body['outgoing_shots']) && is_array($body['outgoing_shots']) ? $body['outgoing_shots'] : [];
164
164
$view = $store->viewFor($userId, $snapshot, $score, $eliminated, $outgoing);
165
165
$profile = $store->profilePayload($userId);
166
$rawLobby = $store->lobbyForUser($userId);
167
$onlineAwarded = $rawLobby ? $store->onlineAwardedFor($userId, $rawLobby) : null;
166
168
jsonOut([
167
169
'ok' => true,
168
170
'csrf' => csrfToken(),
@@ -172,6 +174,7 @@ try {
172
174
'shot_results' => $view['shot_results'],
173
175
'shot_flights' => $view['shot_flights'] ?? [],
174
176
'lifetime_points' => $profile['lifetime_points'],
177
'online_awarded' => $onlineAwarded,
175
178
'locale' => $profile['locale'],
176
179
'locale_explicit' => !empty($profile['locale_explicit']),
177
180
'auth_locale' => sessionAuthLocale(),
@@ -163,6 +163,8 @@ try {163
$outgoing = isset($body['outgoing_shots']) && is_array($body['outgoing_shots']) ? $body['outgoing_shots'] : [];163
$outgoing = isset($body['outgoing_shots']) && is_array($body['outgoing_shots']) ? $body['outgoing_shots'] : [];164
$view = $store->viewFor($userId, $snapshot, $score, $eliminated, $outgoing);164
$view = $store->viewFor($userId, $snapshot, $score, $eliminated, $outgoing);165
$profile = $store->profilePayload($userId);165
$profile = $store->profilePayload($userId);166
$rawLobby = $store->lobbyForUser($userId);167
$onlineAwarded = $rawLobby ? $store->onlineAwardedFor($userId, $rawLobby) : null;166
jsonOut([168
jsonOut([167
'ok' => true,169
'ok' => true,168
'csrf' => csrfToken(),170
'csrf' => csrfToken(),@@ -172,6 +174,7 @@ try {172
'shot_results' => $view['shot_results'],174
'shot_results' => $view['shot_results'],173
'shot_flights' => $view['shot_flights'] ?? [],175
'shot_flights' => $view['shot_flights'] ?? [],174
'lifetime_points' => $profile['lifetime_points'],176
'lifetime_points' => $profile['lifetime_points'],177
'online_awarded' => $onlineAwarded,175
'locale' => $profile['locale'],178
'locale' => $profile['locale'],176
'locale_explicit' => !empty($profile['locale_explicit']),179
'locale_explicit' => !empty($profile['locale_explicit']),177
'auth_locale' => sessionAuthLocale(),180
'auth_locale' => sessionAuthLocale(),@@ -635,7 +635,7 @@ SQL);
635
635
return;
636
636
}
637
637
$finished = (int) ($lobby['finished'] ?? 0);
638
if ($finished === 0 || time() < $finished + METEORS_PODIUM_SECONDS) {
638
if ($finished === 0 || $this->now() < $finished + METEORS_PODIUM_SECONDS) {
639
639
return;
640
640
}
641
641
$this->pdo->prepare(
@@ -1345,6 +1345,68 @@ SQL);
1345
1345
});
1346
1346
}
1347
1347
1348
/**
1349
* Award key for one player's online match. The lobby is reused after the
1350
* podium (maybeResetLobby), so the key must include the match start time
1351
* (t1278). Older keys were only lobby+user and blocked every rematch.
1352
*
1353
* @param array<string,mixed> $lobby
1354
*/
1355
public function onlineAwardKey(array $lobby, string $userId): string
1356
{
1357
$id = (string) ($lobby['id'] ?? '');
1358
$started = (int) ($lobby['started'] ?? 0);
1359
if ($started > 0) {
1360
return 'online:' . $id . ':' . $started . ':' . $userId;
1361
}
1362
return 'online:' . $id . ':' . $userId;
1363
}
1364
1365
/**
1366
* Key to use for this match: the per-start key, unless this same match
1367
* was already awarded with the pre-t1278 lobby-only key (created at or
1368
* after started). That avoids a double award after deploy mid-podium.
1369
*
1370
* @param array<string,mixed> $lobby
1371
*/
1372
public function onlineAwardKeyForMatch(array $lobby, string $userId): string
1373
{
1374
$newKey = $this->onlineAwardKey($lobby, $userId);
1375
$oldKey = 'online:' . ($lobby['id'] ?? '') . ':' . $userId;
1376
if ($newKey === $oldKey) {
1377
return $oldKey;
1378
}
1379
$started = (int) ($lobby['started'] ?? 0);
1380
$stmt = $this->pdo->prepare('SELECT created FROM point_awards WHERE award_key = ?');
1381
$stmt->execute([$oldKey]);
1382
$row = $stmt->fetch();
1383
if ($row && $started > 0 && (int) $row['created'] >= $started) {
1384
return $oldKey;
1385
}
1386
return $newKey;
1387
}
1388
1389
/**
1390
* Points already recorded for this user in the current online match, or
1391
* null when the match is still running and the player is not eliminated.
1392
*
1393
* @param array<string,mixed> $lobby
1394
*/
1395
public function onlineAwardedFor(string $userId, array $lobby): ?int
1396
{
1397
$finished = ($lobby['status'] ?? '') === 'finished' || !empty($lobby['finished']);
1398
$member = $this->member((string) ($lobby['id'] ?? ''), $userId);
1399
$eliminated = $member && (int) $member['eliminated'];
1400
if (!$finished && !$eliminated) {
1401
return null;
1402
}
1403
$key = $this->onlineAwardKeyForMatch($lobby, $userId);
1404
$stmt = $this->pdo->prepare('SELECT points FROM point_awards WHERE award_key = ?');
1405
$stmt->execute([$key]);
1406
$row = $stmt->fetch();
1407
return $row ? (int) $row['points'] : 0;
1408
}
1409
1348
1410
/** @param array<string,mixed> $lobby */
1349
1411
public function maybeAwardOnlineLobby(array $lobby): void
1350
1412
{
@@ -1354,7 +1416,7 @@ SQL);
1354
1416
continue;
1355
1417
}
1356
1418
$uid = (string) $m['user_id'];
1357
$key = 'online:' . $lobby['id'] . ':' . $uid;
1419
$key = $this->onlineAwardKeyForMatch($lobby, $uid);
1358
1420
$this->awardPoints($uid, (int) $m['score'], $key, 'online');
1359
1421
}
1360
1422
}
@@ -635,7 +635,7 @@ SQL);635
return;635
return;636
}636
}637
$finished = (int) ($lobby['finished'] ?? 0);637
$finished = (int) ($lobby['finished'] ?? 0);638
if ($finished === 0 || time() < $finished + METEORS_PODIUM_SECONDS) {638
if ($finished === 0 || $this->now() < $finished + METEORS_PODIUM_SECONDS) {639
return;639
return;640
}640
}641
$this->pdo->prepare(641
$this->pdo->prepare(@@ -1345,6 +1345,68 @@ SQL);1345
});1345
});1346
}1346
}1347
1347
1348
/**1349
* Award key for one player's online match. The lobby is reused after the1350
* podium (maybeResetLobby), so the key must include the match start time1351
* (t1278). Older keys were only lobby+user and blocked every rematch.1352
*1353
* @param array<string,mixed> $lobby1354
*/1355
public function onlineAwardKey(array $lobby, string $userId): string1356
{1357
$id = (string) ($lobby['id'] ?? '');1358
$started = (int) ($lobby['started'] ?? 0);1359
if ($started > 0) {1360
return 'online:' . $id . ':' . $started . ':' . $userId;1361
}1362
return 'online:' . $id . ':' . $userId;1363
}1364
1365
/**1366
* Key to use for this match: the per-start key, unless this same match1367
* was already awarded with the pre-t1278 lobby-only key (created at or1368
* after started). That avoids a double award after deploy mid-podium.1369
*1370
* @param array<string,mixed> $lobby1371
*/1372
public function onlineAwardKeyForMatch(array $lobby, string $userId): string1373
{1374
$newKey = $this->onlineAwardKey($lobby, $userId);1375
$oldKey = 'online:' . ($lobby['id'] ?? '') . ':' . $userId;1376
if ($newKey === $oldKey) {1377
return $oldKey;1378
}1379
$started = (int) ($lobby['started'] ?? 0);1380
$stmt = $this->pdo->prepare('SELECT created FROM point_awards WHERE award_key = ?');1381
$stmt->execute([$oldKey]);1382
$row = $stmt->fetch();1383
if ($row && $started > 0 && (int) $row['created'] >= $started) {1384
return $oldKey;1385
}1386
return $newKey;1387
}1388
1389
/**1390
* Points already recorded for this user in the current online match, or1391
* null when the match is still running and the player is not eliminated.1392
*1393
* @param array<string,mixed> $lobby1394
*/1395
public function onlineAwardedFor(string $userId, array $lobby): ?int1396
{1397
$finished = ($lobby['status'] ?? '') === 'finished' || !empty($lobby['finished']);1398
$member = $this->member((string) ($lobby['id'] ?? ''), $userId);1399
$eliminated = $member && (int) $member['eliminated'];1400
if (!$finished && !$eliminated) {1401
return null;1402
}1403
$key = $this->onlineAwardKeyForMatch($lobby, $userId);1404
$stmt = $this->pdo->prepare('SELECT points FROM point_awards WHERE award_key = ?');1405
$stmt->execute([$key]);1406
$row = $stmt->fetch();1407
return $row ? (int) $row['points'] : 0;1408
}1409
1348
/** @param array<string,mixed> $lobby */1410
/** @param array<string,mixed> $lobby */1349
public function maybeAwardOnlineLobby(array $lobby): void1411
public function maybeAwardOnlineLobby(array $lobby): void1350
{1412
{@@ -1354,7 +1416,7 @@ SQL);1354
continue;1416
continue;1355
}1417
}1356
$uid = (string) $m['user_id'];1418
$uid = (string) $m['user_id'];1357
$key = 'online:' . $lobby['id'] . ':' . $uid;1419
$key = $this->onlineAwardKeyForMatch($lobby, $uid);1358
$this->awardPoints($uid, (int) $m['score'], $key, 'online');1420
$this->awardPoints($uid, (int) $m['score'], $key, 'online');1359
}1421
}1360
}1422
}@@ -556,6 +556,74 @@ expect($ptsStore->lifetimePoints($u3) === 80, 'online elimination awards the sco
556
556
$ptsStore->viewFor($u3, null, 999, true, []);
557
557
expect($ptsStore->lifetimePoints($u3) === 80, 'online award_key is idempotent');
558
558
559
// t1278: a rematch in the same (reset) lobby must award again, otherwise
560
// the client's reward tally sees before === after and skips the count.
561
echo "Online rematch awards (t1278)\n";
562
$uR = 'local:rematch_a';
563
$vR = 'local:rematch_b';
564
$ptsStore->touchProfile($uR, 'Ra', null);
565
$ptsStore->touchProfile($vR, 'Rb', null);
566
$lobR = $ptsStore->createLobby($uR, 'Ra', 0.0, 'terra');
567
$ptsStore->joinLobby($vR, 'Rb', $lobR['code']);
568
$ptsStore->setReady($uR, true);
569
$ptsStore->setReady($vR, true);
570
$start1 = $ptsStore->startGame($uR);
571
expect(!empty($start1['started']), 'first match has a started timestamp');
572
$ptsStore->viewFor($uR, null, 90, false, []);
573
$ptsStore->viewFor($vR, null, 40, true, []);
574
expect($ptsStore->lifetimePoints($uR) === 90, 'match 1 winner awarded 90 (got ' . $ptsStore->lifetimePoints($uR) . ')');
575
expect($ptsStore->lifetimePoints($vR) === 40, 'match 1 loser awarded 40');
576
$lobAfter1 = $ptsStore->lobbyForUser($uR);
577
expect(($lobAfter1['status'] ?? '') === 'finished', 'lobby finished after last player is out');
578
expect($ptsStore->onlineAwardedFor($uR, $lobAfter1) === 90, 'winner online_awarded is 90');
579
expect($ptsStore->onlineAwardedFor($vR, $lobAfter1) === 40, 'loser online_awarded is 40');
580
$key1 = $ptsStore->onlineAwardKey($lobAfter1, $uR);
581
expect(strpos($key1, ':' . (int) $start1['started'] . ':') !== false, 'award key includes match start');
582
583
// Same match is idempotent under the new key too.
584
$ptsStore->viewFor($uR, null, 90, false, []);
585
expect($ptsStore->lifetimePoints($uR) === 90, 'same match stays idempotent');
586
587
$ptsStore->testNow = ((int) ($lobAfter1['finished'] ?? time())) + METEORS_PODIUM_SECONDS + 1;
588
$ptsStore->viewFor($uR);
589
$lobWait = $ptsStore->lobbyForUser($uR);
590
expect(($lobWait['status'] ?? '') === 'waiting', 'lobby resets after the podium');
591
expect($ptsStore->onlineAwardedFor($uR, $lobWait) === null, 'waiting lobby has no current award');
592
593
$ptsStore->setReady($uR, true);
594
$ptsStore->setReady($vR, true);
595
$start2 = $ptsStore->startGame($uR);
596
expect((int) $start2['started'] !== (int) $start1['started'], 'rematch gets a new started time');
597
$beforeRematchU = $ptsStore->lifetimePoints($uR);
598
$beforeRematchV = $ptsStore->lifetimePoints($vR);
599
$ptsStore->viewFor($uR, null, 70, false, []);
600
$ptsStore->viewFor($vR, null, 25, true, []);
601
expect($ptsStore->lifetimePoints($uR) === $beforeRematchU + 70, 'rematch winner is awarded again (got ' . $ptsStore->lifetimePoints($uR) . ')');
602
expect($ptsStore->lifetimePoints($vR) === $beforeRematchV + 25, 'rematch loser is awarded again');
603
$lobAfter2 = $ptsStore->lobbyForUser($uR);
604
expect($ptsStore->onlineAwardedFor($uR, $lobAfter2) === 70, 'rematch online_awarded is the new score, not the first');
605
606
// Mid-podium old-key compatibility: a first-match award stored under the
607
// pre-t1278 key must not be granted a second time after deploy.
608
$uOld = 'local:oldkey_a';
609
$vOld = 'local:oldkey_b';
610
$ptsStore->touchProfile($uOld, 'Oa', null);
611
$ptsStore->touchProfile($vOld, 'Ob', null);
612
$lobOld = $ptsStore->createLobby($uOld, 'Oa', 0.0, 'terra');
613
$ptsStore->joinLobby($vOld, 'Ob', $lobOld['code']);
614
$ptsStore->setReady($uOld, true);
615
$ptsStore->setReady($vOld, true);
616
$stOld = $ptsStore->startGame($uOld);
617
$ptsStore->viewFor($uOld, null, 15, false, []);
618
// Pretend the current match was already awarded with the old lobby-only key
619
// (as a live lobby would be, mid-podium, right after deploy).
620
$ptsStore->awardPoints($uOld, 15, 'online:' . $stOld['id'] . ':' . $uOld, 'online');
621
expect($ptsStore->lifetimePoints($uOld) === 15, 'seeded old-key award');
622
$ptsStore->viewFor($vOld, null, 5, true, []);
623
expect($ptsStore->lifetimePoints($uOld) === 15, 'old key for this same match is not awarded twice (got ' . $ptsStore->lifetimePoints($uOld) . ')');
624
expect($ptsStore->lifetimePoints($vOld) === 5, 'opponent still gets the new-key award');
625
$ptsStore->testNow = null;
626
559
627
$ptsStore->setLocale($u, 'nl');
560
628
expect($ptsStore->locale($u) === 'nl', 'setLocale stores nl');
561
629
try {
@@ -556,6 +556,74 @@ expect($ptsStore->lifetimePoints($u3) === 80, 'online elimination awards the sco556
$ptsStore->viewFor($u3, null, 999, true, []);556
$ptsStore->viewFor($u3, null, 999, true, []);557
expect($ptsStore->lifetimePoints($u3) === 80, 'online award_key is idempotent');557
expect($ptsStore->lifetimePoints($u3) === 80, 'online award_key is idempotent');558
558
559
// t1278: a rematch in the same (reset) lobby must award again, otherwise560
// the client's reward tally sees before === after and skips the count.561
echo "Online rematch awards (t1278)\n";562
$uR = 'local:rematch_a';563
$vR = 'local:rematch_b';564
$ptsStore->touchProfile($uR, 'Ra', null);565
$ptsStore->touchProfile($vR, 'Rb', null);566
$lobR = $ptsStore->createLobby($uR, 'Ra', 0.0, 'terra');567
$ptsStore->joinLobby($vR, 'Rb', $lobR['code']);568
$ptsStore->setReady($uR, true);569
$ptsStore->setReady($vR, true);570
$start1 = $ptsStore->startGame($uR);571
expect(!empty($start1['started']), 'first match has a started timestamp');572
$ptsStore->viewFor($uR, null, 90, false, []);573
$ptsStore->viewFor($vR, null, 40, true, []);574
expect($ptsStore->lifetimePoints($uR) === 90, 'match 1 winner awarded 90 (got ' . $ptsStore->lifetimePoints($uR) . ')');575
expect($ptsStore->lifetimePoints($vR) === 40, 'match 1 loser awarded 40');576
$lobAfter1 = $ptsStore->lobbyForUser($uR);577
expect(($lobAfter1['status'] ?? '') === 'finished', 'lobby finished after last player is out');578
expect($ptsStore->onlineAwardedFor($uR, $lobAfter1) === 90, 'winner online_awarded is 90');579
expect($ptsStore->onlineAwardedFor($vR, $lobAfter1) === 40, 'loser online_awarded is 40');580
$key1 = $ptsStore->onlineAwardKey($lobAfter1, $uR);581
expect(strpos($key1, ':' . (int) $start1['started'] . ':') !== false, 'award key includes match start');582
583
// Same match is idempotent under the new key too.584
$ptsStore->viewFor($uR, null, 90, false, []);585
expect($ptsStore->lifetimePoints($uR) === 90, 'same match stays idempotent');586
587
$ptsStore->testNow = ((int) ($lobAfter1['finished'] ?? time())) + METEORS_PODIUM_SECONDS + 1;588
$ptsStore->viewFor($uR);589
$lobWait = $ptsStore->lobbyForUser($uR);590
expect(($lobWait['status'] ?? '') === 'waiting', 'lobby resets after the podium');591
expect($ptsStore->onlineAwardedFor($uR, $lobWait) === null, 'waiting lobby has no current award');592
593
$ptsStore->setReady($uR, true);594
$ptsStore->setReady($vR, true);595
$start2 = $ptsStore->startGame($uR);596
expect((int) $start2['started'] !== (int) $start1['started'], 'rematch gets a new started time');597
$beforeRematchU = $ptsStore->lifetimePoints($uR);598
$beforeRematchV = $ptsStore->lifetimePoints($vR);599
$ptsStore->viewFor($uR, null, 70, false, []);600
$ptsStore->viewFor($vR, null, 25, true, []);601
expect($ptsStore->lifetimePoints($uR) === $beforeRematchU + 70, 'rematch winner is awarded again (got ' . $ptsStore->lifetimePoints($uR) . ')');602
expect($ptsStore->lifetimePoints($vR) === $beforeRematchV + 25, 'rematch loser is awarded again');603
$lobAfter2 = $ptsStore->lobbyForUser($uR);604
expect($ptsStore->onlineAwardedFor($uR, $lobAfter2) === 70, 'rematch online_awarded is the new score, not the first');605
606
// Mid-podium old-key compatibility: a first-match award stored under the607
// pre-t1278 key must not be granted a second time after deploy.608
$uOld = 'local:oldkey_a';609
$vOld = 'local:oldkey_b';610
$ptsStore->touchProfile($uOld, 'Oa', null);611
$ptsStore->touchProfile($vOld, 'Ob', null);612
$lobOld = $ptsStore->createLobby($uOld, 'Oa', 0.0, 'terra');613
$ptsStore->joinLobby($vOld, 'Ob', $lobOld['code']);614
$ptsStore->setReady($uOld, true);615
$ptsStore->setReady($vOld, true);616
$stOld = $ptsStore->startGame($uOld);617
$ptsStore->viewFor($uOld, null, 15, false, []);618
// Pretend the current match was already awarded with the old lobby-only key619
// (as a live lobby would be, mid-podium, right after deploy).620
$ptsStore->awardPoints($uOld, 15, 'online:' . $stOld['id'] . ':' . $uOld, 'online');621
expect($ptsStore->lifetimePoints($uOld) === 15, 'seeded old-key award');622
$ptsStore->viewFor($vOld, null, 5, true, []);623
expect($ptsStore->lifetimePoints($uOld) === 15, 'old key for this same match is not awarded twice (got ' . $ptsStore->lifetimePoints($uOld) . ')');624
expect($ptsStore->lifetimePoints($vOld) === 5, 'opponent still gets the new-key award');625
$ptsStore->testNow = null;626
559
$ptsStore->setLocale($u, 'nl');627
$ptsStore->setLocale($u, 'nl');560
expect($ptsStore->locale($u) === 'nl', 'setLocale stores nl');628
expect($ptsStore->locale($u) === 'nl', 'setLocale stores nl');561
try {629
try {@@ -1999,7 +1999,9 @@ function startOnlineMatch ()
1999
1999
if (typeof me.planet.miss_chance === 'number')
2000
2000
{ miss = me.planet.miss_chance; }
2001
2001
}
2002
app.onlineBefore = (typeof Online !== 'undefined' && Online.lifetimePoints) || 0;
2002
app.onlineBefore = Number((typeof Online !== 'undefined' && Online.lifetimePoints) || 0) || 0;
2003
if (typeof Online !== 'undefined')
2004
{ Online.onlineAwarded = null; }
2003
2005
app.pendingLobbyReturn = null;
2004
2006
startPlay({ online: true, planet: planet, missChance: miss });
2005
2007
if (typeof Online !== 'undefined')
@@ -2153,9 +2155,17 @@ function bindOnlineUi ()
2153
2155
{
2154
2156
if (app.mode === 'playing' && app.online && rewardEnabled() && !app.rewardActive)
2155
2157
{
2156
// Lifetime points in this same poll already include the
2157
// server's online award (maybeAwardOnlineLobby).
2158
var result = { before: app.onlineBefore || 0, after: Online.lifetimePoints || 0 };
2158
// Prefer the poll's online_awarded (t1278): same formula as
2159
// play_finish. Rematches in a reused lobby used to leave
2160
// lifetimePoints unchanged, so before === after and the
2161
// tally never started even though "You won!" still rose.
2162
var result = (typeof Online.rewardResult === 'function')
2163
? Online.rewardResult({
2164
lifetimePoints: Online.lifetimePoints,
2165
awarded: Online.onlineAwarded,
2166
before: app.onlineBefore
2167
})
2168
: { before: app.onlineBefore || 0, after: Online.lifetimePoints || 0 };
2159
2169
showReward(myOnlinePlace(lobby) === 1, Promise.resolve(result), function ()
2160
2170
{
2161
2171
var pending = app.pendingLobbyReturn;
@@ -1999,7 +1999,9 @@ function startOnlineMatch ()1999
if (typeof me.planet.miss_chance === 'number')1999
if (typeof me.planet.miss_chance === 'number')2000
{ miss = me.planet.miss_chance; }2000
{ miss = me.planet.miss_chance; }2001
}2001
}2002
app.onlineBefore = (typeof Online !== 'undefined' && Online.lifetimePoints) || 0;2002
app.onlineBefore = Number((typeof Online !== 'undefined' && Online.lifetimePoints) || 0) || 0;2003
if (typeof Online !== 'undefined')2004
{ Online.onlineAwarded = null; }2003
app.pendingLobbyReturn = null;2005
app.pendingLobbyReturn = null;2004
startPlay({ online: true, planet: planet, missChance: miss });2006
startPlay({ online: true, planet: planet, missChance: miss });2005
if (typeof Online !== 'undefined')2007
if (typeof Online !== 'undefined')@@ -2153,9 +2155,17 @@ function bindOnlineUi ()2153
{2155
{2154
if (app.mode === 'playing' && app.online && rewardEnabled() && !app.rewardActive)2156
if (app.mode === 'playing' && app.online && rewardEnabled() && !app.rewardActive)2155
{2157
{2156
// Lifetime points in this same poll already include the2158
// Prefer the poll's online_awarded (t1278): same formula as2157
// server's online award (maybeAwardOnlineLobby).2159
// play_finish. Rematches in a reused lobby used to leave2158
var result = { before: app.onlineBefore || 0, after: Online.lifetimePoints || 0 };2160
// lifetimePoints unchanged, so before === after and the2161
// tally never started even though "You won!" still rose.2162
var result = (typeof Online.rewardResult === 'function')2163
? Online.rewardResult({2164
lifetimePoints: Online.lifetimePoints,2165
awarded: Online.onlineAwarded,2166
before: app.onlineBefore2167
})2168
: { before: app.onlineBefore || 0, after: Online.lifetimePoints || 0 };2159
showReward(myOnlinePlace(lobby) === 1, Promise.resolve(result), function ()2169
showReward(myOnlinePlace(lobby) === 1, Promise.resolve(result), function ()2160
{2170
{2161
var pending = app.pendingLobbyReturn;2171
var pending = app.pendingLobbyReturn;@@ -15,6 +15,7 @@ var Online = {
15
15
csrf: '',
16
16
me: null,
17
17
lifetimePoints: 0,
18
onlineAwarded: null,
18
19
locale: null,
19
20
localeExplicit: false,
20
21
authLocale: null,
@@ -77,6 +78,8 @@ Online._apply = function (data)
77
78
{ this.error = ''; }
78
79
if (data.lifetime_points != null)
79
80
{ this.lifetimePoints = data.lifetime_points; }
81
if (data.online_awarded !== undefined)
82
{ this.onlineAwarded = data.online_awarded; }
80
83
if (data.locale !== undefined)
81
84
{ this.locale = data.locale; }
82
85
if (data.locale_explicit !== undefined)
@@ -2024,6 +2027,37 @@ Online.clearFlights = function ()
2024
2027
this._miniPredict = Object.create(null);
2025
2028
};
2026
2029
2030
/**
2031
* Totals for the end-of-match reward (t1173 / t1278). Prefers the
2032
* server's online_awarded (same shape as play_finish: after − awarded)
2033
* so a rematch or a stringy payload still starts the tally. Falls back
2034
* to the snapshot taken at match start.
2035
*/
2036
Online.rewardResult = function (opts)
2037
{
2038
opts = opts || {};
2039
var after = Number(opts.lifetimePoints);
2040
if (!isFinite(after))
2041
{ return null; }
2042
after = Math.max(0, Math.floor(after));
2043
if (opts.awarded != null && opts.awarded !== '')
2044
{
2045
var awarded = Number(opts.awarded);
2046
if (isFinite(awarded))
2047
{
2048
awarded = Math.max(0, Math.floor(awarded));
2049
return { before: Math.max(0, after - awarded), after: after };
2050
}
2051
}
2052
var before = Number(opts.before);
2053
if (!isFinite(before))
2054
{ before = after; }
2055
before = Math.max(0, Math.floor(before));
2056
if (before > after)
2057
{ before = after; }
2058
return { before: before, after: after };
2059
};
2060
2027
2061
if (typeof globalThis !== 'undefined')
2028
2062
{ globalThis.Online = Online; }
2029
2063
if (typeof module !== 'undefined' && module.exports)
@@ -15,6 +15,7 @@ var Online = {15
csrf: '',15
csrf: '',16
me: null,16
me: null,17
lifetimePoints: 0,17
lifetimePoints: 0,18
onlineAwarded: null,18
locale: null,19
locale: null,19
localeExplicit: false,20
localeExplicit: false,20
authLocale: null,21
authLocale: null,@@ -77,6 +78,8 @@ Online._apply = function (data)77
{ this.error = ''; }78
{ this.error = ''; }78
if (data.lifetime_points != null)79
if (data.lifetime_points != null)79
{ this.lifetimePoints = data.lifetime_points; }80
{ this.lifetimePoints = data.lifetime_points; }81
if (data.online_awarded !== undefined)82
{ this.onlineAwarded = data.online_awarded; }80
if (data.locale !== undefined)83
if (data.locale !== undefined)81
{ this.locale = data.locale; }84
{ this.locale = data.locale; }82
if (data.locale_explicit !== undefined)85
if (data.locale_explicit !== undefined)@@ -2024,6 +2027,37 @@ Online.clearFlights = function ()2024
this._miniPredict = Object.create(null);2027
this._miniPredict = Object.create(null);2025
};2028
};2026
2029
2030
/**2031
* Totals for the end-of-match reward (t1173 / t1278). Prefers the2032
* server's online_awarded (same shape as play_finish: after − awarded)2033
* so a rematch or a stringy payload still starts the tally. Falls back2034
* to the snapshot taken at match start.2035
*/2036
Online.rewardResult = function (opts)2037
{2038
opts = opts || {};2039
var after = Number(opts.lifetimePoints);2040
if (!isFinite(after))2041
{ return null; }2042
after = Math.max(0, Math.floor(after));2043
if (opts.awarded != null && opts.awarded !== '')2044
{2045
var awarded = Number(opts.awarded);2046
if (isFinite(awarded))2047
{2048
awarded = Math.max(0, Math.floor(awarded));2049
return { before: Math.max(0, after - awarded), after: after };2050
}2051
}2052
var before = Number(opts.before);2053
if (!isFinite(before))2054
{ before = after; }2055
before = Math.max(0, Math.floor(before));2056
if (before > after)2057
{ before = after; }2058
return { before: before, after: after };2059
};2060
2027
if (typeof globalThis !== 'undefined')2061
if (typeof globalThis !== 'undefined')2028
{ globalThis.Online = Online; }2062
{ globalThis.Online = Online; }2029
if (typeof module !== 'undefined' && module.exports)2063
if (typeof module !== 'undefined' && module.exports)@@ -118,19 +118,33 @@ function createSequence (opts)
118
118
counter: 0
119
119
};
120
120
121
function toCount (v)
122
{
123
var n = Number(v);
124
if (!isFinite(n))
125
{ return null; }
126
return Math.max(0, Math.floor(n));
127
}
128
121
129
s.setResult = function (res)
122
130
{
123
131
if (s.hasResult)
124
132
{ return; }
125
133
s.hasResult = true;
126
if (!res || typeof res.after !== 'number' || !isFinite(res.after))
134
if (!res)
127
135
{
128
136
s.failed = true;
129
137
return;
130
138
}
131
var after = Math.max(0, Math.floor(res.after));
132
var before = typeof res.before === 'number' && isFinite(res.before)
133
? Math.max(0, Math.floor(res.before)) : after;
139
var after = toCount(res.after);
140
if (after == null)
141
{
142
s.failed = true;
143
return;
144
}
145
var before = (res.before != null && res.before !== '') ? toCount(res.before) : after;
146
if (before == null)
147
{ before = after; }
134
148
if (before > after)
135
149
{ before = after; }
136
150
s.before = before;
@@ -118,19 +118,33 @@ function createSequence (opts)118
counter: 0118
counter: 0119
};119
};120
120
121
function toCount (v)122
{123
var n = Number(v);124
if (!isFinite(n))125
{ return null; }126
return Math.max(0, Math.floor(n));127
}128
121
s.setResult = function (res)129
s.setResult = function (res)122
{130
{123
if (s.hasResult)131
if (s.hasResult)124
{ return; }132
{ return; }125
s.hasResult = true;133
s.hasResult = true;126
if (!res || typeof res.after !== 'number' || !isFinite(res.after))134
if (!res)127
{135
{128
s.failed = true;136
s.failed = true;129
return;137
return;130
}138
}131
var after = Math.max(0, Math.floor(res.after));139
var after = toCount(res.after);132
var before = typeof res.before === 'number' && isFinite(res.before)140
if (after == null)133
? Math.max(0, Math.floor(res.before)) : after;141
{142
s.failed = true;143
return;144
}145
var before = (res.before != null && res.before !== '') ? toCount(res.before) : after;146
if (before == null)147
{ before = after; }134
if (before > after)148
if (before > after)135
{ before = after; }149
{ before = after; }136
s.before = before;150
s.before = before;@@ -0,0 +1,86 @@
1
'use strict';
2
3
// t1278: the multiplayer end path must produce a tally (earned > 0)
4
// after a rematch in the same lobby, using the server's online_awarded
5
// the same way play_finish uses awarded.
6
7
const { describe, it } = require('node:test');
8
const assert = require('node:assert/strict');
9
const fs = require('fs');
10
const path = require('path');
11
const Online = require('../src/online.js');
12
const Reward = require('../src/reward.js');
13
14
const main = fs.readFileSync(path.join(__dirname, '../src/main.js'), 'utf8');
15
const store = fs.readFileSync(path.join(__dirname, '../server/lib/Store.php'), 'utf8');
16
17
describe('Online reward totals (t1278)', () =>
18
{
19
it('rewardResult uses awarded the same way as play_finish', () =>
20
{
21
assert.deepEqual(
22
Online.rewardResult({ lifetimePoints: 250, awarded: 70, before: 100 }),
23
{ before: 180, after: 250 }
24
);
25
assert.deepEqual(
26
Online.rewardResult({ lifetimePoints: 90, awarded: 90, before: 0 }),
27
{ before: 0, after: 90 }
28
);
29
assert.deepEqual(
30
Online.rewardResult({ lifetimePoints: '150', awarded: '25', before: '0' }),
31
{ before: 125, after: 150 },
32
'string payloads from JSON still count'
33
);
34
});
35
36
it('falls back to the pre-match snapshot when awarded is unknown', () =>
37
{
38
assert.deepEqual(
39
Online.rewardResult({ lifetimePoints: 190, before: 100 }),
40
{ before: 100, after: 190 }
41
);
42
assert.deepEqual(
43
Online.rewardResult({ lifetimePoints: 100, before: 100 }),
44
{ before: 100, after: 100 },
45
'equal totals (the rematch bug) yield earned 0'
46
);
47
assert.equal(Online.rewardResult({ lifetimePoints: 'nope' }), null);
48
});
49
50
it('_apply stores online_awarded from a finished poll', () =>
51
{
52
Online.lifetimePoints = 0;
53
Online.onlineAwarded = null;
54
Online._apply({ ok: true, lifetime_points: 160, online_awarded: 70 });
55
assert.equal(Online.lifetimePoints, 160);
56
assert.equal(Online.onlineAwarded, 70);
57
const res = Online.rewardResult({
58
lifetimePoints: Online.lifetimePoints,
59
awarded: Online.onlineAwarded,
60
before: 90
61
});
62
assert.deepEqual(res, { before: 90, after: 160 });
63
const seq = Reward.createSequence({ intro: 0, rise: 0, flight: 0, hold: 0 });
64
seq.setResult(res);
65
assert.equal(seq.earned, 70);
66
const out = seq.tick(0);
67
assert.equal(out.phase, 'count');
68
assert.ok(out.spawn.length >= 1, 'tally starts (blocks spawn)');
69
});
70
71
it('onFinished in main.js builds the result via Online.rewardResult', () =>
72
{
73
const i = main.indexOf('Online.onFinished = function');
74
assert.ok(i >= 0);
75
const body = main.slice(i, i + 900);
76
assert.match(body, /Online\.rewardResult/);
77
assert.match(body, /Online\.onlineAwarded/);
78
assert.match(body, /showReward\(/);
79
});
80
81
it('the server award key includes the match start time', () =>
82
{
83
assert.match(store, /'online:' \. \$id \. ':' \. \$started \. ':' \. \$userId/);
84
assert.match(store, /function onlineAwardKeyForMatch/);
85
});
86
});
@@ -0,0 +1,86 @@1
'use strict';2
3
// t1278: the multiplayer end path must produce a tally (earned > 0)4
// after a rematch in the same lobby, using the server's online_awarded5
// the same way play_finish uses awarded.6
7
const { describe, it } = require('node:test');8
const assert = require('node:assert/strict');9
const fs = require('fs');10
const path = require('path');11
const Online = require('../src/online.js');12
const Reward = require('../src/reward.js');13
14
const main = fs.readFileSync(path.join(__dirname, '../src/main.js'), 'utf8');15
const store = fs.readFileSync(path.join(__dirname, '../server/lib/Store.php'), 'utf8');16
17
describe('Online reward totals (t1278)', () =>18
{19
it('rewardResult uses awarded the same way as play_finish', () =>20
{21
assert.deepEqual(22
Online.rewardResult({ lifetimePoints: 250, awarded: 70, before: 100 }),23
{ before: 180, after: 250 }24
);25
assert.deepEqual(26
Online.rewardResult({ lifetimePoints: 90, awarded: 90, before: 0 }),27
{ before: 0, after: 90 }28
);29
assert.deepEqual(30
Online.rewardResult({ lifetimePoints: '150', awarded: '25', before: '0' }),31
{ before: 125, after: 150 },32
'string payloads from JSON still count'33
);34
});35
36
it('falls back to the pre-match snapshot when awarded is unknown', () =>37
{38
assert.deepEqual(39
Online.rewardResult({ lifetimePoints: 190, before: 100 }),40
{ before: 100, after: 190 }41
);42
assert.deepEqual(43
Online.rewardResult({ lifetimePoints: 100, before: 100 }),44
{ before: 100, after: 100 },45
'equal totals (the rematch bug) yield earned 0'46
);47
assert.equal(Online.rewardResult({ lifetimePoints: 'nope' }), null);48
});49
50
it('_apply stores online_awarded from a finished poll', () =>51
{52
Online.lifetimePoints = 0;53
Online.onlineAwarded = null;54
Online._apply({ ok: true, lifetime_points: 160, online_awarded: 70 });55
assert.equal(Online.lifetimePoints, 160);56
assert.equal(Online.onlineAwarded, 70);57
const res = Online.rewardResult({58
lifetimePoints: Online.lifetimePoints,59
awarded: Online.onlineAwarded,60
before: 9061
});62
assert.deepEqual(res, { before: 90, after: 160 });63
const seq = Reward.createSequence({ intro: 0, rise: 0, flight: 0, hold: 0 });64
seq.setResult(res);65
assert.equal(seq.earned, 70);66
const out = seq.tick(0);67
assert.equal(out.phase, 'count');68
assert.ok(out.spawn.length >= 1, 'tally starts (blocks spawn)');69
});70
71
it('onFinished in main.js builds the result via Online.rewardResult', () =>72
{73
const i = main.indexOf('Online.onFinished = function');74
assert.ok(i >= 0);75
const body = main.slice(i, i + 900);76
assert.match(body, /Online\.rewardResult/);77
assert.match(body, /Online\.onlineAwarded/);78
assert.match(body, /showReward\(/);79
});80
81
it('the server award key includes the match start time', () =>82
{83
assert.match(store, /'online:' \. \$id \. ':' \. \$started \. ':' \. \$userId/);84
assert.match(store, /function onlineAwardKeyForMatch/);85
});86
});@@ -212,6 +212,18 @@ describe('Reward sequence (t1173)', () =>
212
212
assert.equal(b.before, 77);
213
213
});
214
214
215
it('numeric strings are accepted (t1278)', () =>
216
{
217
const seq = Reward.createSequence({ intro: 0, rise: 0, flight: 0, hold: 0 });
218
seq.setResult({ before: '100', after: '109' });
219
assert.equal(seq.failed, false);
220
assert.equal(seq.earned, 9);
221
assert.equal(seq.before, 100);
222
assert.equal(seq.after, 109);
223
const out = seq.tick(0);
224
assert.equal(out.phase, 'count');
225
});
226
215
227
it('a huge frame (tab in background) still lands exactly on the total', () =>
216
228
{
217
229
const seq = Reward.createSequence({});
@@ -212,6 +212,18 @@ describe('Reward sequence (t1173)', () =>212
assert.equal(b.before, 77);212
assert.equal(b.before, 77);213
});213
});214
214
215
it('numeric strings are accepted (t1278)', () =>216
{217
const seq = Reward.createSequence({ intro: 0, rise: 0, flight: 0, hold: 0 });218
seq.setResult({ before: '100', after: '109' });219
assert.equal(seq.failed, false);220
assert.equal(seq.earned, 9);221
assert.equal(seq.before, 100);222
assert.equal(seq.after, 109);223
const out = seq.tick(0);224
assert.equal(out.phase, 'count');225
});226
215
it('a huge frame (tab in background) still lands exactly on the total', () =>227
it('a huge frame (tab in background) still lands exactly on the total', () =>216
{228
{217
const seq = Reward.createSequence({});229
const seq = Reward.createSequence({});@@ -290,6 +290,54 @@ def test_online(browser):
290
290
p.wait_for_function("() => app.mode === 'online' && !document.getElementById('online-lobby').hidden", timeout=15000)
291
291
check(True, f"online {tag}: back in the lobby afterwards")
292
292
shot(p1, "t1173-local-online-winner-4-lobby.png")
293
294
# t1278: a second match in the same lobby must tally again.
295
print("\n== online rematch in the same lobby ==")
296
for p in (p1, p2):
297
p.locator("#btn-ready").click()
298
start = p1.locator("#btn-start")
299
for _ in range(20):
300
if start.is_visible() and start.is_enabled():
301
break
302
p1.wait_for_timeout(400)
303
start.click()
304
for p in (p1, p2):
305
p.wait_for_function("() => app && app.mode === 'playing' && app.online && app.core", timeout=10000)
306
b1r = p1.evaluate("() => app.onlineBefore")
307
b2r = p2.evaluate("() => app.onlineBefore")
308
check(b1r == 9, f"rematch: winner starts from previous total {b1r}")
309
check(b2r == 6, f"rematch: loser starts from previous total {b2r}")
310
p1.wait_for_timeout(1500)
311
p1.evaluate("() => { app.core.score = 11; }")
312
p2.evaluate("() => { app.core.score = 8; }")
313
p1.wait_for_timeout(1200)
314
p2.evaluate("() => { app.core.state = 'gameover'; app.core.gameOverTime = 0; }")
315
p1.wait_for_function("() => !document.getElementById('reward').hidden", timeout=12000)
316
p2.wait_for_function("() => !document.getElementById('reward').hidden", timeout=12000)
317
p1.wait_for_timeout(300)
318
s1, s2 = state(p1), state(p2)
319
check(s1["title"] == "You won!", f"rematch winner sees You won! ({s1['title']!r})")
320
check(s2["title"] == "You lost...", f"rematch loser sees You lost... ({s2['title']!r})")
321
p1.wait_for_function("() => Reward.debugState() && Reward.debugState().phase === 'count'", timeout=8000)
322
p1.wait_for_timeout(400)
323
shot(p1, "t1173-local-online-rematch-winner-counting.png")
324
dest = Path("/workspace/screenshots/meteors-mp-reward")
325
dest.mkdir(parents=True, exist_ok=True)
326
p1.screenshot(path=str(dest / "winner-counting.png"), full_page=False)
327
print(f"wrote {dest / 'winner-counting.png'}")
328
d1 = p1.evaluate("() => Reward.debugState()")
329
check(d1 and d1["earned"] == 11, f"rematch winner tally earned {d1 and d1['earned']} == 11")
330
check(d1 and d1["before"] == b1r, f"rematch winner counter starts at {b1r}")
331
p2.wait_for_function("() => Reward.debugState() && ['count','hold'].includes(Reward.debugState().phase)", timeout=8000)
332
p2.screenshot(path=str(dest / "loser-counting.png"), full_page=False)
333
print(f"wrote {dest / 'loser-counting.png'}")
334
for p, b, earned, tag in ((p1, b1r, 11, "winner"), (p2, b2r, 8, "loser")):
335
p.wait_for_function("() => Reward.debugState() && Reward.debugState().phase === 'hold'", timeout=20000)
336
d = state(p)["dbg"]
337
check(d["before"] == b and d["after"] - d["before"] == earned,
338
f"rematch {tag}: {d['before']} → {d['after']} (+{earned})")
339
p1.screenshot(path=str(dest / "winner-final.png"), full_page=False)
340
print(f"wrote {dest / 'winner-final.png'}")
293
341
c1.close()
294
342
c2.close()
295
343
@@ -290,6 +290,54 @@ def test_online(browser):290
p.wait_for_function("() => app.mode === 'online' && !document.getElementById('online-lobby').hidden", timeout=15000)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")291
check(True, f"online {tag}: back in the lobby afterwards")292
shot(p1, "t1173-local-online-winner-4-lobby.png")292
shot(p1, "t1173-local-online-winner-4-lobby.png")293
294
# t1278: a second match in the same lobby must tally again.295
print("\n== online rematch in the same lobby ==")296
for p in (p1, p2):297
p.locator("#btn-ready").click()298
start = p1.locator("#btn-start")299
for _ in range(20):300
if start.is_visible() and start.is_enabled():301
break302
p1.wait_for_timeout(400)303
start.click()304
for p in (p1, p2):305
p.wait_for_function("() => app && app.mode === 'playing' && app.online && app.core", timeout=10000)306
b1r = p1.evaluate("() => app.onlineBefore")307
b2r = p2.evaluate("() => app.onlineBefore")308
check(b1r == 9, f"rematch: winner starts from previous total {b1r}")309
check(b2r == 6, f"rematch: loser starts from previous total {b2r}")310
p1.wait_for_timeout(1500)311
p1.evaluate("() => { app.core.score = 11; }")312
p2.evaluate("() => { app.core.score = 8; }")313
p1.wait_for_timeout(1200)314
p2.evaluate("() => { app.core.state = 'gameover'; app.core.gameOverTime = 0; }")315
p1.wait_for_function("() => !document.getElementById('reward').hidden", timeout=12000)316
p2.wait_for_function("() => !document.getElementById('reward').hidden", timeout=12000)317
p1.wait_for_timeout(300)318
s1, s2 = state(p1), state(p2)319
check(s1["title"] == "You won!", f"rematch winner sees You won! ({s1['title']!r})")320
check(s2["title"] == "You lost...", f"rematch loser sees You lost... ({s2['title']!r})")321
p1.wait_for_function("() => Reward.debugState() && Reward.debugState().phase === 'count'", timeout=8000)322
p1.wait_for_timeout(400)323
shot(p1, "t1173-local-online-rematch-winner-counting.png")324
dest = Path("/workspace/screenshots/meteors-mp-reward")325
dest.mkdir(parents=True, exist_ok=True)326
p1.screenshot(path=str(dest / "winner-counting.png"), full_page=False)327
print(f"wrote {dest / 'winner-counting.png'}")328
d1 = p1.evaluate("() => Reward.debugState()")329
check(d1 and d1["earned"] == 11, f"rematch winner tally earned {d1 and d1['earned']} == 11")330
check(d1 and d1["before"] == b1r, f"rematch winner counter starts at {b1r}")331
p2.wait_for_function("() => Reward.debugState() && ['count','hold'].includes(Reward.debugState().phase)", timeout=8000)332
p2.screenshot(path=str(dest / "loser-counting.png"), full_page=False)333
print(f"wrote {dest / 'loser-counting.png'}")334
for p, b, earned, tag in ((p1, b1r, 11, "winner"), (p2, b2r, 8, "loser")):335
p.wait_for_function("() => Reward.debugState() && Reward.debugState().phase === 'hold'", timeout=20000)336
d = state(p)["dbg"]337
check(d["before"] == b and d["after"] - d["before"] == earned,338
f"rematch {tag}: {d['before']} → {d['after']} (+{earned})")339
p1.screenshot(path=str(dest / "winner-final.png"), full_page=False)340
print(f"wrote {dest / 'winner-final.png'}")293
c1.close()341
c1.close()294
c2.close()342
c2.close()295
343