Merge branch 'feature/t1119-offline-strijd'
@@ -8,7 +8,8 @@ Live (na de eerste deploy): https://projects.timfalken.com/meteors/
8
8
9
9
## Spelen
10
10
11
1. Open `build/index.html` (lokaal of live) en druk op **Spelen**.
11
1. Open `build/index.html` (lokaal of live) en druk op **Spelen**, of op
12
**Offline Strijd** voor een singleplayer-wedstrijd tegen lokale bots.
12
13
2. Elke seconde valt er een blokje van één van vijf kleuren in een willekeurige kolom.
13
14
3. In een stilliggende kolom sleep je blokjes verticaal; ze wisselen om met de blokjes waar je langs gaat.
14
15
4. Drie of meer blokjes van dezelfde kleur op een rij (horizontaal of verticaal) worden donkergrijs, krijgen een vlam en springen omhoog. Alles wat erop stond, vliegt mee.
@@ -59,6 +60,7 @@ De spelkern is deterministisch en staat los van tekenen en invoer, zodat stage 2
59
60
| `src/easing.js` | Qt-eases (easeOutBack / easeOutElastic) en Click-Tween-defaults voor de selectie-animatie |
60
61
| `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` |
61
62
| `src/main.js` | Menu, HUD, frameworkv3-scene, muis/touch, schaal naar het scherm, landing-bounce, selectie-tween, online-lobby |
63
| `src/offline.js` | Offline Strijd: progressie, bot-AI, lokale 'multiplayer'-schoten |
62
64
| `src/online.js` | API-client, polling, opponent-miniaturen, vlucht-tweens van afgeschoten blokjes |
63
65
| `server/` | PHP API: OAuth, lobby, shots, SQLite in `data/` (niet gedeployed) |
64
66
| `server/lib/planets.json` | Catalogus van 12 planeten (JS en PHP delen dit bestand) |
@@ -68,7 +70,21 @@ De spelkern is deterministisch en staat los van tekenen en invoer, zodat stage 2
68
70
| `test/` | Unit tests (`node --test`) voor de kern en de deploy-guard; `server/tests/run.php` voor de API |
69
71
| `ci/` | FTP-deploy, **zonder** `--delete`. Expandeert `$timftproot` zelf. Raakt `favicon.ico` en `data/` (config, database) niet aan. |
70
72
71
Sprongfysica is parametrisch. Een horizontale match van 3 springt `13 / jumpsToClear` tegels hoog; een verticale match van 3 krijgt 120 % daarvan, en elk extra blokje +5 % (wordt nergens in het spel uitgelegd). De massa bepaalt hoe lang de sprong omhoog duurt (onafhankelijk van de hoogte). Op de apex versnelt de cluster geleidelijk tot de valsnelheid (`apexEaseTime = 0,15 × fallTime`); daarna is de daal snelheid constant. De luchtweerstand (`fallTime`) bepaalt die valsnelheid én hoe snel de visuele landing-bounce is (`bounceDuration = 0,12 × fallTime`). Een vastgehouden blokje krijgt dezelfde schaal-tween als Tim's KWin Click Tween (150 ms easeOutBack naar 80 %, 720 ms easeOutElastic terug). Zie `docs/ASSUMPTIONS.md`.
73
Sprongfysica is parametrisch. Een horizontale match van 3 springt
74
`1,5 × 13 / jumpsToClear` tegels hoog (t1119: de minimumsprong is 50 %
75
hoger); een verticale match van 3 krijgt 120 % daarvan, en elk extra
76
blokje +5 % (wordt nergens in het spel uitgelegd). De massa bepaalt hoe
77
lang de sprong omhoog duurt (onafhankelijk van de hoogte). Op de apex
78
versnelt de cluster geleidelijk tot de valsnelheid
79
(`apexEaseTime = 0,15 × fallTime`); daarna is de daalsnelheid constant
80
en **gehalveerd** (`fallSpeed = 0,5 × 13 / fallTime`, t1122). De
81
luchtweerstand (`fallTime`) bepaalt die valsnelheid én hoe snel de
82
visuele landing-bounce is (`bounceDuration = 0,12 × fallTime`). Een
83
vastgehouden blokje krijgt dezelfde schaal-tween als Tim's KWin Click
84
Tween (150 ms easeOutBack naar 80 %, 720 ms easeOutElastic terug).
85
Wissels (speler en bot) animeren visueel in 100 ms easeOutCubic (t1121).
86
Landt een cluster meteen in een match, dan is die sprong 25 % sterker,
87
stapeling additief (t1120). Zie `docs/ASSUMPTIONS.md`.
72
88
73
89
74
90
## Planeten (stage 3)
@@ -98,6 +114,15 @@ BlueGit CI (`blue-ci-cd.yml`) draait tests en een build op feature-branches en o
98
114
99
115
Secrets: `timftphost` / `timftpuser` / `timftppassword` / `timftproot` (groep), `projectftp` (dit project), en `auth_client_secret` (dit project, zie hieronder). De groep en de andere projecten (verhalenboek, microchess) hebben geen auth-geheim; alleen FTP-gegevens.
100
116
117
## Offline Strijd
118
119
Op het menu kies je **Offline Strijd**, daarna een planeet. Je speelt
120
tegen lokale bots alsof het multiplayer is (schoten, miss-kans,
121
miniatuurvelden), helemaal in de browser. Eerst 1 tegenstander, daarna
122
2, en verder N tegenstanders voor N−1 rondes, met stijgende skill
123
(5 % + 1 % per ronde). Als je verliest zie je de bereikte ronde.
124
Zie `docs/ASSUMPTIONS.md` (t1119).
125
101
126
## Online spelen (stage 2)
102
127
103
128
Solo blijft werken, ook als online nog niet is ingesteld. Op het menu kies je
@@ -8,7 +8,8 @@ Live (na de eerste deploy): https://projects.timfalken.com/meteors/8
8
9
## Spelen9
## Spelen10
10
11
1. Open `build/index.html` (lokaal of live) en druk op **Spelen**.11
1. Open `build/index.html` (lokaal of live) en druk op **Spelen**, of op12
**Offline Strijd** voor een singleplayer-wedstrijd tegen lokale bots.12
2. Elke seconde valt er een blokje van één van vijf kleuren in een willekeurige kolom.13
2. Elke seconde valt er een blokje van één van vijf kleuren in een willekeurige kolom.13
3. In een stilliggende kolom sleep je blokjes verticaal; ze wisselen om met de blokjes waar je langs gaat.14
3. In een stilliggende kolom sleep je blokjes verticaal; ze wisselen om met de blokjes waar je langs gaat.14
4. Drie of meer blokjes van dezelfde kleur op een rij (horizontaal of verticaal) worden donkergrijs, krijgen een vlam en springen omhoog. Alles wat erop stond, vliegt mee.15
4. Drie of meer blokjes van dezelfde kleur op een rij (horizontaal of verticaal) worden donkergrijs, krijgen een vlam en springen omhoog. Alles wat erop stond, vliegt mee.@@ -59,6 +60,7 @@ De spelkern is deterministisch en staat los van tekenen en invoer, zodat stage 259
| `src/easing.js` | Qt-eases (easeOutBack / easeOutElastic) en Click-Tween-defaults voor de selectie-animatie |60
| `src/easing.js` | Qt-eases (easeOutBack / easeOutElastic) en Click-Tween-defaults voor de selectie-animatie |60
| `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` |61
| `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` |61
| `src/main.js` | Menu, HUD, frameworkv3-scene, muis/touch, schaal naar het scherm, landing-bounce, selectie-tween, online-lobby |62
| `src/main.js` | Menu, HUD, frameworkv3-scene, muis/touch, schaal naar het scherm, landing-bounce, selectie-tween, online-lobby |63
| `src/offline.js` | Offline Strijd: progressie, bot-AI, lokale 'multiplayer'-schoten |62
| `src/online.js` | API-client, polling, opponent-miniaturen, vlucht-tweens van afgeschoten blokjes |64
| `src/online.js` | API-client, polling, opponent-miniaturen, vlucht-tweens van afgeschoten blokjes |63
| `server/` | PHP API: OAuth, lobby, shots, SQLite in `data/` (niet gedeployed) |65
| `server/` | PHP API: OAuth, lobby, shots, SQLite in `data/` (niet gedeployed) |64
| `server/lib/planets.json` | Catalogus van 12 planeten (JS en PHP delen dit bestand) |66
| `server/lib/planets.json` | Catalogus van 12 planeten (JS en PHP delen dit bestand) |@@ -68,7 +70,21 @@ De spelkern is deterministisch en staat los van tekenen en invoer, zodat stage 268
| `test/` | Unit tests (`node --test`) voor de kern en de deploy-guard; `server/tests/run.php` voor de API |70
| `test/` | Unit tests (`node --test`) voor de kern en de deploy-guard; `server/tests/run.php` voor de API |69
| `ci/` | FTP-deploy, **zonder** `--delete`. Expandeert `$timftproot` zelf. Raakt `favicon.ico` en `data/` (config, database) niet aan. |71
| `ci/` | FTP-deploy, **zonder** `--delete`. Expandeert `$timftproot` zelf. Raakt `favicon.ico` en `data/` (config, database) niet aan. |70
72
71
Sprongfysica is parametrisch. Een horizontale match van 3 springt `13 / jumpsToClear` tegels hoog; een verticale match van 3 krijgt 120 % daarvan, en elk extra blokje +5 % (wordt nergens in het spel uitgelegd). De massa bepaalt hoe lang de sprong omhoog duurt (onafhankelijk van de hoogte). Op de apex versnelt de cluster geleidelijk tot de valsnelheid (`apexEaseTime = 0,15 × fallTime`); daarna is de daal snelheid constant. De luchtweerstand (`fallTime`) bepaalt die valsnelheid én hoe snel de visuele landing-bounce is (`bounceDuration = 0,12 × fallTime`). Een vastgehouden blokje krijgt dezelfde schaal-tween als Tim's KWin Click Tween (150 ms easeOutBack naar 80 %, 720 ms easeOutElastic terug). Zie `docs/ASSUMPTIONS.md`.73
Sprongfysica is parametrisch. Een horizontale match van 3 springt74
`1,5 × 13 / jumpsToClear` tegels hoog (t1119: de minimumsprong is 50 %75
hoger); een verticale match van 3 krijgt 120 % daarvan, en elk extra76
blokje +5 % (wordt nergens in het spel uitgelegd). De massa bepaalt hoe77
lang de sprong omhoog duurt (onafhankelijk van de hoogte). Op de apex78
versnelt de cluster geleidelijk tot de valsnelheid79
(`apexEaseTime = 0,15 × fallTime`); daarna is de daalsnelheid constant80
en **gehalveerd** (`fallSpeed = 0,5 × 13 / fallTime`, t1122). De81
luchtweerstand (`fallTime`) bepaalt die valsnelheid én hoe snel de82
visuele landing-bounce is (`bounceDuration = 0,12 × fallTime`). Een83
vastgehouden blokje krijgt dezelfde schaal-tween als Tim's KWin Click84
Tween (150 ms easeOutBack naar 80 %, 720 ms easeOutElastic terug).85
Wissels (speler en bot) animeren visueel in 100 ms easeOutCubic (t1121).86
Landt een cluster meteen in een match, dan is die sprong 25 % sterker,87
stapeling additief (t1120). Zie `docs/ASSUMPTIONS.md`.72
88
73
89
74
## Planeten (stage 3)90
## Planeten (stage 3)@@ -98,6 +114,15 @@ BlueGit CI (`blue-ci-cd.yml`) draait tests en een build op feature-branches en o98
114
99
Secrets: `timftphost` / `timftpuser` / `timftppassword` / `timftproot` (groep), `projectftp` (dit project), en `auth_client_secret` (dit project, zie hieronder). De groep en de andere projecten (verhalenboek, microchess) hebben geen auth-geheim; alleen FTP-gegevens.115
Secrets: `timftphost` / `timftpuser` / `timftppassword` / `timftproot` (groep), `projectftp` (dit project), en `auth_client_secret` (dit project, zie hieronder). De groep en de andere projecten (verhalenboek, microchess) hebben geen auth-geheim; alleen FTP-gegevens.100
116
117
## Offline Strijd118
119
Op het menu kies je **Offline Strijd**, daarna een planeet. Je speelt120
tegen lokale bots alsof het multiplayer is (schoten, miss-kans,121
miniatuurvelden), helemaal in de browser. Eerst 1 tegenstander, daarna122
2, en verder N tegenstanders voor N−1 rondes, met stijgende skill123
(5 % + 1 % per ronde). Als je verliest zie je de bereikte ronde.124
Zie `docs/ASSUMPTIONS.md` (t1119).125
101
## Online spelen (stage 2)126
## Online spelen (stage 2)102
127
103
Solo blijft werken, ook als online nog niet is ingesteld. Op het menu kies je128
Solo blijft werken, ook als online nog niet is ingesteld. Op het menu kies je@@ -256,10 +256,16 @@ else if (typeof globalThis !== 'undefined')
256
256
* that later planets only need new data, not new physics code.
257
257
*
258
258
* Gravity (jumpsToClear): 1 (easy, high jump) .. 4 (hard, short jump).
259
* A horizontal match of 3 jumps FIELD_HEIGHT / jumpsToClear tiles —
260
* at 1, one jump from the floor clears the field; at 4, you need four.
259
* A horizontal match of 3 jumps JUMP_HEIGHT_SCALE * FIELD_HEIGHT
260
* / jumpsToClear tiles (JUMP_HEIGHT_SCALE is 1.5 since t1119: the
261
* minimum jump is 50% higher). At gravity 1 that is 19.5 tiles, so
262
* one jump from the floor clears the 13-tile field with room to spare;
263
* at 4 you still need more than one jump, but each is 50% taller.
261
264
* Air (fallTime): 1 s (hard, fast fall) .. 5 s (easy, slow fall).
262
* After a jump peaks, blocks float down at FIELD_HEIGHT / fallTime tiles/s.
265
* After a jump peaks, blocks float down at DESCENT_SPEED_SCALE *
266
* FIELD_HEIGHT / fallTime tiles/s (DESCENT_SPEED_SCALE is 0.5 since
267
* t1122: all descent speeds are halved). Relative differences between
268
* planets (1 / fallTime) are unchanged. Upward launch is not affected.
263
269
* Mass (riseTime): 0.5 s (hard, fast jump) .. 3 s (easy, slow jump).
264
270
* Time to reach the apex, independent of jump height.
265
271
*
@@ -274,6 +280,14 @@ else if (typeof globalThis !== 'undefined')
274
280
275
281
var FIELD_WIDTH = 10;
276
282
var FIELD_HEIGHT = 13;
283
/** t1119: every match jump (the gravity-applied minimum and the
284
* vertical / extra-block bonuses derived from it) is 50% higher. */
285
var JUMP_HEIGHT_SCALE = 1.5;
286
/** t1122: every descent speed is halved. Terminal fallSpeed, spawn
287
* fall, unsupported / released / cargo fall, and the post-apex
288
* float-down all use this scale. Upward launch is unchanged. */
289
var DESCENT_SPEED_SCALE = 0.5;
290
277
291
278
292
function clamp (value, lo, hi)
279
293
{
@@ -306,12 +320,14 @@ function createPlanet (opts)
306
320
fallTime: fallTime,
307
321
riseTime: riseTime,
308
322
colors: colors,
309
baseJumpHeight: FIELD_HEIGHT / jumpsToClear,
310
fallSpeed: FIELD_HEIGHT / fallTime,
323
baseJumpHeight: JUMP_HEIGHT_SCALE * FIELD_HEIGHT / jumpsToClear,
324
fallSpeed: DESCENT_SPEED_SCALE * FIELD_HEIGHT / fallTime,
311
325
// Time to ease from vy=0 at the apex to terminal fallSpeed.
312
// Shorter when air resistance is low (small fallTime).
326
// Shorter when air resistance is low (small fallTime). The ease
327
// duration is unchanged; fallAccel scales with the halved
328
// fallSpeed so the ease still lasts apexEaseTime seconds.
313
329
apexEaseTime: 0.15 * fallTime,
314
fallAccel: (FIELD_HEIGHT / fallTime) / (0.15 * fallTime),
330
fallAccel: (DESCENT_SPEED_SCALE * FIELD_HEIGHT / fallTime) / (0.15 * fallTime),
315
331
// Visual landing bounce: faster at low air resistance. Stage-3 params.
316
332
bounceDuration: 0.12 * fallTime,
317
333
bounceSquash: 0.16
@@ -480,6 +496,8 @@ function displayValues (planet)
480
496
var Planet = {
481
497
FIELD_WIDTH: FIELD_WIDTH,
482
498
FIELD_HEIGHT: FIELD_HEIGHT,
499
JUMP_HEIGHT_SCALE: JUMP_HEIGHT_SCALE,
500
DESCENT_SPEED_SCALE: DESCENT_SPEED_SCALE,
483
501
COLOR_COUNT: 5,
484
502
SETTLE_TIME: 3,
485
503
SPAWN_INTERVAL: 1,
@@ -571,11 +589,29 @@ function easeOutElastic (t)
571
589
return Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p) + 1;
572
590
}
573
591
592
/** easeOutCubic: 1 − (1−t)³. Smooth, no overshoot (easings.net). */
593
function easeOutCubic (t)
594
{
595
t = clamp01(t);
596
var u = 1 - t;
597
return 1 - u * u * u;
598
}
599
574
600
function tween (from, to, t, ease)
575
601
{
576
602
return from + (to - from) * ease(clamp01(t));
577
603
}
578
604
605
/**
606
* Visual-only block swap tween (t1121). Game logic and the grid update
607
* immediately; this only moves the displaced sprite. 100 ms sits in the
608
* requested 80–120 ms range.
609
*/
610
var SWAP_TWEEN = {
611
duration: 0.100,
612
ease: easeOutCubic
613
};
614
579
615
/**
580
616
* DEFAULT settings of Tim's KWin Click Tween
581
617
* (git.timfalken.com/timfa/click-tween).
@@ -619,8 +655,10 @@ var Easing = {
619
655
ELASTIC_AMPLITUDE: ELASTIC_AMPLITUDE,
620
656
easeOutBack: easeOutBack,
621
657
easeOutElastic: easeOutElastic,
658
easeOutCubic: easeOutCubic,
622
659
tween: tween,
623
660
CLICK_TWEEN: CLICK_TWEEN,
661
SWAP_TWEEN: SWAP_TWEEN,
624
662
clamp01: clamp01,
625
663
bouncePose: bouncePose
626
664
};
@@ -672,6 +710,13 @@ var SWAP_DISTANCE = 0.25;
672
710
var SNAP_Y = 0.5;
673
711
// Horizontal slop (tiles) for snapping to a neighbouring column on press.
674
712
var HORIZONTAL_SLOP = 0.35;
713
/** t1120: additive jump bonus per landing-chain step. A landing that
714
* immediately makes a match launches at (1 + 0.25 * chain) times the
715
* usual height, with chain 1, 2, 3, … → ×1.25, ×1.50, ×1.75. */
716
var LANDING_CHAIN_BONUS = 0.25;
717
/** t1123: a column pulses red at or above this many grounded rows
718
* (10 of 13 is just over 70%). */
719
var COLUMN_WARN_ROWS = 10;
675
720
676
721
function UnionFind ()
677
722
{
@@ -726,6 +771,10 @@ function GameCore (planet, rng)
726
771
this.strictInvariants = false;
727
772
this.debugInvariants = false;
728
773
this.lastInvariantViolations = [];
774
// t1121: visual-only swap events, consumed by the view each frame.
775
this.swapEvents = [];
776
// t1120: last landing-chain indicator { chain, bonusPct }, or null.
777
this.lastChainIndicator = null;
729
778
}
730
779
731
780
function optsMissChance (args)
@@ -744,6 +793,8 @@ GameCore.LAUNCH_PULL = LAUNCH_PULL;
744
793
GameCore.SWAP_DISTANCE = SWAP_DISTANCE;
745
794
GameCore.SNAP_Y = SNAP_Y;
746
795
GameCore.HORIZONTAL_SLOP = HORIZONTAL_SLOP;
796
GameCore.LANDING_CHAIN_BONUS = LANDING_CHAIN_BONUS;
797
GameCore.COLUMN_WARN_ROWS = COLUMN_WARN_ROWS;
747
798
GameCore.DEFAULT_MISS_CHANCE = 0.30;
748
799
GameCore.STATE_STILL = STATE_STILL;
749
800
GameCore.STATE_FALLING = STATE_FALLING;
@@ -892,6 +943,56 @@ GameCore.prototype.groundedCount = function (col)
892
943
return n;
893
944
};
894
945
946
GameCore.prototype.columnNeedsWarn = function (col)
947
{
948
return this.groundedCount(col) >= COLUMN_WARN_ROWS;
949
};
950
951
/**
952
* Which columns of a field snapshot should pulse (t1123). Flying,
953
* falling and manual (airborne) blocks do not count: they are
954
* temporary and would flicker the warning. Still, settling and
955
* locked (grounded) blocks do.
956
*/
957
GameCore.warnColumnsFromSnapshot = function (snapshot, threshold)
958
{
959
threshold = threshold == null ? COLUMN_WARN_ROWS : threshold;
960
var width = (snapshot && snapshot.width) || 10;
961
var flags = [];
962
var counts = [];
963
for (var c = 0; c < width; c++)
964
{
965
counts[c] = 0;
966
flags[c] = false;
967
}
968
var blocks = (snapshot && snapshot.blocks) || [];
969
for (var i = 0; i < blocks.length; i++)
970
{
971
var b = blocks[i];
972
if (b.col < 0 || b.col >= width)
973
{ continue; }
974
if (b.state === 'still' || b.state === 'settling' || b.state === 'locked')
975
{ counts[b.col]++; }
976
}
977
for (var c = 0; c < width; c++)
978
{ flags[c] = counts[c] >= threshold; }
979
return flags;
980
};
981
982
GameCore.columnWarnPulse = function (timeSec)
983
{
984
// Smooth sine, ~0.5 Hz, alpha 0.16–0.44. Shared by the player
985
// field and opponent / bot minis so they pulse in sync.
986
var t = timeSec;
987
if (t == null)
988
{
989
t = (typeof performance !== 'undefined' && performance.now)
990
? performance.now() / 1000
991
: Date.now() / 1000;
992
}
993
return 0.16 + 0.28 * (0.5 + 0.5 * Math.sin(t * Math.PI * 2 * 0.55));
994
};
995
895
996
GameCore.prototype.blockAt = function (col, row)
896
997
{
897
998
for (var i = 0; i < this.blocks.length; i++)
@@ -1513,6 +1614,14 @@ GameCore.prototype.mergeClusterGroup = function (clusters)
1513
1614
keep.decel = decelSum / n;
1514
1615
keep.jumpHeight = hSum / n;
1515
1616
keep.phase = keep.vy > 1e-10 ? 'up' : 'down';
1617
var maxChain = 0;
1618
for (var c = 0; c < clusters.length; c++)
1619
{
1620
var ch = clusters[c].landingChain || 0;
1621
if (ch > maxChain)
1622
{ maxChain = ch; }
1623
}
1624
keep.landingChain = maxChain;
1516
1625
for (var c = 0; c < clusters.length; c++)
1517
1626
{
1518
1627
var mem = this.clusterMembers(clusters[c].id);
@@ -1907,6 +2016,9 @@ GameCore.prototype.landCluster = function (cluster, members)
1907
2016
}
1908
2017
cluster.phase = 'landed';
1909
2018
cluster.vy = 0;
2019
cluster.landedPending = true;
2020
if (cluster.landingChain == null)
2021
{ cluster.landingChain = 0; }
1910
2022
};
1911
2023
1912
2024
/**
@@ -1928,6 +2040,10 @@ GameCore.prototype.releaseLandedCluster = function (cluster)
1928
2040
block.color = this.randomColor();
1929
2041
block.settleTime = 0;
1930
2042
}
2043
// Persist the chain across release so a post-recolor match in
2044
// this same tick still gets the landing bonus (t1120).
2045
block.justLanded = !!cluster.landedPending;
2046
block.landingChain = cluster.landingChain || 0;
1931
2047
this.leaveCluster(block);
1932
2048
// Always drop leftover launch / manual velocity. A stale upward
1933
2049
// vy here is what sends blocks off the top "very fast" after
@@ -2803,7 +2919,10 @@ GameCore.prototype.resolveMatches = function ()
2803
2919
{ return []; }
2804
2920
var lines = this.findMatchLines();
2805
2921
if (!lines.length)
2806
{ return []; }
2922
{
2923
this.finishLandingChains([]);
2924
return [];
2925
}
2807
2926
2808
2927
var uf = new UnionFind();
2809
2928
var blockById = Object.create(null);
@@ -2870,9 +2989,19 @@ GameCore.prototype.resolveMatches = function ()
2870
2989
{ height = h; }
2871
2990
}
2872
2991
}
2873
this.launchCluster(group, height);
2874
launched.push({ blocks: group, jumpHeight: height });
2992
var chain = this.landingChainFor(group);
2993
var bonusMul = 1 + LANDING_CHAIN_BONUS * chain;
2994
height *= bonusMul;
2995
this.launchCluster(group, height, { landingChain: chain });
2996
launched.push({
2997
blocks: group,
2998
jumpHeight: height,
2999
landingChain: chain,
3000
chainBonus: bonusMul
3001
});
2875
3002
}
3003
this.finishLandingChains(launched);
3004
this.updateChainIndicator(launched);
2876
3005
return launched;
2877
3006
};
2878
3007
@@ -2880,8 +3009,9 @@ GameCore.prototype.resolveMatches = function ()
2880
3009
* Gray the matched blocks, take everything sitting on top of them in
2881
3010
* those columns, link them, and launch with jump height `height`.
2882
3011
*/
2883
GameCore.prototype.launchCluster = function (matchedBlocks, height)
3012
GameCore.prototype.launchCluster = function (matchedBlocks, height, opts)
2884
3013
{
3014
opts = opts || {};
2885
3015
var lowestInCol = Object.create(null);
2886
3016
var matchedIds = Object.create(null);
2887
3017
for (var i = 0; i < matchedBlocks.length; i++)
@@ -2898,7 +3028,9 @@ GameCore.prototype.launchCluster = function (matchedBlocks, height)
2898
3028
jumpHeight: height,
2899
3029
vy: PlanetMod.launchVelocity(this.planet, height),
2900
3030
decel: PlanetMod.launchDeceleration(this.planet, height),
2901
phase: 'up'
3031
phase: 'up',
3032
landingChain: opts.landingChain || 0,
3033
landedPending: false
2902
3034
};
2903
3035
this.clusters[clusterId] = cluster;
2904
3036
@@ -3274,10 +3406,149 @@ GameCore.prototype.swapToward = function (block, targetY)
3274
3406
3275
3407
GameCore.prototype.swapBlocks = function (a, b)
3276
3408
{
3277
var y = a.y;
3278
a.y = b.y;
3279
b.y = y;
3409
var ay = a.y;
3410
var by = b.y;
3411
a.y = by;
3412
b.y = ay;
3280
3413
this.transferLandedMembership(a, b);
3414
if (!this.swapEvents)
3415
{ this.swapEvents = []; }
3416
this.swapEvents.push({ id: a.id, fromY: ay, toY: by, col: a.col });
3417
this.swapEvents.push({ id: b.id, fromY: by, toY: ay, col: b.col });
3418
};
3419
3420
GameCore.prototype.consumeSwapEvents = function ()
3421
{
3422
var ev = this.swapEvents || [];
3423
this.swapEvents = [];
3424
return ev;
3425
};
3426
3427
/**
3428
* Highest landing-chain counter among just-landed members of this
3429
* match group, plus one. Returns 0 when the match did not come from
3430
* a cluster landing (player/bot swap, mid-air, etc.).
3431
*/
3432
GameCore.prototype.landingChainFor = function (group)
3433
{
3434
var maxChain = 0;
3435
var fromLanding = false;
3436
for (var i = 0; i < group.length; i++)
3437
{
3438
var block = group[i];
3439
if (block.justLanded)
3440
{
3441
fromLanding = true;
3442
if ((block.landingChain || 0) > maxChain)
3443
{ maxChain = block.landingChain || 0; }
3444
}
3445
if (block.clusterId != null)
3446
{
3447
var cluster = this.clusters[block.clusterId];
3448
if (cluster && cluster.landedPending)
3449
{
3450
fromLanding = true;
3451
if ((cluster.landingChain || 0) > maxChain)
3452
{ maxChain = cluster.landingChain || 0; }
3453
}
3454
}
3455
}
3456
if (!fromLanding)
3457
{ return 0; }
3458
return maxChain + 1;
3459
};
3460
3461
/**
3462
* After resolveMatches: clear the landing-pending flag and reset the
3463
* chain on landings that did not make a match. A cluster that is still
3464
* settling (greys not yet recolored) keeps landedPending so a later
3465
* post-recolor match in this same landing still gets the bonus.
3466
*/
3467
GameCore.prototype.finishLandingChains = function (launched)
3468
{
3469
var launchedIds = Object.create(null);
3470
launched = launched || [];
3471
for (var i = 0; i < launched.length; i++)
3472
{
3473
var blocks = launched[i].blocks || [];
3474
for (var j = 0; j < blocks.length; j++)
3475
{ launchedIds[blocks[j].id] = true; }
3476
}
3477
3478
for (var i = 0; i < this.blocks.length; i++)
3479
{
3480
var block = this.blocks[i];
3481
if (!block.justLanded)
3482
{ continue; }
3483
if (!launchedIds[block.id])
3484
{ block.landingChain = 0; }
3485
block.justLanded = false;
3486
}
3487
3488
var ids = Object.keys(this.clusters);
3489
for (var c = 0; c < ids.length; c++)
3490
{
3491
var cluster = this.clusters[ids[c]];
3492
if (!cluster || !cluster.landedPending)
3493
{ continue; }
3494
var members = this.clusterMembers(cluster.id);
3495
var anyLaunched = false;
3496
var stillSettling = false;
3497
for (var i = 0; i < members.length; i++)
3498
{
3499
if (launchedIds[members[i].id])
3500
{ anyLaunched = true; }
3501
if (members[i].state === STATE_SETTLING)
3502
{ stillSettling = true; }
3503
}
3504
if (anyLaunched)
3505
{
3506
cluster.landingChain = 0;
3507
cluster.landedPending = false;
3508
}
3509
else if (!stillSettling)
3510
{
3511
// Released leftovers or a fully-still landed group that
3512
// already had its match opportunity and missed it.
3513
cluster.landingChain = 0;
3514
cluster.landedPending = false;
3515
}
3516
// else: still settling, no match yet — keep landedPending.
3517
}
3518
};
3519
3520
GameCore.prototype.updateChainIndicator = function (launched)
3521
{
3522
var maxChain = 0;
3523
for (var i = 0; i < launched.length; i++)
3524
{
3525
var ch = launched[i].landingChain || 0;
3526
if (ch > maxChain)
3527
{ maxChain = ch; }
3528
}
3529
if (maxChain >= 1)
3530
{
3531
this.lastChainIndicator = {
3532
chain: maxChain,
3533
bonusPct: Math.round(maxChain * LANDING_CHAIN_BONUS * 100)
3534
};
3535
return;
3536
}
3537
if (!this.hasActiveLandingChain())
3538
{ this.lastChainIndicator = null; }
3539
};
3540
3541
GameCore.prototype.hasActiveLandingChain = function ()
3542
{
3543
var ids = Object.keys(this.clusters);
3544
for (var i = 0; i < ids.length; i++)
3545
{
3546
var cluster = this.clusters[ids[i]];
3547
if (cluster && (cluster.landingChain || 0) >= 1
3548
&& cluster.phase !== 'landed')
3549
{ return true; }
3550
}
3551
return false;
3281
3552
};
3282
3553
3283
3554
/**
@@ -3811,6 +4082,19 @@ Online._drawMini = function (canvas, snapshot, planet)
3811
4082
}
3812
4083
if (!snapshot || !snapshot.blocks)
3813
4084
{ return; }
4085
// t1123: cheap sine pulse behind blocks of nearly-full columns.
4086
if (typeof GameCore !== 'undefined' && GameCore.warnColumnsFromSnapshot)
4087
{
4088
var warns = GameCore.warnColumnsFromSnapshot(snapshot);
4089
var pulse = GameCore.columnWarnPulse();
4090
for (var wc = 0; wc < warns.length; wc++)
4091
{
4092
if (!warns[wc])
4093
{ continue; }
4094
ctx.fillStyle = 'rgba(220, 36, 36,' + pulse + ')';
4095
ctx.fillRect(wc * tw, 0, tw, canvas.height);
4096
}
4097
}
3814
4098
var blocks = snapshot.blocks;
3815
4099
for (var i = 0; i < blocks.length; i++)
3816
4100
{
@@ -4014,146 +4298,792 @@ if (typeof module !== 'undefined' && module.exports)
4014
4298
4015
4299
/*
4016
4300
* Start File:
4017
* /workspace/meteors/src/main.js
4301
* /workspace/meteors/src/offline.js
4018
4302
*/
4019
4303
'use strict';
4020
4304
4021
4305
/**
4022
* View and input for Meteors. The simulation lives in GameCore; this file
4023
* only draws it, scales it to the viewport, and translates pointer events
4024
* into beginDrag / moveDrag / endDrag. Online play (stage 2) is wired
4025
* through Online (src/online.js) and the same GameCore.
4306
* Offline Strijd: a client-side single-player mode that plays like
4307
* multiplayer (shots, miss chance, opponent minis) against local bots
4308
* (t1119). Pure simulation — no server.
4026
4309
*/
4027
4310
4028
function planetImages ()
4311
var Offline = (function ()
4029
4312
{
4030
var list = [
4031
{ name: 'gray', url: 'images/block-gray.png' },
4032
{ name: 'locked', url: 'images/block-locked.png' },
4033
{ name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 },
4034
{ name: 'cell', url: 'images/cell.png' },
4035
{ name: 'pixel', url: 'images/pixel.png' },
4036
// Keep the original Terra placeholders as aliases (Tim may still have them).
4037
{ name: 'ember', url: 'images/block-ember.png' },
4038
{ name: 'aqua', url: 'images/block-aqua.png' },
4039
{ name: 'leaf', url: 'images/block-leaf.png' },
4040
{ name: 'sun', url: 'images/block-sun.png' },
4041
{ name: 'orchid', url: 'images/block-orchid.png' }
4042
];
4043
var planets = (typeof Planet !== 'undefined' ? Planet.allPlanets() : []);
4044
for (var i = 0; i < planets.length; i++)
4313
4314
var BOT_INTERVAL = 0.5;
4315
var SKILL_START = 0.05;
4316
var SKILL_STEP = 0.01;
4317
var SKILL_CAP = 1;
4318
var FLIGHT_DURATION = 1.2;
4319
var ROUND_WON_DELAY = 1.5;
4320
4321
/**
4322
* N opponents for N−1 rounds when N >= 2; 1 opponent for 1 round.
4323
* Documented in docs/ASSUMPTIONS.md (t1119).
4324
*/
4325
function roundsAtOpponentCount (n)
4326
{
4327
if (n <= 1)
4328
{ return 1; }
4329
return n - 1;
4330
}
4331
4332
function skillForRound (round)
4333
{
4334
var r = Math.max(1, Math.floor(Number(round) || 1));
4335
var pct = 5 + (r - 1);
4336
if (pct > 100)
4337
{ pct = 100; }
4338
return pct / 100;
4339
}
4340
4341
function scheduleForRound (round)
4342
{
4343
var r = Math.max(1, Math.floor(Number(round) || 1));
4344
var cursor = 1;
4345
var n = 1;
4346
for (;;)
4045
4347
{
4046
var pl = planets[i];
4047
for (var c = 0; c < pl.colors.length; c++)
4348
var count = roundsAtOpponentCount(n);
4349
if (r < cursor + count)
4048
4350
{
4049
list.push({
4050
name: Planet.spriteKey(pl, c),
4051
url: pl.colors[c].image
4052
});
4351
return {
4352
round: r,
4353
opponents: n,
4354
skill: skillForRound(r),
4355
roundsAtLevel: count,
4356
indexInLevel: r - cursor + 1
4357
};
4358
}
4359
cursor += count;
4360
n++;
4361
if (n > 10000)
4362
{
4363
return {
4364
round: r,
4365
opponents: n,
4366
skill: SKILL_CAP,
4367
roundsAtLevel: roundsAtOpponentCount(n),
4368
indexInLevel: 1
4369
};
4053
4370
}
4054
4371
}
4055
return list;
4056
4372
}
4057
4373
4058
var IMAGES = planetImages();
4059
var GAME_OVER_DELAY = 2;
4374
function GameCoreCtor ()
4375
{
4376
if (typeof GameCore !== 'undefined')
4377
{ return GameCore; }
4378
if (typeof module !== 'undefined')
4379
{ return require('./gameCore.js').GameCore; }
4380
return null;
4381
}
4060
4382
4061
var game = new Game();
4062
var app = {
4063
mode: 'menu',
4064
core: null,
4065
scene: null,
4066
manager: null,
4067
planet: null,
4068
lastScore: 0,
4069
tile: 48,
4070
fieldX: 0,
4071
fieldY: 0,
4072
fieldW: 0,
4073
fieldH: 0,
4074
hudH: 56,
4075
sprites: Object.create(null),
4076
flames: Object.create(null),
4077
cells: [],
4078
pointerId: null,
4079
pointerType: null,
4080
activeTouchId: null,
4081
debugDrag: false,
4082
debugPhysics: false,
4083
gameOverShown: false,
4084
selectTween: null,
4085
online: false,
4086
eliminatedReported: false,
4087
spectating: false,
4088
miniH: 0,
4089
selectedPlanetId: 'terra',
4090
planetSelectContext: 'solo'
4091
};
4383
function PlanetMod ()
4384
{
4385
if (typeof Planet !== 'undefined')
4386
{ return Planet; }
4387
if (typeof module !== 'undefined')
4388
{ return require('./planet.js'); }
4389
return null;
4390
}
4092
4391
4093
window.onload = function ()
4392
/**
4393
* Integer-row colour grid of grounded (still / settling / locked)
4394
* blocks, including greys (color < 0) so a swap can shift them.
4395
*/
4396
function snapshotGrid (core)
4094
4397
{
4095
app.debugDrag = isDragDebugEnabled();
4096
app.debugPhysics = isPhysicsDebugEnabled();
4097
var play = document.getElementById('btn-play');
4098
play.addEventListener('click', onPlay);
4099
play.addEventListener('pointerup', function (e)
4398
var width = core.width;
4399
var height = core.height;
4400
var grid = [];
4401
for (var c = 0; c < width; c++)
4100
4402
{
4101
// A touch-friendly path: some mobile browsers swallow the click
4102
// after a slightly sloppy tap. Ignore the following click.
4103
if (e.pointerType === 'touch' || e.pointerType === 'pen')
4104
{
4105
e.preventDefault();
4106
onPlay();
4107
}
4108
});
4109
4110
game.preloadImagesThenStart(IMAGES, function ()
4403
grid[c] = [];
4404
for (var r = 0; r < height; r++)
4405
{ grid[c][r] = null; }
4406
}
4407
for (var i = 0; i < core.blocks.length; i++)
4111
4408
{
4112
if (game.images.flame && game.images.flame.addAnimationCycle)
4113
{ game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); }
4114
});
4409
var b = core.blocks[i];
4410
if (!core.isGrounded(b))
4411
{ continue; }
4412
var row = Math.round(b.y);
4413
if (row < 0 || row >= height || b.col < 0 || b.col >= width)
4414
{ continue; }
4415
if (Math.abs(b.y - row) > 0.2)
4416
{ continue; }
4417
grid[b.col][row] = b.color;
4418
}
4419
return grid;
4420
}
4115
4421
4116
bindOnlineUi();
4117
bindPlanetSelect();
4118
restoreSelectedPlanet();
4119
};
4422
function cloneGrid (grid)
4423
{
4424
var out = [];
4425
for (var c = 0; c < grid.length; c++)
4426
{ out[c] = grid[c].slice(); }
4427
return out;
4428
}
4120
4429
4121
function onPlay ()
4430
/**
4431
* Apply swapToward's net result: the block at fromRow moves to toRow,
4432
* and the blocks it passed through each shift one cell toward fromRow.
4433
*/
4434
function applyColumnMove (grid, col, fromRow, toRow)
4122
4435
{
4123
if (app.mode === 'playing')
4436
if (fromRow === toRow)
4124
4437
{ return; }
4125
openPlanetSelect('solo');
4438
var moving = grid[col][fromRow];
4439
if (toRow > fromRow)
4440
{
4441
for (var y = fromRow; y < toRow; y++)
4442
{ grid[col][y] = grid[col][y + 1]; }
4443
grid[col][toRow] = moving;
4444
}
4445
else
4446
{
4447
for (var y = fromRow; y > toRow; y--)
4448
{ grid[col][y] = grid[col][y - 1]; }
4449
grid[col][toRow] = moving;
4450
}
4126
4451
}
4127
4452
4128
function startPlay (opts)
4453
function hasMatch (grid, width, height)
4129
4454
{
4130
opts = opts || {};
4131
hideEl('menu');
4132
hideEl('game-over');
4133
hideEl('online-panel');
4134
hideEl('spectator');
4135
hideEl('podium');
4136
hideEl('planet-select');
4137
showEl('hud');
4138
4139
var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod;
4140
app.planet = opts.planet || planetMod.planetById(selectedPlanetId());
4141
var miss = opts.missChance;
4142
if (typeof miss !== 'number' || !isFinite(miss))
4143
{ miss = planetMod.missChance(app.planet); }
4144
app.core = new GameCore(app.planet, Math.random, miss);
4145
if (app.debugPhysics)
4146
{ app.core.debugInvariants = true; }
4147
app.mode = 'playing';
4148
app.online = !!opts.online;
4149
app.gameOverShown = false;
4150
app.eliminatedReported = false;
4151
app.spectating = false;
4152
app.sprites = Object.create(null);
4153
app.flames = Object.create(null);
4154
app.cells = [];
4155
app.pointerId = null;
4455
var c, r, run, prev;
4456
for (r = 0; r < height; r++)
4457
{
4458
run = 0;
4459
prev = null;
4460
for (c = 0; c < width; c++)
4461
{
4462
var color = grid[c][r];
4463
if (color != null && color >= 0 && color === prev)
4464
{
4465
run++;
4466
if (run >= 3)
4467
{ return true; }
4468
}
4469
else
4470
{
4471
run = (color != null && color >= 0) ? 1 : 0;
4472
prev = (color != null && color >= 0) ? color : null;
4473
}
4474
}
4475
}
4476
for (c = 0; c < width; c++)
4477
{
4478
run = 0;
4479
prev = null;
4480
for (r = 0; r < height; r++)
4481
{
4482
var color = grid[c][r];
4483
if (color != null && color >= 0 && color === prev)
4484
{
4485
run++;
4486
if (run >= 3)
4487
{ return true; }
4488
}
4489
else
4490
{
4491
run = (color != null && color >= 0) ? 1 : 0;
4492
prev = (color != null && color >= 0) ? color : null;
4493
}
4494
}
4495
}
4496
return false;
4497
}
4498
4499
/**
4500
* Contiguous segments of draggable, nearly-integer-y blocks in a
4501
* column. Gaps break a segment the same way swapToward stops at gaps.
4502
*/
4503
function contiguousSegments (core, col)
4504
{
4505
if (!core.columnAllowsDrag(col))
4506
{ return []; }
4507
var list = core.blocksInColumn(col).filter(function (b)
4508
{
4509
return core.isDraggableBlock(b);
4510
});
4511
list.sort(function (a, b) { return a.y - b.y; });
4512
var segs = [];
4513
var cur = [];
4514
for (var i = 0; i < list.length; i++)
4515
{
4516
var y = list[i].y;
4517
if (Math.abs(y - Math.round(y)) > 0.15)
4518
{
4519
if (cur.length)
4520
{
4521
segs.push(cur);
4522
cur = [];
4523
}
4524
continue;
4525
}
4526
if (cur.length && Math.abs(y - (cur[cur.length - 1].y + 1)) > 0.15)
4527
{
4528
segs.push(cur);
4529
cur = [list[i]];
4530
}
4531
else
4532
{ cur.push(list[i]); }
4533
}
4534
if (cur.length)
4535
{ segs.push(cur); }
4536
return segs;
4537
}
4538
4539
/**
4540
* The shortest vertical move that would create a 3+ match, or null.
4541
* Ties break on lowest column, then lowest fromY, then lowest toY.
4542
*/
4543
function findBotMove (core)
4544
{
4545
var grid = snapshotGrid(core);
4546
if (hasMatch(grid, core.width, core.height))
4547
{ return null; }
4548
var best = null;
4549
for (var col = 0; col < core.width; col++)
4550
{
4551
var segs = contiguousSegments(core, col);
4552
for (var s = 0; s < segs.length; s++)
4553
{
4554
var seg = segs[s];
4555
if (seg.length < 2)
4556
{ continue; }
4557
for (var i = 0; i < seg.length; i++)
4558
{
4559
var fromY = Math.round(seg[i].y);
4560
for (var j = 0; j < seg.length; j++)
4561
{
4562
if (i === j)
4563
{ continue; }
4564
var toY = Math.round(seg[j].y);
4565
var dist = Math.abs(toY - fromY);
4566
if (best && dist > best.dist)
4567
{ continue; }
4568
var trial = cloneGrid(grid);
4569
applyColumnMove(trial, col, fromY, toY);
4570
if (!hasMatch(trial, core.width, core.height))
4571
{ continue; }
4572
var cand = {
4573
col: col,
4574
fromY: fromY,
4575
toY: toY,
4576
dist: dist,
4577
blockId: seg[i].id
4578
};
4579
if (!best || dist < best.dist
4580
|| (dist === best.dist && col < best.col)
4581
|| (dist === best.dist && col === best.col && fromY < best.fromY)
4582
|| (dist === best.dist && col === best.col && fromY === best.fromY
4583
&& toY < best.toY))
4584
{ best = cand; }
4585
}
4586
}
4587
}
4588
}
4589
return best;
4590
}
4591
4592
function executeBotMove (core, move)
4593
{
4594
if (!core || !move)
4595
{ return false; }
4596
var list = core.blocksInColumn(move.col);
4597
var block = null;
4598
for (var i = 0; i < list.length; i++)
4599
{
4600
if (move.blockId != null && list[i].id === move.blockId)
4601
{
4602
block = list[i];
4603
break;
4604
}
4605
if (Math.abs(list[i].y - move.fromY) < 0.2)
4606
{ block = list[i]; }
4607
}
4608
if (!block || !core.isDraggableBlock(block))
4609
{ return false; }
4610
core.swapToward(block, move.toY);
4611
return true;
4612
}
4613
4614
/**
4615
* One AI tick. `rng` is a () => [0,1) function. Success if roll < skill.
4616
* At skill 0 the bot never moves; at skill 1 it always looks for a move.
4617
*/
4618
function tryBotRoll (core, skill, rng)
4619
{
4620
rng = rng || Math.random;
4621
var roll = rng();
4622
if (!(roll < skill))
4623
{
4624
return { rolled: true, success: false, moved: false, roll: roll, move: null };
4625
}
4626
var move = findBotMove(core);
4627
if (!move)
4628
{
4629
return { rolled: true, success: true, moved: false, roll: roll, move: null };
4630
}
4631
var ok = executeBotMove(core, move);
4632
return { rolled: true, success: true, moved: !!ok, roll: roll, move: move };
4633
}
4634
4635
function pickPlanet (rng, P)
4636
{
4637
var all = P.allPlanets();
4638
if (!all.length)
4639
{ return P.defaultPlanet(); }
4640
var i = Math.floor(rng() * all.length) % all.length;
4641
return all[i];
4642
}
4643
4644
function OfflineBattle (opts)
4645
{
4646
opts = opts || {};
4647
var P = PlanetMod();
4648
this.playerPlanet = opts.playerPlanet || (P && P.defaultPlanet());
4649
this.rng = opts.rng || Math.random;
4650
this.round = opts.round || 1;
4651
this.schedule = scheduleForRound(this.round);
4652
this.clock = 0;
4653
this.state = 'playing';
4654
this.pending = [];
4655
this.flightResults = [];
4656
this.shotLocals = [];
4657
this.bots = [];
4658
this.playerId = 'player';
4659
this._initBots();
4660
}
4661
4662
OfflineBattle.prototype._initBots = function ()
4663
{
4664
var P = PlanetMod();
4665
var Ctor = GameCoreCtor();
4666
var n = this.schedule.opponents;
4667
this.bots = [];
4668
for (var i = 0; i < n; i++)
4669
{
4670
var planet = pickPlanet(this.rng, P);
4671
var miss = P.missChance(planet);
4672
var core = new Ctor(planet, this.rng, miss);
4673
this.bots.push({
4674
id: 'bot-' + (i + 1),
4675
name: 'Bot ' + (i + 1),
4676
planet: planet,
4677
core: core,
4678
eliminated: false,
4679
score: 0,
4680
aiAcc: 0
4681
});
4682
}
4683
};
4684
4685
OfflineBattle.prototype.aliveBots = function ()
4686
{
4687
var out = [];
4688
for (var i = 0; i < this.bots.length; i++)
4689
{
4690
if (!this.bots[i].eliminated && this.bots[i].core
4691
&& this.bots[i].core.state !== 'gameover')
4692
{ out.push(this.bots[i]); }
4693
}
4694
return out;
4695
};
4696
4697
OfflineBattle.prototype.coreFor = function (id, playerCore)
4698
{
4699
if (id === this.playerId)
4700
{ return playerCore; }
4701
for (var i = 0; i < this.bots.length; i++)
4702
{
4703
if (this.bots[i].id === id)
4704
{ return this.bots[i].core; }
4705
}
4706
return null;
4707
};
4708
4709
OfflineBattle.prototype._targetsFor = function (fromId, playerCore)
4710
{
4711
var targets = [];
4712
if (fromId !== this.playerId && playerCore && playerCore.state === 'playing')
4713
{ targets.push({ id: this.playerId, core: playerCore }); }
4714
for (var i = 0; i < this.bots.length; i++)
4715
{
4716
var bot = this.bots[i];
4717
if (bot.id === fromId || bot.eliminated)
4718
{ continue; }
4719
if (bot.core && bot.core.state === 'playing')
4720
{ targets.push({ id: bot.id, core: bot.core }); }
4721
}
4722
return targets;
4723
};
4724
4725
OfflineBattle.prototype._dispatchShots = function (fromId, core, planet, playerCore)
4726
{
4727
if (!core || !core.consumeOutgoingShots)
4728
{ return; }
4729
var shots = core.consumeOutgoingShots();
4730
if (!shots.length)
4731
{ return; }
4732
var P = PlanetMod();
4733
var missChance = (P && planet) ? P.missChance(planet) : 0.30;
4734
var targets = this._targetsFor(fromId, playerCore);
4735
for (var i = 0; i < shots.length; i++)
4736
{
4737
var shot = shots[i];
4738
var miss = targets.length === 0 || this.rng() < missChance;
4739
var target = null;
4740
if (!miss)
4741
{
4742
var idx = Math.floor(this.rng() * targets.length) % targets.length;
4743
target = targets[idx];
4744
}
4745
var clientId = fromId + '-' + shot.id + '-' + this.clock;
4746
var result = {
4747
client_id: clientId,
4748
miss: miss,
4749
target_id: target ? target.id : null,
4750
color: shot.color,
4751
flight_duration: FLIGHT_DURATION,
4752
from_id: fromId,
4753
col: shot.col,
4754
y: shot.y
4755
};
4756
this.flightResults.push(result);
4757
this.shotLocals.push({
4758
client_id: clientId,
4759
col: shot.col,
4760
y: shot.y,
4761
color: shot.color,
4762
from_id: fromId
4763
});
4764
if (!miss && target)
4765
{
4766
this.pending.push({
4767
at: this.clock + FLIGHT_DURATION,
4768
targetId: target.id,
4769
color: shot.color,
4770
fromId: fromId
4771
});
4772
}
4773
}
4774
};
4775
4776
OfflineBattle.prototype._deliver = function (playerCore)
4777
{
4778
var keep = [];
4779
for (var i = 0; i < this.pending.length; i++)
4780
{
4781
var ev = this.pending[i];
4782
if (this.clock + 1e-9 < ev.at)
4783
{
4784
keep.push(ev);
4785
continue;
4786
}
4787
var core = this.coreFor(ev.targetId, playerCore);
4788
if (core && core.state === 'playing' && core.ingestGarbage)
4789
{ core.ingestGarbage(); }
4790
}
4791
this.pending = keep;
4792
};
4793
4794
OfflineBattle.prototype.tick = function (dt, playerCore)
4795
{
4796
this.flightResults = [];
4797
this.shotLocals = [];
4798
if (this.state !== 'playing')
4799
{ return { flights: [], locals: [] }; }
4800
if (dt < 0)
4801
{ dt = 0; }
4802
this.clock += dt;
4803
4804
var skill = this.schedule.skill;
4805
for (var i = 0; i < this.bots.length; i++)
4806
{
4807
var bot = this.bots[i];
4808
if (bot.eliminated)
4809
{ continue; }
4810
if (bot.core.state === 'gameover')
4811
{
4812
bot.eliminated = true;
4813
bot.score = bot.core.score;
4814
continue;
4815
}
4816
bot.core.tick(dt);
4817
bot.score = bot.core.score;
4818
bot.aiAcc += dt;
4819
while (bot.aiAcc >= BOT_INTERVAL)
4820
{
4821
bot.aiAcc -= BOT_INTERVAL;
4822
if (bot.core.state === 'playing' && !bot.core.drag)
4823
{ tryBotRoll(bot.core, skill, this.rng); }
4824
}
4825
}
4826
4827
this._dispatchShots(this.playerId, playerCore, this.playerPlanet, playerCore);
4828
for (var i = 0; i < this.bots.length; i++)
4829
{
4830
var bot = this.bots[i];
4831
if (bot.eliminated)
4832
{ continue; }
4833
this._dispatchShots(bot.id, bot.core, bot.planet, playerCore);
4834
}
4835
this._deliver(playerCore);
4836
4837
for (var i = 0; i < this.bots.length; i++)
4838
{
4839
if (this.bots[i].core && this.bots[i].core.state === 'gameover')
4840
{
4841
this.bots[i].eliminated = true;
4842
this.bots[i].score = this.bots[i].core.score;
4843
}
4844
}
4845
4846
if (playerCore && playerCore.state === 'gameover')
4847
{ this.state = 'lost'; }
4848
else if (this.aliveBots().length === 0 && this.bots.length > 0)
4849
{ this.state = 'round_won'; }
4850
4851
return { flights: this.flightResults, locals: this.shotLocals };
4852
};
4853
4854
/**
4855
* Start the next round (fresh bots, new skill and opponent count).
4856
* The caller must also give the player a fresh GameCore.
4857
*/
4858
OfflineBattle.prototype.advanceRound = function ()
4859
{
4860
this.round += 1;
4861
this.schedule = scheduleForRound(this.round);
4862
this.state = 'playing';
4863
this.pending = [];
4864
this.flightResults = [];
4865
this.shotLocals = [];
4866
this.clock = 0;
4867
this._initBots();
4868
return this.schedule;
4869
};
4870
4871
function createBattle (opts)
4872
{
4873
return new OfflineBattle(opts);
4874
}
4875
4876
var api = {
4877
BOT_INTERVAL: BOT_INTERVAL,
4878
SKILL_START: SKILL_START,
4879
SKILL_STEP: SKILL_STEP,
4880
SKILL_CAP: SKILL_CAP,
4881
FLIGHT_DURATION: FLIGHT_DURATION,
4882
ROUND_WON_DELAY: ROUND_WON_DELAY,
4883
roundsAtOpponentCount: roundsAtOpponentCount,
4884
skillForRound: skillForRound,
4885
scheduleForRound: scheduleForRound,
4886
findBotMove: findBotMove,
4887
tryBotRoll: tryBotRoll,
4888
executeBotMove: executeBotMove,
4889
snapshotGrid: snapshotGrid,
4890
applyColumnMove: applyColumnMove,
4891
hasMatch: hasMatch,
4892
createBattle: createBattle,
4893
OfflineBattle: OfflineBattle
4894
};
4895
4896
if (typeof module !== 'undefined' && module.exports)
4897
{ module.exports = api; }
4898
else if (typeof globalThis !== 'undefined')
4899
{ globalThis.Offline = api; }
4900
4901
return api;
4902
4903
})();
4904
4905
if (typeof module !== 'undefined' && module.exports && typeof Offline !== 'undefined')
4906
{ module.exports = Offline; }
4907
4908
/*
4909
* End File:
4910
* /workspace/meteors/src/offline.js
4911
*/
4912
4913
/*
4914
* Start File:
4915
* /workspace/meteors/src/main.js
4916
*/
4917
'use strict';
4918
4919
/**
4920
* View and input for Meteors. The simulation lives in GameCore; this file
4921
* only draws it, scales it to the viewport, and translates pointer events
4922
* into beginDrag / moveDrag / endDrag. Online play (stage 2) is wired
4923
* through Online (src/online.js) and the same GameCore. Offline Strijd
4924
* (t1119) uses Offline (src/offline.js) against local bots.
4925
*/
4926
4927
function planetImages ()
4928
{
4929
var list = [
4930
{ name: 'gray', url: 'images/block-gray.png' },
4931
{ name: 'locked', url: 'images/block-locked.png' },
4932
{ name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 },
4933
{ name: 'cell', url: 'images/cell.png' },
4934
{ name: 'pixel', url: 'images/pixel.png' },
4935
{ name: 'columnWarn', url: 'images/column-warn.png' },
4936
// Keep the original Terra placeholders as aliases (Tim may still have them).
4937
{ name: 'ember', url: 'images/block-ember.png' },
4938
{ name: 'aqua', url: 'images/block-aqua.png' },
4939
{ name: 'leaf', url: 'images/block-leaf.png' },
4940
{ name: 'sun', url: 'images/block-sun.png' },
4941
{ name: 'orchid', url: 'images/block-orchid.png' }
4942
];
4943
var planets = (typeof Planet !== 'undefined' ? Planet.allPlanets() : []);
4944
for (var i = 0; i < planets.length; i++)
4945
{
4946
var pl = planets[i];
4947
for (var c = 0; c < pl.colors.length; c++)
4948
{
4949
list.push({
4950
name: Planet.spriteKey(pl, c),
4951
url: pl.colors[c].image
4952
});
4953
}
4954
}
4955
return list;
4956
}
4957
4958
var IMAGES = planetImages();
4959
var GAME_OVER_DELAY = 2;
4960
4961
var game = new Game();
4962
var app = {
4963
mode: 'menu',
4964
core: null,
4965
scene: null,
4966
manager: null,
4967
planet: null,
4968
lastScore: 0,
4969
tile: 48,
4970
fieldX: 0,
4971
fieldY: 0,
4972
fieldW: 0,
4973
fieldH: 0,
4974
hudH: 56,
4975
sprites: Object.create(null),
4976
flames: Object.create(null),
4977
cells: [],
4978
pointerId: null,
4979
pointerType: null,
4980
activeTouchId: null,
4981
debugDrag: false,
4982
debugPhysics: false,
4983
gameOverShown: false,
4984
selectTween: null,
4985
online: false,
4986
eliminatedReported: false,
4987
spectating: false,
4988
miniH: 0,
4989
selectedPlanetId: 'terra',
4990
planetSelectContext: 'solo',
4991
offline: false,
4992
battle: null,
4993
swapTweens: null,
4994
columnWarn: null,
4995
warnClock: 0,
4996
miniAcc: 0,
4997
offlineResultShown: false,
4998
roundWonDelay: 0,
4999
roundWonHandled: false
5000
};
5001
5002
window.onload = function ()
5003
{
5004
app.debugDrag = isDragDebugEnabled();
5005
app.debugPhysics = isPhysicsDebugEnabled();
5006
var play = document.getElementById('btn-play');
5007
play.addEventListener('click', onPlay);
5008
play.addEventListener('pointerup', function (e)
5009
{
5010
// A touch-friendly path: some mobile browsers swallow the click
5011
// after a slightly sloppy tap. Ignore the following click.
5012
if (e.pointerType === 'touch' || e.pointerType === 'pen')
5013
{
5014
e.preventDefault();
5015
onPlay();
5016
}
5017
});
5018
5019
game.preloadImagesThenStart(IMAGES, function ()
5020
{
5021
if (game.images.flame && game.images.flame.addAnimationCycle)
5022
{ game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); }
5023
});
5024
5025
bindOnlineUi();
5026
bindOfflineUi();
5027
bindPlanetSelect();
5028
restoreSelectedPlanet();
5029
};
5030
5031
function onPlay ()
5032
{
5033
if (app.mode === 'playing')
5034
{ return; }
5035
openPlanetSelect('solo');
5036
}
5037
5038
function startPlay (opts)
5039
{
5040
opts = opts || {};
5041
hideEl('menu');
5042
hideEl('game-over');
5043
hideEl('online-panel');
5044
hideEl('spectator');
5045
hideEl('podium');
5046
hideEl('planet-select');
5047
hideEl('offline-result');
5048
showEl('hud');
5049
5050
var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod;
5051
app.planet = opts.planet || planetMod.planetById(selectedPlanetId());
5052
var miss = opts.missChance;
5053
if (typeof miss !== 'number' || !isFinite(miss))
5054
{ miss = planetMod.missChance(app.planet); }
5055
app.core = new GameCore(app.planet, Math.random, miss);
5056
if (app.debugPhysics)
5057
{ app.core.debugInvariants = true; }
5058
app.mode = 'playing';
5059
app.online = !!opts.online;
5060
app.offline = !!opts.offline;
5061
app.gameOverShown = false;
5062
app.eliminatedReported = false;
5063
app.spectating = false;
5064
app.sprites = Object.create(null);
5065
app.flames = Object.create(null);
5066
app.cells = [];
5067
app.pointerId = null;
4156
5068
app.selectTween = null;
5069
app.swapTweens = Object.create(null);
5070
app.columnWarn = [];
5071
app.warnClock = 0;
5072
app.miniAcc = 1; // draw minis on the first frame
5073
app.offlineResultShown = false;
5074
if (!opts.keepBattle)
5075
{
5076
app.roundWonDelay = 0;
5077
app.roundWonHandled = false;
5078
}
5079
if (app.offline && !opts.keepBattle && typeof Offline !== 'undefined')
5080
{
5081
app.battle = Offline.createBattle({
5082
playerPlanet: app.planet,
5083
rng: Math.random,
5084
round: opts.round || 1
5085
});
5086
}
4157
5087
4158
5088
layout();
4159
5089
if (app.scene)
@@ -4171,10 +5101,13 @@ function startPlay (opts)
4171
5101
if (!app.spectating)
4172
5102
{ bindPointer(app.scene.canvas); }
4173
5103
refreshHud();
4174
if (app.online)
5104
if (app.online || app.offline)
4175
5105
{ showEl('minis'); }
4176
5106
else
4177
5107
{ hideEl('minis'); }
5108
buildColumnWarn();
5109
refreshOfflineHud();
5110
refreshChainIndicator();
4178
5111
}
4179
5112
4180
5113
function teardownPlay ()
@@ -4191,14 +5124,25 @@ function teardownPlay ()
4191
5124
app.flames = Object.create(null);
4192
5125
app.cells = [];
4193
5126
app.selectTween = null;
5127
app.swapTweens = Object.create(null);
5128
app.columnWarn = [];
4194
5129
app.pointerId = null;
4195
5130
app.gameOverShown = false;
4196
5131
hideEl('hud');
4197
5132
hideEl('game-over');
4198
5133
hideEl('spectator');
4199
5134
hideEl('minis');
5135
hideEl('offline-result');
5136
hideOfflineHud();
5137
hideChainIndicator();
4200
5138
if (typeof Online !== 'undefined')
4201
5139
{ Online.clearFlights(); }
5140
if (!app._keepBattleOnTeardown)
5141
{
5142
app.battle = null;
5143
app.offline = false;
5144
}
5145
app._keepBattleOnTeardown = false;
4202
5146
}
4203
5147
4204
5148
function returnToMenu ()
@@ -4212,6 +5156,8 @@ function returnToMenu ()
4212
5156
teardownPlay();
4213
5157
app.mode = 'menu';
4214
5158
app.online = false;
5159
app.offline = false;
5160
app.battle = null;
4215
5161
hideEl('planet-select');
4216
5162
showEl('menu');
4217
5163
var last = document.getElementById('last-score');
@@ -4276,8 +5222,12 @@ function layout ()
4276
5222
catch (e) { /* ignore */ }
4277
5223
app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop);
4278
5224
app.miniH = 0;
4279
if (app.online)
4280
{ app.miniH = Math.min(150, Math.max(86, Math.round(vh * 0.20))); }
5225
if (app.online || app.offline)
5226
{
5227
var nBots = (app.battle && app.battle.bots) ? app.battle.bots.length : 2;
5228
var share = nBots > 6 ? 0.26 : 0.20;
5229
app.miniH = Math.min(nBots > 6 ? 180 : 150, Math.max(86, Math.round(vh * share)));
5230
}
4281
5231
var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015));
4282
5232
var availW = Math.max(80, vw - margin * 2);
4283
5233
var availH = Math.max(80, vh - app.hudH - app.miniH - margin);
@@ -4315,10 +5265,13 @@ function spriteFor (block)
4315
5265
return game.images[key] || game.images.gray;
4316
5266
}
4317
5267
4318
function syncSprites ()
5268
function syncSprites (dt)
4319
5269
{
4320
5270
if (!app.core || !app.scene)
4321
5271
{ return; }
5272
dt = dt || 0;
5273
consumeAndStartSwapTweens();
5274
advanceSwapTweens(dt);
4322
5275
var seen = Object.create(null);
4323
5276
var blocks = app.core.blocks;
4324
5277
for (var i = 0; i < blocks.length; i++)
@@ -4333,7 +5286,7 @@ function syncSprites ()
4333
5286
app.sprites[block.id] = obj;
4334
5287
}
4335
5288
obj.renderer.sprite = spriteFor(block);
4336
placeTile(obj, block.col, block.y);
5289
placeTile(obj, block.col, blockVisualY(block));
4337
5290
applyBlockVisual(obj, block);
4338
5291
obj.renderer.visible = true;
4339
5292
obj.renderer.alpha = 1;
@@ -4471,6 +5424,95 @@ function updateSelectTween (dt)
4471
5424
tw.scale = ease ? Easing.tween(tw.from, tw.to, u, ease) : tw.from + (tw.to - tw.from) * u;
4472
5425
}
4473
5426
5427
5428
/* ---------- visual-only swap tween (t1121) -------------------------- */
5429
5430
function swapTweenSpec ()
5431
{
5432
if (typeof Easing !== 'undefined' && Easing.SWAP_TWEEN)
5433
{ return Easing.SWAP_TWEEN; }
5434
return { duration: 0.100, ease: null };
5435
}
5436
5437
function swapEase (u)
5438
{
5439
if (typeof Easing !== 'undefined' && Easing.easeOutCubic)
5440
{ return Easing.easeOutCubic(u); }
5441
var v = 1 - Math.max(0, Math.min(1, u));
5442
return 1 - v * v * v;
5443
}
5444
5445
function tweenVisualY (tw)
5446
{
5447
var u = tw.duration > 0 ? Math.min(1, tw.age / tw.duration) : 1;
5448
return tw.fromY + (tw.toY - tw.fromY) * swapEase(u);
5449
}
5450
5451
/**
5452
* Consume GameCore swap events. The currently dragged block is skipped
5453
* (it follows the pointer). A block that is mid-tween and is swapped
5454
* again restarts from its current visual y, so rapid swaps chain
5455
* smoothly without snapping.
5456
*/
5457
function consumeAndStartSwapTweens ()
5458
{
5459
if (!app.core || !app.core.consumeSwapEvents)
5460
{ return; }
5461
if (!app.swapTweens)
5462
{ app.swapTweens = Object.create(null); }
5463
var ev = app.core.consumeSwapEvents();
5464
if (!ev.length)
5465
{ return; }
5466
var dragId = app.core.drag && app.core.drag.blockId;
5467
var duration = swapTweenSpec().duration;
5468
for (var i = 0; i < ev.length; i++)
5469
{
5470
var e = ev[i];
5471
if (e.id === dragId)
5472
{
5473
delete app.swapTweens[e.id];
5474
continue;
5475
}
5476
var fromY = e.fromY;
5477
var existing = app.swapTweens[e.id];
5478
if (existing)
5479
{ fromY = tweenVisualY(existing); }
5480
app.swapTweens[e.id] = {
5481
fromY: fromY,
5482
toY: e.toY,
5483
age: 0,
5484
duration: duration
5485
};
5486
}
5487
}
5488
5489
function advanceSwapTweens (dt)
5490
{
5491
if (!app.swapTweens)
5492
{ return; }
5493
var ids = Object.keys(app.swapTweens);
5494
for (var i = 0; i < ids.length; i++)
5495
{
5496
var tw = app.swapTweens[ids[i]];
5497
tw.age += dt;
5498
if (tw.age >= tw.duration)
5499
{ delete app.swapTweens[ids[i]]; }
5500
}
5501
}
5502
5503
function blockVisualY (block)
5504
{
5505
if (!app.swapTweens)
5506
{ return block.y; }
5507
var dragId = app.core && app.core.drag && app.core.drag.blockId;
5508
if (block.id === dragId)
5509
{ return block.y; }
5510
var tw = app.swapTweens[block.id];
5511
if (!tw)
5512
{ return block.y; }
5513
return tweenVisualY(tw);
5514
}
5515
4474
5516
function refreshHud ()
4475
5517
{
4476
5518
if (!app.core)
@@ -4512,9 +5554,14 @@ function tickView (dt)
4512
5554
}
4513
5555
4514
5556
app.core.tick(dt);
5557
if (app.offline && app.battle)
5558
{ tickOffline(dt); }
4515
5559
updateSelectTween(dt);
4516
syncSprites();
5560
syncSprites(dt);
5561
updateColumnWarn(dt);
4517
5562
refreshHud();
5563
refreshOfflineHud();
5564
refreshChainIndicator();
4518
5565
tickOnline(dt);
4519
5566
if (app.debugPhysics)
4520
5567
{ logPhysicsDebug(); }
@@ -4526,10 +5573,13 @@ function tickView (dt)
4526
5573
document.getElementById('go-score').textContent = String(app.lastScore);
4527
5574
if (app.online)
4528
5575
{ onOnlineEliminated(); }
5576
else if (app.offline)
5577
{ /* Offline result is shown from tickOffline. */ }
4529
5578
else
4530
5579
{ showEl('game-over'); }
4531
5580
}
4532
if (!app.online && app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY)
5581
if (!app.online && !app.offline && app.core.state === 'gameover'
5582
&& app.core.gameOverTime >= GAME_OVER_DELAY)
4533
5583
{ returnToMenu(); }
4534
5584
}
4535
5585
@@ -5032,6 +6082,313 @@ function tickOnline (dt)
5032
6082
Online.renderMinis(document.getElementById('minis'));
5033
6083
}
5034
6084
6085
6086
/* ---------- Offline Strijd (t1119) + column warn (t1123) ----------- */
6087
6088
function bindOfflineUi ()
6089
{
6090
var btn = document.getElementById('btn-offline');
6091
if (btn)
6092
{
6093
btn.addEventListener('click', onOffline);
6094
btn.addEventListener('pointerup', function (e)
6095
{
6096
if (e.pointerType === 'touch' || e.pointerType === 'pen')
6097
{
6098
e.preventDefault();
6099
onOffline();
6100
}
6101
});
6102
}
6103
var back = document.getElementById('btn-offline-menu');
6104
if (back)
6105
{
6106
back.addEventListener('click', function ()
6107
{
6108
teardownPlay();
6109
app.mode = 'menu';
6110
app.offline = false;
6111
app.battle = null;
6112
hideEl('offline-result');
6113
showEl('menu');
6114
});
6115
}
6116
}
6117
6118
function onOffline ()
6119
{
6120
openPlanetSelect('offline');
6121
}
6122
6123
function tickOffline (dt)
6124
{
6125
if (!app.battle || !app.core || typeof Offline === 'undefined')
6126
{ return; }
6127
6128
if (app.battle.state === 'round_won')
6129
{
6130
if (!app.roundWonHandled)
6131
{
6132
app.roundWonHandled = true;
6133
app.roundWonDelay = Offline.ROUND_WON_DELAY || 1.5;
6134
}
6135
app.roundWonDelay -= dt;
6136
if (app.roundWonDelay <= 0)
6137
{ startNextOfflineRound(); }
6138
updateOfflineMinis(dt, true);
6139
return;
6140
}
6141
6142
var result = app.battle.tick(dt, app.core);
6143
if (result && result.flights && result.flights.length
6144
&& typeof Online !== 'undefined' && Online.spawnFlights)
6145
{
6146
var locals = Object.create(null);
6147
var list = result.locals || [];
6148
for (var i = 0; i < list.length; i++)
6149
{
6150
var s = list[i];
6151
var start;
6152
if (s.from_id === 'player')
6153
{ start = fieldToViewport(s.col, s.y + 1); }
6154
else
6155
{ start = miniViewportCenter(s.from_id); }
6156
locals[s.client_id] = {
6157
col: s.col,
6158
y: s.y,
6159
color: s.color,
6160
startX: start.x,
6161
startY: start.y
6162
};
6163
}
6164
Online.spawnFlights(result.flights, locals);
6165
}
6166
if (typeof Online !== 'undefined' && Online.tickFlights)
6167
{ Online.tickFlights(); }
6168
updateOfflineMinis(dt, false);
6169
6170
if (app.battle.state === 'lost' && !app.offlineResultShown)
6171
{ showOfflineResult(); }
6172
}
6173
6174
function startNextOfflineRound ()
6175
{
6176
if (!app.battle)
6177
{ return; }
6178
app.battle.advanceRound();
6179
app.roundWonHandled = false;
6180
app.roundWonDelay = 0;
6181
app._keepBattleOnTeardown = true;
6182
// Tear down the current scene then start a fresh player field,
6183
// keeping the same battle (already advanced).
6184
var planet = app.battle.playerPlanet;
6185
app._keepBattleOnTeardown = true;
6186
teardownPlay();
6187
app.offline = true;
6188
app.battle = app.battle; // kept
6189
startPlay({ planet: planet, offline: true, keepBattle: true });
6190
}
6191
6192
function showOfflineResult ()
6193
{
6194
app.offlineResultShown = true;
6195
var battle = app.battle;
6196
var reached = document.getElementById('offline-reached');
6197
if (reached)
6198
{ reached.textContent = String(battle.round); }
6199
var detail = document.getElementById('offline-result-detail');
6200
if (detail)
6201
{
6202
var sch = battle.schedule;
6203
var n = sch.opponents;
6204
var noun = n === 1 ? 'tegenstander' : 'tegenstanders';
6205
detail.textContent = 'Je speelde tegen ' + n + ' ' + noun
6206
+ ' met skill ' + Math.round(sch.skill * 100) + '%.';
6207
}
6208
hideEl('game-over');
6209
showEl('offline-result');
6210
}
6211
6212
function refreshOfflineHud ()
6213
{
6214
var el = document.getElementById('offline-hud');
6215
if (!el)
6216
{ return; }
6217
if (!(app.offline && app.battle && app.mode === 'playing'))
6218
{
6219
el.hidden = true;
6220
return;
6221
}
6222
el.hidden = false;
6223
var sch = app.battle.schedule;
6224
var n = sch.opponents;
6225
var noun = n === 1 ? 'tegenstander' : 'tegenstanders';
6226
var r = document.getElementById('offline-round');
6227
var o = document.getElementById('offline-opponents');
6228
var s = document.getElementById('offline-skill');
6229
if (r)
6230
{ r.textContent = 'Ronde ' + sch.round; }
6231
if (o)
6232
{ o.textContent = n + ' ' + noun; }
6233
if (s)
6234
{ s.textContent = 'Skill ' + Math.round(sch.skill * 100) + '%'; }
6235
}
6236
6237
function hideOfflineHud ()
6238
{
6239
var el = document.getElementById('offline-hud');
6240
if (el)
6241
{ el.hidden = true; }
6242
}
6243
6244
function refreshChainIndicator ()
6245
{
6246
var el = document.getElementById('chain-indicator');
6247
if (!el)
6248
{ return; }
6249
var info = app.core && app.core.lastChainIndicator;
6250
var active = app.core && app.core.hasActiveLandingChain
6251
&& app.core.hasActiveLandingChain();
6252
// Show only while a chained cluster is still in the air.
6253
if (!info || info.chain < 1 || app.mode !== 'playing' || !active)
6254
{
6255
el.hidden = true;
6256
return;
6257
}
6258
el.hidden = false;
6259
el.textContent = 'x' + info.chain + ' +' + info.bonusPct + '%';
6260
}
6261
6262
function hideChainIndicator ()
6263
{
6264
var el = document.getElementById('chain-indicator');
6265
if (el)
6266
{ el.hidden = true; }
6267
}
6268
6269
function miniViewportCenter (botId)
6270
{
6271
var el = document.querySelector('#minis .mini[data-player="' + botId + '"] canvas');
6272
if (!el)
6273
{ return { x: window.innerWidth / 2, y: 40 }; }
6274
var rect = el.getBoundingClientRect();
6275
return { x: rect.left + rect.width / 2, y: rect.bottom };
6276
}
6277
6278
function offlineMiniSize (n)
6279
{
6280
if (n >= 10)
6281
{ return { w: 40, h: 52 }; }
6282
if (n >= 6)
6283
{ return { w: 56, h: 73 }; }
6284
return { w: 80, h: 104 };
6285
}
6286
6287
function updateOfflineMinis (dt, force)
6288
{
6289
app.miniAcc = (app.miniAcc || 0) + dt;
6290
if (!force && app.miniAcc < 0.1)
6291
{ return; }
6292
app.miniAcc = 0;
6293
renderOfflineMinis();
6294
}
6295
6296
function renderOfflineMinis ()
6297
{
6298
var container = document.getElementById('minis');
6299
if (!container || !app.battle)
6300
{ return; }
6301
var bots = app.battle.bots;
6302
var size = offlineMiniSize(bots.length);
6303
container.classList.toggle('crowded', bots.length > 5);
6304
var existing = {};
6305
var kids = container.querySelectorAll('[data-player]');
6306
for (var i = 0; i < kids.length; i++)
6307
{ existing[kids[i].getAttribute('data-player')] = kids[i]; }
6308
var seen = Object.create(null);
6309
for (var i = 0; i < bots.length; i++)
6310
{
6311
var bot = bots[i];
6312
seen[bot.id] = true;
6313
var el = existing[bot.id];
6314
if (!el)
6315
{
6316
el = document.createElement('div');
6317
el.className = 'mini';
6318
el.setAttribute('data-player', bot.id);
6319
el.innerHTML = '<div class="mini-name"></div>'
6320
+ '<canvas class="mini-canvas" width="' + size.w
6321
+ '" height="' + size.h + '"></canvas>'
6322
+ '<div class="mini-meta"></div>';
6323
container.appendChild(el);
6324
}
6325
var canvas = el.querySelector('canvas');
6326
if (canvas && (canvas.width !== size.w || canvas.height !== size.h))
6327
{
6328
canvas.width = size.w;
6329
canvas.height = size.h;
6330
}
6331
el.classList.toggle('eliminated', !!bot.eliminated);
6332
var planetName = bot.planet && bot.planet.name ? bot.planet.name : '';
6333
el.querySelector('.mini-name').textContent = bot.name
6334
+ (planetName ? ' · ' + planetName : '');
6335
el.querySelector('.mini-meta').textContent = bot.eliminated
6336
? 'Uit'
6337
: ('Punten ' + (bot.score || 0));
6338
var snap = bot.core ? bot.core.fieldSnapshot() : { blocks: [] };
6339
if (typeof Online !== 'undefined' && Online._drawMini)
6340
{ Online._drawMini(canvas, snap, bot.planet); }
6341
}
6342
for (var id in existing)
6343
{
6344
if (!seen[id])
6345
{ existing[id].remove(); }
6346
}
6347
}
6348
6349
function buildColumnWarn ()
6350
{
6351
app.columnWarn = [];
6352
if (!app.scene)
6353
{ return; }
6354
var img = (game.images && (game.images.columnWarn || game.images.pixel)) || null;
6355
if (!img)
6356
{ return; }
6357
for (var c = 0; c < 10; c++)
6358
{
6359
var obj = new GameObject(0, 0, img, 0);
6360
obj.renderer.alpha = 0;
6361
obj.renderer.visible = false;
6362
app.scene.addObject(obj);
6363
app.columnWarn.push(obj);
6364
}
6365
updateColumnWarn(0);
6366
}
6367
6368
function updateColumnWarn (dt)
6369
{
6370
if (!app.columnWarn || !app.core)
6371
{ return; }
6372
app.warnClock = (app.warnClock || 0) + (dt || 0);
6373
var pulse = (typeof GameCore !== 'undefined' && GameCore.columnWarnPulse)
6374
? GameCore.columnWarnPulse(app.warnClock)
6375
: 0.16 + 0.28 * (0.5 + 0.5 * Math.sin(app.warnClock * 3.45575));
6376
var t = app.tile;
6377
for (var c = 0; c < app.columnWarn.length; c++)
6378
{
6379
var obj = app.columnWarn[c];
6380
var on = app.core.columnNeedsWarn && app.core.columnNeedsWarn(c);
6381
obj.renderer.visible = !!on;
6382
obj.renderer.alpha = on ? pulse : 0;
6383
if (t)
6384
{
6385
obj.transform.position.x = c * t + t / 2;
6386
obj.transform.position.y = app.fieldH / 2;
6387
obj.transform.size = { x: t, y: app.fieldH };
6388
}
6389
}
6390
}
6391
5035
6392
function fieldToViewport (col, fieldY)
5036
6393
{
5037
6394
var canvas = app.scene && app.scene.canvas;
@@ -5519,6 +6876,11 @@ function confirmPlanetSelect ()
5519
6876
openOnlinePanel();
5520
6877
return;
5521
6878
}
6879
if (app.planetSelectContext === 'offline')
6880
{
6881
startPlay({ planet: planet, offline: true });
6882
return;
6883
}
5522
6884
startPlay({ planet: planet });
5523
6885
}
5524
6886
@@ -256,10 +256,16 @@ else if (typeof globalThis !== 'undefined')256
* that later planets only need new data, not new physics code.256
* that later planets only need new data, not new physics code.257
*257
*258
* Gravity (jumpsToClear): 1 (easy, high jump) .. 4 (hard, short jump).258
* Gravity (jumpsToClear): 1 (easy, high jump) .. 4 (hard, short jump).259
* A horizontal match of 3 jumps FIELD_HEIGHT / jumpsToClear tiles —259
* A horizontal match of 3 jumps JUMP_HEIGHT_SCALE * FIELD_HEIGHT260
* at 1, one jump from the floor clears the field; at 4, you need four.260
* / jumpsToClear tiles (JUMP_HEIGHT_SCALE is 1.5 since t1119: the261
* minimum jump is 50% higher). At gravity 1 that is 19.5 tiles, so262
* one jump from the floor clears the 13-tile field with room to spare;263
* at 4 you still need more than one jump, but each is 50% taller.261
* Air (fallTime): 1 s (hard, fast fall) .. 5 s (easy, slow fall).264
* Air (fallTime): 1 s (hard, fast fall) .. 5 s (easy, slow fall).262
* After a jump peaks, blocks float down at FIELD_HEIGHT / fallTime tiles/s.265
* After a jump peaks, blocks float down at DESCENT_SPEED_SCALE *266
* FIELD_HEIGHT / fallTime tiles/s (DESCENT_SPEED_SCALE is 0.5 since267
* t1122: all descent speeds are halved). Relative differences between268
* planets (1 / fallTime) are unchanged. Upward launch is not affected.263
* Mass (riseTime): 0.5 s (hard, fast jump) .. 3 s (easy, slow jump).269
* Mass (riseTime): 0.5 s (hard, fast jump) .. 3 s (easy, slow jump).264
* Time to reach the apex, independent of jump height.270
* Time to reach the apex, independent of jump height.265
*271
*@@ -274,6 +280,14 @@ else if (typeof globalThis !== 'undefined')274
280
275
var FIELD_WIDTH = 10;281
var FIELD_WIDTH = 10;276
var FIELD_HEIGHT = 13;282
var FIELD_HEIGHT = 13;283
/** t1119: every match jump (the gravity-applied minimum and the284
* vertical / extra-block bonuses derived from it) is 50% higher. */285
var JUMP_HEIGHT_SCALE = 1.5;286
/** t1122: every descent speed is halved. Terminal fallSpeed, spawn287
* fall, unsupported / released / cargo fall, and the post-apex288
* float-down all use this scale. Upward launch is unchanged. */289
var DESCENT_SPEED_SCALE = 0.5;290
277
291
278
function clamp (value, lo, hi)292
function clamp (value, lo, hi)279
{293
{@@ -306,12 +320,14 @@ function createPlanet (opts)306
fallTime: fallTime,320
fallTime: fallTime,307
riseTime: riseTime,321
riseTime: riseTime,308
colors: colors,322
colors: colors,309
baseJumpHeight: FIELD_HEIGHT / jumpsToClear,323
baseJumpHeight: JUMP_HEIGHT_SCALE * FIELD_HEIGHT / jumpsToClear,310
fallSpeed: FIELD_HEIGHT / fallTime,324
fallSpeed: DESCENT_SPEED_SCALE * FIELD_HEIGHT / fallTime,311
// Time to ease from vy=0 at the apex to terminal fallSpeed.325
// Time to ease from vy=0 at the apex to terminal fallSpeed.312
// Shorter when air resistance is low (small fallTime).326
// Shorter when air resistance is low (small fallTime). The ease327
// duration is unchanged; fallAccel scales with the halved328
// fallSpeed so the ease still lasts apexEaseTime seconds.313
apexEaseTime: 0.15 * fallTime,329
apexEaseTime: 0.15 * fallTime,314
fallAccel: (FIELD_HEIGHT / fallTime) / (0.15 * fallTime),330
fallAccel: (DESCENT_SPEED_SCALE * FIELD_HEIGHT / fallTime) / (0.15 * fallTime),315
// Visual landing bounce: faster at low air resistance. Stage-3 params.331
// Visual landing bounce: faster at low air resistance. Stage-3 params.316
bounceDuration: 0.12 * fallTime,332
bounceDuration: 0.12 * fallTime,317
bounceSquash: 0.16333
bounceSquash: 0.16@@ -480,6 +496,8 @@ function displayValues (planet)480
var Planet = {496
var Planet = {481
FIELD_WIDTH: FIELD_WIDTH,497
FIELD_WIDTH: FIELD_WIDTH,482
FIELD_HEIGHT: FIELD_HEIGHT,498
FIELD_HEIGHT: FIELD_HEIGHT,499
JUMP_HEIGHT_SCALE: JUMP_HEIGHT_SCALE,500
DESCENT_SPEED_SCALE: DESCENT_SPEED_SCALE,483
COLOR_COUNT: 5,501
COLOR_COUNT: 5,484
SETTLE_TIME: 3,502
SETTLE_TIME: 3,485
SPAWN_INTERVAL: 1,503
SPAWN_INTERVAL: 1,@@ -571,11 +589,29 @@ function easeOutElastic (t)571
return Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p) + 1;589
return Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p) + 1;572
}590
}573
591
592
/** easeOutCubic: 1 − (1−t)³. Smooth, no overshoot (easings.net). */593
function easeOutCubic (t)594
{595
t = clamp01(t);596
var u = 1 - t;597
return 1 - u * u * u;598
}599
574
function tween (from, to, t, ease)600
function tween (from, to, t, ease)575
{601
{576
return from + (to - from) * ease(clamp01(t));602
return from + (to - from) * ease(clamp01(t));577
}603
}578
604
605
/**606
* Visual-only block swap tween (t1121). Game logic and the grid update607
* immediately; this only moves the displaced sprite. 100 ms sits in the608
* requested 80–120 ms range.609
*/610
var SWAP_TWEEN = {611
duration: 0.100,612
ease: easeOutCubic613
};614
579
/**615
/**580
* DEFAULT settings of Tim's KWin Click Tween616
* DEFAULT settings of Tim's KWin Click Tween581
* (git.timfalken.com/timfa/click-tween).617
* (git.timfalken.com/timfa/click-tween).@@ -619,8 +655,10 @@ var Easing = {619
ELASTIC_AMPLITUDE: ELASTIC_AMPLITUDE,655
ELASTIC_AMPLITUDE: ELASTIC_AMPLITUDE,620
easeOutBack: easeOutBack,656
easeOutBack: easeOutBack,621
easeOutElastic: easeOutElastic,657
easeOutElastic: easeOutElastic,658
easeOutCubic: easeOutCubic,622
tween: tween,659
tween: tween,623
CLICK_TWEEN: CLICK_TWEEN,660
CLICK_TWEEN: CLICK_TWEEN,661
SWAP_TWEEN: SWAP_TWEEN,624
clamp01: clamp01,662
clamp01: clamp01,625
bouncePose: bouncePose663
bouncePose: bouncePose626
};664
};@@ -672,6 +710,13 @@ var SWAP_DISTANCE = 0.25;672
var SNAP_Y = 0.5;710
var SNAP_Y = 0.5;673
// Horizontal slop (tiles) for snapping to a neighbouring column on press.711
// Horizontal slop (tiles) for snapping to a neighbouring column on press.674
var HORIZONTAL_SLOP = 0.35;712
var HORIZONTAL_SLOP = 0.35;713
/** t1120: additive jump bonus per landing-chain step. A landing that714
* immediately makes a match launches at (1 + 0.25 * chain) times the715
* usual height, with chain 1, 2, 3, … → ×1.25, ×1.50, ×1.75. */716
var LANDING_CHAIN_BONUS = 0.25;717
/** t1123: a column pulses red at or above this many grounded rows718
* (10 of 13 is just over 70%). */719
var COLUMN_WARN_ROWS = 10;675
720
676
function UnionFind ()721
function UnionFind ()677
{722
{@@ -726,6 +771,10 @@ function GameCore (planet, rng)726
this.strictInvariants = false;771
this.strictInvariants = false;727
this.debugInvariants = false;772
this.debugInvariants = false;728
this.lastInvariantViolations = [];773
this.lastInvariantViolations = [];774
// t1121: visual-only swap events, consumed by the view each frame.775
this.swapEvents = [];776
// t1120: last landing-chain indicator { chain, bonusPct }, or null.777
this.lastChainIndicator = null;729
}778
}730
779
731
function optsMissChance (args)780
function optsMissChance (args)@@ -744,6 +793,8 @@ GameCore.LAUNCH_PULL = LAUNCH_PULL;744
GameCore.SWAP_DISTANCE = SWAP_DISTANCE;793
GameCore.SWAP_DISTANCE = SWAP_DISTANCE;745
GameCore.SNAP_Y = SNAP_Y;794
GameCore.SNAP_Y = SNAP_Y;746
GameCore.HORIZONTAL_SLOP = HORIZONTAL_SLOP;795
GameCore.HORIZONTAL_SLOP = HORIZONTAL_SLOP;796
GameCore.LANDING_CHAIN_BONUS = LANDING_CHAIN_BONUS;797
GameCore.COLUMN_WARN_ROWS = COLUMN_WARN_ROWS;747
GameCore.DEFAULT_MISS_CHANCE = 0.30;798
GameCore.DEFAULT_MISS_CHANCE = 0.30;748
GameCore.STATE_STILL = STATE_STILL;799
GameCore.STATE_STILL = STATE_STILL;749
GameCore.STATE_FALLING = STATE_FALLING;800
GameCore.STATE_FALLING = STATE_FALLING;@@ -892,6 +943,56 @@ GameCore.prototype.groundedCount = function (col)892
return n;943
return n;893
};944
};894
945
946
GameCore.prototype.columnNeedsWarn = function (col)947
{948
return this.groundedCount(col) >= COLUMN_WARN_ROWS;949
};950
951
/**952
* Which columns of a field snapshot should pulse (t1123). Flying,953
* falling and manual (airborne) blocks do not count: they are954
* temporary and would flicker the warning. Still, settling and955
* locked (grounded) blocks do.956
*/957
GameCore.warnColumnsFromSnapshot = function (snapshot, threshold)958
{959
threshold = threshold == null ? COLUMN_WARN_ROWS : threshold;960
var width = (snapshot && snapshot.width) || 10;961
var flags = [];962
var counts = [];963
for (var c = 0; c < width; c++)964
{965
counts[c] = 0;966
flags[c] = false;967
}968
var blocks = (snapshot && snapshot.blocks) || [];969
for (var i = 0; i < blocks.length; i++)970
{971
var b = blocks[i];972
if (b.col < 0 || b.col >= width)973
{ continue; }974
if (b.state === 'still' || b.state === 'settling' || b.state === 'locked')975
{ counts[b.col]++; }976
}977
for (var c = 0; c < width; c++)978
{ flags[c] = counts[c] >= threshold; }979
return flags;980
};981
982
GameCore.columnWarnPulse = function (timeSec)983
{984
// Smooth sine, ~0.5 Hz, alpha 0.16–0.44. Shared by the player985
// field and opponent / bot minis so they pulse in sync.986
var t = timeSec;987
if (t == null)988
{989
t = (typeof performance !== 'undefined' && performance.now)990
? performance.now() / 1000991
: Date.now() / 1000;992
}993
return 0.16 + 0.28 * (0.5 + 0.5 * Math.sin(t * Math.PI * 2 * 0.55));994
};995
895
GameCore.prototype.blockAt = function (col, row)996
GameCore.prototype.blockAt = function (col, row)896
{997
{897
for (var i = 0; i < this.blocks.length; i++)998
for (var i = 0; i < this.blocks.length; i++)@@ -1513,6 +1614,14 @@ GameCore.prototype.mergeClusterGroup = function (clusters)1513
keep.decel = decelSum / n;1614
keep.decel = decelSum / n;1514
keep.jumpHeight = hSum / n;1615
keep.jumpHeight = hSum / n;1515
keep.phase = keep.vy > 1e-10 ? 'up' : 'down';1616
keep.phase = keep.vy > 1e-10 ? 'up' : 'down';1617
var maxChain = 0;1618
for (var c = 0; c < clusters.length; c++)1619
{1620
var ch = clusters[c].landingChain || 0;1621
if (ch > maxChain)1622
{ maxChain = ch; }1623
}1624
keep.landingChain = maxChain;1516
for (var c = 0; c < clusters.length; c++)1625
for (var c = 0; c < clusters.length; c++)1517
{1626
{1518
var mem = this.clusterMembers(clusters[c].id);1627
var mem = this.clusterMembers(clusters[c].id);@@ -1907,6 +2016,9 @@ GameCore.prototype.landCluster = function (cluster, members)1907
}2016
}1908
cluster.phase = 'landed';2017
cluster.phase = 'landed';1909
cluster.vy = 0;2018
cluster.vy = 0;2019
cluster.landedPending = true;2020
if (cluster.landingChain == null)2021
{ cluster.landingChain = 0; }1910
};2022
};1911
2023
1912
/**2024
/**@@ -1928,6 +2040,10 @@ GameCore.prototype.releaseLandedCluster = function (cluster)1928
block.color = this.randomColor();2040
block.color = this.randomColor();1929
block.settleTime = 0;2041
block.settleTime = 0;1930
}2042
}2043
// Persist the chain across release so a post-recolor match in2044
// this same tick still gets the landing bonus (t1120).2045
block.justLanded = !!cluster.landedPending;2046
block.landingChain = cluster.landingChain || 0;1931
this.leaveCluster(block);2047
this.leaveCluster(block);1932
// Always drop leftover launch / manual velocity. A stale upward2048
// Always drop leftover launch / manual velocity. A stale upward1933
// vy here is what sends blocks off the top "very fast" after2049
// vy here is what sends blocks off the top "very fast" after@@ -2803,7 +2919,10 @@ GameCore.prototype.resolveMatches = function ()2803
{ return []; }2919
{ return []; }2804
var lines = this.findMatchLines();2920
var lines = this.findMatchLines();2805
if (!lines.length)2921
if (!lines.length)2806
{ return []; }2922
{2923
this.finishLandingChains([]);2924
return [];2925
}2807
2926
2808
var uf = new UnionFind();2927
var uf = new UnionFind();2809
var blockById = Object.create(null);2928
var blockById = Object.create(null);@@ -2870,9 +2989,19 @@ GameCore.prototype.resolveMatches = function ()2870
{ height = h; }2989
{ height = h; }2871
}2990
}2872
}2991
}2873
this.launchCluster(group, height);2992
var chain = this.landingChainFor(group);2874
launched.push({ blocks: group, jumpHeight: height });2993
var bonusMul = 1 + LANDING_CHAIN_BONUS * chain;2994
height *= bonusMul;2995
this.launchCluster(group, height, { landingChain: chain });2996
launched.push({2997
blocks: group,2998
jumpHeight: height,2999
landingChain: chain,3000
chainBonus: bonusMul3001
});2875
}3002
}3003
this.finishLandingChains(launched);3004
this.updateChainIndicator(launched);2876
return launched;3005
return launched;2877
};3006
};2878
3007
@@ -2880,8 +3009,9 @@ GameCore.prototype.resolveMatches = function ()2880
* Gray the matched blocks, take everything sitting on top of them in3009
* Gray the matched blocks, take everything sitting on top of them in2881
* those columns, link them, and launch with jump height `height`.3010
* those columns, link them, and launch with jump height `height`.2882
*/3011
*/2883
GameCore.prototype.launchCluster = function (matchedBlocks, height)3012
GameCore.prototype.launchCluster = function (matchedBlocks, height, opts)2884
{3013
{3014
opts = opts || {};2885
var lowestInCol = Object.create(null);3015
var lowestInCol = Object.create(null);2886
var matchedIds = Object.create(null);3016
var matchedIds = Object.create(null);2887
for (var i = 0; i < matchedBlocks.length; i++)3017
for (var i = 0; i < matchedBlocks.length; i++)@@ -2898,7 +3028,9 @@ GameCore.prototype.launchCluster = function (matchedBlocks, height)2898
jumpHeight: height,3028
jumpHeight: height,2899
vy: PlanetMod.launchVelocity(this.planet, height),3029
vy: PlanetMod.launchVelocity(this.planet, height),2900
decel: PlanetMod.launchDeceleration(this.planet, height),3030
decel: PlanetMod.launchDeceleration(this.planet, height),2901
phase: 'up'3031
phase: 'up',3032
landingChain: opts.landingChain || 0,3033
landedPending: false2902
};3034
};2903
this.clusters[clusterId] = cluster;3035
this.clusters[clusterId] = cluster;2904
3036
@@ -3274,10 +3406,149 @@ GameCore.prototype.swapToward = function (block, targetY)3274
3406
3275
GameCore.prototype.swapBlocks = function (a, b)3407
GameCore.prototype.swapBlocks = function (a, b)3276
{3408
{3277
var y = a.y;3409
var ay = a.y;3278
a.y = b.y;3410
var by = b.y;3279
b.y = y;3411
a.y = by;3412
b.y = ay;3280
this.transferLandedMembership(a, b);3413
this.transferLandedMembership(a, b);3414
if (!this.swapEvents)3415
{ this.swapEvents = []; }3416
this.swapEvents.push({ id: a.id, fromY: ay, toY: by, col: a.col });3417
this.swapEvents.push({ id: b.id, fromY: by, toY: ay, col: b.col });3418
};3419
3420
GameCore.prototype.consumeSwapEvents = function ()3421
{3422
var ev = this.swapEvents || [];3423
this.swapEvents = [];3424
return ev;3425
};3426
3427
/**3428
* Highest landing-chain counter among just-landed members of this3429
* match group, plus one. Returns 0 when the match did not come from3430
* a cluster landing (player/bot swap, mid-air, etc.).3431
*/3432
GameCore.prototype.landingChainFor = function (group)3433
{3434
var maxChain = 0;3435
var fromLanding = false;3436
for (var i = 0; i < group.length; i++)3437
{3438
var block = group[i];3439
if (block.justLanded)3440
{3441
fromLanding = true;3442
if ((block.landingChain || 0) > maxChain)3443
{ maxChain = block.landingChain || 0; }3444
}3445
if (block.clusterId != null)3446
{3447
var cluster = this.clusters[block.clusterId];3448
if (cluster && cluster.landedPending)3449
{3450
fromLanding = true;3451
if ((cluster.landingChain || 0) > maxChain)3452
{ maxChain = cluster.landingChain || 0; }3453
}3454
}3455
}3456
if (!fromLanding)3457
{ return 0; }3458
return maxChain + 1;3459
};3460
3461
/**3462
* After resolveMatches: clear the landing-pending flag and reset the3463
* chain on landings that did not make a match. A cluster that is still3464
* settling (greys not yet recolored) keeps landedPending so a later3465
* post-recolor match in this same landing still gets the bonus.3466
*/3467
GameCore.prototype.finishLandingChains = function (launched)3468
{3469
var launchedIds = Object.create(null);3470
launched = launched || [];3471
for (var i = 0; i < launched.length; i++)3472
{3473
var blocks = launched[i].blocks || [];3474
for (var j = 0; j < blocks.length; j++)3475
{ launchedIds[blocks[j].id] = true; }3476
}3477
3478
for (var i = 0; i < this.blocks.length; i++)3479
{3480
var block = this.blocks[i];3481
if (!block.justLanded)3482
{ continue; }3483
if (!launchedIds[block.id])3484
{ block.landingChain = 0; }3485
block.justLanded = false;3486
}3487
3488
var ids = Object.keys(this.clusters);3489
for (var c = 0; c < ids.length; c++)3490
{3491
var cluster = this.clusters[ids[c]];3492
if (!cluster || !cluster.landedPending)3493
{ continue; }3494
var members = this.clusterMembers(cluster.id);3495
var anyLaunched = false;3496
var stillSettling = false;3497
for (var i = 0; i < members.length; i++)3498
{3499
if (launchedIds[members[i].id])3500
{ anyLaunched = true; }3501
if (members[i].state === STATE_SETTLING)3502
{ stillSettling = true; }3503
}3504
if (anyLaunched)3505
{3506
cluster.landingChain = 0;3507
cluster.landedPending = false;3508
}3509
else if (!stillSettling)3510
{3511
// Released leftovers or a fully-still landed group that3512
// already had its match opportunity and missed it.3513
cluster.landingChain = 0;3514
cluster.landedPending = false;3515
}3516
// else: still settling, no match yet — keep landedPending.3517
}3518
};3519
3520
GameCore.prototype.updateChainIndicator = function (launched)3521
{3522
var maxChain = 0;3523
for (var i = 0; i < launched.length; i++)3524
{3525
var ch = launched[i].landingChain || 0;3526
if (ch > maxChain)3527
{ maxChain = ch; }3528
}3529
if (maxChain >= 1)3530
{3531
this.lastChainIndicator = {3532
chain: maxChain,3533
bonusPct: Math.round(maxChain * LANDING_CHAIN_BONUS * 100)3534
};3535
return;3536
}3537
if (!this.hasActiveLandingChain())3538
{ this.lastChainIndicator = null; }3539
};3540
3541
GameCore.prototype.hasActiveLandingChain = function ()3542
{3543
var ids = Object.keys(this.clusters);3544
for (var i = 0; i < ids.length; i++)3545
{3546
var cluster = this.clusters[ids[i]];3547
if (cluster && (cluster.landingChain || 0) >= 13548
&& cluster.phase !== 'landed')3549
{ return true; }3550
}3551
return false;3281
};3552
};3282
3553
3283
/**3554
/**@@ -3811,6 +4082,19 @@ Online._drawMini = function (canvas, snapshot, planet)3811
}4082
}3812
if (!snapshot || !snapshot.blocks)4083
if (!snapshot || !snapshot.blocks)3813
{ return; }4084
{ return; }4085
// t1123: cheap sine pulse behind blocks of nearly-full columns.4086
if (typeof GameCore !== 'undefined' && GameCore.warnColumnsFromSnapshot)4087
{4088
var warns = GameCore.warnColumnsFromSnapshot(snapshot);4089
var pulse = GameCore.columnWarnPulse();4090
for (var wc = 0; wc < warns.length; wc++)4091
{4092
if (!warns[wc])4093
{ continue; }4094
ctx.fillStyle = 'rgba(220, 36, 36,' + pulse + ')';4095
ctx.fillRect(wc * tw, 0, tw, canvas.height);4096
}4097
}3814
var blocks = snapshot.blocks;4098
var blocks = snapshot.blocks;3815
for (var i = 0; i < blocks.length; i++)4099
for (var i = 0; i < blocks.length; i++)3816
{4100
{@@ -4014,146 +4298,792 @@ if (typeof module !== 'undefined' && module.exports)4014
4298
4015
/*4299
/*4016
* Start File:4300
* Start File:4017
* /workspace/meteors/src/main.js4301
* /workspace/meteors/src/offline.js4018
*/ 4302
*/ 4019
'use strict';4303
'use strict';4020
4304
4021
/**4305
/**4022
* View and input for Meteors. The simulation lives in GameCore; this file4306
* Offline Strijd: a client-side single-player mode that plays like4023
* only draws it, scales it to the viewport, and translates pointer events4307
* multiplayer (shots, miss chance, opponent minis) against local bots4024
* into beginDrag / moveDrag / endDrag. Online play (stage 2) is wired4308
* (t1119). Pure simulation — no server.4025
* through Online (src/online.js) and the same GameCore.4026
*/4309
*/4027
4310
4028
function planetImages ()4311
var Offline = (function ()4029
{4312
{4030
var list = [4313
4031
{ name: 'gray', url: 'images/block-gray.png' },4314
var BOT_INTERVAL = 0.5;4032
{ name: 'locked', url: 'images/block-locked.png' },4315
var SKILL_START = 0.05;4033
{ name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 },4316
var SKILL_STEP = 0.01;4034
{ name: 'cell', url: 'images/cell.png' },4317
var SKILL_CAP = 1;4035
{ name: 'pixel', url: 'images/pixel.png' },4318
var FLIGHT_DURATION = 1.2;4036
// Keep the original Terra placeholders as aliases (Tim may still have them).4319
var ROUND_WON_DELAY = 1.5;4037
{ name: 'ember', url: 'images/block-ember.png' },4320
4038
{ name: 'aqua', url: 'images/block-aqua.png' },4321
/**4039
{ name: 'leaf', url: 'images/block-leaf.png' },4322
* N opponents for N−1 rounds when N >= 2; 1 opponent for 1 round.4040
{ name: 'sun', url: 'images/block-sun.png' },4323
* Documented in docs/ASSUMPTIONS.md (t1119).4041
{ name: 'orchid', url: 'images/block-orchid.png' }4324
*/4042
];4325
function roundsAtOpponentCount (n)4043
var planets = (typeof Planet !== 'undefined' ? Planet.allPlanets() : []);4326
{4044
for (var i = 0; i < planets.length; i++)4327
if (n <= 1)4328
{ return 1; }4329
return n - 1;4330
}4331
4332
function skillForRound (round)4333
{4334
var r = Math.max(1, Math.floor(Number(round) || 1));4335
var pct = 5 + (r - 1);4336
if (pct > 100)4337
{ pct = 100; }4338
return pct / 100;4339
}4340
4341
function scheduleForRound (round)4342
{4343
var r = Math.max(1, Math.floor(Number(round) || 1));4344
var cursor = 1;4345
var n = 1;4346
for (;;)4045
{4347
{4046
var pl = planets[i];4348
var count = roundsAtOpponentCount(n);4047
for (var c = 0; c < pl.colors.length; c++)4349
if (r < cursor + count)4048
{4350
{4049
list.push({4351
return {4050
name: Planet.spriteKey(pl, c),4352
round: r,4051
url: pl.colors[c].image4353
opponents: n,4052
});4354
skill: skillForRound(r),4355
roundsAtLevel: count,4356
indexInLevel: r - cursor + 14357
};4358
}4359
cursor += count;4360
n++;4361
if (n > 10000)4362
{4363
return {4364
round: r,4365
opponents: n,4366
skill: SKILL_CAP,4367
roundsAtLevel: roundsAtOpponentCount(n),4368
indexInLevel: 14369
};4053
}4370
}4054
}4371
}4055
return list;4056
}4372
}4057
4373
4058
var IMAGES = planetImages();4374
function GameCoreCtor ()4059
var GAME_OVER_DELAY = 2;4375
{4376
if (typeof GameCore !== 'undefined')4377
{ return GameCore; }4378
if (typeof module !== 'undefined')4379
{ return require('./gameCore.js').GameCore; }4380
return null;4381
}4060
4382
4061
var game = new Game();4383
function PlanetMod ()4062
var app = {4384
{4063
mode: 'menu',4385
if (typeof Planet !== 'undefined')4064
core: null,4386
{ return Planet; }4065
scene: null,4387
if (typeof module !== 'undefined')4066
manager: null,4388
{ return require('./planet.js'); }4067
planet: null,4389
return null;4068
lastScore: 0,4390
}4069
tile: 48,4070
fieldX: 0,4071
fieldY: 0,4072
fieldW: 0,4073
fieldH: 0,4074
hudH: 56,4075
sprites: Object.create(null),4076
flames: Object.create(null),4077
cells: [],4078
pointerId: null,4079
pointerType: null,4080
activeTouchId: null,4081
debugDrag: false,4082
debugPhysics: false,4083
gameOverShown: false,4084
selectTween: null,4085
online: false,4086
eliminatedReported: false,4087
spectating: false,4088
miniH: 0,4089
selectedPlanetId: 'terra',4090
planetSelectContext: 'solo'4091
};4092
4391
4093
window.onload = function ()4392
/**4393
* Integer-row colour grid of grounded (still / settling / locked)4394
* blocks, including greys (color < 0) so a swap can shift them.4395
*/4396
function snapshotGrid (core)4094
{4397
{4095
app.debugDrag = isDragDebugEnabled();4398
var width = core.width;4096
app.debugPhysics = isPhysicsDebugEnabled();4399
var height = core.height;4097
var play = document.getElementById('btn-play');4400
var grid = [];4098
play.addEventListener('click', onPlay);4401
for (var c = 0; c < width; c++)4099
play.addEventListener('pointerup', function (e)4100
{4402
{4101
// A touch-friendly path: some mobile browsers swallow the click4403
grid[c] = [];4102
// after a slightly sloppy tap. Ignore the following click.4404
for (var r = 0; r < height; r++)4103
if (e.pointerType === 'touch' || e.pointerType === 'pen')4405
{ grid[c][r] = null; }4104
{4406
}4105
e.preventDefault();4407
for (var i = 0; i < core.blocks.length; i++)4106
onPlay();4107
}4108
});4109
4110
game.preloadImagesThenStart(IMAGES, function ()4111
{4408
{4112
if (game.images.flame && game.images.flame.addAnimationCycle)4409
var b = core.blocks[i];4113
{ game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); }4410
if (!core.isGrounded(b))4114
});4411
{ continue; }4412
var row = Math.round(b.y);4413
if (row < 0 || row >= height || b.col < 0 || b.col >= width)4414
{ continue; }4415
if (Math.abs(b.y - row) > 0.2)4416
{ continue; }4417
grid[b.col][row] = b.color;4418
}4419
return grid;4420
}4115
4421
4116
bindOnlineUi();4422
function cloneGrid (grid)4117
bindPlanetSelect();4423
{4118
restoreSelectedPlanet();4424
var out = [];4119
};4425
for (var c = 0; c < grid.length; c++)4426
{ out[c] = grid[c].slice(); }4427
return out;4428
}4120
4429
4121
function onPlay ()4430
/**4431
* Apply swapToward's net result: the block at fromRow moves to toRow,4432
* and the blocks it passed through each shift one cell toward fromRow.4433
*/4434
function applyColumnMove (grid, col, fromRow, toRow)4122
{4435
{4123
if (app.mode === 'playing')4436
if (fromRow === toRow)4124
{ return; }4437
{ return; }4125
openPlanetSelect('solo');4438
var moving = grid[col][fromRow];4439
if (toRow > fromRow)4440
{4441
for (var y = fromRow; y < toRow; y++)4442
{ grid[col][y] = grid[col][y + 1]; }4443
grid[col][toRow] = moving;4444
}4445
else4446
{4447
for (var y = fromRow; y > toRow; y--)4448
{ grid[col][y] = grid[col][y - 1]; }4449
grid[col][toRow] = moving;4450
}4126
}4451
}4127
4452
4128
function startPlay (opts)4453
function hasMatch (grid, width, height)4129
{4454
{4130
opts = opts || {};4455
var c, r, run, prev;4131
hideEl('menu');4456
for (r = 0; r < height; r++)4132
hideEl('game-over');4457
{4133
hideEl('online-panel');4458
run = 0;4134
hideEl('spectator');4459
prev = null;4135
hideEl('podium');4460
for (c = 0; c < width; c++)4136
hideEl('planet-select');4461
{4137
showEl('hud');4462
var color = grid[c][r];4138
4463
if (color != null && color >= 0 && color === prev)4139
var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod;4464
{4140
app.planet = opts.planet || planetMod.planetById(selectedPlanetId());4465
run++;4141
var miss = opts.missChance;4466
if (run >= 3)4142
if (typeof miss !== 'number' || !isFinite(miss))4467
{ return true; }4143
{ miss = planetMod.missChance(app.planet); }4468
}4144
app.core = new GameCore(app.planet, Math.random, miss);4469
else4145
if (app.debugPhysics)4470
{4146
{ app.core.debugInvariants = true; }4471
run = (color != null && color >= 0) ? 1 : 0;4147
app.mode = 'playing';4472
prev = (color != null && color >= 0) ? color : null;4148
app.online = !!opts.online;4473
}4149
app.gameOverShown = false;4474
}4150
app.eliminatedReported = false;4475
}4151
app.spectating = false;4476
for (c = 0; c < width; c++)4152
app.sprites = Object.create(null);4477
{4153
app.flames = Object.create(null);4478
run = 0;4154
app.cells = [];4479
prev = null;4155
app.pointerId = null;4480
for (r = 0; r < height; r++)4481
{4482
var color = grid[c][r];4483
if (color != null && color >= 0 && color === prev)4484
{4485
run++;4486
if (run >= 3)4487
{ return true; }4488
}4489
else4490
{4491
run = (color != null && color >= 0) ? 1 : 0;4492
prev = (color != null && color >= 0) ? color : null;4493
}4494
}4495
}4496
return false;4497
}4498
4499
/**4500
* Contiguous segments of draggable, nearly-integer-y blocks in a4501
* column. Gaps break a segment the same way swapToward stops at gaps.4502
*/4503
function contiguousSegments (core, col)4504
{4505
if (!core.columnAllowsDrag(col))4506
{ return []; }4507
var list = core.blocksInColumn(col).filter(function (b)4508
{4509
return core.isDraggableBlock(b);4510
});4511
list.sort(function (a, b) { return a.y - b.y; });4512
var segs = [];4513
var cur = [];4514
for (var i = 0; i < list.length; i++)4515
{4516
var y = list[i].y;4517
if (Math.abs(y - Math.round(y)) > 0.15)4518
{4519
if (cur.length)4520
{4521
segs.push(cur);4522
cur = [];4523
}4524
continue;4525
}4526
if (cur.length && Math.abs(y - (cur[cur.length - 1].y + 1)) > 0.15)4527
{4528
segs.push(cur);4529
cur = [list[i]];4530
}4531
else4532
{ cur.push(list[i]); }4533
}4534
if (cur.length)4535
{ segs.push(cur); }4536
return segs;4537
}4538
4539
/**4540
* The shortest vertical move that would create a 3+ match, or null.4541
* Ties break on lowest column, then lowest fromY, then lowest toY.4542
*/4543
function findBotMove (core)4544
{4545
var grid = snapshotGrid(core);4546
if (hasMatch(grid, core.width, core.height))4547
{ return null; }4548
var best = null;4549
for (var col = 0; col < core.width; col++)4550
{4551
var segs = contiguousSegments(core, col);4552
for (var s = 0; s < segs.length; s++)4553
{4554
var seg = segs[s];4555
if (seg.length < 2)4556
{ continue; }4557
for (var i = 0; i < seg.length; i++)4558
{4559
var fromY = Math.round(seg[i].y);4560
for (var j = 0; j < seg.length; j++)4561
{4562
if (i === j)4563
{ continue; }4564
var toY = Math.round(seg[j].y);4565
var dist = Math.abs(toY - fromY);4566
if (best && dist > best.dist)4567
{ continue; }4568
var trial = cloneGrid(grid);4569
applyColumnMove(trial, col, fromY, toY);4570
if (!hasMatch(trial, core.width, core.height))4571
{ continue; }4572
var cand = {4573
col: col,4574
fromY: fromY,4575
toY: toY,4576
dist: dist,4577
blockId: seg[i].id4578
};4579
if (!best || dist < best.dist4580
|| (dist === best.dist && col < best.col)4581
|| (dist === best.dist && col === best.col && fromY < best.fromY)4582
|| (dist === best.dist && col === best.col && fromY === best.fromY4583
&& toY < best.toY))4584
{ best = cand; }4585
}4586
}4587
}4588
}4589
return best;4590
}4591
4592
function executeBotMove (core, move)4593
{4594
if (!core || !move)4595
{ return false; }4596
var list = core.blocksInColumn(move.col);4597
var block = null;4598
for (var i = 0; i < list.length; i++)4599
{4600
if (move.blockId != null && list[i].id === move.blockId)4601
{4602
block = list[i];4603
break;4604
}4605
if (Math.abs(list[i].y - move.fromY) < 0.2)4606
{ block = list[i]; }4607
}4608
if (!block || !core.isDraggableBlock(block))4609
{ return false; }4610
core.swapToward(block, move.toY);4611
return true;4612
}4613
4614
/**4615
* One AI tick. `rng` is a () => [0,1) function. Success if roll < skill.4616
* At skill 0 the bot never moves; at skill 1 it always looks for a move.4617
*/4618
function tryBotRoll (core, skill, rng)4619
{4620
rng = rng || Math.random;4621
var roll = rng();4622
if (!(roll < skill))4623
{4624
return { rolled: true, success: false, moved: false, roll: roll, move: null };4625
}4626
var move = findBotMove(core);4627
if (!move)4628
{4629
return { rolled: true, success: true, moved: false, roll: roll, move: null };4630
}4631
var ok = executeBotMove(core, move);4632
return { rolled: true, success: true, moved: !!ok, roll: roll, move: move };4633
}4634
4635
function pickPlanet (rng, P)4636
{4637
var all = P.allPlanets();4638
if (!all.length)4639
{ return P.defaultPlanet(); }4640
var i = Math.floor(rng() * all.length) % all.length;4641
return all[i];4642
}4643
4644
function OfflineBattle (opts)4645
{4646
opts = opts || {};4647
var P = PlanetMod();4648
this.playerPlanet = opts.playerPlanet || (P && P.defaultPlanet());4649
this.rng = opts.rng || Math.random;4650
this.round = opts.round || 1;4651
this.schedule = scheduleForRound(this.round);4652
this.clock = 0;4653
this.state = 'playing';4654
this.pending = [];4655
this.flightResults = [];4656
this.shotLocals = [];4657
this.bots = [];4658
this.playerId = 'player';4659
this._initBots();4660
}4661
4662
OfflineBattle.prototype._initBots = function ()4663
{4664
var P = PlanetMod();4665
var Ctor = GameCoreCtor();4666
var n = this.schedule.opponents;4667
this.bots = [];4668
for (var i = 0; i < n; i++)4669
{4670
var planet = pickPlanet(this.rng, P);4671
var miss = P.missChance(planet);4672
var core = new Ctor(planet, this.rng, miss);4673
this.bots.push({4674
id: 'bot-' + (i + 1),4675
name: 'Bot ' + (i + 1),4676
planet: planet,4677
core: core,4678
eliminated: false,4679
score: 0,4680
aiAcc: 04681
});4682
}4683
};4684
4685
OfflineBattle.prototype.aliveBots = function ()4686
{4687
var out = [];4688
for (var i = 0; i < this.bots.length; i++)4689
{4690
if (!this.bots[i].eliminated && this.bots[i].core4691
&& this.bots[i].core.state !== 'gameover')4692
{ out.push(this.bots[i]); }4693
}4694
return out;4695
};4696
4697
OfflineBattle.prototype.coreFor = function (id, playerCore)4698
{4699
if (id === this.playerId)4700
{ return playerCore; }4701
for (var i = 0; i < this.bots.length; i++)4702
{4703
if (this.bots[i].id === id)4704
{ return this.bots[i].core; }4705
}4706
return null;4707
};4708
4709
OfflineBattle.prototype._targetsFor = function (fromId, playerCore)4710
{4711
var targets = [];4712
if (fromId !== this.playerId && playerCore && playerCore.state === 'playing')4713
{ targets.push({ id: this.playerId, core: playerCore }); }4714
for (var i = 0; i < this.bots.length; i++)4715
{4716
var bot = this.bots[i];4717
if (bot.id === fromId || bot.eliminated)4718
{ continue; }4719
if (bot.core && bot.core.state === 'playing')4720
{ targets.push({ id: bot.id, core: bot.core }); }4721
}4722
return targets;4723
};4724
4725
OfflineBattle.prototype._dispatchShots = function (fromId, core, planet, playerCore)4726
{4727
if (!core || !core.consumeOutgoingShots)4728
{ return; }4729
var shots = core.consumeOutgoingShots();4730
if (!shots.length)4731
{ return; }4732
var P = PlanetMod();4733
var missChance = (P && planet) ? P.missChance(planet) : 0.30;4734
var targets = this._targetsFor(fromId, playerCore);4735
for (var i = 0; i < shots.length; i++)4736
{4737
var shot = shots[i];4738
var miss = targets.length === 0 || this.rng() < missChance;4739
var target = null;4740
if (!miss)4741
{4742
var idx = Math.floor(this.rng() * targets.length) % targets.length;4743
target = targets[idx];4744
}4745
var clientId = fromId + '-' + shot.id + '-' + this.clock;4746
var result = {4747
client_id: clientId,4748
miss: miss,4749
target_id: target ? target.id : null,4750
color: shot.color,4751
flight_duration: FLIGHT_DURATION,4752
from_id: fromId,4753
col: shot.col,4754
y: shot.y4755
};4756
this.flightResults.push(result);4757
this.shotLocals.push({4758
client_id: clientId,4759
col: shot.col,4760
y: shot.y,4761
color: shot.color,4762
from_id: fromId4763
});4764
if (!miss && target)4765
{4766
this.pending.push({4767
at: this.clock + FLIGHT_DURATION,4768
targetId: target.id,4769
color: shot.color,4770
fromId: fromId4771
});4772
}4773
}4774
};4775
4776
OfflineBattle.prototype._deliver = function (playerCore)4777
{4778
var keep = [];4779
for (var i = 0; i < this.pending.length; i++)4780
{4781
var ev = this.pending[i];4782
if (this.clock + 1e-9 < ev.at)4783
{4784
keep.push(ev);4785
continue;4786
}4787
var core = this.coreFor(ev.targetId, playerCore);4788
if (core && core.state === 'playing' && core.ingestGarbage)4789
{ core.ingestGarbage(); }4790
}4791
this.pending = keep;4792
};4793
4794
OfflineBattle.prototype.tick = function (dt, playerCore)4795
{4796
this.flightResults = [];4797
this.shotLocals = [];4798
if (this.state !== 'playing')4799
{ return { flights: [], locals: [] }; }4800
if (dt < 0)4801
{ dt = 0; }4802
this.clock += dt;4803
4804
var skill = this.schedule.skill;4805
for (var i = 0; i < this.bots.length; i++)4806
{4807
var bot = this.bots[i];4808
if (bot.eliminated)4809
{ continue; }4810
if (bot.core.state === 'gameover')4811
{4812
bot.eliminated = true;4813
bot.score = bot.core.score;4814
continue;4815
}4816
bot.core.tick(dt);4817
bot.score = bot.core.score;4818
bot.aiAcc += dt;4819
while (bot.aiAcc >= BOT_INTERVAL)4820
{4821
bot.aiAcc -= BOT_INTERVAL;4822
if (bot.core.state === 'playing' && !bot.core.drag)4823
{ tryBotRoll(bot.core, skill, this.rng); }4824
}4825
}4826
4827
this._dispatchShots(this.playerId, playerCore, this.playerPlanet, playerCore);4828
for (var i = 0; i < this.bots.length; i++)4829
{4830
var bot = this.bots[i];4831
if (bot.eliminated)4832
{ continue; }4833
this._dispatchShots(bot.id, bot.core, bot.planet, playerCore);4834
}4835
this._deliver(playerCore);4836
4837
for (var i = 0; i < this.bots.length; i++)4838
{4839
if (this.bots[i].core && this.bots[i].core.state === 'gameover')4840
{4841
this.bots[i].eliminated = true;4842
this.bots[i].score = this.bots[i].core.score;4843
}4844
}4845
4846
if (playerCore && playerCore.state === 'gameover')4847
{ this.state = 'lost'; }4848
else if (this.aliveBots().length === 0 && this.bots.length > 0)4849
{ this.state = 'round_won'; }4850
4851
return { flights: this.flightResults, locals: this.shotLocals };4852
};4853
4854
/**4855
* Start the next round (fresh bots, new skill and opponent count).4856
* The caller must also give the player a fresh GameCore.4857
*/4858
OfflineBattle.prototype.advanceRound = function ()4859
{4860
this.round += 1;4861
this.schedule = scheduleForRound(this.round);4862
this.state = 'playing';4863
this.pending = [];4864
this.flightResults = [];4865
this.shotLocals = [];4866
this.clock = 0;4867
this._initBots();4868
return this.schedule;4869
};4870
4871
function createBattle (opts)4872
{4873
return new OfflineBattle(opts);4874
}4875
4876
var api = {4877
BOT_INTERVAL: BOT_INTERVAL,4878
SKILL_START: SKILL_START,4879
SKILL_STEP: SKILL_STEP,4880
SKILL_CAP: SKILL_CAP,4881
FLIGHT_DURATION: FLIGHT_DURATION,4882
ROUND_WON_DELAY: ROUND_WON_DELAY,4883
roundsAtOpponentCount: roundsAtOpponentCount,4884
skillForRound: skillForRound,4885
scheduleForRound: scheduleForRound,4886
findBotMove: findBotMove,4887
tryBotRoll: tryBotRoll,4888
executeBotMove: executeBotMove,4889
snapshotGrid: snapshotGrid,4890
applyColumnMove: applyColumnMove,4891
hasMatch: hasMatch,4892
createBattle: createBattle,4893
OfflineBattle: OfflineBattle4894
};4895
4896
if (typeof module !== 'undefined' && module.exports)4897
{ module.exports = api; }4898
else if (typeof globalThis !== 'undefined')4899
{ globalThis.Offline = api; }4900
4901
return api;4902
4903
})();4904
4905
if (typeof module !== 'undefined' && module.exports && typeof Offline !== 'undefined')4906
{ module.exports = Offline; }4907
4908
/*4909
* End File:4910
* /workspace/meteors/src/offline.js4911
*/ 4912
4913
/*4914
* Start File:4915
* /workspace/meteors/src/main.js4916
*/ 4917
'use strict';4918
4919
/**4920
* View and input for Meteors. The simulation lives in GameCore; this file4921
* only draws it, scales it to the viewport, and translates pointer events4922
* into beginDrag / moveDrag / endDrag. Online play (stage 2) is wired4923
* through Online (src/online.js) and the same GameCore. Offline Strijd4924
* (t1119) uses Offline (src/offline.js) against local bots.4925
*/4926
4927
function planetImages ()4928
{4929
var list = [4930
{ name: 'gray', url: 'images/block-gray.png' },4931
{ name: 'locked', url: 'images/block-locked.png' },4932
{ name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 },4933
{ name: 'cell', url: 'images/cell.png' },4934
{ name: 'pixel', url: 'images/pixel.png' },4935
{ name: 'columnWarn', url: 'images/column-warn.png' },4936
// Keep the original Terra placeholders as aliases (Tim may still have them).4937
{ name: 'ember', url: 'images/block-ember.png' },4938
{ name: 'aqua', url: 'images/block-aqua.png' },4939
{ name: 'leaf', url: 'images/block-leaf.png' },4940
{ name: 'sun', url: 'images/block-sun.png' },4941
{ name: 'orchid', url: 'images/block-orchid.png' }4942
];4943
var planets = (typeof Planet !== 'undefined' ? Planet.allPlanets() : []);4944
for (var i = 0; i < planets.length; i++)4945
{4946
var pl = planets[i];4947
for (var c = 0; c < pl.colors.length; c++)4948
{4949
list.push({4950
name: Planet.spriteKey(pl, c),4951
url: pl.colors[c].image4952
});4953
}4954
}4955
return list;4956
}4957
4958
var IMAGES = planetImages();4959
var GAME_OVER_DELAY = 2;4960
4961
var game = new Game();4962
var app = {4963
mode: 'menu',4964
core: null,4965
scene: null,4966
manager: null,4967
planet: null,4968
lastScore: 0,4969
tile: 48,4970
fieldX: 0,4971
fieldY: 0,4972
fieldW: 0,4973
fieldH: 0,4974
hudH: 56,4975
sprites: Object.create(null),4976
flames: Object.create(null),4977
cells: [],4978
pointerId: null,4979
pointerType: null,4980
activeTouchId: null,4981
debugDrag: false,4982
debugPhysics: false,4983
gameOverShown: false,4984
selectTween: null,4985
online: false,4986
eliminatedReported: false,4987
spectating: false,4988
miniH: 0,4989
selectedPlanetId: 'terra',4990
planetSelectContext: 'solo',4991
offline: false,4992
battle: null,4993
swapTweens: null,4994
columnWarn: null,4995
warnClock: 0,4996
miniAcc: 0,4997
offlineResultShown: false,4998
roundWonDelay: 0,4999
roundWonHandled: false5000
};5001
5002
window.onload = function ()5003
{5004
app.debugDrag = isDragDebugEnabled();5005
app.debugPhysics = isPhysicsDebugEnabled();5006
var play = document.getElementById('btn-play');5007
play.addEventListener('click', onPlay);5008
play.addEventListener('pointerup', function (e)5009
{5010
// A touch-friendly path: some mobile browsers swallow the click5011
// after a slightly sloppy tap. Ignore the following click.5012
if (e.pointerType === 'touch' || e.pointerType === 'pen')5013
{5014
e.preventDefault();5015
onPlay();5016
}5017
});5018
5019
game.preloadImagesThenStart(IMAGES, function ()5020
{5021
if (game.images.flame && game.images.flame.addAnimationCycle)5022
{ game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); }5023
});5024
5025
bindOnlineUi();5026
bindOfflineUi();5027
bindPlanetSelect();5028
restoreSelectedPlanet();5029
};5030
5031
function onPlay ()5032
{5033
if (app.mode === 'playing')5034
{ return; }5035
openPlanetSelect('solo');5036
}5037
5038
function startPlay (opts)5039
{5040
opts = opts || {};5041
hideEl('menu');5042
hideEl('game-over');5043
hideEl('online-panel');5044
hideEl('spectator');5045
hideEl('podium');5046
hideEl('planet-select');5047
hideEl('offline-result');5048
showEl('hud');5049
5050
var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod;5051
app.planet = opts.planet || planetMod.planetById(selectedPlanetId());5052
var miss = opts.missChance;5053
if (typeof miss !== 'number' || !isFinite(miss))5054
{ miss = planetMod.missChance(app.planet); }5055
app.core = new GameCore(app.planet, Math.random, miss);5056
if (app.debugPhysics)5057
{ app.core.debugInvariants = true; }5058
app.mode = 'playing';5059
app.online = !!opts.online;5060
app.offline = !!opts.offline;5061
app.gameOverShown = false;5062
app.eliminatedReported = false;5063
app.spectating = false;5064
app.sprites = Object.create(null);5065
app.flames = Object.create(null);5066
app.cells = [];5067
app.pointerId = null;4156
app.selectTween = null;5068
app.selectTween = null;5069
app.swapTweens = Object.create(null);5070
app.columnWarn = [];5071
app.warnClock = 0;5072
app.miniAcc = 1; // draw minis on the first frame5073
app.offlineResultShown = false;5074
if (!opts.keepBattle)5075
{5076
app.roundWonDelay = 0;5077
app.roundWonHandled = false;5078
}5079
if (app.offline && !opts.keepBattle && typeof Offline !== 'undefined')5080
{5081
app.battle = Offline.createBattle({5082
playerPlanet: app.planet,5083
rng: Math.random,5084
round: opts.round || 15085
});5086
}4157
5087
4158
layout();5088
layout();4159
if (app.scene)5089
if (app.scene)@@ -4171,10 +5101,13 @@ function startPlay (opts)4171
if (!app.spectating)5101
if (!app.spectating)4172
{ bindPointer(app.scene.canvas); }5102
{ bindPointer(app.scene.canvas); }4173
refreshHud();5103
refreshHud();4174
if (app.online)5104
if (app.online || app.offline)4175
{ showEl('minis'); }5105
{ showEl('minis'); }4176
else5106
else4177
{ hideEl('minis'); }5107
{ hideEl('minis'); }5108
buildColumnWarn();5109
refreshOfflineHud();5110
refreshChainIndicator();4178
}5111
}4179
5112
4180
function teardownPlay ()5113
function teardownPlay ()@@ -4191,14 +5124,25 @@ function teardownPlay ()4191
app.flames = Object.create(null);5124
app.flames = Object.create(null);4192
app.cells = [];5125
app.cells = [];4193
app.selectTween = null;5126
app.selectTween = null;5127
app.swapTweens = Object.create(null);5128
app.columnWarn = [];4194
app.pointerId = null;5129
app.pointerId = null;4195
app.gameOverShown = false;5130
app.gameOverShown = false;4196
hideEl('hud');5131
hideEl('hud');4197
hideEl('game-over');5132
hideEl('game-over');4198
hideEl('spectator');5133
hideEl('spectator');4199
hideEl('minis');5134
hideEl('minis');5135
hideEl('offline-result');5136
hideOfflineHud();5137
hideChainIndicator();4200
if (typeof Online !== 'undefined')5138
if (typeof Online !== 'undefined')4201
{ Online.clearFlights(); }5139
{ Online.clearFlights(); }5140
if (!app._keepBattleOnTeardown)5141
{5142
app.battle = null;5143
app.offline = false;5144
}5145
app._keepBattleOnTeardown = false;4202
}5146
}4203
5147
4204
function returnToMenu ()5148
function returnToMenu ()@@ -4212,6 +5156,8 @@ function returnToMenu ()4212
teardownPlay();5156
teardownPlay();4213
app.mode = 'menu';5157
app.mode = 'menu';4214
app.online = false;5158
app.online = false;5159
app.offline = false;5160
app.battle = null;4215
hideEl('planet-select');5161
hideEl('planet-select');4216
showEl('menu');5162
showEl('menu');4217
var last = document.getElementById('last-score');5163
var last = document.getElementById('last-score');@@ -4276,8 +5222,12 @@ function layout ()4276
catch (e) { /* ignore */ }5222
catch (e) { /* ignore */ }4277
app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop);5223
app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop);4278
app.miniH = 0;5224
app.miniH = 0;4279
if (app.online)5225
if (app.online || app.offline)4280
{ app.miniH = Math.min(150, Math.max(86, Math.round(vh * 0.20))); }5226
{5227
var nBots = (app.battle && app.battle.bots) ? app.battle.bots.length : 2;5228
var share = nBots > 6 ? 0.26 : 0.20;5229
app.miniH = Math.min(nBots > 6 ? 180 : 150, Math.max(86, Math.round(vh * share)));5230
}4281
var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015));5231
var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015));4282
var availW = Math.max(80, vw - margin * 2);5232
var availW = Math.max(80, vw - margin * 2);4283
var availH = Math.max(80, vh - app.hudH - app.miniH - margin);5233
var availH = Math.max(80, vh - app.hudH - app.miniH - margin);@@ -4315,10 +5265,13 @@ function spriteFor (block)4315
return game.images[key] || game.images.gray;5265
return game.images[key] || game.images.gray;4316
}5266
}4317
5267
4318
function syncSprites ()5268
function syncSprites (dt)4319
{5269
{4320
if (!app.core || !app.scene)5270
if (!app.core || !app.scene)4321
{ return; }5271
{ return; }5272
dt = dt || 0;5273
consumeAndStartSwapTweens();5274
advanceSwapTweens(dt);4322
var seen = Object.create(null);5275
var seen = Object.create(null);4323
var blocks = app.core.blocks;5276
var blocks = app.core.blocks;4324
for (var i = 0; i < blocks.length; i++)5277
for (var i = 0; i < blocks.length; i++)@@ -4333,7 +5286,7 @@ function syncSprites ()4333
app.sprites[block.id] = obj;5286
app.sprites[block.id] = obj;4334
}5287
}4335
obj.renderer.sprite = spriteFor(block);5288
obj.renderer.sprite = spriteFor(block);4336
placeTile(obj, block.col, block.y);5289
placeTile(obj, block.col, blockVisualY(block));4337
applyBlockVisual(obj, block);5290
applyBlockVisual(obj, block);4338
obj.renderer.visible = true;5291
obj.renderer.visible = true;4339
obj.renderer.alpha = 1;5292
obj.renderer.alpha = 1;@@ -4471,6 +5424,95 @@ function updateSelectTween (dt)4471
tw.scale = ease ? Easing.tween(tw.from, tw.to, u, ease) : tw.from + (tw.to - tw.from) * u;5424
tw.scale = ease ? Easing.tween(tw.from, tw.to, u, ease) : tw.from + (tw.to - tw.from) * u;4472
}5425
}4473
5426
5427
5428
/* ---------- visual-only swap tween (t1121) -------------------------- */5429
5430
function swapTweenSpec ()5431
{5432
if (typeof Easing !== 'undefined' && Easing.SWAP_TWEEN)5433
{ return Easing.SWAP_TWEEN; }5434
return { duration: 0.100, ease: null };5435
}5436
5437
function swapEase (u)5438
{5439
if (typeof Easing !== 'undefined' && Easing.easeOutCubic)5440
{ return Easing.easeOutCubic(u); }5441
var v = 1 - Math.max(0, Math.min(1, u));5442
return 1 - v * v * v;5443
}5444
5445
function tweenVisualY (tw)5446
{5447
var u = tw.duration > 0 ? Math.min(1, tw.age / tw.duration) : 1;5448
return tw.fromY + (tw.toY - tw.fromY) * swapEase(u);5449
}5450
5451
/**5452
* Consume GameCore swap events. The currently dragged block is skipped5453
* (it follows the pointer). A block that is mid-tween and is swapped5454
* again restarts from its current visual y, so rapid swaps chain5455
* smoothly without snapping.5456
*/5457
function consumeAndStartSwapTweens ()5458
{5459
if (!app.core || !app.core.consumeSwapEvents)5460
{ return; }5461
if (!app.swapTweens)5462
{ app.swapTweens = Object.create(null); }5463
var ev = app.core.consumeSwapEvents();5464
if (!ev.length)5465
{ return; }5466
var dragId = app.core.drag && app.core.drag.blockId;5467
var duration = swapTweenSpec().duration;5468
for (var i = 0; i < ev.length; i++)5469
{5470
var e = ev[i];5471
if (e.id === dragId)5472
{5473
delete app.swapTweens[e.id];5474
continue;5475
}5476
var fromY = e.fromY;5477
var existing = app.swapTweens[e.id];5478
if (existing)5479
{ fromY = tweenVisualY(existing); }5480
app.swapTweens[e.id] = {5481
fromY: fromY,5482
toY: e.toY,5483
age: 0,5484
duration: duration5485
};5486
}5487
}5488
5489
function advanceSwapTweens (dt)5490
{5491
if (!app.swapTweens)5492
{ return; }5493
var ids = Object.keys(app.swapTweens);5494
for (var i = 0; i < ids.length; i++)5495
{5496
var tw = app.swapTweens[ids[i]];5497
tw.age += dt;5498
if (tw.age >= tw.duration)5499
{ delete app.swapTweens[ids[i]]; }5500
}5501
}5502
5503
function blockVisualY (block)5504
{5505
if (!app.swapTweens)5506
{ return block.y; }5507
var dragId = app.core && app.core.drag && app.core.drag.blockId;5508
if (block.id === dragId)5509
{ return block.y; }5510
var tw = app.swapTweens[block.id];5511
if (!tw)5512
{ return block.y; }5513
return tweenVisualY(tw);5514
}5515
4474
function refreshHud ()5516
function refreshHud ()4475
{5517
{4476
if (!app.core)5518
if (!app.core)@@ -4512,9 +5554,14 @@ function tickView (dt)4512
}5554
}4513
5555
4514
app.core.tick(dt);5556
app.core.tick(dt);5557
if (app.offline && app.battle)5558
{ tickOffline(dt); }4515
updateSelectTween(dt);5559
updateSelectTween(dt);4516
syncSprites();5560
syncSprites(dt);5561
updateColumnWarn(dt);4517
refreshHud();5562
refreshHud();5563
refreshOfflineHud();5564
refreshChainIndicator();4518
tickOnline(dt);5565
tickOnline(dt);4519
if (app.debugPhysics)5566
if (app.debugPhysics)4520
{ logPhysicsDebug(); }5567
{ logPhysicsDebug(); }@@ -4526,10 +5573,13 @@ function tickView (dt)4526
document.getElementById('go-score').textContent = String(app.lastScore);5573
document.getElementById('go-score').textContent = String(app.lastScore);4527
if (app.online)5574
if (app.online)4528
{ onOnlineEliminated(); }5575
{ onOnlineEliminated(); }5576
else if (app.offline)5577
{ /* Offline result is shown from tickOffline. */ }4529
else5578
else4530
{ showEl('game-over'); }5579
{ showEl('game-over'); }4531
}5580
}4532
if (!app.online && app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY)5581
if (!app.online && !app.offline && app.core.state === 'gameover'5582
&& app.core.gameOverTime >= GAME_OVER_DELAY)4533
{ returnToMenu(); }5583
{ returnToMenu(); }4534
}5584
}4535
5585
@@ -5032,6 +6082,313 @@ function tickOnline (dt)5032
Online.renderMinis(document.getElementById('minis'));6082
Online.renderMinis(document.getElementById('minis'));5033
}6083
}5034
6084
6085
6086
/* ---------- Offline Strijd (t1119) + column warn (t1123) ----------- */6087
6088
function bindOfflineUi ()6089
{6090
var btn = document.getElementById('btn-offline');6091
if (btn)6092
{6093
btn.addEventListener('click', onOffline);6094
btn.addEventListener('pointerup', function (e)6095
{6096
if (e.pointerType === 'touch' || e.pointerType === 'pen')6097
{6098
e.preventDefault();6099
onOffline();6100
}6101
});6102
}6103
var back = document.getElementById('btn-offline-menu');6104
if (back)6105
{6106
back.addEventListener('click', function ()6107
{6108
teardownPlay();6109
app.mode = 'menu';6110
app.offline = false;6111
app.battle = null;6112
hideEl('offline-result');6113
showEl('menu');6114
});6115
}6116
}6117
6118
function onOffline ()6119
{6120
openPlanetSelect('offline');6121
}6122
6123
function tickOffline (dt)6124
{6125
if (!app.battle || !app.core || typeof Offline === 'undefined')6126
{ return; }6127
6128
if (app.battle.state === 'round_won')6129
{6130
if (!app.roundWonHandled)6131
{6132
app.roundWonHandled = true;6133
app.roundWonDelay = Offline.ROUND_WON_DELAY || 1.5;6134
}6135
app.roundWonDelay -= dt;6136
if (app.roundWonDelay <= 0)6137
{ startNextOfflineRound(); }6138
updateOfflineMinis(dt, true);6139
return;6140
}6141
6142
var result = app.battle.tick(dt, app.core);6143
if (result && result.flights && result.flights.length6144
&& typeof Online !== 'undefined' && Online.spawnFlights)6145
{6146
var locals = Object.create(null);6147
var list = result.locals || [];6148
for (var i = 0; i < list.length; i++)6149
{6150
var s = list[i];6151
var start;6152
if (s.from_id === 'player')6153
{ start = fieldToViewport(s.col, s.y + 1); }6154
else6155
{ start = miniViewportCenter(s.from_id); }6156
locals[s.client_id] = {6157
col: s.col,6158
y: s.y,6159
color: s.color,6160
startX: start.x,6161
startY: start.y6162
};6163
}6164
Online.spawnFlights(result.flights, locals);6165
}6166
if (typeof Online !== 'undefined' && Online.tickFlights)6167
{ Online.tickFlights(); }6168
updateOfflineMinis(dt, false);6169
6170
if (app.battle.state === 'lost' && !app.offlineResultShown)6171
{ showOfflineResult(); }6172
}6173
6174
function startNextOfflineRound ()6175
{6176
if (!app.battle)6177
{ return; }6178
app.battle.advanceRound();6179
app.roundWonHandled = false;6180
app.roundWonDelay = 0;6181
app._keepBattleOnTeardown = true;6182
// Tear down the current scene then start a fresh player field,6183
// keeping the same battle (already advanced).6184
var planet = app.battle.playerPlanet;6185
app._keepBattleOnTeardown = true;6186
teardownPlay();6187
app.offline = true;6188
app.battle = app.battle; // kept6189
startPlay({ planet: planet, offline: true, keepBattle: true });6190
}6191
6192
function showOfflineResult ()6193
{6194
app.offlineResultShown = true;6195
var battle = app.battle;6196
var reached = document.getElementById('offline-reached');6197
if (reached)6198
{ reached.textContent = String(battle.round); }6199
var detail = document.getElementById('offline-result-detail');6200
if (detail)6201
{6202
var sch = battle.schedule;6203
var n = sch.opponents;6204
var noun = n === 1 ? 'tegenstander' : 'tegenstanders';6205
detail.textContent = 'Je speelde tegen ' + n + ' ' + noun6206
+ ' met skill ' + Math.round(sch.skill * 100) + '%.';6207
}6208
hideEl('game-over');6209
showEl('offline-result');6210
}6211
6212
function refreshOfflineHud ()6213
{6214
var el = document.getElementById('offline-hud');6215
if (!el)6216
{ return; }6217
if (!(app.offline && app.battle && app.mode === 'playing'))6218
{6219
el.hidden = true;6220
return;6221
}6222
el.hidden = false;6223
var sch = app.battle.schedule;6224
var n = sch.opponents;6225
var noun = n === 1 ? 'tegenstander' : 'tegenstanders';6226
var r = document.getElementById('offline-round');6227
var o = document.getElementById('offline-opponents');6228
var s = document.getElementById('offline-skill');6229
if (r)6230
{ r.textContent = 'Ronde ' + sch.round; }6231
if (o)6232
{ o.textContent = n + ' ' + noun; }6233
if (s)6234
{ s.textContent = 'Skill ' + Math.round(sch.skill * 100) + '%'; }6235
}6236
6237
function hideOfflineHud ()6238
{6239
var el = document.getElementById('offline-hud');6240
if (el)6241
{ el.hidden = true; }6242
}6243
6244
function refreshChainIndicator ()6245
{6246
var el = document.getElementById('chain-indicator');6247
if (!el)6248
{ return; }6249
var info = app.core && app.core.lastChainIndicator;6250
var active = app.core && app.core.hasActiveLandingChain6251
&& app.core.hasActiveLandingChain();6252
// Show only while a chained cluster is still in the air.6253
if (!info || info.chain < 1 || app.mode !== 'playing' || !active)6254
{6255
el.hidden = true;6256
return;6257
}6258
el.hidden = false;6259
el.textContent = 'x' + info.chain + ' +' + info.bonusPct + '%';6260
}6261
6262
function hideChainIndicator ()6263
{6264
var el = document.getElementById('chain-indicator');6265
if (el)6266
{ el.hidden = true; }6267
}6268
6269
function miniViewportCenter (botId)6270
{6271
var el = document.querySelector('#minis .mini[data-player="' + botId + '"] canvas');6272
if (!el)6273
{ return { x: window.innerWidth / 2, y: 40 }; }6274
var rect = el.getBoundingClientRect();6275
return { x: rect.left + rect.width / 2, y: rect.bottom };6276
}6277
6278
function offlineMiniSize (n)6279
{6280
if (n >= 10)6281
{ return { w: 40, h: 52 }; }6282
if (n >= 6)6283
{ return { w: 56, h: 73 }; }6284
return { w: 80, h: 104 };6285
}6286
6287
function updateOfflineMinis (dt, force)6288
{6289
app.miniAcc = (app.miniAcc || 0) + dt;6290
if (!force && app.miniAcc < 0.1)6291
{ return; }6292
app.miniAcc = 0;6293
renderOfflineMinis();6294
}6295
6296
function renderOfflineMinis ()6297
{6298
var container = document.getElementById('minis');6299
if (!container || !app.battle)6300
{ return; }6301
var bots = app.battle.bots;6302
var size = offlineMiniSize(bots.length);6303
container.classList.toggle('crowded', bots.length > 5);6304
var existing = {};6305
var kids = container.querySelectorAll('[data-player]');6306
for (var i = 0; i < kids.length; i++)6307
{ existing[kids[i].getAttribute('data-player')] = kids[i]; }6308
var seen = Object.create(null);6309
for (var i = 0; i < bots.length; i++)6310
{6311
var bot = bots[i];6312
seen[bot.id] = true;6313
var el = existing[bot.id];6314
if (!el)6315
{6316
el = document.createElement('div');6317
el.className = 'mini';6318
el.setAttribute('data-player', bot.id);6319
el.innerHTML = '<div class="mini-name"></div>'6320
+ '<canvas class="mini-canvas" width="' + size.w6321
+ '" height="' + size.h + '"></canvas>'6322
+ '<div class="mini-meta"></div>';6323
container.appendChild(el);6324
}6325
var canvas = el.querySelector('canvas');6326
if (canvas && (canvas.width !== size.w || canvas.height !== size.h))6327
{6328
canvas.width = size.w;6329
canvas.height = size.h;6330
}6331
el.classList.toggle('eliminated', !!bot.eliminated);6332
var planetName = bot.planet && bot.planet.name ? bot.planet.name : '';6333
el.querySelector('.mini-name').textContent = bot.name6334
+ (planetName ? ' · ' + planetName : '');6335
el.querySelector('.mini-meta').textContent = bot.eliminated6336
? 'Uit'6337
: ('Punten ' + (bot.score || 0));6338
var snap = bot.core ? bot.core.fieldSnapshot() : { blocks: [] };6339
if (typeof Online !== 'undefined' && Online._drawMini)6340
{ Online._drawMini(canvas, snap, bot.planet); }6341
}6342
for (var id in existing)6343
{6344
if (!seen[id])6345
{ existing[id].remove(); }6346
}6347
}6348
6349
function buildColumnWarn ()6350
{6351
app.columnWarn = [];6352
if (!app.scene)6353
{ return; }6354
var img = (game.images && (game.images.columnWarn || game.images.pixel)) || null;6355
if (!img)6356
{ return; }6357
for (var c = 0; c < 10; c++)6358
{6359
var obj = new GameObject(0, 0, img, 0);6360
obj.renderer.alpha = 0;6361
obj.renderer.visible = false;6362
app.scene.addObject(obj);6363
app.columnWarn.push(obj);6364
}6365
updateColumnWarn(0);6366
}6367
6368
function updateColumnWarn (dt)6369
{6370
if (!app.columnWarn || !app.core)6371
{ return; }6372
app.warnClock = (app.warnClock || 0) + (dt || 0);6373
var pulse = (typeof GameCore !== 'undefined' && GameCore.columnWarnPulse)6374
? GameCore.columnWarnPulse(app.warnClock)6375
: 0.16 + 0.28 * (0.5 + 0.5 * Math.sin(app.warnClock * 3.45575));6376
var t = app.tile;6377
for (var c = 0; c < app.columnWarn.length; c++)6378
{6379
var obj = app.columnWarn[c];6380
var on = app.core.columnNeedsWarn && app.core.columnNeedsWarn(c);6381
obj.renderer.visible = !!on;6382
obj.renderer.alpha = on ? pulse : 0;6383
if (t)6384
{6385
obj.transform.position.x = c * t + t / 2;6386
obj.transform.position.y = app.fieldH / 2;6387
obj.transform.size = { x: t, y: app.fieldH };6388
}6389
}6390
}6391
5035
function fieldToViewport (col, fieldY)6392
function fieldToViewport (col, fieldY)5036
{6393
{5037
var canvas = app.scene && app.scene.canvas;6394
var canvas = app.scene && app.scene.canvas;@@ -5519,6 +6876,11 @@ function confirmPlanetSelect ()5519
openOnlinePanel();6876
openOnlinePanel();5520
return;6877
return;5521
}6878
}6879
if (app.planetSelectContext === 'offline')6880
{6881
startPlay({ planet: planet, offline: true });6882
return;6883
}5522
startPlay({ planet: planet });6884
startPlay({ planet: planet });5523
}6885
}5524
6886
The contents of this binary file are not shown.
@@ -18,6 +18,7 @@
18
18
<h1>Meteors</h1>
19
19
<p class="tagline">Drie op een rij, en je blokjes krijgen raketmotoren.</p>
20
20
<button type="button" id="btn-play">Spelen</button>
21
<button type="button" id="btn-offline" class="btn-secondary">Offline Strijd</button>
21
22
<button type="button" id="btn-online" class="btn-secondary">Online spelen</button>
22
23
<p id="last-score" class="last-score" hidden>Laatste score: <strong>0</strong></p>
23
24
<p class="hint">Sleep blokjes verticaal om ze te wisselen. Trek een blokje boven zijn kolom om het omhoog te duwen. Blokjes die het veld verlaten, leveren punten op.</p>
@@ -94,6 +95,21 @@
94
95
<div id="planet-name">Terra</div>
95
96
<div id="planet-stats"></div>
96
97
</div>
98
<div id="offline-hud" class="hud-offline" hidden>
99
<span id="offline-round">Ronde 1</span>
100
<span class="hud-sep">·</span>
101
<span id="offline-opponents">1 tegenstander</span>
102
<span class="hud-sep">·</span>
103
<span id="offline-skill">Skill 5%</span>
104
</div>
105
<div id="chain-indicator" hidden></div>
106
</div>
107
108
<div id="offline-result" class="screen overlay" hidden>
109
<h2>Offline Strijd</h2>
110
<p>Je hebt ronde <strong id="offline-reached">1</strong> bereikt.</p>
111
<p id="offline-result-detail" class="tagline"></p>
112
<button type="button" id="btn-offline-menu">Terug naar het menu</button>
97
113
</div>
98
114
99
115
<div id="game-over" class="screen overlay" hidden>
@@ -18,6 +18,7 @@18
<h1>Meteors</h1>18
<h1>Meteors</h1>19
<p class="tagline">Drie op een rij, en je blokjes krijgen raketmotoren.</p>19
<p class="tagline">Drie op een rij, en je blokjes krijgen raketmotoren.</p>20
<button type="button" id="btn-play">Spelen</button>20
<button type="button" id="btn-play">Spelen</button>21
<button type="button" id="btn-offline" class="btn-secondary">Offline Strijd</button>21
<button type="button" id="btn-online" class="btn-secondary">Online spelen</button>22
<button type="button" id="btn-online" class="btn-secondary">Online spelen</button>22
<p id="last-score" class="last-score" hidden>Laatste score: <strong>0</strong></p>23
<p id="last-score" class="last-score" hidden>Laatste score: <strong>0</strong></p>23
<p class="hint">Sleep blokjes verticaal om ze te wisselen. Trek een blokje boven zijn kolom om het omhoog te duwen. Blokjes die het veld verlaten, leveren punten op.</p>24
<p class="hint">Sleep blokjes verticaal om ze te wisselen. Trek een blokje boven zijn kolom om het omhoog te duwen. Blokjes die het veld verlaten, leveren punten op.</p>@@ -94,6 +95,21 @@94
<div id="planet-name">Terra</div>95
<div id="planet-name">Terra</div>95
<div id="planet-stats"></div>96
<div id="planet-stats"></div>96
</div>97
</div>98
<div id="offline-hud" class="hud-offline" hidden>99
<span id="offline-round">Ronde 1</span>100
<span class="hud-sep">·</span>101
<span id="offline-opponents">1 tegenstander</span>102
<span class="hud-sep">·</span>103
<span id="offline-skill">Skill 5%</span>104
</div>105
<div id="chain-indicator" hidden></div>106
</div>107
108
<div id="offline-result" class="screen overlay" hidden>109
<h2>Offline Strijd</h2>110
<p>Je hebt ronde <strong id="offline-reached">1</strong> bereikt.</p>111
<p id="offline-result-detail" class="tagline"></p>112
<button type="button" id="btn-offline-menu">Terug naar het menu</button>97
</div>113
</div>98
114
99
<div id="game-over" class="screen overlay" hidden>115
<div id="game-over" class="screen overlay" hidden>@@ -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], #planet-select[hidden] { display: none !important; }
49
.screen[hidden], #hud[hidden], #game-over[hidden], #online-panel[hidden], #minis[hidden], #spectator[hidden], #podium[hidden], #flights[hidden], #planet-select[hidden], #offline-result[hidden], #offline-hud[hidden], #chain-indicator[hidden] { display: none !important; }
50
50
51
51
h1 {
52
52
font-size: clamp(48px, 14vw, 96px);
@@ -561,3 +561,43 @@ a.button:is(:hover, :focus-visible) {
561
561
overflow: hidden;
562
562
}
563
563
564
565
/* ---- Offline Strijd (t1119), chain bonus (t1120), column warn (t1123) ---- */
566
.hud-offline {
567
position: absolute;
568
left: 50%;
569
transform: translateX(-50%);
570
bottom: 6px;
571
font-size: 12px;
572
color: #c5cae0;
573
white-space: nowrap;
574
letter-spacing: 0.02em;
575
pointer-events: none;
576
}
577
.hud-sep { opacity: 0.55; margin: 0 0.25em; }
578
#chain-indicator {
579
position: absolute;
580
left: 50%;
581
transform: translateX(-50%);
582
top: 100%;
583
margin-top: 4px;
584
color: #ffe27a;
585
font-weight: 700;
586
font-size: 14px;
587
text-shadow: 0 1px 4px #000;
588
pointer-events: none;
589
z-index: 5;
590
}
591
#offline-result h2 { color: #ffe27a; }
592
#minis {
593
overflow: auto;
594
flex-wrap: wrap;
595
}
596
#minis.crowded .mini { min-width: 44px; }
597
#minis.crowded .mini-canvas {
598
width: 56px;
599
height: 73px;
600
}
601
@media (max-width: 520px) {
602
.hud-offline { font-size: 11px; bottom: 4px; }
603
}
@@ -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], #planet-select[hidden] { display: none !important; }49
.screen[hidden], #hud[hidden], #game-over[hidden], #online-panel[hidden], #minis[hidden], #spectator[hidden], #podium[hidden], #flights[hidden], #planet-select[hidden], #offline-result[hidden], #offline-hud[hidden], #chain-indicator[hidden] { display: none !important; }50
50
51
h1 {51
h1 {52
font-size: clamp(48px, 14vw, 96px);52
font-size: clamp(48px, 14vw, 96px);@@ -561,3 +561,43 @@ a.button:is(:hover, :focus-visible) {561
overflow: hidden;561
overflow: hidden;562
}562
}563
563
564
565
/* ---- Offline Strijd (t1119), chain bonus (t1120), column warn (t1123) ---- */566
.hud-offline {567
position: absolute;568
left: 50%;569
transform: translateX(-50%);570
bottom: 6px;571
font-size: 12px;572
color: #c5cae0;573
white-space: nowrap;574
letter-spacing: 0.02em;575
pointer-events: none;576
}577
.hud-sep { opacity: 0.55; margin: 0 0.25em; }578
#chain-indicator {579
position: absolute;580
left: 50%;581
transform: translateX(-50%);582
top: 100%;583
margin-top: 4px;584
color: #ffe27a;585
font-weight: 700;586
font-size: 14px;587
text-shadow: 0 1px 4px #000;588
pointer-events: none;589
z-index: 5;590
}591
#offline-result h2 { color: #ffe27a; }592
#minis {593
overflow: auto;594
flex-wrap: wrap;595
}596
#minis.crowded .mini { min-width: 44px; }597
#minis.crowded .mini-canvas {598
width: 56px;599
height: 73px;600
}601
@media (max-width: 520px) {602
.hud-offline { font-size: 11px; bottom: 4px; }603
}@@ -256,8 +256,10 @@ Aanname:
256
256
telt **12** werelden, van makkelijk (Aurel: gameplay-Power 0, 60 % miss,
257
257
getoonde Power 0 %) tot moeilijk (Cinder: gameplay-Power 1, 5 % miss,
258
258
getoonde Power 92 %). Terra (44 % getoonde Power) blijft de standaard.
259
- Zwaartekracht (`jumpsToClear` 1–4): één sprong haalt `1/jumpsToClear` van
260
de veldhoogte. Luchtweerstand (`fallTime` 1–5 s tot de bodem). Massa
259
- Zwaartekracht (`jumpsToClear` 1–4): één sprong haalt
260
`1,5 / jumpsToClear` van de veldhoogte (t1119, +50 %). Luchtweerstand
261
(`fallTime` 1–5; de tijd tot de bodem is sindsdien 2× `fallTime`
262
door de gehalveerde daalsnelheid, t1122). Massa
261
263
(`riseTime` 0,5–3 s tot de apex). Lage massa en lage luchtweerstand en
262
264
hoge zwaartekracht zijn moeilijker. Bounce-duur en apex-ease schalen al
263
265
met `fallTime` (gebouwd in stage 1).
@@ -448,3 +450,93 @@ Aanname:
448
450
scoren over de bovenkant).
449
451
- `?debug` (of `?debug=physics` / `?debug=drag`) zet de
450
452
invariant-checker aan en toont overtredingen in de overlay.
453
454
## t1119 — Offline Strijd, en +50 % spronghoogte
455
456
- **Offline Strijd** is een knop op het hoofdmenu. Het speelt als
457
multiplayer (zelfde schoten, miss-kans van jouw planeet, zichtbare
458
tegenstandervelden), maar volledig client-side tegen lokale bots.
459
Geen server, geen login.
460
- De speler kiest zelf een planeet (dezelfde kiezer als solo). Elke
461
bot krijgt altijd een willekeurig veld en een willekeurige planeet
462
uit de catalogus.
463
- Progressie, tot de speler verliest: **1 tegenstander voor 1 ronde**;
464
daarna **N tegenstanders voor N−1 rondes** (N ≥ 2). Dus: ronde 1 → 1
465
bot; ronde 2 → 2 bots; ronde 3–4 → 3 bots; ronde 5–7 → 4 bots; enz.
466
Na een gewonnen ronde (alle bots uitgeschakeld, dezelfde winconditie
467
als multiplayer) volgt de volgende ronde met een vers veld. Na verlies
468
een eindscherm met de bereikte ronde (de ronde waarin je verloor) en
469
terug naar het menu.
470
- Bot-skill start op **5 %** in ronde 1 en stijgt **1 % per ronde**,
471
met een plafond van 100 %. De HUD toont ronde, aantal tegenstanders
472
en skill.
473
- Skill-mechaniek: elke 0,5 s dobbelt elke levende bot. Als
474
`roll < skill` mag hij één blokje verticaal in een kolom verplaatsen,
475
zo ver als nodig is om een match te maken, mits zo'n zet bestaat
476
(kortste zet, daarna laagste kolom / fromY / toY). Anders doet hij
477
die tick niets. Bots gehoorzamen verder normale fysica, inclusief
478
landing-chain, schoten en miss-kans van *hun* planeet.
479
- Mini's zijn klein (kleiner naarmate er meer bots zijn) en worden
480
maximaal 10 keer per seconde getekend, zodat veel botvelden op mobiel
481
blijven lopen.
482
- **Minimum spronghoogte +50 %** (t1119, alle modes, ook bots):
483
`baseJumpHeight = 1,5 × FIELD_HEIGHT / jumpsToClear`. Verticale en
484
extra-blok-bonussen blijven relatief hetzelfde (120 %, +5 %). De
485
omhoog-snelheid volgt daaruit via de bestaande `launchVelocity` /
486
`launchDeceleration` (massa / `riseTime` onveranderd). De PHP-server
487
berekent geen spronghoogte; die fysica leeft in `planet.js`, gedeeld
488
door solo, online-client en Offline Strijd. De miss-kans-formules
489
(Power) zijn onveranderd.
490
491
## t1120 — landing-chain sprongbonus
492
493
- Als een cluster landt en die landing **direct** een match maakt
494
(gekleurd cargo in dezelfde tick, of na recolor van de grijzen in
495
dezelfde landing), is die lancering **25 % sterker**.
496
- Valt het cluster opnieuw en maakt de volgende landing weer een
497
match, dan komt er weer **+25 %** bij. De keten is **additief**:
498
stap 1, 2, 3, … → ×1,25, ×1,50, ×1,75
499
(`1 + 0,25 × chain`), niet multiplicatief (niet 1,25³).
500
- De teller hoort bij het cluster. Hij gaat naar 0 als het cluster
501
verdwijnt (scoort over de bovenkant, of oplost) of landt **zonder**
502
match. Mid-lucht-matches (keten-herlancering) gebruiken de bestaande
503
spronghoogte en wijzigen de teller niet. Geldt voor grond- én
504
stapellandingen, en voor bots. Een klein HUD-label toont
505
`x2 +50%` (keten en totale bonus).
506
507
## t1121 — visuele wissel-tween
508
509
- Als twee blokjes van plaats wisselen (spelersleep én bot-zetten),
510
animeert het **verplaatste** blokje naar zijn nieuwe cel in **100 ms**
511
met `easeOutCubic` (in het gevraagde bereik 80–120 ms).
512
- Puur visueel: de simulatie en het rooster zijn meteen bijgewerkt,
513
de invariant-checker ziet alleen de logische posities.
514
- Het vastgehouden (gesleepte) blokje volgt de pointer, zonder tween.
515
- Bij snelle opeenvolgende wissels start een lopende tween opnieuw
516
vanaf de huidige visuele y, zodat er niet wordt gesnapt.
517
518
## t1122 — alle daalsnelheden gehalveerd
519
520
- `fallSpeed = 0,5 × FIELD_HEIGHT / fallTime`. Dat dekt: nieuwe
521
spawn-val, losgelaten en ongesteunde blokjes, clusters na hun sprong
522
(terminale zweefsnelheid), en gevallen cargo. Alle planeten, alle
523
modes (inclusief bots). De relatieve verschillen tussen planeten
524
(omgekeerd evenredig met `fallTime`) blijven.
525
- De apex-ease duurt nog steeds `0,15 × fallTime`; `fallAccel` schaalt
526
mee met de gehalveerde `fallSpeed`. Bounce-duur is onveranderd
527
(`0,12 × fallTime`). Omhoog-lancering is onveranderd, behalve de
528
aparte +50 % spronghoogte van t1119. `fallTime` in de catalogus en
529
in de Power-formule blijft hetzelfde getal (1–5).
530
531
## t1123 — rode puls bij volle kolommen
532
533
- Een kolom die **minstens 10 van de 13 rijen** gevuld heeft (net
534
boven 70 %) pulst rood, als een vloeiende sinus-alpha (ongeveer
535
0,55 Hz, alpha 0,16–0,44) **achter** de blokjes.
536
- Geteld worden alleen rustende blokjes: `still`, `settling` en
537
`locked`. **Vliegende, vallende en handmatig gelanceerde** (in de
538
lucht) blokjes tellen niet mee: die zijn tijdelijk en zouden de
539
waarschuwing laten flikkeren.
540
- Geldt voor het veld van de speler én voor tegenstander-/bot-mini's
541
(zelfde puls-klok). Rendering is goedkoop: tien quads op het
542
hoofdveld, één `fillRect` per waarschuwingskolom op de mini-canvas.
@@ -256,8 +256,10 @@ Aanname:256
telt **12** werelden, van makkelijk (Aurel: gameplay-Power 0, 60 % miss,256
telt **12** werelden, van makkelijk (Aurel: gameplay-Power 0, 60 % miss,257
getoonde Power 0 %) tot moeilijk (Cinder: gameplay-Power 1, 5 % miss,257
getoonde Power 0 %) tot moeilijk (Cinder: gameplay-Power 1, 5 % miss,258
getoonde Power 92 %). Terra (44 % getoonde Power) blijft de standaard.258
getoonde Power 92 %). Terra (44 % getoonde Power) blijft de standaard.259
- Zwaartekracht (`jumpsToClear` 1–4): één sprong haalt `1/jumpsToClear` van259
- Zwaartekracht (`jumpsToClear` 1–4): één sprong haalt260
de veldhoogte. Luchtweerstand (`fallTime` 1–5 s tot de bodem). Massa260
`1,5 / jumpsToClear` van de veldhoogte (t1119, +50 %). Luchtweerstand261
(`fallTime` 1–5; de tijd tot de bodem is sindsdien 2× `fallTime`262
door de gehalveerde daalsnelheid, t1122). Massa261
(`riseTime` 0,5–3 s tot de apex). Lage massa en lage luchtweerstand en263
(`riseTime` 0,5–3 s tot de apex). Lage massa en lage luchtweerstand en262
hoge zwaartekracht zijn moeilijker. Bounce-duur en apex-ease schalen al264
hoge zwaartekracht zijn moeilijker. Bounce-duur en apex-ease schalen al263
met `fallTime` (gebouwd in stage 1).265
met `fallTime` (gebouwd in stage 1).@@ -448,3 +450,93 @@ Aanname:448
scoren over de bovenkant).450
scoren over de bovenkant).449
- `?debug` (of `?debug=physics` / `?debug=drag`) zet de451
- `?debug` (of `?debug=physics` / `?debug=drag`) zet de450
invariant-checker aan en toont overtredingen in de overlay.452
invariant-checker aan en toont overtredingen in de overlay.453
454
## t1119 — Offline Strijd, en +50 % spronghoogte455
456
- **Offline Strijd** is een knop op het hoofdmenu. Het speelt als457
multiplayer (zelfde schoten, miss-kans van jouw planeet, zichtbare458
tegenstandervelden), maar volledig client-side tegen lokale bots.459
Geen server, geen login.460
- De speler kiest zelf een planeet (dezelfde kiezer als solo). Elke461
bot krijgt altijd een willekeurig veld en een willekeurige planeet462
uit de catalogus.463
- Progressie, tot de speler verliest: **1 tegenstander voor 1 ronde**;464
daarna **N tegenstanders voor N−1 rondes** (N ≥ 2). Dus: ronde 1 → 1465
bot; ronde 2 → 2 bots; ronde 3–4 → 3 bots; ronde 5–7 → 4 bots; enz.466
Na een gewonnen ronde (alle bots uitgeschakeld, dezelfde winconditie467
als multiplayer) volgt de volgende ronde met een vers veld. Na verlies468
een eindscherm met de bereikte ronde (de ronde waarin je verloor) en469
terug naar het menu.470
- Bot-skill start op **5 %** in ronde 1 en stijgt **1 % per ronde**,471
met een plafond van 100 %. De HUD toont ronde, aantal tegenstanders472
en skill.473
- Skill-mechaniek: elke 0,5 s dobbelt elke levende bot. Als474
`roll < skill` mag hij één blokje verticaal in een kolom verplaatsen,475
zo ver als nodig is om een match te maken, mits zo'n zet bestaat476
(kortste zet, daarna laagste kolom / fromY / toY). Anders doet hij477
die tick niets. Bots gehoorzamen verder normale fysica, inclusief478
landing-chain, schoten en miss-kans van *hun* planeet.479
- Mini's zijn klein (kleiner naarmate er meer bots zijn) en worden480
maximaal 10 keer per seconde getekend, zodat veel botvelden op mobiel481
blijven lopen.482
- **Minimum spronghoogte +50 %** (t1119, alle modes, ook bots):483
`baseJumpHeight = 1,5 × FIELD_HEIGHT / jumpsToClear`. Verticale en484
extra-blok-bonussen blijven relatief hetzelfde (120 %, +5 %). De485
omhoog-snelheid volgt daaruit via de bestaande `launchVelocity` /486
`launchDeceleration` (massa / `riseTime` onveranderd). De PHP-server487
berekent geen spronghoogte; die fysica leeft in `planet.js`, gedeeld488
door solo, online-client en Offline Strijd. De miss-kans-formules489
(Power) zijn onveranderd.490
491
## t1120 — landing-chain sprongbonus492
493
- Als een cluster landt en die landing **direct** een match maakt494
(gekleurd cargo in dezelfde tick, of na recolor van de grijzen in495
dezelfde landing), is die lancering **25 % sterker**.496
- Valt het cluster opnieuw en maakt de volgende landing weer een497
match, dan komt er weer **+25 %** bij. De keten is **additief**:498
stap 1, 2, 3, … → ×1,25, ×1,50, ×1,75499
(`1 + 0,25 × chain`), niet multiplicatief (niet 1,25³).500
- De teller hoort bij het cluster. Hij gaat naar 0 als het cluster501
verdwijnt (scoort over de bovenkant, of oplost) of landt **zonder**502
match. Mid-lucht-matches (keten-herlancering) gebruiken de bestaande503
spronghoogte en wijzigen de teller niet. Geldt voor grond- én504
stapellandingen, en voor bots. Een klein HUD-label toont505
`x2 +50%` (keten en totale bonus).506
507
## t1121 — visuele wissel-tween508
509
- Als twee blokjes van plaats wisselen (spelersleep én bot-zetten),510
animeert het **verplaatste** blokje naar zijn nieuwe cel in **100 ms**511
met `easeOutCubic` (in het gevraagde bereik 80–120 ms).512
- Puur visueel: de simulatie en het rooster zijn meteen bijgewerkt,513
de invariant-checker ziet alleen de logische posities.514
- Het vastgehouden (gesleepte) blokje volgt de pointer, zonder tween.515
- Bij snelle opeenvolgende wissels start een lopende tween opnieuw516
vanaf de huidige visuele y, zodat er niet wordt gesnapt.517
518
## t1122 — alle daalsnelheden gehalveerd519
520
- `fallSpeed = 0,5 × FIELD_HEIGHT / fallTime`. Dat dekt: nieuwe521
spawn-val, losgelaten en ongesteunde blokjes, clusters na hun sprong522
(terminale zweefsnelheid), en gevallen cargo. Alle planeten, alle523
modes (inclusief bots). De relatieve verschillen tussen planeten524
(omgekeerd evenredig met `fallTime`) blijven.525
- De apex-ease duurt nog steeds `0,15 × fallTime`; `fallAccel` schaalt526
mee met de gehalveerde `fallSpeed`. Bounce-duur is onveranderd527
(`0,12 × fallTime`). Omhoog-lancering is onveranderd, behalve de528
aparte +50 % spronghoogte van t1119. `fallTime` in de catalogus en529
in de Power-formule blijft hetzelfde getal (1–5).530
531
## t1123 — rode puls bij volle kolommen532
533
- Een kolom die **minstens 10 van de 13 rijen** gevuld heeft (net534
boven 70 %) pulst rood, als een vloeiende sinus-alpha (ongeveer535
0,55 Hz, alpha 0,16–0,44) **achter** de blokjes.536
- Geteld worden alleen rustende blokjes: `still`, `settling` en537
`locked`. **Vliegende, vallende en handmatig gelanceerde** (in de538
lucht) blokjes tellen niet mee: die zijn tijdelijk en zouden de539
waarschuwing laten flikkeren.540
- Geldt voor het veld van de speler én voor tegenstander-/bot-mini's541
(zelfde puls-klok). Rendering is goedkoop: tien quads op het542
hoofdveld, één `fillRect` per waarschuwingskolom op de mini-canvas.@@ -18,6 +18,7 @@ FILES=(
18
18
"$SRC_DIR/easing.js"
19
19
"$SRC_DIR/gameCore.js"
20
20
"$SRC_DIR/online.js"
21
"$SRC_DIR/offline.js"
21
22
"$SRC_DIR/main.js"
22
23
)
23
24
@@ -18,6 +18,7 @@ FILES=(18
"$SRC_DIR/easing.js"18
"$SRC_DIR/easing.js"19
"$SRC_DIR/gameCore.js"19
"$SRC_DIR/gameCore.js"20
"$SRC_DIR/online.js"20
"$SRC_DIR/online.js"21
"$SRC_DIR/offline.js"21
"$SRC_DIR/main.js"22
"$SRC_DIR/main.js"22
)23
)23
24
@@ -51,11 +51,29 @@ function easeOutElastic (t)
51
51
return Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p) + 1;
52
52
}
53
53
54
/** easeOutCubic: 1 − (1−t)³. Smooth, no overshoot (easings.net). */
55
function easeOutCubic (t)
56
{
57
t = clamp01(t);
58
var u = 1 - t;
59
return 1 - u * u * u;
60
}
61
54
62
function tween (from, to, t, ease)
55
63
{
56
64
return from + (to - from) * ease(clamp01(t));
57
65
}
58
66
67
/**
68
* Visual-only block swap tween (t1121). Game logic and the grid update
69
* immediately; this only moves the displaced sprite. 100 ms sits in the
70
* requested 80–120 ms range.
71
*/
72
var SWAP_TWEEN = {
73
duration: 0.100,
74
ease: easeOutCubic
75
};
76
59
77
/**
60
78
* DEFAULT settings of Tim's KWin Click Tween
61
79
* (git.timfalken.com/timfa/click-tween).
@@ -99,8 +117,10 @@ var Easing = {
99
117
ELASTIC_AMPLITUDE: ELASTIC_AMPLITUDE,
100
118
easeOutBack: easeOutBack,
101
119
easeOutElastic: easeOutElastic,
120
easeOutCubic: easeOutCubic,
102
121
tween: tween,
103
122
CLICK_TWEEN: CLICK_TWEEN,
123
SWAP_TWEEN: SWAP_TWEEN,
104
124
clamp01: clamp01,
105
125
bouncePose: bouncePose
106
126
};
@@ -51,11 +51,29 @@ function easeOutElastic (t)51
return Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p) + 1;51
return Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p) + 1;52
}52
}53
53
54
/** easeOutCubic: 1 − (1−t)³. Smooth, no overshoot (easings.net). */55
function easeOutCubic (t)56
{57
t = clamp01(t);58
var u = 1 - t;59
return 1 - u * u * u;60
}61
54
function tween (from, to, t, ease)62
function tween (from, to, t, ease)55
{63
{56
return from + (to - from) * ease(clamp01(t));64
return from + (to - from) * ease(clamp01(t));57
}65
}58
66
67
/**68
* Visual-only block swap tween (t1121). Game logic and the grid update69
* immediately; this only moves the displaced sprite. 100 ms sits in the70
* requested 80–120 ms range.71
*/72
var SWAP_TWEEN = {73
duration: 0.100,74
ease: easeOutCubic75
};76
59
/**77
/**60
* DEFAULT settings of Tim's KWin Click Tween78
* DEFAULT settings of Tim's KWin Click Tween61
* (git.timfalken.com/timfa/click-tween).79
* (git.timfalken.com/timfa/click-tween).@@ -99,8 +117,10 @@ var Easing = {99
ELASTIC_AMPLITUDE: ELASTIC_AMPLITUDE,117
ELASTIC_AMPLITUDE: ELASTIC_AMPLITUDE,100
easeOutBack: easeOutBack,118
easeOutBack: easeOutBack,101
easeOutElastic: easeOutElastic,119
easeOutElastic: easeOutElastic,120
easeOutCubic: easeOutCubic,102
tween: tween,121
tween: tween,103
CLICK_TWEEN: CLICK_TWEEN,122
CLICK_TWEEN: CLICK_TWEEN,123
SWAP_TWEEN: SWAP_TWEEN,104
clamp01: clamp01,124
clamp01: clamp01,105
bouncePose: bouncePose125
bouncePose: bouncePose106
};126
};@@ -31,6 +31,13 @@ var SWAP_DISTANCE = 0.25;
31
31
var SNAP_Y = 0.5;
32
32
// Horizontal slop (tiles) for snapping to a neighbouring column on press.
33
33
var HORIZONTAL_SLOP = 0.35;
34
/** t1120: additive jump bonus per landing-chain step. A landing that
35
* immediately makes a match launches at (1 + 0.25 * chain) times the
36
* usual height, with chain 1, 2, 3, … → ×1.25, ×1.50, ×1.75. */
37
var LANDING_CHAIN_BONUS = 0.25;
38
/** t1123: a column pulses red at or above this many grounded rows
39
* (10 of 13 is just over 70%). */
40
var COLUMN_WARN_ROWS = 10;
34
41
35
42
function UnionFind ()
36
43
{
@@ -85,6 +92,10 @@ function GameCore (planet, rng)
85
92
this.strictInvariants = false;
86
93
this.debugInvariants = false;
87
94
this.lastInvariantViolations = [];
95
// t1121: visual-only swap events, consumed by the view each frame.
96
this.swapEvents = [];
97
// t1120: last landing-chain indicator { chain, bonusPct }, or null.
98
this.lastChainIndicator = null;
88
99
}
89
100
90
101
function optsMissChance (args)
@@ -103,6 +114,8 @@ GameCore.LAUNCH_PULL = LAUNCH_PULL;
103
114
GameCore.SWAP_DISTANCE = SWAP_DISTANCE;
104
115
GameCore.SNAP_Y = SNAP_Y;
105
116
GameCore.HORIZONTAL_SLOP = HORIZONTAL_SLOP;
117
GameCore.LANDING_CHAIN_BONUS = LANDING_CHAIN_BONUS;
118
GameCore.COLUMN_WARN_ROWS = COLUMN_WARN_ROWS;
106
119
GameCore.DEFAULT_MISS_CHANCE = 0.30;
107
120
GameCore.STATE_STILL = STATE_STILL;
108
121
GameCore.STATE_FALLING = STATE_FALLING;
@@ -251,6 +264,56 @@ GameCore.prototype.groundedCount = function (col)
251
264
return n;
252
265
};
253
266
267
GameCore.prototype.columnNeedsWarn = function (col)
268
{
269
return this.groundedCount(col) >= COLUMN_WARN_ROWS;
270
};
271
272
/**
273
* Which columns of a field snapshot should pulse (t1123). Flying,
274
* falling and manual (airborne) blocks do not count: they are
275
* temporary and would flicker the warning. Still, settling and
276
* locked (grounded) blocks do.
277
*/
278
GameCore.warnColumnsFromSnapshot = function (snapshot, threshold)
279
{
280
threshold = threshold == null ? COLUMN_WARN_ROWS : threshold;
281
var width = (snapshot && snapshot.width) || 10;
282
var flags = [];
283
var counts = [];
284
for (var c = 0; c < width; c++)
285
{
286
counts[c] = 0;
287
flags[c] = false;
288
}
289
var blocks = (snapshot && snapshot.blocks) || [];
290
for (var i = 0; i < blocks.length; i++)
291
{
292
var b = blocks[i];
293
if (b.col < 0 || b.col >= width)
294
{ continue; }
295
if (b.state === 'still' || b.state === 'settling' || b.state === 'locked')
296
{ counts[b.col]++; }
297
}
298
for (var c = 0; c < width; c++)
299
{ flags[c] = counts[c] >= threshold; }
300
return flags;
301
};
302
303
GameCore.columnWarnPulse = function (timeSec)
304
{
305
// Smooth sine, ~0.5 Hz, alpha 0.16–0.44. Shared by the player
306
// field and opponent / bot minis so they pulse in sync.
307
var t = timeSec;
308
if (t == null)
309
{
310
t = (typeof performance !== 'undefined' && performance.now)
311
? performance.now() / 1000
312
: Date.now() / 1000;
313
}
314
return 0.16 + 0.28 * (0.5 + 0.5 * Math.sin(t * Math.PI * 2 * 0.55));
315
};
316
254
317
GameCore.prototype.blockAt = function (col, row)
255
318
{
256
319
for (var i = 0; i < this.blocks.length; i++)
@@ -872,6 +935,14 @@ GameCore.prototype.mergeClusterGroup = function (clusters)
872
935
keep.decel = decelSum / n;
873
936
keep.jumpHeight = hSum / n;
874
937
keep.phase = keep.vy > 1e-10 ? 'up' : 'down';
938
var maxChain = 0;
939
for (var c = 0; c < clusters.length; c++)
940
{
941
var ch = clusters[c].landingChain || 0;
942
if (ch > maxChain)
943
{ maxChain = ch; }
944
}
945
keep.landingChain = maxChain;
875
946
for (var c = 0; c < clusters.length; c++)
876
947
{
877
948
var mem = this.clusterMembers(clusters[c].id);
@@ -1266,6 +1337,9 @@ GameCore.prototype.landCluster = function (cluster, members)
1266
1337
}
1267
1338
cluster.phase = 'landed';
1268
1339
cluster.vy = 0;
1340
cluster.landedPending = true;
1341
if (cluster.landingChain == null)
1342
{ cluster.landingChain = 0; }
1269
1343
};
1270
1344
1271
1345
/**
@@ -1287,6 +1361,10 @@ GameCore.prototype.releaseLandedCluster = function (cluster)
1287
1361
block.color = this.randomColor();
1288
1362
block.settleTime = 0;
1289
1363
}
1364
// Persist the chain across release so a post-recolor match in
1365
// this same tick still gets the landing bonus (t1120).
1366
block.justLanded = !!cluster.landedPending;
1367
block.landingChain = cluster.landingChain || 0;
1290
1368
this.leaveCluster(block);
1291
1369
// Always drop leftover launch / manual velocity. A stale upward
1292
1370
// vy here is what sends blocks off the top "very fast" after
@@ -2162,7 +2240,10 @@ GameCore.prototype.resolveMatches = function ()
2162
2240
{ return []; }
2163
2241
var lines = this.findMatchLines();
2164
2242
if (!lines.length)
2165
{ return []; }
2243
{
2244
this.finishLandingChains([]);
2245
return [];
2246
}
2166
2247
2167
2248
var uf = new UnionFind();
2168
2249
var blockById = Object.create(null);
@@ -2229,9 +2310,19 @@ GameCore.prototype.resolveMatches = function ()
2229
2310
{ height = h; }
2230
2311
}
2231
2312
}
2232
this.launchCluster(group, height);
2233
launched.push({ blocks: group, jumpHeight: height });
2313
var chain = this.landingChainFor(group);
2314
var bonusMul = 1 + LANDING_CHAIN_BONUS * chain;
2315
height *= bonusMul;
2316
this.launchCluster(group, height, { landingChain: chain });
2317
launched.push({
2318
blocks: group,
2319
jumpHeight: height,
2320
landingChain: chain,
2321
chainBonus: bonusMul
2322
});
2234
2323
}
2324
this.finishLandingChains(launched);
2325
this.updateChainIndicator(launched);
2235
2326
return launched;
2236
2327
};
2237
2328
@@ -2239,8 +2330,9 @@ GameCore.prototype.resolveMatches = function ()
2239
2330
* Gray the matched blocks, take everything sitting on top of them in
2240
2331
* those columns, link them, and launch with jump height `height`.
2241
2332
*/
2242
GameCore.prototype.launchCluster = function (matchedBlocks, height)
2333
GameCore.prototype.launchCluster = function (matchedBlocks, height, opts)
2243
2334
{
2335
opts = opts || {};
2244
2336
var lowestInCol = Object.create(null);
2245
2337
var matchedIds = Object.create(null);
2246
2338
for (var i = 0; i < matchedBlocks.length; i++)
@@ -2257,7 +2349,9 @@ GameCore.prototype.launchCluster = function (matchedBlocks, height)
2257
2349
jumpHeight: height,
2258
2350
vy: PlanetMod.launchVelocity(this.planet, height),
2259
2351
decel: PlanetMod.launchDeceleration(this.planet, height),
2260
phase: 'up'
2352
phase: 'up',
2353
landingChain: opts.landingChain || 0,
2354
landedPending: false
2261
2355
};
2262
2356
this.clusters[clusterId] = cluster;
2263
2357
@@ -2633,10 +2727,149 @@ GameCore.prototype.swapToward = function (block, targetY)
2633
2727
2634
2728
GameCore.prototype.swapBlocks = function (a, b)
2635
2729
{
2636
var y = a.y;
2637
a.y = b.y;
2638
b.y = y;
2730
var ay = a.y;
2731
var by = b.y;
2732
a.y = by;
2733
b.y = ay;
2639
2734
this.transferLandedMembership(a, b);
2735
if (!this.swapEvents)
2736
{ this.swapEvents = []; }
2737
this.swapEvents.push({ id: a.id, fromY: ay, toY: by, col: a.col });
2738
this.swapEvents.push({ id: b.id, fromY: by, toY: ay, col: b.col });
2739
};
2740
2741
GameCore.prototype.consumeSwapEvents = function ()
2742
{
2743
var ev = this.swapEvents || [];
2744
this.swapEvents = [];
2745
return ev;
2746
};
2747
2748
/**
2749
* Highest landing-chain counter among just-landed members of this
2750
* match group, plus one. Returns 0 when the match did not come from
2751
* a cluster landing (player/bot swap, mid-air, etc.).
2752
*/
2753
GameCore.prototype.landingChainFor = function (group)
2754
{
2755
var maxChain = 0;
2756
var fromLanding = false;
2757
for (var i = 0; i < group.length; i++)
2758
{
2759
var block = group[i];
2760
if (block.justLanded)
2761
{
2762
fromLanding = true;
2763
if ((block.landingChain || 0) > maxChain)
2764
{ maxChain = block.landingChain || 0; }
2765
}
2766
if (block.clusterId != null)
2767
{
2768
var cluster = this.clusters[block.clusterId];
2769
if (cluster && cluster.landedPending)
2770
{
2771
fromLanding = true;
2772
if ((cluster.landingChain || 0) > maxChain)
2773
{ maxChain = cluster.landingChain || 0; }
2774
}
2775
}
2776
}
2777
if (!fromLanding)
2778
{ return 0; }
2779
return maxChain + 1;
2780
};
2781
2782
/**
2783
* After resolveMatches: clear the landing-pending flag and reset the
2784
* chain on landings that did not make a match. A cluster that is still
2785
* settling (greys not yet recolored) keeps landedPending so a later
2786
* post-recolor match in this same landing still gets the bonus.
2787
*/
2788
GameCore.prototype.finishLandingChains = function (launched)
2789
{
2790
var launchedIds = Object.create(null);
2791
launched = launched || [];
2792
for (var i = 0; i < launched.length; i++)
2793
{
2794
var blocks = launched[i].blocks || [];
2795
for (var j = 0; j < blocks.length; j++)
2796
{ launchedIds[blocks[j].id] = true; }
2797
}
2798
2799
for (var i = 0; i < this.blocks.length; i++)
2800
{
2801
var block = this.blocks[i];
2802
if (!block.justLanded)
2803
{ continue; }
2804
if (!launchedIds[block.id])
2805
{ block.landingChain = 0; }
2806
block.justLanded = false;
2807
}
2808
2809
var ids = Object.keys(this.clusters);
2810
for (var c = 0; c < ids.length; c++)
2811
{
2812
var cluster = this.clusters[ids[c]];
2813
if (!cluster || !cluster.landedPending)
2814
{ continue; }
2815
var members = this.clusterMembers(cluster.id);
2816
var anyLaunched = false;
2817
var stillSettling = false;
2818
for (var i = 0; i < members.length; i++)
2819
{
2820
if (launchedIds[members[i].id])
2821
{ anyLaunched = true; }
2822
if (members[i].state === STATE_SETTLING)
2823
{ stillSettling = true; }
2824
}
2825
if (anyLaunched)
2826
{
2827
cluster.landingChain = 0;
2828
cluster.landedPending = false;
2829
}
2830
else if (!stillSettling)
2831
{
2832
// Released leftovers or a fully-still landed group that
2833
// already had its match opportunity and missed it.
2834
cluster.landingChain = 0;
2835
cluster.landedPending = false;
2836
}
2837
// else: still settling, no match yet — keep landedPending.
2838
}
2839
};
2840
2841
GameCore.prototype.updateChainIndicator = function (launched)
2842
{
2843
var maxChain = 0;
2844
for (var i = 0; i < launched.length; i++)
2845
{
2846
var ch = launched[i].landingChain || 0;
2847
if (ch > maxChain)
2848
{ maxChain = ch; }
2849
}
2850
if (maxChain >= 1)
2851
{
2852
this.lastChainIndicator = {
2853
chain: maxChain,
2854
bonusPct: Math.round(maxChain * LANDING_CHAIN_BONUS * 100)
2855
};
2856
return;
2857
}
2858
if (!this.hasActiveLandingChain())
2859
{ this.lastChainIndicator = null; }
2860
};
2861
2862
GameCore.prototype.hasActiveLandingChain = function ()
2863
{
2864
var ids = Object.keys(this.clusters);
2865
for (var i = 0; i < ids.length; i++)
2866
{
2867
var cluster = this.clusters[ids[i]];
2868
if (cluster && (cluster.landingChain || 0) >= 1
2869
&& cluster.phase !== 'landed')
2870
{ return true; }
2871
}
2872
return false;
2640
2873
};
2641
2874
2642
2875
/**
@@ -31,6 +31,13 @@ var SWAP_DISTANCE = 0.25;31
var SNAP_Y = 0.5;31
var SNAP_Y = 0.5;32
// Horizontal slop (tiles) for snapping to a neighbouring column on press.32
// Horizontal slop (tiles) for snapping to a neighbouring column on press.33
var HORIZONTAL_SLOP = 0.35;33
var HORIZONTAL_SLOP = 0.35;34
/** t1120: additive jump bonus per landing-chain step. A landing that35
* immediately makes a match launches at (1 + 0.25 * chain) times the36
* usual height, with chain 1, 2, 3, … → ×1.25, ×1.50, ×1.75. */37
var LANDING_CHAIN_BONUS = 0.25;38
/** t1123: a column pulses red at or above this many grounded rows39
* (10 of 13 is just over 70%). */40
var COLUMN_WARN_ROWS = 10;34
41
35
function UnionFind ()42
function UnionFind ()36
{43
{@@ -85,6 +92,10 @@ function GameCore (planet, rng)85
this.strictInvariants = false;92
this.strictInvariants = false;86
this.debugInvariants = false;93
this.debugInvariants = false;87
this.lastInvariantViolations = [];94
this.lastInvariantViolations = [];95
// t1121: visual-only swap events, consumed by the view each frame.96
this.swapEvents = [];97
// t1120: last landing-chain indicator { chain, bonusPct }, or null.98
this.lastChainIndicator = null;88
}99
}89
100
90
function optsMissChance (args)101
function optsMissChance (args)@@ -103,6 +114,8 @@ GameCore.LAUNCH_PULL = LAUNCH_PULL;103
GameCore.SWAP_DISTANCE = SWAP_DISTANCE;114
GameCore.SWAP_DISTANCE = SWAP_DISTANCE;104
GameCore.SNAP_Y = SNAP_Y;115
GameCore.SNAP_Y = SNAP_Y;105
GameCore.HORIZONTAL_SLOP = HORIZONTAL_SLOP;116
GameCore.HORIZONTAL_SLOP = HORIZONTAL_SLOP;117
GameCore.LANDING_CHAIN_BONUS = LANDING_CHAIN_BONUS;118
GameCore.COLUMN_WARN_ROWS = COLUMN_WARN_ROWS;106
GameCore.DEFAULT_MISS_CHANCE = 0.30;119
GameCore.DEFAULT_MISS_CHANCE = 0.30;107
GameCore.STATE_STILL = STATE_STILL;120
GameCore.STATE_STILL = STATE_STILL;108
GameCore.STATE_FALLING = STATE_FALLING;121
GameCore.STATE_FALLING = STATE_FALLING;@@ -251,6 +264,56 @@ GameCore.prototype.groundedCount = function (col)251
return n;264
return n;252
};265
};253
266
267
GameCore.prototype.columnNeedsWarn = function (col)268
{269
return this.groundedCount(col) >= COLUMN_WARN_ROWS;270
};271
272
/**273
* Which columns of a field snapshot should pulse (t1123). Flying,274
* falling and manual (airborne) blocks do not count: they are275
* temporary and would flicker the warning. Still, settling and276
* locked (grounded) blocks do.277
*/278
GameCore.warnColumnsFromSnapshot = function (snapshot, threshold)279
{280
threshold = threshold == null ? COLUMN_WARN_ROWS : threshold;281
var width = (snapshot && snapshot.width) || 10;282
var flags = [];283
var counts = [];284
for (var c = 0; c < width; c++)285
{286
counts[c] = 0;287
flags[c] = false;288
}289
var blocks = (snapshot && snapshot.blocks) || [];290
for (var i = 0; i < blocks.length; i++)291
{292
var b = blocks[i];293
if (b.col < 0 || b.col >= width)294
{ continue; }295
if (b.state === 'still' || b.state === 'settling' || b.state === 'locked')296
{ counts[b.col]++; }297
}298
for (var c = 0; c < width; c++)299
{ flags[c] = counts[c] >= threshold; }300
return flags;301
};302
303
GameCore.columnWarnPulse = function (timeSec)304
{305
// Smooth sine, ~0.5 Hz, alpha 0.16–0.44. Shared by the player306
// field and opponent / bot minis so they pulse in sync.307
var t = timeSec;308
if (t == null)309
{310
t = (typeof performance !== 'undefined' && performance.now)311
? performance.now() / 1000312
: Date.now() / 1000;313
}314
return 0.16 + 0.28 * (0.5 + 0.5 * Math.sin(t * Math.PI * 2 * 0.55));315
};316
254
GameCore.prototype.blockAt = function (col, row)317
GameCore.prototype.blockAt = function (col, row)255
{318
{256
for (var i = 0; i < this.blocks.length; i++)319
for (var i = 0; i < this.blocks.length; i++)@@ -872,6 +935,14 @@ GameCore.prototype.mergeClusterGroup = function (clusters)872
keep.decel = decelSum / n;935
keep.decel = decelSum / n;873
keep.jumpHeight = hSum / n;936
keep.jumpHeight = hSum / n;874
keep.phase = keep.vy > 1e-10 ? 'up' : 'down';937
keep.phase = keep.vy > 1e-10 ? 'up' : 'down';938
var maxChain = 0;939
for (var c = 0; c < clusters.length; c++)940
{941
var ch = clusters[c].landingChain || 0;942
if (ch > maxChain)943
{ maxChain = ch; }944
}945
keep.landingChain = maxChain;875
for (var c = 0; c < clusters.length; c++)946
for (var c = 0; c < clusters.length; c++)876
{947
{877
var mem = this.clusterMembers(clusters[c].id);948
var mem = this.clusterMembers(clusters[c].id);@@ -1266,6 +1337,9 @@ GameCore.prototype.landCluster = function (cluster, members)1266
}1337
}1267
cluster.phase = 'landed';1338
cluster.phase = 'landed';1268
cluster.vy = 0;1339
cluster.vy = 0;1340
cluster.landedPending = true;1341
if (cluster.landingChain == null)1342
{ cluster.landingChain = 0; }1269
};1343
};1270
1344
1271
/**1345
/**@@ -1287,6 +1361,10 @@ GameCore.prototype.releaseLandedCluster = function (cluster)1287
block.color = this.randomColor();1361
block.color = this.randomColor();1288
block.settleTime = 0;1362
block.settleTime = 0;1289
}1363
}1364
// Persist the chain across release so a post-recolor match in1365
// this same tick still gets the landing bonus (t1120).1366
block.justLanded = !!cluster.landedPending;1367
block.landingChain = cluster.landingChain || 0;1290
this.leaveCluster(block);1368
this.leaveCluster(block);1291
// Always drop leftover launch / manual velocity. A stale upward1369
// Always drop leftover launch / manual velocity. A stale upward1292
// vy here is what sends blocks off the top "very fast" after1370
// vy here is what sends blocks off the top "very fast" after@@ -2162,7 +2240,10 @@ GameCore.prototype.resolveMatches = function ()2162
{ return []; }2240
{ return []; }2163
var lines = this.findMatchLines();2241
var lines = this.findMatchLines();2164
if (!lines.length)2242
if (!lines.length)2165
{ return []; }2243
{2244
this.finishLandingChains([]);2245
return [];2246
}2166
2247
2167
var uf = new UnionFind();2248
var uf = new UnionFind();2168
var blockById = Object.create(null);2249
var blockById = Object.create(null);@@ -2229,9 +2310,19 @@ GameCore.prototype.resolveMatches = function ()2229
{ height = h; }2310
{ height = h; }2230
}2311
}2231
}2312
}2232
this.launchCluster(group, height);2313
var chain = this.landingChainFor(group);2233
launched.push({ blocks: group, jumpHeight: height });2314
var bonusMul = 1 + LANDING_CHAIN_BONUS * chain;2315
height *= bonusMul;2316
this.launchCluster(group, height, { landingChain: chain });2317
launched.push({2318
blocks: group,2319
jumpHeight: height,2320
landingChain: chain,2321
chainBonus: bonusMul2322
});2234
}2323
}2324
this.finishLandingChains(launched);2325
this.updateChainIndicator(launched);2235
return launched;2326
return launched;2236
};2327
};2237
2328
@@ -2239,8 +2330,9 @@ GameCore.prototype.resolveMatches = function ()2239
* Gray the matched blocks, take everything sitting on top of them in2330
* Gray the matched blocks, take everything sitting on top of them in2240
* those columns, link them, and launch with jump height `height`.2331
* those columns, link them, and launch with jump height `height`.2241
*/2332
*/2242
GameCore.prototype.launchCluster = function (matchedBlocks, height)2333
GameCore.prototype.launchCluster = function (matchedBlocks, height, opts)2243
{2334
{2335
opts = opts || {};2244
var lowestInCol = Object.create(null);2336
var lowestInCol = Object.create(null);2245
var matchedIds = Object.create(null);2337
var matchedIds = Object.create(null);2246
for (var i = 0; i < matchedBlocks.length; i++)2338
for (var i = 0; i < matchedBlocks.length; i++)@@ -2257,7 +2349,9 @@ GameCore.prototype.launchCluster = function (matchedBlocks, height)2257
jumpHeight: height,2349
jumpHeight: height,2258
vy: PlanetMod.launchVelocity(this.planet, height),2350
vy: PlanetMod.launchVelocity(this.planet, height),2259
decel: PlanetMod.launchDeceleration(this.planet, height),2351
decel: PlanetMod.launchDeceleration(this.planet, height),2260
phase: 'up'2352
phase: 'up',2353
landingChain: opts.landingChain || 0,2354
landedPending: false2261
};2355
};2262
this.clusters[clusterId] = cluster;2356
this.clusters[clusterId] = cluster;2263
2357
@@ -2633,10 +2727,149 @@ GameCore.prototype.swapToward = function (block, targetY)2633
2727
2634
GameCore.prototype.swapBlocks = function (a, b)2728
GameCore.prototype.swapBlocks = function (a, b)2635
{2729
{2636
var y = a.y;2730
var ay = a.y;2637
a.y = b.y;2731
var by = b.y;2638
b.y = y;2732
a.y = by;2733
b.y = ay;2639
this.transferLandedMembership(a, b);2734
this.transferLandedMembership(a, b);2735
if (!this.swapEvents)2736
{ this.swapEvents = []; }2737
this.swapEvents.push({ id: a.id, fromY: ay, toY: by, col: a.col });2738
this.swapEvents.push({ id: b.id, fromY: by, toY: ay, col: b.col });2739
};2740
2741
GameCore.prototype.consumeSwapEvents = function ()2742
{2743
var ev = this.swapEvents || [];2744
this.swapEvents = [];2745
return ev;2746
};2747
2748
/**2749
* Highest landing-chain counter among just-landed members of this2750
* match group, plus one. Returns 0 when the match did not come from2751
* a cluster landing (player/bot swap, mid-air, etc.).2752
*/2753
GameCore.prototype.landingChainFor = function (group)2754
{2755
var maxChain = 0;2756
var fromLanding = false;2757
for (var i = 0; i < group.length; i++)2758
{2759
var block = group[i];2760
if (block.justLanded)2761
{2762
fromLanding = true;2763
if ((block.landingChain || 0) > maxChain)2764
{ maxChain = block.landingChain || 0; }2765
}2766
if (block.clusterId != null)2767
{2768
var cluster = this.clusters[block.clusterId];2769
if (cluster && cluster.landedPending)2770
{2771
fromLanding = true;2772
if ((cluster.landingChain || 0) > maxChain)2773
{ maxChain = cluster.landingChain || 0; }2774
}2775
}2776
}2777
if (!fromLanding)2778
{ return 0; }2779
return maxChain + 1;2780
};2781
2782
/**2783
* After resolveMatches: clear the landing-pending flag and reset the2784
* chain on landings that did not make a match. A cluster that is still2785
* settling (greys not yet recolored) keeps landedPending so a later2786
* post-recolor match in this same landing still gets the bonus.2787
*/2788
GameCore.prototype.finishLandingChains = function (launched)2789
{2790
var launchedIds = Object.create(null);2791
launched = launched || [];2792
for (var i = 0; i < launched.length; i++)2793
{2794
var blocks = launched[i].blocks || [];2795
for (var j = 0; j < blocks.length; j++)2796
{ launchedIds[blocks[j].id] = true; }2797
}2798
2799
for (var i = 0; i < this.blocks.length; i++)2800
{2801
var block = this.blocks[i];2802
if (!block.justLanded)2803
{ continue; }2804
if (!launchedIds[block.id])2805
{ block.landingChain = 0; }2806
block.justLanded = false;2807
}2808
2809
var ids = Object.keys(this.clusters);2810
for (var c = 0; c < ids.length; c++)2811
{2812
var cluster = this.clusters[ids[c]];2813
if (!cluster || !cluster.landedPending)2814
{ continue; }2815
var members = this.clusterMembers(cluster.id);2816
var anyLaunched = false;2817
var stillSettling = false;2818
for (var i = 0; i < members.length; i++)2819
{2820
if (launchedIds[members[i].id])2821
{ anyLaunched = true; }2822
if (members[i].state === STATE_SETTLING)2823
{ stillSettling = true; }2824
}2825
if (anyLaunched)2826
{2827
cluster.landingChain = 0;2828
cluster.landedPending = false;2829
}2830
else if (!stillSettling)2831
{2832
// Released leftovers or a fully-still landed group that2833
// already had its match opportunity and missed it.2834
cluster.landingChain = 0;2835
cluster.landedPending = false;2836
}2837
// else: still settling, no match yet — keep landedPending.2838
}2839
};2840
2841
GameCore.prototype.updateChainIndicator = function (launched)2842
{2843
var maxChain = 0;2844
for (var i = 0; i < launched.length; i++)2845
{2846
var ch = launched[i].landingChain || 0;2847
if (ch > maxChain)2848
{ maxChain = ch; }2849
}2850
if (maxChain >= 1)2851
{2852
this.lastChainIndicator = {2853
chain: maxChain,2854
bonusPct: Math.round(maxChain * LANDING_CHAIN_BONUS * 100)2855
};2856
return;2857
}2858
if (!this.hasActiveLandingChain())2859
{ this.lastChainIndicator = null; }2860
};2861
2862
GameCore.prototype.hasActiveLandingChain = function ()2863
{2864
var ids = Object.keys(this.clusters);2865
for (var i = 0; i < ids.length; i++)2866
{2867
var cluster = this.clusters[ids[i]];2868
if (cluster && (cluster.landingChain || 0) >= 12869
&& cluster.phase !== 'landed')2870
{ return true; }2871
}2872
return false;2640
};2873
};2641
2874
2642
/**2875
/**@@ -4,7 +4,8 @@
4
4
* View and input for Meteors. The simulation lives in GameCore; this file
5
5
* only draws it, scales it to the viewport, and translates pointer events
6
6
* into beginDrag / moveDrag / endDrag. Online play (stage 2) is wired
7
* through Online (src/online.js) and the same GameCore.
7
* through Online (src/online.js) and the same GameCore. Offline Strijd
8
* (t1119) uses Offline (src/offline.js) against local bots.
8
9
*/
9
10
10
11
function planetImages ()
@@ -15,6 +16,7 @@ function planetImages ()
15
16
{ name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 },
16
17
{ name: 'cell', url: 'images/cell.png' },
17
18
{ name: 'pixel', url: 'images/pixel.png' },
19
{ name: 'columnWarn', url: 'images/column-warn.png' },
18
20
// Keep the original Terra placeholders as aliases (Tim may still have them).
19
21
{ name: 'ember', url: 'images/block-ember.png' },
20
22
{ name: 'aqua', url: 'images/block-aqua.png' },
@@ -69,7 +71,16 @@ var app = {
69
71
spectating: false,
70
72
miniH: 0,
71
73
selectedPlanetId: 'terra',
72
planetSelectContext: 'solo'
74
planetSelectContext: 'solo',
75
offline: false,
76
battle: null,
77
swapTweens: null,
78
columnWarn: null,
79
warnClock: 0,
80
miniAcc: 0,
81
offlineResultShown: false,
82
roundWonDelay: 0,
83
roundWonHandled: false
73
84
};
74
85
75
86
window.onload = function ()
@@ -96,6 +107,7 @@ window.onload = function ()
96
107
});
97
108
98
109
bindOnlineUi();
110
bindOfflineUi();
99
111
bindPlanetSelect();
100
112
restoreSelectedPlanet();
101
113
};
@@ -116,6 +128,7 @@ function startPlay (opts)
116
128
hideEl('spectator');
117
129
hideEl('podium');
118
130
hideEl('planet-select');
131
hideEl('offline-result');
119
132
showEl('hud');
120
133
121
134
var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod;
@@ -128,6 +141,7 @@ function startPlay (opts)
128
141
{ app.core.debugInvariants = true; }
129
142
app.mode = 'playing';
130
143
app.online = !!opts.online;
144
app.offline = !!opts.offline;
131
145
app.gameOverShown = false;
132
146
app.eliminatedReported = false;
133
147
app.spectating = false;
@@ -136,6 +150,24 @@ function startPlay (opts)
136
150
app.cells = [];
137
151
app.pointerId = null;
138
152
app.selectTween = null;
153
app.swapTweens = Object.create(null);
154
app.columnWarn = [];
155
app.warnClock = 0;
156
app.miniAcc = 1; // draw minis on the first frame
157
app.offlineResultShown = false;
158
if (!opts.keepBattle)
159
{
160
app.roundWonDelay = 0;
161
app.roundWonHandled = false;
162
}
163
if (app.offline && !opts.keepBattle && typeof Offline !== 'undefined')
164
{
165
app.battle = Offline.createBattle({
166
playerPlanet: app.planet,
167
rng: Math.random,
168
round: opts.round || 1
169
});
170
}
139
171
140
172
layout();
141
173
if (app.scene)
@@ -153,10 +185,13 @@ function startPlay (opts)
153
185
if (!app.spectating)
154
186
{ bindPointer(app.scene.canvas); }
155
187
refreshHud();
156
if (app.online)
188
if (app.online || app.offline)
157
189
{ showEl('minis'); }
158
190
else
159
191
{ hideEl('minis'); }
192
buildColumnWarn();
193
refreshOfflineHud();
194
refreshChainIndicator();
160
195
}
161
196
162
197
function teardownPlay ()
@@ -173,14 +208,25 @@ function teardownPlay ()
173
208
app.flames = Object.create(null);
174
209
app.cells = [];
175
210
app.selectTween = null;
211
app.swapTweens = Object.create(null);
212
app.columnWarn = [];
176
213
app.pointerId = null;
177
214
app.gameOverShown = false;
178
215
hideEl('hud');
179
216
hideEl('game-over');
180
217
hideEl('spectator');
181
218
hideEl('minis');
219
hideEl('offline-result');
220
hideOfflineHud();
221
hideChainIndicator();
182
222
if (typeof Online !== 'undefined')
183
223
{ Online.clearFlights(); }
224
if (!app._keepBattleOnTeardown)
225
{
226
app.battle = null;
227
app.offline = false;
228
}
229
app._keepBattleOnTeardown = false;
184
230
}
185
231
186
232
function returnToMenu ()
@@ -194,6 +240,8 @@ function returnToMenu ()
194
240
teardownPlay();
195
241
app.mode = 'menu';
196
242
app.online = false;
243
app.offline = false;
244
app.battle = null;
197
245
hideEl('planet-select');
198
246
showEl('menu');
199
247
var last = document.getElementById('last-score');
@@ -258,8 +306,12 @@ function layout ()
258
306
catch (e) { /* ignore */ }
259
307
app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop);
260
308
app.miniH = 0;
261
if (app.online)
262
{ app.miniH = Math.min(150, Math.max(86, Math.round(vh * 0.20))); }
309
if (app.online || app.offline)
310
{
311
var nBots = (app.battle && app.battle.bots) ? app.battle.bots.length : 2;
312
var share = nBots > 6 ? 0.26 : 0.20;
313
app.miniH = Math.min(nBots > 6 ? 180 : 150, Math.max(86, Math.round(vh * share)));
314
}
263
315
var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015));
264
316
var availW = Math.max(80, vw - margin * 2);
265
317
var availH = Math.max(80, vh - app.hudH - app.miniH - margin);
@@ -297,10 +349,13 @@ function spriteFor (block)
297
349
return game.images[key] || game.images.gray;
298
350
}
299
351
300
function syncSprites ()
352
function syncSprites (dt)
301
353
{
302
354
if (!app.core || !app.scene)
303
355
{ return; }
356
dt = dt || 0;
357
consumeAndStartSwapTweens();
358
advanceSwapTweens(dt);
304
359
var seen = Object.create(null);
305
360
var blocks = app.core.blocks;
306
361
for (var i = 0; i < blocks.length; i++)
@@ -315,7 +370,7 @@ function syncSprites ()
315
370
app.sprites[block.id] = obj;
316
371
}
317
372
obj.renderer.sprite = spriteFor(block);
318
placeTile(obj, block.col, block.y);
373
placeTile(obj, block.col, blockVisualY(block));
319
374
applyBlockVisual(obj, block);
320
375
obj.renderer.visible = true;
321
376
obj.renderer.alpha = 1;
@@ -453,6 +508,95 @@ function updateSelectTween (dt)
453
508
tw.scale = ease ? Easing.tween(tw.from, tw.to, u, ease) : tw.from + (tw.to - tw.from) * u;
454
509
}
455
510
511
512
/* ---------- visual-only swap tween (t1121) -------------------------- */
513
514
function swapTweenSpec ()
515
{
516
if (typeof Easing !== 'undefined' && Easing.SWAP_TWEEN)
517
{ return Easing.SWAP_TWEEN; }
518
return { duration: 0.100, ease: null };
519
}
520
521
function swapEase (u)
522
{
523
if (typeof Easing !== 'undefined' && Easing.easeOutCubic)
524
{ return Easing.easeOutCubic(u); }
525
var v = 1 - Math.max(0, Math.min(1, u));
526
return 1 - v * v * v;
527
}
528
529
function tweenVisualY (tw)
530
{
531
var u = tw.duration > 0 ? Math.min(1, tw.age / tw.duration) : 1;
532
return tw.fromY + (tw.toY - tw.fromY) * swapEase(u);
533
}
534
535
/**
536
* Consume GameCore swap events. The currently dragged block is skipped
537
* (it follows the pointer). A block that is mid-tween and is swapped
538
* again restarts from its current visual y, so rapid swaps chain
539
* smoothly without snapping.
540
*/
541
function consumeAndStartSwapTweens ()
542
{
543
if (!app.core || !app.core.consumeSwapEvents)
544
{ return; }
545
if (!app.swapTweens)
546
{ app.swapTweens = Object.create(null); }
547
var ev = app.core.consumeSwapEvents();
548
if (!ev.length)
549
{ return; }
550
var dragId = app.core.drag && app.core.drag.blockId;
551
var duration = swapTweenSpec().duration;
552
for (var i = 0; i < ev.length; i++)
553
{
554
var e = ev[i];
555
if (e.id === dragId)
556
{
557
delete app.swapTweens[e.id];
558
continue;
559
}
560
var fromY = e.fromY;
561
var existing = app.swapTweens[e.id];
562
if (existing)
563
{ fromY = tweenVisualY(existing); }
564
app.swapTweens[e.id] = {
565
fromY: fromY,
566
toY: e.toY,
567
age: 0,
568
duration: duration
569
};
570
}
571
}
572
573
function advanceSwapTweens (dt)
574
{
575
if (!app.swapTweens)
576
{ return; }
577
var ids = Object.keys(app.swapTweens);
578
for (var i = 0; i < ids.length; i++)
579
{
580
var tw = app.swapTweens[ids[i]];
581
tw.age += dt;
582
if (tw.age >= tw.duration)
583
{ delete app.swapTweens[ids[i]]; }
584
}
585
}
586
587
function blockVisualY (block)
588
{
589
if (!app.swapTweens)
590
{ return block.y; }
591
var dragId = app.core && app.core.drag && app.core.drag.blockId;
592
if (block.id === dragId)
593
{ return block.y; }
594
var tw = app.swapTweens[block.id];
595
if (!tw)
596
{ return block.y; }
597
return tweenVisualY(tw);
598
}
599
456
600
function refreshHud ()
457
601
{
458
602
if (!app.core)
@@ -494,9 +638,14 @@ function tickView (dt)
494
638
}
495
639
496
640
app.core.tick(dt);
641
if (app.offline && app.battle)
642
{ tickOffline(dt); }
497
643
updateSelectTween(dt);
498
syncSprites();
644
syncSprites(dt);
645
updateColumnWarn(dt);
499
646
refreshHud();
647
refreshOfflineHud();
648
refreshChainIndicator();
500
649
tickOnline(dt);
501
650
if (app.debugPhysics)
502
651
{ logPhysicsDebug(); }
@@ -508,10 +657,13 @@ function tickView (dt)
508
657
document.getElementById('go-score').textContent = String(app.lastScore);
509
658
if (app.online)
510
659
{ onOnlineEliminated(); }
660
else if (app.offline)
661
{ /* Offline result is shown from tickOffline. */ }
511
662
else
512
663
{ showEl('game-over'); }
513
664
}
514
if (!app.online && app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY)
665
if (!app.online && !app.offline && app.core.state === 'gameover'
666
&& app.core.gameOverTime >= GAME_OVER_DELAY)
515
667
{ returnToMenu(); }
516
668
}
517
669
@@ -1014,6 +1166,313 @@ function tickOnline (dt)
1014
1166
Online.renderMinis(document.getElementById('minis'));
1015
1167
}
1016
1168
1169
1170
/* ---------- Offline Strijd (t1119) + column warn (t1123) ----------- */
1171
1172
function bindOfflineUi ()
1173
{
1174
var btn = document.getElementById('btn-offline');
1175
if (btn)
1176
{
1177
btn.addEventListener('click', onOffline);
1178
btn.addEventListener('pointerup', function (e)
1179
{
1180
if (e.pointerType === 'touch' || e.pointerType === 'pen')
1181
{
1182
e.preventDefault();
1183
onOffline();
1184
}
1185
});
1186
}
1187
var back = document.getElementById('btn-offline-menu');
1188
if (back)
1189
{
1190
back.addEventListener('click', function ()
1191
{
1192
teardownPlay();
1193
app.mode = 'menu';
1194
app.offline = false;
1195
app.battle = null;
1196
hideEl('offline-result');
1197
showEl('menu');
1198
});
1199
}
1200
}
1201
1202
function onOffline ()
1203
{
1204
openPlanetSelect('offline');
1205
}
1206
1207
function tickOffline (dt)
1208
{
1209
if (!app.battle || !app.core || typeof Offline === 'undefined')
1210
{ return; }
1211
1212
if (app.battle.state === 'round_won')
1213
{
1214
if (!app.roundWonHandled)
1215
{
1216
app.roundWonHandled = true;
1217
app.roundWonDelay = Offline.ROUND_WON_DELAY || 1.5;
1218
}
1219
app.roundWonDelay -= dt;
1220
if (app.roundWonDelay <= 0)
1221
{ startNextOfflineRound(); }
1222
updateOfflineMinis(dt, true);
1223
return;
1224
}
1225
1226
var result = app.battle.tick(dt, app.core);
1227
if (result && result.flights && result.flights.length
1228
&& typeof Online !== 'undefined' && Online.spawnFlights)
1229
{
1230
var locals = Object.create(null);
1231
var list = result.locals || [];
1232
for (var i = 0; i < list.length; i++)
1233
{
1234
var s = list[i];
1235
var start;
1236
if (s.from_id === 'player')
1237
{ start = fieldToViewport(s.col, s.y + 1); }
1238
else
1239
{ start = miniViewportCenter(s.from_id); }
1240
locals[s.client_id] = {
1241
col: s.col,
1242
y: s.y,
1243
color: s.color,
1244
startX: start.x,
1245
startY: start.y
1246
};
1247
}
1248
Online.spawnFlights(result.flights, locals);
1249
}
1250
if (typeof Online !== 'undefined' && Online.tickFlights)
1251
{ Online.tickFlights(); }
1252
updateOfflineMinis(dt, false);
1253
1254
if (app.battle.state === 'lost' && !app.offlineResultShown)
1255
{ showOfflineResult(); }
1256
}
1257
1258
function startNextOfflineRound ()
1259
{
1260
if (!app.battle)
1261
{ return; }
1262
app.battle.advanceRound();
1263
app.roundWonHandled = false;
1264
app.roundWonDelay = 0;
1265
app._keepBattleOnTeardown = true;
1266
// Tear down the current scene then start a fresh player field,
1267
// keeping the same battle (already advanced).
1268
var planet = app.battle.playerPlanet;
1269
app._keepBattleOnTeardown = true;
1270
teardownPlay();
1271
app.offline = true;
1272
app.battle = app.battle; // kept
1273
startPlay({ planet: planet, offline: true, keepBattle: true });
1274
}
1275
1276
function showOfflineResult ()
1277
{
1278
app.offlineResultShown = true;
1279
var battle = app.battle;
1280
var reached = document.getElementById('offline-reached');
1281
if (reached)
1282
{ reached.textContent = String(battle.round); }
1283
var detail = document.getElementById('offline-result-detail');
1284
if (detail)
1285
{
1286
var sch = battle.schedule;
1287
var n = sch.opponents;
1288
var noun = n === 1 ? 'tegenstander' : 'tegenstanders';
1289
detail.textContent = 'Je speelde tegen ' + n + ' ' + noun
1290
+ ' met skill ' + Math.round(sch.skill * 100) + '%.';
1291
}
1292
hideEl('game-over');
1293
showEl('offline-result');
1294
}
1295
1296
function refreshOfflineHud ()
1297
{
1298
var el = document.getElementById('offline-hud');
1299
if (!el)
1300
{ return; }
1301
if (!(app.offline && app.battle && app.mode === 'playing'))
1302
{
1303
el.hidden = true;
1304
return;
1305
}
1306
el.hidden = false;
1307
var sch = app.battle.schedule;
1308
var n = sch.opponents;
1309
var noun = n === 1 ? 'tegenstander' : 'tegenstanders';
1310
var r = document.getElementById('offline-round');
1311
var o = document.getElementById('offline-opponents');
1312
var s = document.getElementById('offline-skill');
1313
if (r)
1314
{ r.textContent = 'Ronde ' + sch.round; }
1315
if (o)
1316
{ o.textContent = n + ' ' + noun; }
1317
if (s)
1318
{ s.textContent = 'Skill ' + Math.round(sch.skill * 100) + '%'; }
1319
}
1320
1321
function hideOfflineHud ()
1322
{
1323
var el = document.getElementById('offline-hud');
1324
if (el)
1325
{ el.hidden = true; }
1326
}
1327
1328
function refreshChainIndicator ()
1329
{
1330
var el = document.getElementById('chain-indicator');
1331
if (!el)
1332
{ return; }
1333
var info = app.core && app.core.lastChainIndicator;
1334
var active = app.core && app.core.hasActiveLandingChain
1335
&& app.core.hasActiveLandingChain();
1336
// Show only while a chained cluster is still in the air.
1337
if (!info || info.chain < 1 || app.mode !== 'playing' || !active)
1338
{
1339
el.hidden = true;
1340
return;
1341
}
1342
el.hidden = false;
1343
el.textContent = 'x' + info.chain + ' +' + info.bonusPct + '%';
1344
}
1345
1346
function hideChainIndicator ()
1347
{
1348
var el = document.getElementById('chain-indicator');
1349
if (el)
1350
{ el.hidden = true; }
1351
}
1352
1353
function miniViewportCenter (botId)
1354
{
1355
var el = document.querySelector('#minis .mini[data-player="' + botId + '"] canvas');
1356
if (!el)
1357
{ return { x: window.innerWidth / 2, y: 40 }; }
1358
var rect = el.getBoundingClientRect();
1359
return { x: rect.left + rect.width / 2, y: rect.bottom };
1360
}
1361
1362
function offlineMiniSize (n)
1363
{
1364
if (n >= 10)
1365
{ return { w: 40, h: 52 }; }
1366
if (n >= 6)
1367
{ return { w: 56, h: 73 }; }
1368
return { w: 80, h: 104 };
1369
}
1370
1371
function updateOfflineMinis (dt, force)
1372
{
1373
app.miniAcc = (app.miniAcc || 0) + dt;
1374
if (!force && app.miniAcc < 0.1)
1375
{ return; }
1376
app.miniAcc = 0;
1377
renderOfflineMinis();
1378
}
1379
1380
function renderOfflineMinis ()
1381
{
1382
var container = document.getElementById('minis');
1383
if (!container || !app.battle)
1384
{ return; }
1385
var bots = app.battle.bots;
1386
var size = offlineMiniSize(bots.length);
1387
container.classList.toggle('crowded', bots.length > 5);
1388
var existing = {};
1389
var kids = container.querySelectorAll('[data-player]');
1390
for (var i = 0; i < kids.length; i++)
1391
{ existing[kids[i].getAttribute('data-player')] = kids[i]; }
1392
var seen = Object.create(null);
1393
for (var i = 0; i < bots.length; i++)
1394
{
1395
var bot = bots[i];
1396
seen[bot.id] = true;
1397
var el = existing[bot.id];
1398
if (!el)
1399
{
1400
el = document.createElement('div');
1401
el.className = 'mini';
1402
el.setAttribute('data-player', bot.id);
1403
el.innerHTML = '<div class="mini-name"></div>'
1404
+ '<canvas class="mini-canvas" width="' + size.w
1405
+ '" height="' + size.h + '"></canvas>'
1406
+ '<div class="mini-meta"></div>';
1407
container.appendChild(el);
1408
}
1409
var canvas = el.querySelector('canvas');
1410
if (canvas && (canvas.width !== size.w || canvas.height !== size.h))
1411
{
1412
canvas.width = size.w;
1413
canvas.height = size.h;
1414
}
1415
el.classList.toggle('eliminated', !!bot.eliminated);
1416
var planetName = bot.planet && bot.planet.name ? bot.planet.name : '';
1417
el.querySelector('.mini-name').textContent = bot.name
1418
+ (planetName ? ' · ' + planetName : '');
1419
el.querySelector('.mini-meta').textContent = bot.eliminated
1420
? 'Uit'
1421
: ('Punten ' + (bot.score || 0));
1422
var snap = bot.core ? bot.core.fieldSnapshot() : { blocks: [] };
1423
if (typeof Online !== 'undefined' && Online._drawMini)
1424
{ Online._drawMini(canvas, snap, bot.planet); }
1425
}
1426
for (var id in existing)
1427
{
1428
if (!seen[id])
1429
{ existing[id].remove(); }
1430
}
1431
}
1432
1433
function buildColumnWarn ()
1434
{
1435
app.columnWarn = [];
1436
if (!app.scene)
1437
{ return; }
1438
var img = (game.images && (game.images.columnWarn || game.images.pixel)) || null;
1439
if (!img)
1440
{ return; }
1441
for (var c = 0; c < 10; c++)
1442
{
1443
var obj = new GameObject(0, 0, img, 0);
1444
obj.renderer.alpha = 0;
1445
obj.renderer.visible = false;
1446
app.scene.addObject(obj);
1447
app.columnWarn.push(obj);
1448
}
1449
updateColumnWarn(0);
1450
}
1451
1452
function updateColumnWarn (dt)
1453
{
1454
if (!app.columnWarn || !app.core)
1455
{ return; }
1456
app.warnClock = (app.warnClock || 0) + (dt || 0);
1457
var pulse = (typeof GameCore !== 'undefined' && GameCore.columnWarnPulse)
1458
? GameCore.columnWarnPulse(app.warnClock)
1459
: 0.16 + 0.28 * (0.5 + 0.5 * Math.sin(app.warnClock * 3.45575));
1460
var t = app.tile;
1461
for (var c = 0; c < app.columnWarn.length; c++)
1462
{
1463
var obj = app.columnWarn[c];
1464
var on = app.core.columnNeedsWarn && app.core.columnNeedsWarn(c);
1465
obj.renderer.visible = !!on;
1466
obj.renderer.alpha = on ? pulse : 0;
1467
if (t)
1468
{
1469
obj.transform.position.x = c * t + t / 2;
1470
obj.transform.position.y = app.fieldH / 2;
1471
obj.transform.size = { x: t, y: app.fieldH };
1472
}
1473
}
1474
}
1475
1017
1476
function fieldToViewport (col, fieldY)
1018
1477
{
1019
1478
var canvas = app.scene && app.scene.canvas;
@@ -1501,6 +1960,11 @@ function confirmPlanetSelect ()
1501
1960
openOnlinePanel();
1502
1961
return;
1503
1962
}
1963
if (app.planetSelectContext === 'offline')
1964
{
1965
startPlay({ planet: planet, offline: true });
1966
return;
1967
}
1504
1968
startPlay({ planet: planet });
1505
1969
}
1506
1970
@@ -4,7 +4,8 @@4
* View and input for Meteors. The simulation lives in GameCore; this file4
* View and input for Meteors. The simulation lives in GameCore; this file5
* only draws it, scales it to the viewport, and translates pointer events5
* only draws it, scales it to the viewport, and translates pointer events6
* into beginDrag / moveDrag / endDrag. Online play (stage 2) is wired6
* into beginDrag / moveDrag / endDrag. Online play (stage 2) is wired7
* through Online (src/online.js) and the same GameCore.7
* through Online (src/online.js) and the same GameCore. Offline Strijd8
* (t1119) uses Offline (src/offline.js) against local bots.8
*/9
*/9
10
10
function planetImages ()11
function planetImages ()@@ -15,6 +16,7 @@ function planetImages ()15
{ name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 },16
{ name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 },16
{ name: 'cell', url: 'images/cell.png' },17
{ name: 'cell', url: 'images/cell.png' },17
{ name: 'pixel', url: 'images/pixel.png' },18
{ name: 'pixel', url: 'images/pixel.png' },19
{ name: 'columnWarn', url: 'images/column-warn.png' },18
// Keep the original Terra placeholders as aliases (Tim may still have them).20
// Keep the original Terra placeholders as aliases (Tim may still have them).19
{ name: 'ember', url: 'images/block-ember.png' },21
{ name: 'ember', url: 'images/block-ember.png' },20
{ name: 'aqua', url: 'images/block-aqua.png' },22
{ name: 'aqua', url: 'images/block-aqua.png' },@@ -69,7 +71,16 @@ var app = {69
spectating: false,71
spectating: false,70
miniH: 0,72
miniH: 0,71
selectedPlanetId: 'terra',73
selectedPlanetId: 'terra',72
planetSelectContext: 'solo'74
planetSelectContext: 'solo',75
offline: false,76
battle: null,77
swapTweens: null,78
columnWarn: null,79
warnClock: 0,80
miniAcc: 0,81
offlineResultShown: false,82
roundWonDelay: 0,83
roundWonHandled: false73
};84
};74
85
75
window.onload = function ()86
window.onload = function ()@@ -96,6 +107,7 @@ window.onload = function ()96
});107
});97
108
98
bindOnlineUi();109
bindOnlineUi();110
bindOfflineUi();99
bindPlanetSelect();111
bindPlanetSelect();100
restoreSelectedPlanet();112
restoreSelectedPlanet();101
};113
};@@ -116,6 +128,7 @@ function startPlay (opts)116
hideEl('spectator');128
hideEl('spectator');117
hideEl('podium');129
hideEl('podium');118
hideEl('planet-select');130
hideEl('planet-select');131
hideEl('offline-result');119
showEl('hud');132
showEl('hud');120
133
121
var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod;134
var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod;@@ -128,6 +141,7 @@ function startPlay (opts)128
{ app.core.debugInvariants = true; }141
{ app.core.debugInvariants = true; }129
app.mode = 'playing';142
app.mode = 'playing';130
app.online = !!opts.online;143
app.online = !!opts.online;144
app.offline = !!opts.offline;131
app.gameOverShown = false;145
app.gameOverShown = false;132
app.eliminatedReported = false;146
app.eliminatedReported = false;133
app.spectating = false;147
app.spectating = false;@@ -136,6 +150,24 @@ function startPlay (opts)136
app.cells = [];150
app.cells = [];137
app.pointerId = null;151
app.pointerId = null;138
app.selectTween = null;152
app.selectTween = null;153
app.swapTweens = Object.create(null);154
app.columnWarn = [];155
app.warnClock = 0;156
app.miniAcc = 1; // draw minis on the first frame157
app.offlineResultShown = false;158
if (!opts.keepBattle)159
{160
app.roundWonDelay = 0;161
app.roundWonHandled = false;162
}163
if (app.offline && !opts.keepBattle && typeof Offline !== 'undefined')164
{165
app.battle = Offline.createBattle({166
playerPlanet: app.planet,167
rng: Math.random,168
round: opts.round || 1169
});170
}139
171
140
layout();172
layout();141
if (app.scene)173
if (app.scene)@@ -153,10 +185,13 @@ function startPlay (opts)153
if (!app.spectating)185
if (!app.spectating)154
{ bindPointer(app.scene.canvas); }186
{ bindPointer(app.scene.canvas); }155
refreshHud();187
refreshHud();156
if (app.online)188
if (app.online || app.offline)157
{ showEl('minis'); }189
{ showEl('minis'); }158
else190
else159
{ hideEl('minis'); }191
{ hideEl('minis'); }192
buildColumnWarn();193
refreshOfflineHud();194
refreshChainIndicator();160
}195
}161
196
162
function teardownPlay ()197
function teardownPlay ()@@ -173,14 +208,25 @@ function teardownPlay ()173
app.flames = Object.create(null);208
app.flames = Object.create(null);174
app.cells = [];209
app.cells = [];175
app.selectTween = null;210
app.selectTween = null;211
app.swapTweens = Object.create(null);212
app.columnWarn = [];176
app.pointerId = null;213
app.pointerId = null;177
app.gameOverShown = false;214
app.gameOverShown = false;178
hideEl('hud');215
hideEl('hud');179
hideEl('game-over');216
hideEl('game-over');180
hideEl('spectator');217
hideEl('spectator');181
hideEl('minis');218
hideEl('minis');219
hideEl('offline-result');220
hideOfflineHud();221
hideChainIndicator();182
if (typeof Online !== 'undefined')222
if (typeof Online !== 'undefined')183
{ Online.clearFlights(); }223
{ Online.clearFlights(); }224
if (!app._keepBattleOnTeardown)225
{226
app.battle = null;227
app.offline = false;228
}229
app._keepBattleOnTeardown = false;184
}230
}185
231
186
function returnToMenu ()232
function returnToMenu ()@@ -194,6 +240,8 @@ function returnToMenu ()194
teardownPlay();240
teardownPlay();195
app.mode = 'menu';241
app.mode = 'menu';196
app.online = false;242
app.online = false;243
app.offline = false;244
app.battle = null;197
hideEl('planet-select');245
hideEl('planet-select');198
showEl('menu');246
showEl('menu');199
var last = document.getElementById('last-score');247
var last = document.getElementById('last-score');@@ -258,8 +306,12 @@ function layout ()258
catch (e) { /* ignore */ }306
catch (e) { /* ignore */ }259
app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop);307
app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop);260
app.miniH = 0;308
app.miniH = 0;261
if (app.online)309
if (app.online || app.offline)262
{ app.miniH = Math.min(150, Math.max(86, Math.round(vh * 0.20))); }310
{311
var nBots = (app.battle && app.battle.bots) ? app.battle.bots.length : 2;312
var share = nBots > 6 ? 0.26 : 0.20;313
app.miniH = Math.min(nBots > 6 ? 180 : 150, Math.max(86, Math.round(vh * share)));314
}263
var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015));315
var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015));264
var availW = Math.max(80, vw - margin * 2);316
var availW = Math.max(80, vw - margin * 2);265
var availH = Math.max(80, vh - app.hudH - app.miniH - margin);317
var availH = Math.max(80, vh - app.hudH - app.miniH - margin);@@ -297,10 +349,13 @@ function spriteFor (block)297
return game.images[key] || game.images.gray;349
return game.images[key] || game.images.gray;298
}350
}299
351
300
function syncSprites ()352
function syncSprites (dt)301
{353
{302
if (!app.core || !app.scene)354
if (!app.core || !app.scene)303
{ return; }355
{ return; }356
dt = dt || 0;357
consumeAndStartSwapTweens();358
advanceSwapTweens(dt);304
var seen = Object.create(null);359
var seen = Object.create(null);305
var blocks = app.core.blocks;360
var blocks = app.core.blocks;306
for (var i = 0; i < blocks.length; i++)361
for (var i = 0; i < blocks.length; i++)@@ -315,7 +370,7 @@ function syncSprites ()315
app.sprites[block.id] = obj;370
app.sprites[block.id] = obj;316
}371
}317
obj.renderer.sprite = spriteFor(block);372
obj.renderer.sprite = spriteFor(block);318
placeTile(obj, block.col, block.y);373
placeTile(obj, block.col, blockVisualY(block));319
applyBlockVisual(obj, block);374
applyBlockVisual(obj, block);320
obj.renderer.visible = true;375
obj.renderer.visible = true;321
obj.renderer.alpha = 1;376
obj.renderer.alpha = 1;@@ -453,6 +508,95 @@ function updateSelectTween (dt)453
tw.scale = ease ? Easing.tween(tw.from, tw.to, u, ease) : tw.from + (tw.to - tw.from) * u;508
tw.scale = ease ? Easing.tween(tw.from, tw.to, u, ease) : tw.from + (tw.to - tw.from) * u;454
}509
}455
510
511
512
/* ---------- visual-only swap tween (t1121) -------------------------- */513
514
function swapTweenSpec ()515
{516
if (typeof Easing !== 'undefined' && Easing.SWAP_TWEEN)517
{ return Easing.SWAP_TWEEN; }518
return { duration: 0.100, ease: null };519
}520
521
function swapEase (u)522
{523
if (typeof Easing !== 'undefined' && Easing.easeOutCubic)524
{ return Easing.easeOutCubic(u); }525
var v = 1 - Math.max(0, Math.min(1, u));526
return 1 - v * v * v;527
}528
529
function tweenVisualY (tw)530
{531
var u = tw.duration > 0 ? Math.min(1, tw.age / tw.duration) : 1;532
return tw.fromY + (tw.toY - tw.fromY) * swapEase(u);533
}534
535
/**536
* Consume GameCore swap events. The currently dragged block is skipped537
* (it follows the pointer). A block that is mid-tween and is swapped538
* again restarts from its current visual y, so rapid swaps chain539
* smoothly without snapping.540
*/541
function consumeAndStartSwapTweens ()542
{543
if (!app.core || !app.core.consumeSwapEvents)544
{ return; }545
if (!app.swapTweens)546
{ app.swapTweens = Object.create(null); }547
var ev = app.core.consumeSwapEvents();548
if (!ev.length)549
{ return; }550
var dragId = app.core.drag && app.core.drag.blockId;551
var duration = swapTweenSpec().duration;552
for (var i = 0; i < ev.length; i++)553
{554
var e = ev[i];555
if (e.id === dragId)556
{557
delete app.swapTweens[e.id];558
continue;559
}560
var fromY = e.fromY;561
var existing = app.swapTweens[e.id];562
if (existing)563
{ fromY = tweenVisualY(existing); }564
app.swapTweens[e.id] = {565
fromY: fromY,566
toY: e.toY,567
age: 0,568
duration: duration569
};570
}571
}572
573
function advanceSwapTweens (dt)574
{575
if (!app.swapTweens)576
{ return; }577
var ids = Object.keys(app.swapTweens);578
for (var i = 0; i < ids.length; i++)579
{580
var tw = app.swapTweens[ids[i]];581
tw.age += dt;582
if (tw.age >= tw.duration)583
{ delete app.swapTweens[ids[i]]; }584
}585
}586
587
function blockVisualY (block)588
{589
if (!app.swapTweens)590
{ return block.y; }591
var dragId = app.core && app.core.drag && app.core.drag.blockId;592
if (block.id === dragId)593
{ return block.y; }594
var tw = app.swapTweens[block.id];595
if (!tw)596
{ return block.y; }597
return tweenVisualY(tw);598
}599
456
function refreshHud ()600
function refreshHud ()457
{601
{458
if (!app.core)602
if (!app.core)@@ -494,9 +638,14 @@ function tickView (dt)494
}638
}495
639
496
app.core.tick(dt);640
app.core.tick(dt);641
if (app.offline && app.battle)642
{ tickOffline(dt); }497
updateSelectTween(dt);643
updateSelectTween(dt);498
syncSprites();644
syncSprites(dt);645
updateColumnWarn(dt);499
refreshHud();646
refreshHud();647
refreshOfflineHud();648
refreshChainIndicator();500
tickOnline(dt);649
tickOnline(dt);501
if (app.debugPhysics)650
if (app.debugPhysics)502
{ logPhysicsDebug(); }651
{ logPhysicsDebug(); }@@ -508,10 +657,13 @@ function tickView (dt)508
document.getElementById('go-score').textContent = String(app.lastScore);657
document.getElementById('go-score').textContent = String(app.lastScore);509
if (app.online)658
if (app.online)510
{ onOnlineEliminated(); }659
{ onOnlineEliminated(); }660
else if (app.offline)661
{ /* Offline result is shown from tickOffline. */ }511
else662
else512
{ showEl('game-over'); }663
{ showEl('game-over'); }513
}664
}514
if (!app.online && app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY)665
if (!app.online && !app.offline && app.core.state === 'gameover'666
&& app.core.gameOverTime >= GAME_OVER_DELAY)515
{ returnToMenu(); }667
{ returnToMenu(); }516
}668
}517
669
@@ -1014,6 +1166,313 @@ function tickOnline (dt)1014
Online.renderMinis(document.getElementById('minis'));1166
Online.renderMinis(document.getElementById('minis'));1015
}1167
}1016
1168
1169
1170
/* ---------- Offline Strijd (t1119) + column warn (t1123) ----------- */1171
1172
function bindOfflineUi ()1173
{1174
var btn = document.getElementById('btn-offline');1175
if (btn)1176
{1177
btn.addEventListener('click', onOffline);1178
btn.addEventListener('pointerup', function (e)1179
{1180
if (e.pointerType === 'touch' || e.pointerType === 'pen')1181
{1182
e.preventDefault();1183
onOffline();1184
}1185
});1186
}1187
var back = document.getElementById('btn-offline-menu');1188
if (back)1189
{1190
back.addEventListener('click', function ()1191
{1192
teardownPlay();1193
app.mode = 'menu';1194
app.offline = false;1195
app.battle = null;1196
hideEl('offline-result');1197
showEl('menu');1198
});1199
}1200
}1201
1202
function onOffline ()1203
{1204
openPlanetSelect('offline');1205
}1206
1207
function tickOffline (dt)1208
{1209
if (!app.battle || !app.core || typeof Offline === 'undefined')1210
{ return; }1211
1212
if (app.battle.state === 'round_won')1213
{1214
if (!app.roundWonHandled)1215
{1216
app.roundWonHandled = true;1217
app.roundWonDelay = Offline.ROUND_WON_DELAY || 1.5;1218
}1219
app.roundWonDelay -= dt;1220
if (app.roundWonDelay <= 0)1221
{ startNextOfflineRound(); }1222
updateOfflineMinis(dt, true);1223
return;1224
}1225
1226
var result = app.battle.tick(dt, app.core);1227
if (result && result.flights && result.flights.length1228
&& typeof Online !== 'undefined' && Online.spawnFlights)1229
{1230
var locals = Object.create(null);1231
var list = result.locals || [];1232
for (var i = 0; i < list.length; i++)1233
{1234
var s = list[i];1235
var start;1236
if (s.from_id === 'player')1237
{ start = fieldToViewport(s.col, s.y + 1); }1238
else1239
{ start = miniViewportCenter(s.from_id); }1240
locals[s.client_id] = {1241
col: s.col,1242
y: s.y,1243
color: s.color,1244
startX: start.x,1245
startY: start.y1246
};1247
}1248
Online.spawnFlights(result.flights, locals);1249
}1250
if (typeof Online !== 'undefined' && Online.tickFlights)1251
{ Online.tickFlights(); }1252
updateOfflineMinis(dt, false);1253
1254
if (app.battle.state === 'lost' && !app.offlineResultShown)1255
{ showOfflineResult(); }1256
}1257
1258
function startNextOfflineRound ()1259
{1260
if (!app.battle)1261
{ return; }1262
app.battle.advanceRound();1263
app.roundWonHandled = false;1264
app.roundWonDelay = 0;1265
app._keepBattleOnTeardown = true;1266
// Tear down the current scene then start a fresh player field,1267
// keeping the same battle (already advanced).1268
var planet = app.battle.playerPlanet;1269
app._keepBattleOnTeardown = true;1270
teardownPlay();1271
app.offline = true;1272
app.battle = app.battle; // kept1273
startPlay({ planet: planet, offline: true, keepBattle: true });1274
}1275
1276
function showOfflineResult ()1277
{1278
app.offlineResultShown = true;1279
var battle = app.battle;1280
var reached = document.getElementById('offline-reached');1281
if (reached)1282
{ reached.textContent = String(battle.round); }1283
var detail = document.getElementById('offline-result-detail');1284
if (detail)1285
{1286
var sch = battle.schedule;1287
var n = sch.opponents;1288
var noun = n === 1 ? 'tegenstander' : 'tegenstanders';1289
detail.textContent = 'Je speelde tegen ' + n + ' ' + noun1290
+ ' met skill ' + Math.round(sch.skill * 100) + '%.';1291
}1292
hideEl('game-over');1293
showEl('offline-result');1294
}1295
1296
function refreshOfflineHud ()1297
{1298
var el = document.getElementById('offline-hud');1299
if (!el)1300
{ return; }1301
if (!(app.offline && app.battle && app.mode === 'playing'))1302
{1303
el.hidden = true;1304
return;1305
}1306
el.hidden = false;1307
var sch = app.battle.schedule;1308
var n = sch.opponents;1309
var noun = n === 1 ? 'tegenstander' : 'tegenstanders';1310
var r = document.getElementById('offline-round');1311
var o = document.getElementById('offline-opponents');1312
var s = document.getElementById('offline-skill');1313
if (r)1314
{ r.textContent = 'Ronde ' + sch.round; }1315
if (o)1316
{ o.textContent = n + ' ' + noun; }1317
if (s)1318
{ s.textContent = 'Skill ' + Math.round(sch.skill * 100) + '%'; }1319
}1320
1321
function hideOfflineHud ()1322
{1323
var el = document.getElementById('offline-hud');1324
if (el)1325
{ el.hidden = true; }1326
}1327
1328
function refreshChainIndicator ()1329
{1330
var el = document.getElementById('chain-indicator');1331
if (!el)1332
{ return; }1333
var info = app.core && app.core.lastChainIndicator;1334
var active = app.core && app.core.hasActiveLandingChain1335
&& app.core.hasActiveLandingChain();1336
// Show only while a chained cluster is still in the air.1337
if (!info || info.chain < 1 || app.mode !== 'playing' || !active)1338
{1339
el.hidden = true;1340
return;1341
}1342
el.hidden = false;1343
el.textContent = 'x' + info.chain + ' +' + info.bonusPct + '%';1344
}1345
1346
function hideChainIndicator ()1347
{1348
var el = document.getElementById('chain-indicator');1349
if (el)1350
{ el.hidden = true; }1351
}1352
1353
function miniViewportCenter (botId)1354
{1355
var el = document.querySelector('#minis .mini[data-player="' + botId + '"] canvas');1356
if (!el)1357
{ return { x: window.innerWidth / 2, y: 40 }; }1358
var rect = el.getBoundingClientRect();1359
return { x: rect.left + rect.width / 2, y: rect.bottom };1360
}1361
1362
function offlineMiniSize (n)1363
{1364
if (n >= 10)1365
{ return { w: 40, h: 52 }; }1366
if (n >= 6)1367
{ return { w: 56, h: 73 }; }1368
return { w: 80, h: 104 };1369
}1370
1371
function updateOfflineMinis (dt, force)1372
{1373
app.miniAcc = (app.miniAcc || 0) + dt;1374
if (!force && app.miniAcc < 0.1)1375
{ return; }1376
app.miniAcc = 0;1377
renderOfflineMinis();1378
}1379
1380
function renderOfflineMinis ()1381
{1382
var container = document.getElementById('minis');1383
if (!container || !app.battle)1384
{ return; }1385
var bots = app.battle.bots;1386
var size = offlineMiniSize(bots.length);1387
container.classList.toggle('crowded', bots.length > 5);1388
var existing = {};1389
var kids = container.querySelectorAll('[data-player]');1390
for (var i = 0; i < kids.length; i++)1391
{ existing[kids[i].getAttribute('data-player')] = kids[i]; }1392
var seen = Object.create(null);1393
for (var i = 0; i < bots.length; i++)1394
{1395
var bot = bots[i];1396
seen[bot.id] = true;1397
var el = existing[bot.id];1398
if (!el)1399
{1400
el = document.createElement('div');1401
el.className = 'mini';1402
el.setAttribute('data-player', bot.id);1403
el.innerHTML = '<div class="mini-name"></div>'1404
+ '<canvas class="mini-canvas" width="' + size.w1405
+ '" height="' + size.h + '"></canvas>'1406
+ '<div class="mini-meta"></div>';1407
container.appendChild(el);1408
}1409
var canvas = el.querySelector('canvas');1410
if (canvas && (canvas.width !== size.w || canvas.height !== size.h))1411
{1412
canvas.width = size.w;1413
canvas.height = size.h;1414
}1415
el.classList.toggle('eliminated', !!bot.eliminated);1416
var planetName = bot.planet && bot.planet.name ? bot.planet.name : '';1417
el.querySelector('.mini-name').textContent = bot.name1418
+ (planetName ? ' · ' + planetName : '');1419
el.querySelector('.mini-meta').textContent = bot.eliminated1420
? 'Uit'1421
: ('Punten ' + (bot.score || 0));1422
var snap = bot.core ? bot.core.fieldSnapshot() : { blocks: [] };1423
if (typeof Online !== 'undefined' && Online._drawMini)1424
{ Online._drawMini(canvas, snap, bot.planet); }1425
}1426
for (var id in existing)1427
{1428
if (!seen[id])1429
{ existing[id].remove(); }1430
}1431
}1432
1433
function buildColumnWarn ()1434
{1435
app.columnWarn = [];1436
if (!app.scene)1437
{ return; }1438
var img = (game.images && (game.images.columnWarn || game.images.pixel)) || null;1439
if (!img)1440
{ return; }1441
for (var c = 0; c < 10; c++)1442
{1443
var obj = new GameObject(0, 0, img, 0);1444
obj.renderer.alpha = 0;1445
obj.renderer.visible = false;1446
app.scene.addObject(obj);1447
app.columnWarn.push(obj);1448
}1449
updateColumnWarn(0);1450
}1451
1452
function updateColumnWarn (dt)1453
{1454
if (!app.columnWarn || !app.core)1455
{ return; }1456
app.warnClock = (app.warnClock || 0) + (dt || 0);1457
var pulse = (typeof GameCore !== 'undefined' && GameCore.columnWarnPulse)1458
? GameCore.columnWarnPulse(app.warnClock)1459
: 0.16 + 0.28 * (0.5 + 0.5 * Math.sin(app.warnClock * 3.45575));1460
var t = app.tile;1461
for (var c = 0; c < app.columnWarn.length; c++)1462
{1463
var obj = app.columnWarn[c];1464
var on = app.core.columnNeedsWarn && app.core.columnNeedsWarn(c);1465
obj.renderer.visible = !!on;1466
obj.renderer.alpha = on ? pulse : 0;1467
if (t)1468
{1469
obj.transform.position.x = c * t + t / 2;1470
obj.transform.position.y = app.fieldH / 2;1471
obj.transform.size = { x: t, y: app.fieldH };1472
}1473
}1474
}1475
1017
function fieldToViewport (col, fieldY)1476
function fieldToViewport (col, fieldY)1018
{1477
{1019
var canvas = app.scene && app.scene.canvas;1478
var canvas = app.scene && app.scene.canvas;@@ -1501,6 +1960,11 @@ function confirmPlanetSelect ()1501
openOnlinePanel();1960
openOnlinePanel();1502
return;1961
return;1503
}1962
}1963
if (app.planetSelectContext === 'offline')1964
{1965
startPlay({ planet: planet, offline: true });1966
return;1967
}1504
startPlay({ planet: planet });1968
startPlay({ planet: planet });1505
}1969
}1506
1970
@@ -0,0 +1,604 @@
1
'use strict';
2
3
/**
4
* Offline Strijd: a client-side single-player mode that plays like
5
* multiplayer (shots, miss chance, opponent minis) against local bots
6
* (t1119). Pure simulation — no server.
7
*/
8
9
var Offline = (function ()
10
{
11
12
var BOT_INTERVAL = 0.5;
13
var SKILL_START = 0.05;
14
var SKILL_STEP = 0.01;
15
var SKILL_CAP = 1;
16
var FLIGHT_DURATION = 1.2;
17
var ROUND_WON_DELAY = 1.5;
18
19
/**
20
* N opponents for N−1 rounds when N >= 2; 1 opponent for 1 round.
21
* Documented in docs/ASSUMPTIONS.md (t1119).
22
*/
23
function roundsAtOpponentCount (n)
24
{
25
if (n <= 1)
26
{ return 1; }
27
return n - 1;
28
}
29
30
function skillForRound (round)
31
{
32
var r = Math.max(1, Math.floor(Number(round) || 1));
33
var pct = 5 + (r - 1);
34
if (pct > 100)
35
{ pct = 100; }
36
return pct / 100;
37
}
38
39
function scheduleForRound (round)
40
{
41
var r = Math.max(1, Math.floor(Number(round) || 1));
42
var cursor = 1;
43
var n = 1;
44
for (;;)
45
{
46
var count = roundsAtOpponentCount(n);
47
if (r < cursor + count)
48
{
49
return {
50
round: r,
51
opponents: n,
52
skill: skillForRound(r),
53
roundsAtLevel: count,
54
indexInLevel: r - cursor + 1
55
};
56
}
57
cursor += count;
58
n++;
59
if (n > 10000)
60
{
61
return {
62
round: r,
63
opponents: n,
64
skill: SKILL_CAP,
65
roundsAtLevel: roundsAtOpponentCount(n),
66
indexInLevel: 1
67
};
68
}
69
}
70
}
71
72
function GameCoreCtor ()
73
{
74
if (typeof GameCore !== 'undefined')
75
{ return GameCore; }
76
if (typeof module !== 'undefined')
77
{ return require('./gameCore.js').GameCore; }
78
return null;
79
}
80
81
function PlanetMod ()
82
{
83
if (typeof Planet !== 'undefined')
84
{ return Planet; }
85
if (typeof module !== 'undefined')
86
{ return require('./planet.js'); }
87
return null;
88
}
89
90
/**
91
* Integer-row colour grid of grounded (still / settling / locked)
92
* blocks, including greys (color < 0) so a swap can shift them.
93
*/
94
function snapshotGrid (core)
95
{
96
var width = core.width;
97
var height = core.height;
98
var grid = [];
99
for (var c = 0; c < width; c++)
100
{
101
grid[c] = [];
102
for (var r = 0; r < height; r++)
103
{ grid[c][r] = null; }
104
}
105
for (var i = 0; i < core.blocks.length; i++)
106
{
107
var b = core.blocks[i];
108
if (!core.isGrounded(b))
109
{ continue; }
110
var row = Math.round(b.y);
111
if (row < 0 || row >= height || b.col < 0 || b.col >= width)
112
{ continue; }
113
if (Math.abs(b.y - row) > 0.2)
114
{ continue; }
115
grid[b.col][row] = b.color;
116
}
117
return grid;
118
}
119
120
function cloneGrid (grid)
121
{
122
var out = [];
123
for (var c = 0; c < grid.length; c++)
124
{ out[c] = grid[c].slice(); }
125
return out;
126
}
127
128
/**
129
* Apply swapToward's net result: the block at fromRow moves to toRow,
130
* and the blocks it passed through each shift one cell toward fromRow.
131
*/
132
function applyColumnMove (grid, col, fromRow, toRow)
133
{
134
if (fromRow === toRow)
135
{ return; }
136
var moving = grid[col][fromRow];
137
if (toRow > fromRow)
138
{
139
for (var y = fromRow; y < toRow; y++)
140
{ grid[col][y] = grid[col][y + 1]; }
141
grid[col][toRow] = moving;
142
}
143
else
144
{
145
for (var y = fromRow; y > toRow; y--)
146
{ grid[col][y] = grid[col][y - 1]; }
147
grid[col][toRow] = moving;
148
}
149
}
150
151
function hasMatch (grid, width, height)
152
{
153
var c, r, run, prev;
154
for (r = 0; r < height; r++)
155
{
156
run = 0;
157
prev = null;
158
for (c = 0; c < width; c++)
159
{
160
var color = grid[c][r];
161
if (color != null && color >= 0 && color === prev)
162
{
163
run++;
164
if (run >= 3)
165
{ return true; }
166
}
167
else
168
{
169
run = (color != null && color >= 0) ? 1 : 0;
170
prev = (color != null && color >= 0) ? color : null;
171
}
172
}
173
}
174
for (c = 0; c < width; c++)
175
{
176
run = 0;
177
prev = null;
178
for (r = 0; r < height; r++)
179
{
180
var color = grid[c][r];
181
if (color != null && color >= 0 && color === prev)
182
{
183
run++;
184
if (run >= 3)
185
{ return true; }
186
}
187
else
188
{
189
run = (color != null && color >= 0) ? 1 : 0;
190
prev = (color != null && color >= 0) ? color : null;
191
}
192
}
193
}
194
return false;
195
}
196
197
/**
198
* Contiguous segments of draggable, nearly-integer-y blocks in a
199
* column. Gaps break a segment the same way swapToward stops at gaps.
200
*/
201
function contiguousSegments (core, col)
202
{
203
if (!core.columnAllowsDrag(col))
204
{ return []; }
205
var list = core.blocksInColumn(col).filter(function (b)
206
{
207
return core.isDraggableBlock(b);
208
});
209
list.sort(function (a, b) { return a.y - b.y; });
210
var segs = [];
211
var cur = [];
212
for (var i = 0; i < list.length; i++)
213
{
214
var y = list[i].y;
215
if (Math.abs(y - Math.round(y)) > 0.15)
216
{
217
if (cur.length)
218
{
219
segs.push(cur);
220
cur = [];
221
}
222
continue;
223
}
224
if (cur.length && Math.abs(y - (cur[cur.length - 1].y + 1)) > 0.15)
225
{
226
segs.push(cur);
227
cur = [list[i]];
228
}
229
else
230
{ cur.push(list[i]); }
231
}
232
if (cur.length)
233
{ segs.push(cur); }
234
return segs;
235
}
236
237
/**
238
* The shortest vertical move that would create a 3+ match, or null.
239
* Ties break on lowest column, then lowest fromY, then lowest toY.
240
*/
241
function findBotMove (core)
242
{
243
var grid = snapshotGrid(core);
244
if (hasMatch(grid, core.width, core.height))
245
{ return null; }
246
var best = null;
247
for (var col = 0; col < core.width; col++)
248
{
249
var segs = contiguousSegments(core, col);
250
for (var s = 0; s < segs.length; s++)
251
{
252
var seg = segs[s];
253
if (seg.length < 2)
254
{ continue; }
255
for (var i = 0; i < seg.length; i++)
256
{
257
var fromY = Math.round(seg[i].y);
258
for (var j = 0; j < seg.length; j++)
259
{
260
if (i === j)
261
{ continue; }
262
var toY = Math.round(seg[j].y);
263
var dist = Math.abs(toY - fromY);
264
if (best && dist > best.dist)
265
{ continue; }
266
var trial = cloneGrid(grid);
267
applyColumnMove(trial, col, fromY, toY);
268
if (!hasMatch(trial, core.width, core.height))
269
{ continue; }
270
var cand = {
271
col: col,
272
fromY: fromY,
273
toY: toY,
274
dist: dist,
275
blockId: seg[i].id
276
};
277
if (!best || dist < best.dist
278
|| (dist === best.dist && col < best.col)
279
|| (dist === best.dist && col === best.col && fromY < best.fromY)
280
|| (dist === best.dist && col === best.col && fromY === best.fromY
281
&& toY < best.toY))
282
{ best = cand; }
283
}
284
}
285
}
286
}
287
return best;
288
}
289
290
function executeBotMove (core, move)
291
{
292
if (!core || !move)
293
{ return false; }
294
var list = core.blocksInColumn(move.col);
295
var block = null;
296
for (var i = 0; i < list.length; i++)
297
{
298
if (move.blockId != null && list[i].id === move.blockId)
299
{
300
block = list[i];
301
break;
302
}
303
if (Math.abs(list[i].y - move.fromY) < 0.2)
304
{ block = list[i]; }
305
}
306
if (!block || !core.isDraggableBlock(block))
307
{ return false; }
308
core.swapToward(block, move.toY);
309
return true;
310
}
311
312
/**
313
* One AI tick. `rng` is a () => [0,1) function. Success if roll < skill.
314
* At skill 0 the bot never moves; at skill 1 it always looks for a move.
315
*/
316
function tryBotRoll (core, skill, rng)
317
{
318
rng = rng || Math.random;
319
var roll = rng();
320
if (!(roll < skill))
321
{
322
return { rolled: true, success: false, moved: false, roll: roll, move: null };
323
}
324
var move = findBotMove(core);
325
if (!move)
326
{
327
return { rolled: true, success: true, moved: false, roll: roll, move: null };
328
}
329
var ok = executeBotMove(core, move);
330
return { rolled: true, success: true, moved: !!ok, roll: roll, move: move };
331
}
332
333
function pickPlanet (rng, P)
334
{
335
var all = P.allPlanets();
336
if (!all.length)
337
{ return P.defaultPlanet(); }
338
var i = Math.floor(rng() * all.length) % all.length;
339
return all[i];
340
}
341
342
function OfflineBattle (opts)
343
{
344
opts = opts || {};
345
var P = PlanetMod();
346
this.playerPlanet = opts.playerPlanet || (P && P.defaultPlanet());
347
this.rng = opts.rng || Math.random;
348
this.round = opts.round || 1;
349
this.schedule = scheduleForRound(this.round);
350
this.clock = 0;
351
this.state = 'playing';
352
this.pending = [];
353
this.flightResults = [];
354
this.shotLocals = [];
355
this.bots = [];
356
this.playerId = 'player';
357
this._initBots();
358
}
359
360
OfflineBattle.prototype._initBots = function ()
361
{
362
var P = PlanetMod();
363
var Ctor = GameCoreCtor();
364
var n = this.schedule.opponents;
365
this.bots = [];
366
for (var i = 0; i < n; i++)
367
{
368
var planet = pickPlanet(this.rng, P);
369
var miss = P.missChance(planet);
370
var core = new Ctor(planet, this.rng, miss);
371
this.bots.push({
372
id: 'bot-' + (i + 1),
373
name: 'Bot ' + (i + 1),
374
planet: planet,
375
core: core,
376
eliminated: false,
377
score: 0,
378
aiAcc: 0
379
});
380
}
381
};
382
383
OfflineBattle.prototype.aliveBots = function ()
384
{
385
var out = [];
386
for (var i = 0; i < this.bots.length; i++)
387
{
388
if (!this.bots[i].eliminated && this.bots[i].core
389
&& this.bots[i].core.state !== 'gameover')
390
{ out.push(this.bots[i]); }
391
}
392
return out;
393
};
394
395
OfflineBattle.prototype.coreFor = function (id, playerCore)
396
{
397
if (id === this.playerId)
398
{ return playerCore; }
399
for (var i = 0; i < this.bots.length; i++)
400
{
401
if (this.bots[i].id === id)
402
{ return this.bots[i].core; }
403
}
404
return null;
405
};
406
407
OfflineBattle.prototype._targetsFor = function (fromId, playerCore)
408
{
409
var targets = [];
410
if (fromId !== this.playerId && playerCore && playerCore.state === 'playing')
411
{ targets.push({ id: this.playerId, core: playerCore }); }
412
for (var i = 0; i < this.bots.length; i++)
413
{
414
var bot = this.bots[i];
415
if (bot.id === fromId || bot.eliminated)
416
{ continue; }
417
if (bot.core && bot.core.state === 'playing')
418
{ targets.push({ id: bot.id, core: bot.core }); }
419
}
420
return targets;
421
};
422
423
OfflineBattle.prototype._dispatchShots = function (fromId, core, planet, playerCore)
424
{
425
if (!core || !core.consumeOutgoingShots)
426
{ return; }
427
var shots = core.consumeOutgoingShots();
428
if (!shots.length)
429
{ return; }
430
var P = PlanetMod();
431
var missChance = (P && planet) ? P.missChance(planet) : 0.30;
432
var targets = this._targetsFor(fromId, playerCore);
433
for (var i = 0; i < shots.length; i++)
434
{
435
var shot = shots[i];
436
var miss = targets.length === 0 || this.rng() < missChance;
437
var target = null;
438
if (!miss)
439
{
440
var idx = Math.floor(this.rng() * targets.length) % targets.length;
441
target = targets[idx];
442
}
443
var clientId = fromId + '-' + shot.id + '-' + this.clock;
444
var result = {
445
client_id: clientId,
446
miss: miss,
447
target_id: target ? target.id : null,
448
color: shot.color,
449
flight_duration: FLIGHT_DURATION,
450
from_id: fromId,
451
col: shot.col,
452
y: shot.y
453
};
454
this.flightResults.push(result);
455
this.shotLocals.push({
456
client_id: clientId,
457
col: shot.col,
458
y: shot.y,
459
color: shot.color,
460
from_id: fromId
461
});
462
if (!miss && target)
463
{
464
this.pending.push({
465
at: this.clock + FLIGHT_DURATION,
466
targetId: target.id,
467
color: shot.color,
468
fromId: fromId
469
});
470
}
471
}
472
};
473
474
OfflineBattle.prototype._deliver = function (playerCore)
475
{
476
var keep = [];
477
for (var i = 0; i < this.pending.length; i++)
478
{
479
var ev = this.pending[i];
480
if (this.clock + 1e-9 < ev.at)
481
{
482
keep.push(ev);
483
continue;
484
}
485
var core = this.coreFor(ev.targetId, playerCore);
486
if (core && core.state === 'playing' && core.ingestGarbage)
487
{ core.ingestGarbage(); }
488
}
489
this.pending = keep;
490
};
491
492
OfflineBattle.prototype.tick = function (dt, playerCore)
493
{
494
this.flightResults = [];
495
this.shotLocals = [];
496
if (this.state !== 'playing')
497
{ return { flights: [], locals: [] }; }
498
if (dt < 0)
499
{ dt = 0; }
500
this.clock += dt;
501
502
var skill = this.schedule.skill;
503
for (var i = 0; i < this.bots.length; i++)
504
{
505
var bot = this.bots[i];
506
if (bot.eliminated)
507
{ continue; }
508
if (bot.core.state === 'gameover')
509
{
510
bot.eliminated = true;
511
bot.score = bot.core.score;
512
continue;
513
}
514
bot.core.tick(dt);
515
bot.score = bot.core.score;
516
bot.aiAcc += dt;
517
while (bot.aiAcc >= BOT_INTERVAL)
518
{
519
bot.aiAcc -= BOT_INTERVAL;
520
if (bot.core.state === 'playing' && !bot.core.drag)
521
{ tryBotRoll(bot.core, skill, this.rng); }
522
}
523
}
524
525
this._dispatchShots(this.playerId, playerCore, this.playerPlanet, playerCore);
526
for (var i = 0; i < this.bots.length; i++)
527
{
528
var bot = this.bots[i];
529
if (bot.eliminated)
530
{ continue; }
531
this._dispatchShots(bot.id, bot.core, bot.planet, playerCore);
532
}
533
this._deliver(playerCore);
534
535
for (var i = 0; i < this.bots.length; i++)
536
{
537
if (this.bots[i].core && this.bots[i].core.state === 'gameover')
538
{
539
this.bots[i].eliminated = true;
540
this.bots[i].score = this.bots[i].core.score;
541
}
542
}
543
544
if (playerCore && playerCore.state === 'gameover')
545
{ this.state = 'lost'; }
546
else if (this.aliveBots().length === 0 && this.bots.length > 0)
547
{ this.state = 'round_won'; }
548
549
return { flights: this.flightResults, locals: this.shotLocals };
550
};
551
552
/**
553
* Start the next round (fresh bots, new skill and opponent count).
554
* The caller must also give the player a fresh GameCore.
555
*/
556
OfflineBattle.prototype.advanceRound = function ()
557
{
558
this.round += 1;
559
this.schedule = scheduleForRound(this.round);
560
this.state = 'playing';
561
this.pending = [];
562
this.flightResults = [];
563
this.shotLocals = [];
564
this.clock = 0;
565
this._initBots();
566
return this.schedule;
567
};
568
569
function createBattle (opts)
570
{
571
return new OfflineBattle(opts);
572
}
573
574
var api = {
575
BOT_INTERVAL: BOT_INTERVAL,
576
SKILL_START: SKILL_START,
577
SKILL_STEP: SKILL_STEP,
578
SKILL_CAP: SKILL_CAP,
579
FLIGHT_DURATION: FLIGHT_DURATION,
580
ROUND_WON_DELAY: ROUND_WON_DELAY,
581
roundsAtOpponentCount: roundsAtOpponentCount,
582
skillForRound: skillForRound,
583
scheduleForRound: scheduleForRound,
584
findBotMove: findBotMove,
585
tryBotRoll: tryBotRoll,
586
executeBotMove: executeBotMove,
587
snapshotGrid: snapshotGrid,
588
applyColumnMove: applyColumnMove,
589
hasMatch: hasMatch,
590
createBattle: createBattle,
591
OfflineBattle: OfflineBattle
592
};
593
594
if (typeof module !== 'undefined' && module.exports)
595
{ module.exports = api; }
596
else if (typeof globalThis !== 'undefined')
597
{ globalThis.Offline = api; }
598
599
return api;
600
601
})();
602
603
if (typeof module !== 'undefined' && module.exports && typeof Offline !== 'undefined')
604
{ module.exports = Offline; }
@@ -0,0 +1,604 @@1
'use strict';2
3
/**4
* Offline Strijd: a client-side single-player mode that plays like5
* multiplayer (shots, miss chance, opponent minis) against local bots6
* (t1119). Pure simulation — no server.7
*/8
9
var Offline = (function ()10
{11
12
var BOT_INTERVAL = 0.5;13
var SKILL_START = 0.05;14
var SKILL_STEP = 0.01;15
var SKILL_CAP = 1;16
var FLIGHT_DURATION = 1.2;17
var ROUND_WON_DELAY = 1.5;18
19
/**20
* N opponents for N−1 rounds when N >= 2; 1 opponent for 1 round.21
* Documented in docs/ASSUMPTIONS.md (t1119).22
*/23
function roundsAtOpponentCount (n)24
{25
if (n <= 1)26
{ return 1; }27
return n - 1;28
}29
30
function skillForRound (round)31
{32
var r = Math.max(1, Math.floor(Number(round) || 1));33
var pct = 5 + (r - 1);34
if (pct > 100)35
{ pct = 100; }36
return pct / 100;37
}38
39
function scheduleForRound (round)40
{41
var r = Math.max(1, Math.floor(Number(round) || 1));42
var cursor = 1;43
var n = 1;44
for (;;)45
{46
var count = roundsAtOpponentCount(n);47
if (r < cursor + count)48
{49
return {50
round: r,51
opponents: n,52
skill: skillForRound(r),53
roundsAtLevel: count,54
indexInLevel: r - cursor + 155
};56
}57
cursor += count;58
n++;59
if (n > 10000)60
{61
return {62
round: r,63
opponents: n,64
skill: SKILL_CAP,65
roundsAtLevel: roundsAtOpponentCount(n),66
indexInLevel: 167
};68
}69
}70
}71
72
function GameCoreCtor ()73
{74
if (typeof GameCore !== 'undefined')75
{ return GameCore; }76
if (typeof module !== 'undefined')77
{ return require('./gameCore.js').GameCore; }78
return null;79
}80
81
function PlanetMod ()82
{83
if (typeof Planet !== 'undefined')84
{ return Planet; }85
if (typeof module !== 'undefined')86
{ return require('./planet.js'); }87
return null;88
}89
90
/**91
* Integer-row colour grid of grounded (still / settling / locked)92
* blocks, including greys (color < 0) so a swap can shift them.93
*/94
function snapshotGrid (core)95
{96
var width = core.width;97
var height = core.height;98
var grid = [];99
for (var c = 0; c < width; c++)100
{101
grid[c] = [];102
for (var r = 0; r < height; r++)103
{ grid[c][r] = null; }104
}105
for (var i = 0; i < core.blocks.length; i++)106
{107
var b = core.blocks[i];108
if (!core.isGrounded(b))109
{ continue; }110
var row = Math.round(b.y);111
if (row < 0 || row >= height || b.col < 0 || b.col >= width)112
{ continue; }113
if (Math.abs(b.y - row) > 0.2)114
{ continue; }115
grid[b.col][row] = b.color;116
}117
return grid;118
}119
120
function cloneGrid (grid)121
{122
var out = [];123
for (var c = 0; c < grid.length; c++)124
{ out[c] = grid[c].slice(); }125
return out;126
}127
128
/**129
* Apply swapToward's net result: the block at fromRow moves to toRow,130
* and the blocks it passed through each shift one cell toward fromRow.131
*/132
function applyColumnMove (grid, col, fromRow, toRow)133
{134
if (fromRow === toRow)135
{ return; }136
var moving = grid[col][fromRow];137
if (toRow > fromRow)138
{139
for (var y = fromRow; y < toRow; y++)140
{ grid[col][y] = grid[col][y + 1]; }141
grid[col][toRow] = moving;142
}143
else144
{145
for (var y = fromRow; y > toRow; y--)146
{ grid[col][y] = grid[col][y - 1]; }147
grid[col][toRow] = moving;148
}149
}150
151
function hasMatch (grid, width, height)152
{153
var c, r, run, prev;154
for (r = 0; r < height; r++)155
{156
run = 0;157
prev = null;158
for (c = 0; c < width; c++)159
{160
var color = grid[c][r];161
if (color != null && color >= 0 && color === prev)162
{163
run++;164
if (run >= 3)165
{ return true; }166
}167
else168
{169
run = (color != null && color >= 0) ? 1 : 0;170
prev = (color != null && color >= 0) ? color : null;171
}172
}173
}174
for (c = 0; c < width; c++)175
{176
run = 0;177
prev = null;178
for (r = 0; r < height; r++)179
{180
var color = grid[c][r];181
if (color != null && color >= 0 && color === prev)182
{183
run++;184
if (run >= 3)185
{ return true; }186
}187
else188
{189
run = (color != null && color >= 0) ? 1 : 0;190
prev = (color != null && color >= 0) ? color : null;191
}192
}193
}194
return false;195
}196
197
/**198
* Contiguous segments of draggable, nearly-integer-y blocks in a199
* column. Gaps break a segment the same way swapToward stops at gaps.200
*/201
function contiguousSegments (core, col)202
{203
if (!core.columnAllowsDrag(col))204
{ return []; }205
var list = core.blocksInColumn(col).filter(function (b)206
{207
return core.isDraggableBlock(b);208
});209
list.sort(function (a, b) { return a.y - b.y; });210
var segs = [];211
var cur = [];212
for (var i = 0; i < list.length; i++)213
{214
var y = list[i].y;215
if (Math.abs(y - Math.round(y)) > 0.15)216
{217
if (cur.length)218
{219
segs.push(cur);220
cur = [];221
}222
continue;223
}224
if (cur.length && Math.abs(y - (cur[cur.length - 1].y + 1)) > 0.15)225
{226
segs.push(cur);227
cur = [list[i]];228
}229
else230
{ cur.push(list[i]); }231
}232
if (cur.length)233
{ segs.push(cur); }234
return segs;235
}236
237
/**238
* The shortest vertical move that would create a 3+ match, or null.239
* Ties break on lowest column, then lowest fromY, then lowest toY.240
*/241
function findBotMove (core)242
{243
var grid = snapshotGrid(core);244
if (hasMatch(grid, core.width, core.height))245
{ return null; }246
var best = null;247
for (var col = 0; col < core.width; col++)248
{249
var segs = contiguousSegments(core, col);250
for (var s = 0; s < segs.length; s++)251
{252
var seg = segs[s];253
if (seg.length < 2)254
{ continue; }255
for (var i = 0; i < seg.length; i++)256
{257
var fromY = Math.round(seg[i].y);258
for (var j = 0; j < seg.length; j++)259
{260
if (i === j)261
{ continue; }262
var toY = Math.round(seg[j].y);263
var dist = Math.abs(toY - fromY);264
if (best && dist > best.dist)265
{ continue; }266
var trial = cloneGrid(grid);267
applyColumnMove(trial, col, fromY, toY);268
if (!hasMatch(trial, core.width, core.height))269
{ continue; }270
var cand = {271
col: col,272
fromY: fromY,273
toY: toY,274
dist: dist,275
blockId: seg[i].id276
};277
if (!best || dist < best.dist278
|| (dist === best.dist && col < best.col)279
|| (dist === best.dist && col === best.col && fromY < best.fromY)280
|| (dist === best.dist && col === best.col && fromY === best.fromY281
&& toY < best.toY))282
{ best = cand; }283
}284
}285
}286
}287
return best;288
}289
290
function executeBotMove (core, move)291
{292
if (!core || !move)293
{ return false; }294
var list = core.blocksInColumn(move.col);295
var block = null;296
for (var i = 0; i < list.length; i++)297
{298
if (move.blockId != null && list[i].id === move.blockId)299
{300
block = list[i];301
break;302
}303
if (Math.abs(list[i].y - move.fromY) < 0.2)304
{ block = list[i]; }305
}306
if (!block || !core.isDraggableBlock(block))307
{ return false; }308
core.swapToward(block, move.toY);309
return true;310
}311
312
/**313
* One AI tick. `rng` is a () => [0,1) function. Success if roll < skill.314
* At skill 0 the bot never moves; at skill 1 it always looks for a move.315
*/316
function tryBotRoll (core, skill, rng)317
{318
rng = rng || Math.random;319
var roll = rng();320
if (!(roll < skill))321
{322
return { rolled: true, success: false, moved: false, roll: roll, move: null };323
}324
var move = findBotMove(core);325
if (!move)326
{327
return { rolled: true, success: true, moved: false, roll: roll, move: null };328
}329
var ok = executeBotMove(core, move);330
return { rolled: true, success: true, moved: !!ok, roll: roll, move: move };331
}332
333
function pickPlanet (rng, P)334
{335
var all = P.allPlanets();336
if (!all.length)337
{ return P.defaultPlanet(); }338
var i = Math.floor(rng() * all.length) % all.length;339
return all[i];340
}341
342
function OfflineBattle (opts)343
{344
opts = opts || {};345
var P = PlanetMod();346
this.playerPlanet = opts.playerPlanet || (P && P.defaultPlanet());347
this.rng = opts.rng || Math.random;348
this.round = opts.round || 1;349
this.schedule = scheduleForRound(this.round);350
this.clock = 0;351
this.state = 'playing';352
this.pending = [];353
this.flightResults = [];354
this.shotLocals = [];355
this.bots = [];356
this.playerId = 'player';357
this._initBots();358
}359
360
OfflineBattle.prototype._initBots = function ()361
{362
var P = PlanetMod();363
var Ctor = GameCoreCtor();364
var n = this.schedule.opponents;365
this.bots = [];366
for (var i = 0; i < n; i++)367
{368
var planet = pickPlanet(this.rng, P);369
var miss = P.missChance(planet);370
var core = new Ctor(planet, this.rng, miss);371
this.bots.push({372
id: 'bot-' + (i + 1),373
name: 'Bot ' + (i + 1),374
planet: planet,375
core: core,376
eliminated: false,377
score: 0,378
aiAcc: 0379
});380
}381
};382
383
OfflineBattle.prototype.aliveBots = function ()384
{385
var out = [];386
for (var i = 0; i < this.bots.length; i++)387
{388
if (!this.bots[i].eliminated && this.bots[i].core389
&& this.bots[i].core.state !== 'gameover')390
{ out.push(this.bots[i]); }391
}392
return out;393
};394
395
OfflineBattle.prototype.coreFor = function (id, playerCore)396
{397
if (id === this.playerId)398
{ return playerCore; }399
for (var i = 0; i < this.bots.length; i++)400
{401
if (this.bots[i].id === id)402
{ return this.bots[i].core; }403
}404
return null;405
};406
407
OfflineBattle.prototype._targetsFor = function (fromId, playerCore)408
{409
var targets = [];410
if (fromId !== this.playerId && playerCore && playerCore.state === 'playing')411
{ targets.push({ id: this.playerId, core: playerCore }); }412
for (var i = 0; i < this.bots.length; i++)413
{414
var bot = this.bots[i];415
if (bot.id === fromId || bot.eliminated)416
{ continue; }417
if (bot.core && bot.core.state === 'playing')418
{ targets.push({ id: bot.id, core: bot.core }); }419
}420
return targets;421
};422
423
OfflineBattle.prototype._dispatchShots = function (fromId, core, planet, playerCore)424
{425
if (!core || !core.consumeOutgoingShots)426
{ return; }427
var shots = core.consumeOutgoingShots();428
if (!shots.length)429
{ return; }430
var P = PlanetMod();431
var missChance = (P && planet) ? P.missChance(planet) : 0.30;432
var targets = this._targetsFor(fromId, playerCore);433
for (var i = 0; i < shots.length; i++)434
{435
var shot = shots[i];436
var miss = targets.length === 0 || this.rng() < missChance;437
var target = null;438
if (!miss)439
{440
var idx = Math.floor(this.rng() * targets.length) % targets.length;441
target = targets[idx];442
}443
var clientId = fromId + '-' + shot.id + '-' + this.clock;444
var result = {445
client_id: clientId,446
miss: miss,447
target_id: target ? target.id : null,448
color: shot.color,449
flight_duration: FLIGHT_DURATION,450
from_id: fromId,451
col: shot.col,452
y: shot.y453
};454
this.flightResults.push(result);455
this.shotLocals.push({456
client_id: clientId,457
col: shot.col,458
y: shot.y,459
color: shot.color,460
from_id: fromId461
});462
if (!miss && target)463
{464
this.pending.push({465
at: this.clock + FLIGHT_DURATION,466
targetId: target.id,467
color: shot.color,468
fromId: fromId469
});470
}471
}472
};473
474
OfflineBattle.prototype._deliver = function (playerCore)475
{476
var keep = [];477
for (var i = 0; i < this.pending.length; i++)478
{479
var ev = this.pending[i];480
if (this.clock + 1e-9 < ev.at)481
{482
keep.push(ev);483
continue;484
}485
var core = this.coreFor(ev.targetId, playerCore);486
if (core && core.state === 'playing' && core.ingestGarbage)487
{ core.ingestGarbage(); }488
}489
this.pending = keep;490
};491
492
OfflineBattle.prototype.tick = function (dt, playerCore)493
{494
this.flightResults = [];495
this.shotLocals = [];496
if (this.state !== 'playing')497
{ return { flights: [], locals: [] }; }498
if (dt < 0)499
{ dt = 0; }500
this.clock += dt;501
502
var skill = this.schedule.skill;503
for (var i = 0; i < this.bots.length; i++)504
{505
var bot = this.bots[i];506
if (bot.eliminated)507
{ continue; }508
if (bot.core.state === 'gameover')509
{510
bot.eliminated = true;511
bot.score = bot.core.score;512
continue;513
}514
bot.core.tick(dt);515
bot.score = bot.core.score;516
bot.aiAcc += dt;517
while (bot.aiAcc >= BOT_INTERVAL)518
{519
bot.aiAcc -= BOT_INTERVAL;520
if (bot.core.state === 'playing' && !bot.core.drag)521
{ tryBotRoll(bot.core, skill, this.rng); }522
}523
}524
525
this._dispatchShots(this.playerId, playerCore, this.playerPlanet, playerCore);526
for (var i = 0; i < this.bots.length; i++)527
{528
var bot = this.bots[i];529
if (bot.eliminated)530
{ continue; }531
this._dispatchShots(bot.id, bot.core, bot.planet, playerCore);532
}533
this._deliver(playerCore);534
535
for (var i = 0; i < this.bots.length; i++)536
{537
if (this.bots[i].core && this.bots[i].core.state === 'gameover')538
{539
this.bots[i].eliminated = true;540
this.bots[i].score = this.bots[i].core.score;541
}542
}543
544
if (playerCore && playerCore.state === 'gameover')545
{ this.state = 'lost'; }546
else if (this.aliveBots().length === 0 && this.bots.length > 0)547
{ this.state = 'round_won'; }548
549
return { flights: this.flightResults, locals: this.shotLocals };550
};551
552
/**553
* Start the next round (fresh bots, new skill and opponent count).554
* The caller must also give the player a fresh GameCore.555
*/556
OfflineBattle.prototype.advanceRound = function ()557
{558
this.round += 1;559
this.schedule = scheduleForRound(this.round);560
this.state = 'playing';561
this.pending = [];562
this.flightResults = [];563
this.shotLocals = [];564
this.clock = 0;565
this._initBots();566
return this.schedule;567
};568
569
function createBattle (opts)570
{571
return new OfflineBattle(opts);572
}573
574
var api = {575
BOT_INTERVAL: BOT_INTERVAL,576
SKILL_START: SKILL_START,577
SKILL_STEP: SKILL_STEP,578
SKILL_CAP: SKILL_CAP,579
FLIGHT_DURATION: FLIGHT_DURATION,580
ROUND_WON_DELAY: ROUND_WON_DELAY,581
roundsAtOpponentCount: roundsAtOpponentCount,582
skillForRound: skillForRound,583
scheduleForRound: scheduleForRound,584
findBotMove: findBotMove,585
tryBotRoll: tryBotRoll,586
executeBotMove: executeBotMove,587
snapshotGrid: snapshotGrid,588
applyColumnMove: applyColumnMove,589
hasMatch: hasMatch,590
createBattle: createBattle,591
OfflineBattle: OfflineBattle592
};593
594
if (typeof module !== 'undefined' && module.exports)595
{ module.exports = api; }596
else if (typeof globalThis !== 'undefined')597
{ globalThis.Offline = api; }598
599
return api;600
601
})();602
603
if (typeof module !== 'undefined' && module.exports && typeof Offline !== 'undefined')604
{ module.exports = Offline; }@@ -348,6 +348,19 @@ Online._drawMini = function (canvas, snapshot, planet)
348
348
}
349
349
if (!snapshot || !snapshot.blocks)
350
350
{ return; }
351
// t1123: cheap sine pulse behind blocks of nearly-full columns.
352
if (typeof GameCore !== 'undefined' && GameCore.warnColumnsFromSnapshot)
353
{
354
var warns = GameCore.warnColumnsFromSnapshot(snapshot);
355
var pulse = GameCore.columnWarnPulse();
356
for (var wc = 0; wc < warns.length; wc++)
357
{
358
if (!warns[wc])
359
{ continue; }
360
ctx.fillStyle = 'rgba(220, 36, 36,' + pulse + ')';
361
ctx.fillRect(wc * tw, 0, tw, canvas.height);
362
}
363
}
351
364
var blocks = snapshot.blocks;
352
365
for (var i = 0; i < blocks.length; i++)
353
366
{
@@ -348,6 +348,19 @@ Online._drawMini = function (canvas, snapshot, planet)348
}348
}349
if (!snapshot || !snapshot.blocks)349
if (!snapshot || !snapshot.blocks)350
{ return; }350
{ return; }351
// t1123: cheap sine pulse behind blocks of nearly-full columns.352
if (typeof GameCore !== 'undefined' && GameCore.warnColumnsFromSnapshot)353
{354
var warns = GameCore.warnColumnsFromSnapshot(snapshot);355
var pulse = GameCore.columnWarnPulse();356
for (var wc = 0; wc < warns.length; wc++)357
{358
if (!warns[wc])359
{ continue; }360
ctx.fillStyle = 'rgba(220, 36, 36,' + pulse + ')';361
ctx.fillRect(wc * tw, 0, tw, canvas.height);362
}363
}351
var blocks = snapshot.blocks;364
var blocks = snapshot.blocks;352
for (var i = 0; i < blocks.length; i++)365
for (var i = 0; i < blocks.length; i++)353
{366
{@@ -8,10 +8,16 @@
8
8
* that later planets only need new data, not new physics code.
9
9
*
10
10
* Gravity (jumpsToClear): 1 (easy, high jump) .. 4 (hard, short jump).
11
* A horizontal match of 3 jumps FIELD_HEIGHT / jumpsToClear tiles —
12
* at 1, one jump from the floor clears the field; at 4, you need four.
11
* A horizontal match of 3 jumps JUMP_HEIGHT_SCALE * FIELD_HEIGHT
12
* / jumpsToClear tiles (JUMP_HEIGHT_SCALE is 1.5 since t1119: the
13
* minimum jump is 50% higher). At gravity 1 that is 19.5 tiles, so
14
* one jump from the floor clears the 13-tile field with room to spare;
15
* at 4 you still need more than one jump, but each is 50% taller.
13
16
* Air (fallTime): 1 s (hard, fast fall) .. 5 s (easy, slow fall).
14
* After a jump peaks, blocks float down at FIELD_HEIGHT / fallTime tiles/s.
17
* After a jump peaks, blocks float down at DESCENT_SPEED_SCALE *
18
* FIELD_HEIGHT / fallTime tiles/s (DESCENT_SPEED_SCALE is 0.5 since
19
* t1122: all descent speeds are halved). Relative differences between
20
* planets (1 / fallTime) are unchanged. Upward launch is not affected.
15
21
* Mass (riseTime): 0.5 s (hard, fast jump) .. 3 s (easy, slow jump).
16
22
* Time to reach the apex, independent of jump height.
17
23
*
@@ -26,6 +32,14 @@
26
32
27
33
var FIELD_WIDTH = 10;
28
34
var FIELD_HEIGHT = 13;
35
/** t1119: every match jump (the gravity-applied minimum and the
36
* vertical / extra-block bonuses derived from it) is 50% higher. */
37
var JUMP_HEIGHT_SCALE = 1.5;
38
/** t1122: every descent speed is halved. Terminal fallSpeed, spawn
39
* fall, unsupported / released / cargo fall, and the post-apex
40
* float-down all use this scale. Upward launch is unchanged. */
41
var DESCENT_SPEED_SCALE = 0.5;
42
29
43
30
44
function clamp (value, lo, hi)
31
45
{
@@ -58,12 +72,14 @@ function createPlanet (opts)
58
72
fallTime: fallTime,
59
73
riseTime: riseTime,
60
74
colors: colors,
61
baseJumpHeight: FIELD_HEIGHT / jumpsToClear,
62
fallSpeed: FIELD_HEIGHT / fallTime,
75
baseJumpHeight: JUMP_HEIGHT_SCALE * FIELD_HEIGHT / jumpsToClear,
76
fallSpeed: DESCENT_SPEED_SCALE * FIELD_HEIGHT / fallTime,
63
77
// Time to ease from vy=0 at the apex to terminal fallSpeed.
64
// Shorter when air resistance is low (small fallTime).
78
// Shorter when air resistance is low (small fallTime). The ease
79
// duration is unchanged; fallAccel scales with the halved
80
// fallSpeed so the ease still lasts apexEaseTime seconds.
65
81
apexEaseTime: 0.15 * fallTime,
66
fallAccel: (FIELD_HEIGHT / fallTime) / (0.15 * fallTime),
82
fallAccel: (DESCENT_SPEED_SCALE * FIELD_HEIGHT / fallTime) / (0.15 * fallTime),
67
83
// Visual landing bounce: faster at low air resistance. Stage-3 params.
68
84
bounceDuration: 0.12 * fallTime,
69
85
bounceSquash: 0.16
@@ -232,6 +248,8 @@ function displayValues (planet)
232
248
var Planet = {
233
249
FIELD_WIDTH: FIELD_WIDTH,
234
250
FIELD_HEIGHT: FIELD_HEIGHT,
251
JUMP_HEIGHT_SCALE: JUMP_HEIGHT_SCALE,
252
DESCENT_SPEED_SCALE: DESCENT_SPEED_SCALE,
235
253
COLOR_COUNT: 5,
236
254
SETTLE_TIME: 3,
237
255
SPAWN_INTERVAL: 1,
@@ -8,10 +8,16 @@8
* that later planets only need new data, not new physics code.8
* that later planets only need new data, not new physics code.9
*9
*10
* Gravity (jumpsToClear): 1 (easy, high jump) .. 4 (hard, short jump).10
* Gravity (jumpsToClear): 1 (easy, high jump) .. 4 (hard, short jump).11
* A horizontal match of 3 jumps FIELD_HEIGHT / jumpsToClear tiles —11
* A horizontal match of 3 jumps JUMP_HEIGHT_SCALE * FIELD_HEIGHT12
* at 1, one jump from the floor clears the field; at 4, you need four.12
* / jumpsToClear tiles (JUMP_HEIGHT_SCALE is 1.5 since t1119: the13
* minimum jump is 50% higher). At gravity 1 that is 19.5 tiles, so14
* one jump from the floor clears the 13-tile field with room to spare;15
* at 4 you still need more than one jump, but each is 50% taller.13
* Air (fallTime): 1 s (hard, fast fall) .. 5 s (easy, slow fall).16
* Air (fallTime): 1 s (hard, fast fall) .. 5 s (easy, slow fall).14
* After a jump peaks, blocks float down at FIELD_HEIGHT / fallTime tiles/s.17
* After a jump peaks, blocks float down at DESCENT_SPEED_SCALE *18
* FIELD_HEIGHT / fallTime tiles/s (DESCENT_SPEED_SCALE is 0.5 since19
* t1122: all descent speeds are halved). Relative differences between20
* planets (1 / fallTime) are unchanged. Upward launch is not affected.15
* Mass (riseTime): 0.5 s (hard, fast jump) .. 3 s (easy, slow jump).21
* Mass (riseTime): 0.5 s (hard, fast jump) .. 3 s (easy, slow jump).16
* Time to reach the apex, independent of jump height.22
* Time to reach the apex, independent of jump height.17
*23
*@@ -26,6 +32,14 @@26
32
27
var FIELD_WIDTH = 10;33
var FIELD_WIDTH = 10;28
var FIELD_HEIGHT = 13;34
var FIELD_HEIGHT = 13;35
/** t1119: every match jump (the gravity-applied minimum and the36
* vertical / extra-block bonuses derived from it) is 50% higher. */37
var JUMP_HEIGHT_SCALE = 1.5;38
/** t1122: every descent speed is halved. Terminal fallSpeed, spawn39
* fall, unsupported / released / cargo fall, and the post-apex40
* float-down all use this scale. Upward launch is unchanged. */41
var DESCENT_SPEED_SCALE = 0.5;42
29
43
30
function clamp (value, lo, hi)44
function clamp (value, lo, hi)31
{45
{@@ -58,12 +72,14 @@ function createPlanet (opts)58
fallTime: fallTime,72
fallTime: fallTime,59
riseTime: riseTime,73
riseTime: riseTime,60
colors: colors,74
colors: colors,61
baseJumpHeight: FIELD_HEIGHT / jumpsToClear,75
baseJumpHeight: JUMP_HEIGHT_SCALE * FIELD_HEIGHT / jumpsToClear,62
fallSpeed: FIELD_HEIGHT / fallTime,76
fallSpeed: DESCENT_SPEED_SCALE * FIELD_HEIGHT / fallTime,63
// Time to ease from vy=0 at the apex to terminal fallSpeed.77
// Time to ease from vy=0 at the apex to terminal fallSpeed.64
// Shorter when air resistance is low (small fallTime).78
// Shorter when air resistance is low (small fallTime). The ease79
// duration is unchanged; fallAccel scales with the halved80
// fallSpeed so the ease still lasts apexEaseTime seconds.65
apexEaseTime: 0.15 * fallTime,81
apexEaseTime: 0.15 * fallTime,66
fallAccel: (FIELD_HEIGHT / fallTime) / (0.15 * fallTime),82
fallAccel: (DESCENT_SPEED_SCALE * FIELD_HEIGHT / fallTime) / (0.15 * fallTime),67
// Visual landing bounce: faster at low air resistance. Stage-3 params.83
// Visual landing bounce: faster at low air resistance. Stage-3 params.68
bounceDuration: 0.12 * fallTime,84
bounceDuration: 0.12 * fallTime,69
bounceSquash: 0.1685
bounceSquash: 0.16@@ -232,6 +248,8 @@ function displayValues (planet)232
var Planet = {248
var Planet = {233
FIELD_WIDTH: FIELD_WIDTH,249
FIELD_WIDTH: FIELD_WIDTH,234
FIELD_HEIGHT: FIELD_HEIGHT,250
FIELD_HEIGHT: FIELD_HEIGHT,251
JUMP_HEIGHT_SCALE: JUMP_HEIGHT_SCALE,252
DESCENT_SPEED_SCALE: DESCENT_SPEED_SCALE,235
COLOR_COUNT: 5,253
COLOR_COUNT: 5,236
SETTLE_TIME: 3,254
SETTLE_TIME: 3,237
SPAWN_INTERVAL: 1,255
SPAWN_INTERVAL: 1,@@ -0,0 +1,59 @@
1
'use strict';
2
3
const { describe, it } = require('node:test');
4
const assert = require('node:assert/strict');
5
const { makeGame, fillColumn, GameCore } = require('./helpers.js');
6
7
describe('Column fill warning (t1123)', () =>
8
{
9
it('pulses at 10 grounded rows (at least 70% of 13) and not at 9', () =>
10
{
11
assert.equal(GameCore.COLUMN_WARN_ROWS, 10);
12
const g = makeGame({ noSpawn: true });
13
fillColumn(g, 0, 9);
14
assert.equal(g.groundedCount(0), 9);
15
assert.equal(g.columnNeedsWarn(0), false);
16
g.place(0, 9, 0);
17
assert.equal(g.groundedCount(0), 10);
18
assert.equal(g.columnNeedsWarn(0), true);
19
fillColumn(g, 3, 13);
20
assert.equal(g.columnNeedsWarn(3), true);
21
});
22
23
it('flying, falling and manual blocks do not count; settling and locked do', () =>
24
{
25
const g = makeGame({ noSpawn: true });
26
fillColumn(g, 2, 9);
27
const flying = g.createBlock(2, 10, 1, 'flying');
28
const falling = g.createBlock(2, 11, 2, 'falling');
29
assert.equal(g.columnNeedsWarn(2), false, 'airborne must not trip the warning');
30
flying.state = 'still';
31
falling.state = 'still';
32
// now 11 still — but flying was at y=10, falling at 11, plus 9 = 11
33
assert.equal(g.columnNeedsWarn(2), true);
34
});
35
36
it('warnColumnsFromSnapshot agrees with the live field and ignores flying', () =>
37
{
38
const g = makeGame({ noSpawn: true });
39
fillColumn(g, 1, 10);
40
g.createBlock(1, 11, 0, 'flying');
41
g.createBlock(4, 0, 1, 'falling');
42
const flags = GameCore.warnColumnsFromSnapshot(g.fieldSnapshot());
43
assert.equal(flags[1], true);
44
assert.equal(flags[4], false);
45
assert.equal(flags[0], false);
46
});
47
48
it('columnWarnPulse is a sine in a cheap 0.16–0.44 alpha band', () =>
49
{
50
const mid = GameCore.columnWarnPulse(0); // sin(0) = 0 → mid 0.30
51
const peak = GameCore.columnWarnPulse(0.25 / 0.55);
52
const trough = GameCore.columnWarnPulse(0.75 / 0.55);
53
for (const v of [mid, peak, trough])
54
{ assert.ok(v >= 0.16 - 1e-9 && v <= 0.44 + 1e-9, 'pulse=' + v); }
55
assert.ok(peak > mid && mid > trough, 'peak=' + peak + ' mid=' + mid + ' trough=' + trough);
56
assert.ok(Math.abs(peak - 0.44) < 1e-9, 'peak=' + peak);
57
assert.ok(Math.abs(trough - 0.16) < 1e-9, 'trough=' + trough);
58
});
59
});
@@ -0,0 +1,59 @@1
'use strict';2
3
const { describe, it } = require('node:test');4
const assert = require('node:assert/strict');5
const { makeGame, fillColumn, GameCore } = require('./helpers.js');6
7
describe('Column fill warning (t1123)', () =>8
{9
it('pulses at 10 grounded rows (at least 70% of 13) and not at 9', () =>10
{11
assert.equal(GameCore.COLUMN_WARN_ROWS, 10);12
const g = makeGame({ noSpawn: true });13
fillColumn(g, 0, 9);14
assert.equal(g.groundedCount(0), 9);15
assert.equal(g.columnNeedsWarn(0), false);16
g.place(0, 9, 0);17
assert.equal(g.groundedCount(0), 10);18
assert.equal(g.columnNeedsWarn(0), true);19
fillColumn(g, 3, 13);20
assert.equal(g.columnNeedsWarn(3), true);21
});22
23
it('flying, falling and manual blocks do not count; settling and locked do', () =>24
{25
const g = makeGame({ noSpawn: true });26
fillColumn(g, 2, 9);27
const flying = g.createBlock(2, 10, 1, 'flying');28
const falling = g.createBlock(2, 11, 2, 'falling');29
assert.equal(g.columnNeedsWarn(2), false, 'airborne must not trip the warning');30
flying.state = 'still';31
falling.state = 'still';32
// now 11 still — but flying was at y=10, falling at 11, plus 9 = 1133
assert.equal(g.columnNeedsWarn(2), true);34
});35
36
it('warnColumnsFromSnapshot agrees with the live field and ignores flying', () =>37
{38
const g = makeGame({ noSpawn: true });39
fillColumn(g, 1, 10);40
g.createBlock(1, 11, 0, 'flying');41
g.createBlock(4, 0, 1, 'falling');42
const flags = GameCore.warnColumnsFromSnapshot(g.fieldSnapshot());43
assert.equal(flags[1], true);44
assert.equal(flags[4], false);45
assert.equal(flags[0], false);46
});47
48
it('columnWarnPulse is a sine in a cheap 0.16–0.44 alpha band', () =>49
{50
const mid = GameCore.columnWarnPulse(0); // sin(0) = 0 → mid 0.3051
const peak = GameCore.columnWarnPulse(0.25 / 0.55);52
const trough = GameCore.columnWarnPulse(0.75 / 0.55);53
for (const v of [mid, peak, trough])54
{ assert.ok(v >= 0.16 - 1e-9 && v <= 0.44 + 1e-9, 'pulse=' + v); }55
assert.ok(peak > mid && mid > trough, 'peak=' + peak + ' mid=' + mid + ' trough=' + trough);56
assert.ok(Math.abs(peak - 0.44) < 1e-9, 'peak=' + peak);57
assert.ok(Math.abs(trough - 0.16) < 1e-9, 'trough=' + trough);58
});59
});@@ -85,3 +85,21 @@ describe('Planet apex-ease and bounce parameters', () =>
85
85
assert.ok(Math.abs(terra.fallAccel - terra.fallSpeed / terra.apexEaseTime) < 1e-9);
86
86
});
87
87
});
88
89
describe('Swap tween (t1121)', () =>
90
{
91
it('easeOutCubic is 0 at 0, 1 at 1, and 0.875 at 0.5', () =>
92
{
93
assert.equal(Easing.easeOutCubic(0), 0);
94
assert.equal(Easing.easeOutCubic(1), 1);
95
assert.ok(Math.abs(Easing.easeOutCubic(0.5) - 0.875) < 1e-12);
96
assert.ok(Easing.easeOutCubic(0.25) > 0.25, 'front-loaded (fast finish)');
97
});
98
99
it('SWAP_TWEEN lasts 80–120 ms and uses easeOutCubic', () =>
100
{
101
const s = Easing.SWAP_TWEEN;
102
assert.ok(s.duration >= 0.08 && s.duration <= 0.12, 'duration=' + s.duration);
103
assert.equal(s.ease, Easing.easeOutCubic);
104
});
105
});
@@ -85,3 +85,21 @@ describe('Planet apex-ease and bounce parameters', () =>85
assert.ok(Math.abs(terra.fallAccel - terra.fallSpeed / terra.apexEaseTime) < 1e-9);85
assert.ok(Math.abs(terra.fallAccel - terra.fallSpeed / terra.apexEaseTime) < 1e-9);86
});86
});87
});87
});88
89
describe('Swap tween (t1121)', () =>90
{91
it('easeOutCubic is 0 at 0, 1 at 1, and 0.875 at 0.5', () =>92
{93
assert.equal(Easing.easeOutCubic(0), 0);94
assert.equal(Easing.easeOutCubic(1), 1);95
assert.ok(Math.abs(Easing.easeOutCubic(0.5) - 0.875) < 1e-12);96
assert.ok(Easing.easeOutCubic(0.25) > 0.25, 'front-loaded (fast finish)');97
});98
99
it('SWAP_TWEEN lasts 80–120 ms and uses easeOutCubic', () =>100
{101
const s = Easing.SWAP_TWEEN;102
assert.ok(s.duration >= 0.08 && s.duration <= 0.12, 'duration=' + s.duration);103
assert.equal(s.ease, Easing.easeOutCubic);104
});105
});@@ -38,8 +38,9 @@ describe('Falling blocks land on flying clusters', () =>
38
38
cluster.vy = 0;
39
39
const falling = g.createBlock(3, 10, 1, 'falling');
40
40
falling.vy = -g.planet.fallSpeed;
41
// Fall from 10 onto 6+1=7: distance 3, at fallSpeed 13/3 ≈ 4.33 → ~0.7s
42
g.step(1.0, 1 / 120);
41
// Fall from 10 onto 6+1=7: distance 3, at halved fallSpeed
42
// 0.5 * 13/3 ≈ 2.17 → ~1.4s (t1122).
43
g.step(2.0, 1 / 120);
43
44
assert.equal(falling.state, 'flying', 'should have attached, state=' + falling.state + ' y=' + falling.y);
44
45
assert.equal(falling.clusterId, cluster.id);
45
46
assert.equal(falling.flame, false, 'cargo has no flame');
@@ -68,7 +69,10 @@ describe('Falling blocks land on flying clusters', () =>
68
69
cluster.vy = -g.planet.fallSpeed;
69
70
const falling = g.createBlock(1, 8, 2, 'falling');
70
71
falling.vy = -g.planet.fallSpeed;
71
g.step(2.0, 1 / 120);
72
// Same terminal speed as the cluster, so they only meet after
73
// the cluster lands. With halved descent (t1122) that takes
74
// roughly 2× as long as before (~3.7 s).
75
g.step(5.0, 1 / 120);
72
76
assert.notEqual(falling.state, 'falling');
73
77
assert.ok(falling.state === 'flying' || falling.state === 'settling' || falling.state === 'still',
74
78
'must not still be falling through, state=' + falling.state + ' y=' + falling.y);
@@ -89,7 +93,7 @@ describe('Falling blocks land on flying clusters', () =>
89
93
members[0].vy = cluster.vy;
90
94
const falling = g.createBlock(5, 7, 3, 'falling');
91
95
falling.vy = -g.planet.fallSpeed;
92
g.step(0.8, 1 / 120);
96
g.step(1.6, 1 / 120);
93
97
assert.equal(falling.state, 'flying', 'picked up, state=' + falling.state + ' y=' + falling.y);
94
98
assert.equal(falling.clusterId, cluster.id);
95
99
assert.ok(falling.y >= members[0].y, 'sits at or above the flyer, cargo=' + falling.y + ' flyer=' + members[0].y);
@@ -170,7 +174,7 @@ describe('Rigid grey landing', () =>
170
174
assert.ok(right.state === 'falling' || (right.state === 'still' && almost(right.y, 0, 0.05)),
171
175
'right falls, state=' + right.state);
172
176
// Give them time to land individually.
173
g.step(g.planet.fallTime + 0.5, 1 / 60);
177
g.step(g.planet.fallTime / Planet.DESCENT_SPEED_SCALE + 0.5, 1 / 60);
174
178
assert.equal(left.state, 'still');
175
179
assert.ok(almost(left.y, 0, 0.05), 'left lands on the floor, y=' + left.y);
176
180
assert.equal(right.state, 'still');
@@ -347,11 +351,13 @@ describe('Recolor must not shoot blocks off the top (t1102)', () =>
347
351
348
352
const cluster = Object.values(g.clusters).find((c) => c.phase === 'up');
349
353
assert.ok(cluster, 'a new match must launch\n' + g.snapshot().picture + '\nair=' + JSON.stringify(g.snapshot().airborne));
350
const expectedH = Planet.jumpHeight(g.planet, 3, false);
354
// Recolor-on-landing is a landing-chain match (t1120): +25%.
355
const expectedH = Planet.jumpHeight(g.planet, 3, false) * (1 + GameCore.LANDING_CHAIN_BONUS);
351
356
const expectedVy = Planet.launchVelocity(g.planet, expectedH);
352
357
const expectedDecel = Planet.launchDeceleration(g.planet, expectedH);
353
358
assert.ok(almost(cluster.jumpHeight, expectedH, 1e-9), 'jumpHeight=' + cluster.jumpHeight + ' expected ' + expectedH);
354
assert.ok(almost(cluster.vy, expectedVy, 0.15), 'vy must be the normal launch speed ' + expectedVy + ', got ' + cluster.vy + ' (leftover 40 would be wrong)');
359
assert.equal(cluster.landingChain, 1);
360
assert.ok(almost(cluster.vy, expectedVy, 0.35), 'vy must be the normal launch speed ' + expectedVy + ', got ' + cluster.vy + ' (leftover 40 would be wrong)');
355
361
assert.ok(almost(cluster.decel, expectedDecel, 0.15), 'decel=' + cluster.decel);
356
362
assert.ok(cluster.vy < 40, 'must not keep the leftover vy');
357
363
// Riders share the same (normal) velocity.
@@ -369,6 +375,10 @@ describe('Recolor must not shoot blocks off the top (t1102)', () =>
369
375
apex = Math.max(apex, cargoA.y, cargoB.y);
370
376
}
371
377
assert.ok(apex <= startY + expectedH + 0.35, 'apex must follow normal jump height, apex=' + apex + ' start=' + startY + ' H=' + expectedH);
372
assert.ok(apex >= startY + expectedH - 0.85, 'should actually reach the jump, apex=' + apex);
378
// With t1119 (+50% jump) and t1120 (landing-chain +25%), a chain-1
379
// horizontal-3 from y≈3 clears the 13-tile field, so the apex may
380
// be the top of the field rather than startY+H.
381
assert.ok(apex >= Math.min(g.height - 1, startY + expectedH - 0.85) - 0.05,
382
'should actually rise, apex=' + apex + ' start=' + startY + ' H=' + expectedH);
373
383
});
374
384
});
@@ -38,8 +38,9 @@ describe('Falling blocks land on flying clusters', () =>38
cluster.vy = 0;38
cluster.vy = 0;39
const falling = g.createBlock(3, 10, 1, 'falling');39
const falling = g.createBlock(3, 10, 1, 'falling');40
falling.vy = -g.planet.fallSpeed;40
falling.vy = -g.planet.fallSpeed;41
// Fall from 10 onto 6+1=7: distance 3, at fallSpeed 13/3 ≈ 4.33 → ~0.7s41
// Fall from 10 onto 6+1=7: distance 3, at halved fallSpeed42
g.step(1.0, 1 / 120);42
// 0.5 * 13/3 ≈ 2.17 → ~1.4s (t1122).43
g.step(2.0, 1 / 120);43
assert.equal(falling.state, 'flying', 'should have attached, state=' + falling.state + ' y=' + falling.y);44
assert.equal(falling.state, 'flying', 'should have attached, state=' + falling.state + ' y=' + falling.y);44
assert.equal(falling.clusterId, cluster.id);45
assert.equal(falling.clusterId, cluster.id);45
assert.equal(falling.flame, false, 'cargo has no flame');46
assert.equal(falling.flame, false, 'cargo has no flame');@@ -68,7 +69,10 @@ describe('Falling blocks land on flying clusters', () =>68
cluster.vy = -g.planet.fallSpeed;69
cluster.vy = -g.planet.fallSpeed;69
const falling = g.createBlock(1, 8, 2, 'falling');70
const falling = g.createBlock(1, 8, 2, 'falling');70
falling.vy = -g.planet.fallSpeed;71
falling.vy = -g.planet.fallSpeed;71
g.step(2.0, 1 / 120);72
// Same terminal speed as the cluster, so they only meet after73
// the cluster lands. With halved descent (t1122) that takes74
// roughly 2× as long as before (~3.7 s).75
g.step(5.0, 1 / 120);72
assert.notEqual(falling.state, 'falling');76
assert.notEqual(falling.state, 'falling');73
assert.ok(falling.state === 'flying' || falling.state === 'settling' || falling.state === 'still',77
assert.ok(falling.state === 'flying' || falling.state === 'settling' || falling.state === 'still',74
'must not still be falling through, state=' + falling.state + ' y=' + falling.y);78
'must not still be falling through, state=' + falling.state + ' y=' + falling.y);@@ -89,7 +93,7 @@ describe('Falling blocks land on flying clusters', () =>89
members[0].vy = cluster.vy;93
members[0].vy = cluster.vy;90
const falling = g.createBlock(5, 7, 3, 'falling');94
const falling = g.createBlock(5, 7, 3, 'falling');91
falling.vy = -g.planet.fallSpeed;95
falling.vy = -g.planet.fallSpeed;92
g.step(0.8, 1 / 120);96
g.step(1.6, 1 / 120);93
assert.equal(falling.state, 'flying', 'picked up, state=' + falling.state + ' y=' + falling.y);97
assert.equal(falling.state, 'flying', 'picked up, state=' + falling.state + ' y=' + falling.y);94
assert.equal(falling.clusterId, cluster.id);98
assert.equal(falling.clusterId, cluster.id);95
assert.ok(falling.y >= members[0].y, 'sits at or above the flyer, cargo=' + falling.y + ' flyer=' + members[0].y);99
assert.ok(falling.y >= members[0].y, 'sits at or above the flyer, cargo=' + falling.y + ' flyer=' + members[0].y);@@ -170,7 +174,7 @@ describe('Rigid grey landing', () =>170
assert.ok(right.state === 'falling' || (right.state === 'still' && almost(right.y, 0, 0.05)),174
assert.ok(right.state === 'falling' || (right.state === 'still' && almost(right.y, 0, 0.05)),171
'right falls, state=' + right.state);175
'right falls, state=' + right.state);172
// Give them time to land individually.176
// Give them time to land individually.173
g.step(g.planet.fallTime + 0.5, 1 / 60);177
g.step(g.planet.fallTime / Planet.DESCENT_SPEED_SCALE + 0.5, 1 / 60);174
assert.equal(left.state, 'still');178
assert.equal(left.state, 'still');175
assert.ok(almost(left.y, 0, 0.05), 'left lands on the floor, y=' + left.y);179
assert.ok(almost(left.y, 0, 0.05), 'left lands on the floor, y=' + left.y);176
assert.equal(right.state, 'still');180
assert.equal(right.state, 'still');@@ -347,11 +351,13 @@ describe('Recolor must not shoot blocks off the top (t1102)', () =>347
351
348
const cluster = Object.values(g.clusters).find((c) => c.phase === 'up');352
const cluster = Object.values(g.clusters).find((c) => c.phase === 'up');349
assert.ok(cluster, 'a new match must launch\n' + g.snapshot().picture + '\nair=' + JSON.stringify(g.snapshot().airborne));353
assert.ok(cluster, 'a new match must launch\n' + g.snapshot().picture + '\nair=' + JSON.stringify(g.snapshot().airborne));350
const expectedH = Planet.jumpHeight(g.planet, 3, false);354
// Recolor-on-landing is a landing-chain match (t1120): +25%.355
const expectedH = Planet.jumpHeight(g.planet, 3, false) * (1 + GameCore.LANDING_CHAIN_BONUS);351
const expectedVy = Planet.launchVelocity(g.planet, expectedH);356
const expectedVy = Planet.launchVelocity(g.planet, expectedH);352
const expectedDecel = Planet.launchDeceleration(g.planet, expectedH);357
const expectedDecel = Planet.launchDeceleration(g.planet, expectedH);353
assert.ok(almost(cluster.jumpHeight, expectedH, 1e-9), 'jumpHeight=' + cluster.jumpHeight + ' expected ' + expectedH);358
assert.ok(almost(cluster.jumpHeight, expectedH, 1e-9), 'jumpHeight=' + cluster.jumpHeight + ' expected ' + expectedH);354
assert.ok(almost(cluster.vy, expectedVy, 0.15), 'vy must be the normal launch speed ' + expectedVy + ', got ' + cluster.vy + ' (leftover 40 would be wrong)');359
assert.equal(cluster.landingChain, 1);360
assert.ok(almost(cluster.vy, expectedVy, 0.35), 'vy must be the normal launch speed ' + expectedVy + ', got ' + cluster.vy + ' (leftover 40 would be wrong)');355
assert.ok(almost(cluster.decel, expectedDecel, 0.15), 'decel=' + cluster.decel);361
assert.ok(almost(cluster.decel, expectedDecel, 0.15), 'decel=' + cluster.decel);356
assert.ok(cluster.vy < 40, 'must not keep the leftover vy');362
assert.ok(cluster.vy < 40, 'must not keep the leftover vy');357
// Riders share the same (normal) velocity.363
// Riders share the same (normal) velocity.@@ -369,6 +375,10 @@ describe('Recolor must not shoot blocks off the top (t1102)', () =>369
apex = Math.max(apex, cargoA.y, cargoB.y);375
apex = Math.max(apex, cargoA.y, cargoB.y);370
}376
}371
assert.ok(apex <= startY + expectedH + 0.35, 'apex must follow normal jump height, apex=' + apex + ' start=' + startY + ' H=' + expectedH);377
assert.ok(apex <= startY + expectedH + 0.35, 'apex must follow normal jump height, apex=' + apex + ' start=' + startY + ' H=' + expectedH);372
assert.ok(apex >= startY + expectedH - 0.85, 'should actually reach the jump, apex=' + apex);378
// With t1119 (+50% jump) and t1120 (landing-chain +25%), a chain-1379
// horizontal-3 from y≈3 clears the 13-tile field, so the apex may380
// be the top of the field rather than startY+H.381
assert.ok(apex >= Math.min(g.height - 1, startY + expectedH - 0.85) - 0.05,382
'should actually rise, apex=' + apex + ' start=' + startY + ' H=' + expectedH);373
});383
});374
});384
});@@ -0,0 +1,138 @@
1
'use strict';
2
3
const { describe, it } = require('node:test');
4
const assert = require('node:assert/strict');
5
const { makeGame, almost, GameCore, Planet } = require('./helpers.js');
6
7
function landClusterAt (game, members, opts)
8
{
9
opts = opts || {};
10
const cluster = {
11
id: game.nextClusterId++,
12
jumpHeight: 3,
13
vy: 0,
14
decel: 0,
15
phase: 'down',
16
landingChain: opts.landingChain || 0
17
};
18
game.clusters[cluster.id] = cluster;
19
const blocks = [];
20
for (const m of members)
21
{
22
const b = game.createBlock(m.col, m.y, m.color, 'flying');
23
b.clusterId = cluster.id;
24
b.vy = 0;
25
b.flame = m.color === GameCore.COLOR_GRAY;
26
blocks.push(b);
27
}
28
game.landCluster(cluster, blocks);
29
return { cluster, blocks };
30
}
31
32
describe('Landing-chain jump bonus (t1120)', () =>
33
{
34
it('a landing that immediately makes a match launches 25% stronger (chain 1)', () =>
35
{
36
const g = makeGame({ noSpawn: true });
37
g.place(0, 0, 2);
38
g.place(1, 0, 2);
39
const { blocks } = landClusterAt(g, [{ col: 2, y: 0, color: 2 }]);
40
const launched = g.resolveMatches();
41
assert.ok(launched.length >= 1);
42
const expected = Planet.jumpHeight(g.planet, 3, false) * 1.25;
43
assert.ok(almost(launched[0].jumpHeight, expected, 1e-9),
44
'height=' + launched[0].jumpHeight + ' expected ' + expected);
45
assert.equal(launched[0].landingChain, 1);
46
assert.ok(almost(launched[0].chainBonus, 1.25, 1e-12));
47
const cluster = g.clusters[blocks[0].clusterId];
48
assert.ok(cluster);
49
assert.equal(cluster.landingChain, 1);
50
assert.equal(g.lastChainIndicator.chain, 1);
51
assert.equal(g.lastChainIndicator.bonusPct, 25);
52
});
53
54
it('a second consecutive landing-match stacks additively to +50% (chain 2)', () =>
55
{
56
const g = makeGame({ noSpawn: true });
57
g.place(0, 0, 1);
58
g.place(1, 0, 1);
59
const { blocks } = landClusterAt(g, [{ col: 2, y: 0, color: 1 }], { landingChain: 1 });
60
const launched = g.resolveMatches();
61
assert.ok(launched.length >= 1);
62
const expected = Planet.jumpHeight(g.planet, 3, false) * 1.5;
63
assert.ok(almost(launched[0].jumpHeight, expected, 1e-9),
64
'height=' + launched[0].jumpHeight + ' expected ' + expected);
65
assert.equal(launched[0].landingChain, 2);
66
assert.equal(g.clusters[blocks[0].clusterId].landingChain, 2);
67
assert.equal(g.lastChainIndicator.bonusPct, 50);
68
});
69
70
it('a third step is +75% (x1.75), additive not multiplicative', () =>
71
{
72
const g = makeGame({ noSpawn: true });
73
g.place(3, 0, 0);
74
g.place(4, 0, 0);
75
landClusterAt(g, [{ col: 5, y: 0, color: 0 }], { landingChain: 2 });
76
const launched = g.resolveMatches();
77
const expected = Planet.jumpHeight(g.planet, 3, false) * 1.75;
78
assert.ok(almost(launched[0].jumpHeight, expected, 1e-9));
79
assert.equal(launched[0].landingChain, 3);
80
// Additive was chosen: 1 + 0.25*3 = 1.75, not 1.25^3 ≈ 1.953.
81
assert.ok(!almost(launched[0].jumpHeight, Planet.jumpHeight(g.planet, 3, false) * 1.25 ** 3, 1e-6));
82
});
83
84
it('landing without a match resets the chain, so the next launch is un-bonused', () =>
85
{
86
const g = makeGame({ noSpawn: true });
87
g.place(0, 0, 4);
88
g.place(1, 0, 4);
89
const { cluster, blocks } = landClusterAt(g, [
90
{ col: 2, y: 0, color: 3 }
91
], { landingChain: 2 });
92
// Coloured-only clusters are released in advanceSettle (same as a
93
// real tick), then resolveMatches sees justLanded and, with no
94
// match, resets the chain.
95
g.advanceSettle(0);
96
assert.equal(g.resolveMatches().length, 0);
97
assert.equal(blocks[0].justLanded, false);
98
assert.equal(blocks[0].landingChain || 0, 0, 'reset after a dry landing');
99
// A later ordinary match (no new landing) must not get a bonus.
100
g.place(3, 0, 3);
101
g.place(4, 0, 3);
102
const launched = g.resolveMatches();
103
assert.ok(launched.length >= 1);
104
assert.equal(launched[0].landingChain, 0);
105
assert.ok(almost(launched[0].jumpHeight, Planet.jumpHeight(g.planet, 3, false), 1e-9));
106
});
107
108
it('applies to stacked landings (not only the floor)', () =>
109
{
110
const g = makeGame({ noSpawn: true });
111
g.place(4, 0, 1);
112
g.place(4, 1, 1);
113
const { blocks } = landClusterAt(g, [{ col: 4, y: 2, color: 1 }]);
114
const launched = g.resolveMatches();
115
assert.ok(launched.length >= 1);
116
const expected = Planet.jumpHeight(g.planet, 3, true) * 1.25;
117
assert.ok(almost(launched[0].jumpHeight, expected, 1e-9),
118
'vertical stacked landing height=' + launched[0].jumpHeight);
119
assert.equal(launched[0].landingChain, 1);
120
assert.equal(blocks[0].state, 'flying');
121
});
122
123
it('a regular (non-landing) match is unchanged', () =>
124
{
125
const g = makeGame({ noSpawn: true });
126
g.place(0, 0, 2);
127
g.place(1, 0, 2);
128
g.place(2, 0, 2);
129
const launched = g.resolveMatches();
130
assert.equal(launched[0].landingChain, 0);
131
assert.ok(almost(launched[0].jumpHeight, Planet.jumpHeight(g.planet, 3, false), 1e-9));
132
});
133
134
it('LANDING_CHAIN_BONUS is 0.25 additive per step', () =>
135
{
136
assert.equal(GameCore.LANDING_CHAIN_BONUS, 0.25);
137
});
138
});
@@ -0,0 +1,138 @@1
'use strict';2
3
const { describe, it } = require('node:test');4
const assert = require('node:assert/strict');5
const { makeGame, almost, GameCore, Planet } = require('./helpers.js');6
7
function landClusterAt (game, members, opts)8
{9
opts = opts || {};10
const cluster = {11
id: game.nextClusterId++,12
jumpHeight: 3,13
vy: 0,14
decel: 0,15
phase: 'down',16
landingChain: opts.landingChain || 017
};18
game.clusters[cluster.id] = cluster;19
const blocks = [];20
for (const m of members)21
{22
const b = game.createBlock(m.col, m.y, m.color, 'flying');23
b.clusterId = cluster.id;24
b.vy = 0;25
b.flame = m.color === GameCore.COLOR_GRAY;26
blocks.push(b);27
}28
game.landCluster(cluster, blocks);29
return { cluster, blocks };30
}31
32
describe('Landing-chain jump bonus (t1120)', () =>33
{34
it('a landing that immediately makes a match launches 25% stronger (chain 1)', () =>35
{36
const g = makeGame({ noSpawn: true });37
g.place(0, 0, 2);38
g.place(1, 0, 2);39
const { blocks } = landClusterAt(g, [{ col: 2, y: 0, color: 2 }]);40
const launched = g.resolveMatches();41
assert.ok(launched.length >= 1);42
const expected = Planet.jumpHeight(g.planet, 3, false) * 1.25;43
assert.ok(almost(launched[0].jumpHeight, expected, 1e-9),44
'height=' + launched[0].jumpHeight + ' expected ' + expected);45
assert.equal(launched[0].landingChain, 1);46
assert.ok(almost(launched[0].chainBonus, 1.25, 1e-12));47
const cluster = g.clusters[blocks[0].clusterId];48
assert.ok(cluster);49
assert.equal(cluster.landingChain, 1);50
assert.equal(g.lastChainIndicator.chain, 1);51
assert.equal(g.lastChainIndicator.bonusPct, 25);52
});53
54
it('a second consecutive landing-match stacks additively to +50% (chain 2)', () =>55
{56
const g = makeGame({ noSpawn: true });57
g.place(0, 0, 1);58
g.place(1, 0, 1);59
const { blocks } = landClusterAt(g, [{ col: 2, y: 0, color: 1 }], { landingChain: 1 });60
const launched = g.resolveMatches();61
assert.ok(launched.length >= 1);62
const expected = Planet.jumpHeight(g.planet, 3, false) * 1.5;63
assert.ok(almost(launched[0].jumpHeight, expected, 1e-9),64
'height=' + launched[0].jumpHeight + ' expected ' + expected);65
assert.equal(launched[0].landingChain, 2);66
assert.equal(g.clusters[blocks[0].clusterId].landingChain, 2);67
assert.equal(g.lastChainIndicator.bonusPct, 50);68
});69
70
it('a third step is +75% (x1.75), additive not multiplicative', () =>71
{72
const g = makeGame({ noSpawn: true });73
g.place(3, 0, 0);74
g.place(4, 0, 0);75
landClusterAt(g, [{ col: 5, y: 0, color: 0 }], { landingChain: 2 });76
const launched = g.resolveMatches();77
const expected = Planet.jumpHeight(g.planet, 3, false) * 1.75;78
assert.ok(almost(launched[0].jumpHeight, expected, 1e-9));79
assert.equal(launched[0].landingChain, 3);80
// Additive was chosen: 1 + 0.25*3 = 1.75, not 1.25^3 ≈ 1.953.81
assert.ok(!almost(launched[0].jumpHeight, Planet.jumpHeight(g.planet, 3, false) * 1.25 ** 3, 1e-6));82
});83
84
it('landing without a match resets the chain, so the next launch is un-bonused', () =>85
{86
const g = makeGame({ noSpawn: true });87
g.place(0, 0, 4);88
g.place(1, 0, 4);89
const { cluster, blocks } = landClusterAt(g, [90
{ col: 2, y: 0, color: 3 }91
], { landingChain: 2 });92
// Coloured-only clusters are released in advanceSettle (same as a93
// real tick), then resolveMatches sees justLanded and, with no94
// match, resets the chain.95
g.advanceSettle(0);96
assert.equal(g.resolveMatches().length, 0);97
assert.equal(blocks[0].justLanded, false);98
assert.equal(blocks[0].landingChain || 0, 0, 'reset after a dry landing');99
// A later ordinary match (no new landing) must not get a bonus.100
g.place(3, 0, 3);101
g.place(4, 0, 3);102
const launched = g.resolveMatches();103
assert.ok(launched.length >= 1);104
assert.equal(launched[0].landingChain, 0);105
assert.ok(almost(launched[0].jumpHeight, Planet.jumpHeight(g.planet, 3, false), 1e-9));106
});107
108
it('applies to stacked landings (not only the floor)', () =>109
{110
const g = makeGame({ noSpawn: true });111
g.place(4, 0, 1);112
g.place(4, 1, 1);113
const { blocks } = landClusterAt(g, [{ col: 4, y: 2, color: 1 }]);114
const launched = g.resolveMatches();115
assert.ok(launched.length >= 1);116
const expected = Planet.jumpHeight(g.planet, 3, true) * 1.25;117
assert.ok(almost(launched[0].jumpHeight, expected, 1e-9),118
'vertical stacked landing height=' + launched[0].jumpHeight);119
assert.equal(launched[0].landingChain, 1);120
assert.equal(blocks[0].state, 'flying');121
});122
123
it('a regular (non-landing) match is unchanged', () =>124
{125
const g = makeGame({ noSpawn: true });126
g.place(0, 0, 2);127
g.place(1, 0, 2);128
g.place(2, 0, 2);129
const launched = g.resolveMatches();130
assert.equal(launched[0].landingChain, 0);131
assert.ok(almost(launched[0].jumpHeight, Planet.jumpHeight(g.planet, 3, false), 1e-9));132
});133
134
it('LANDING_CHAIN_BONUS is 0.25 additive per step', () =>135
{136
assert.equal(GameCore.LANDING_CHAIN_BONUS, 0.25);137
});138
});@@ -0,0 +1,199 @@
1
#!/usr/bin/env python3
2
"""Smoke test for Offline Strijd (t1119), chain HUD, column warn (t1123)."""
3
from __future__ import annotations
4
5
import socket
6
import subprocess
7
import sys
8
import time
9
from pathlib import Path
10
11
from playwright.sync_api import sync_playwright
12
13
ROOT = Path("/workspace/meteors")
14
OUT = Path("/workspace/meteors-shots")
15
OUT.mkdir(parents=True, exist_ok=True)
16
CHROME = "/usr/bin/google-chrome"
17
CHROME_ARGS = [
18
"--use-gl=angle",
19
"--use-angle=swiftshader",
20
"--no-sandbox",
21
"--disable-dev-shm-usage",
22
"--disable-gpu-sandbox",
23
]
24
FAILURES = []
25
26
27
def free_port():
28
s = socket.socket()
29
s.bind(("127.0.0.1", 0))
30
port = s.getsockname()[1]
31
s.close()
32
return port
33
34
35
def check(cond, msg):
36
if not cond:
37
FAILURES.append(msg)
38
print("FAIL", msg)
39
else:
40
print("OK ", msg)
41
return cond
42
43
44
def shot(page, name):
45
path = OUT / name
46
page.screenshot(path=str(path), full_page=False)
47
print(f"wrote {path} ({path.stat().st_size} bytes)")
48
return path
49
50
51
def start_http(port):
52
proc = subprocess.Popen(
53
["python3", "-m", "http.server", str(port), "--bind", "127.0.0.1",
54
"--directory", str(ROOT / "build")],
55
stdout=subprocess.DEVNULL,
56
stderr=subprocess.DEVNULL,
57
)
58
time.sleep(0.35)
59
if proc.poll() is not None:
60
raise RuntimeError("http.server failed to start")
61
return proc
62
63
64
def open_offline(page, url):
65
page.goto(url, wait_until="domcontentloaded", timeout=15000)
66
page.wait_for_timeout(400)
67
page.locator("#btn-offline").click()
68
page.wait_for_selector("#planet-select:not([hidden])", timeout=8000)
69
page.locator("#btn-planet-go").click()
70
page.wait_for_function(
71
"() => app && app.mode === 'playing' && app.offline && app.battle && app.core",
72
timeout=10000,
73
)
74
75
76
def run(page, tag):
77
hud = page.evaluate("""() => ({
78
round: document.getElementById('offline-round') && document.getElementById('offline-round').textContent,
79
opponents: document.getElementById('offline-opponents') && document.getElementById('offline-opponents').textContent,
80
skill: document.getElementById('offline-skill') && document.getElementById('offline-skill').textContent,
81
hidden: document.getElementById('offline-hud') && document.getElementById('offline-hud').hidden,
82
bots: app.battle && app.battle.bots.length,
83
schedule: app.battle && app.battle.schedule,
84
jump: app.planet && app.planet.baseJumpHeight,
85
fall: app.planet && app.planet.fallSpeed,
86
})""")
87
print("HUD", hud)
88
check(hud["hidden"] is False, f"{tag}: offline HUD visible")
89
check(hud["round"] == "Ronde 1", f"{tag}: round is Ronde 1 ({hud['round']})")
90
check("1 tegenstander" in (hud["opponents"] or ""), f"{tag}: one opponent ({hud['opponents']})")
91
check(hud["skill"] == "Skill 5%", f"{tag}: skill 5% ({hud['skill']})")
92
check(hud["bots"] == 1, f"{tag}: one bot field")
93
check(abs(hud["jump"] - 1.5 * 13 / 2) < 1e-9, f"{tag}: +50% jump height ({hud['jump']})")
94
check(abs(hud["fall"] - 0.5 * 13 / 3) < 1e-9, f"{tag}: halved fallSpeed ({hud['fall']})")
95
mini = page.locator("#minis .mini")
96
check(mini.count() >= 1, f"{tag}: at least one bot mini")
97
name = mini.first.locator(".mini-name").inner_text()
98
check(name.startswith("Bot 1"), f"{tag}: mini named {name!r}")
99
shot(page, f"t1119-offline-ronde1-{tag}.png")
100
101
# Many opponents: jump to a high-N schedule and check minis stay cheap.
102
info = page.evaluate("""() => {
103
app.battle.advanceRound(); // 2
104
app.battle.advanceRound(); // 3, 3 opponents after two advances from 1?
105
// From round 1, advance → 2 (2 bots), advance → 3 (3 bots).
106
// Call more to get 6 opponents (round 12 starts 6? let's set round).
107
const Offline = window.Offline;
108
app.battle.round = 8;
109
app.battle.schedule = Offline.scheduleForRound(8);
110
app.battle._initBots();
111
if (typeof renderOfflineMinis === 'function') renderOfflineMinis();
112
else if (app.battle) { /* tick will render */ }
113
return { round: app.battle.round, n: app.battle.bots.length, skill: app.battle.schedule.skill };
114
}""")
115
print("many", info)
116
page.wait_for_timeout(200)
117
page.evaluate("() => { if (typeof renderOfflineMinis === 'function') renderOfflineMinis(); }")
118
page.wait_for_timeout(150)
119
nmini = page.locator("#minis .mini").count()
120
check(nmini == info["n"], f"{tag}: {nmini} minis for {info['n']} bots")
121
shot(page, f"t1119-offline-many-{tag}.png")
122
123
# Column warn: 10 grounded in column 0, pulse visible on the player field.
124
page.evaluate("""() => {
125
const g = app.core;
126
// Clear and fill column 0 with 10 still blocks.
127
for (let i = g.blocks.length - 1; i >= 0; i--) {
128
try { g.removeBlock(g.blocks[i]); } catch (e) {}
129
}
130
for (let r = 0; r < 10; r++) g.place(0, r, r % 5);
131
if (typeof updateColumnWarn === 'function') updateColumnWarn(0.4);
132
}""")
133
page.wait_for_timeout(200)
134
warn = page.evaluate("""() => ({
135
needs: app.core.columnNeedsWarn(0),
136
count: app.core.groundedCount(0),
137
visible: !!(app.columnWarn && app.columnWarn[0] && app.columnWarn[0].renderer.visible),
138
alpha: app.columnWarn && app.columnWarn[0] && app.columnWarn[0].renderer.alpha,
139
})""")
140
print("warn", warn)
141
check(warn["needs"] is True and warn["count"] >= 10, f"{tag}: column 0 needs warn")
142
check(warn["visible"] is True and warn["alpha"] > 0, f"{tag}: warn quad visible alpha={warn['alpha']}")
143
shot(page, f"t1123-column-warn-{tag}.png")
144
145
# Result screen.
146
page.evaluate("""() => {
147
app.core.state = 'gameover';
148
app.battle.state = 'lost';
149
if (typeof showOfflineResult === 'function') showOfflineResult();
150
}""")
151
page.wait_for_selector("#offline-result:not([hidden])", timeout=5000)
152
reached = page.locator("#offline-reached").inner_text()
153
check(reached.isdigit() and int(reached) >= 1, f"{tag}: reached round shown ({reached})")
154
shot(page, f"t1119-offline-result-{tag}.png")
155
156
157
def main():
158
# Ensure a fresh build is what we serve.
159
port = free_port()
160
proc = start_http(port)
161
url = f"http://127.0.0.1:{port}/index.html"
162
try:
163
with sync_playwright() as p:
164
browser = p.chromium.launch(executable_path=CHROME, args=CHROME_ARGS)
165
# desktop
166
ctx = browser.new_context(viewport={"width": 1280, "height": 900})
167
page = ctx.new_page()
168
open_offline(page, url)
169
run(page, "desktop")
170
ctx.close()
171
# mobile
172
ctx = browser.new_context(
173
viewport={"width": 393, "height": 851},
174
device_scale_factor=2,
175
is_mobile=True,
176
has_touch=True,
177
)
178
page = ctx.new_page()
179
open_offline(page, url)
180
run(page, "mobile")
181
ctx.close()
182
browser.close()
183
finally:
184
proc.terminate()
185
try:
186
proc.wait(timeout=2)
187
except Exception:
188
proc.kill()
189
190
if FAILURES:
191
print(f"\n{len(FAILURES)} FAILURES:")
192
for f in FAILURES:
193
print(" -", f)
194
sys.exit(1)
195
print("\nall offline playwright checks passed")
196
197
198
if __name__ == "__main__":
199
main()
@@ -0,0 +1,199 @@1
#!/usr/bin/env python32
"""Smoke test for Offline Strijd (t1119), chain HUD, column warn (t1123)."""3
from __future__ import annotations4
5
import socket6
import subprocess7
import sys8
import time9
from pathlib import Path10
11
from playwright.sync_api import sync_playwright12
13
ROOT = Path("/workspace/meteors")14
OUT = Path("/workspace/meteors-shots")15
OUT.mkdir(parents=True, exist_ok=True)16
CHROME = "/usr/bin/google-chrome"17
CHROME_ARGS = [18
"--use-gl=angle",19
"--use-angle=swiftshader",20
"--no-sandbox",21
"--disable-dev-shm-usage",22
"--disable-gpu-sandbox",23
]24
FAILURES = []25
26
27
def free_port():28
s = socket.socket()29
s.bind(("127.0.0.1", 0))30
port = s.getsockname()[1]31
s.close()32
return port33
34
35
def check(cond, msg):36
if not cond:37
FAILURES.append(msg)38
print("FAIL", msg)39
else:40
print("OK ", msg)41
return cond42
43
44
def shot(page, name):45
path = OUT / name46
page.screenshot(path=str(path), full_page=False)47
print(f"wrote {path} ({path.stat().st_size} bytes)")48
return path49
50
51
def start_http(port):52
proc = subprocess.Popen(53
["python3", "-m", "http.server", str(port), "--bind", "127.0.0.1",54
"--directory", str(ROOT / "build")],55
stdout=subprocess.DEVNULL,56
stderr=subprocess.DEVNULL,57
)58
time.sleep(0.35)59
if proc.poll() is not None:60
raise RuntimeError("http.server failed to start")61
return proc62
63
64
def open_offline(page, url):65
page.goto(url, wait_until="domcontentloaded", timeout=15000)66
page.wait_for_timeout(400)67
page.locator("#btn-offline").click()68
page.wait_for_selector("#planet-select:not([hidden])", timeout=8000)69
page.locator("#btn-planet-go").click()70
page.wait_for_function(71
"() => app && app.mode === 'playing' && app.offline && app.battle && app.core",72
timeout=10000,73
)74
75
76
def run(page, tag):77
hud = page.evaluate("""() => ({78
round: document.getElementById('offline-round') && document.getElementById('offline-round').textContent,79
opponents: document.getElementById('offline-opponents') && document.getElementById('offline-opponents').textContent,80
skill: document.getElementById('offline-skill') && document.getElementById('offline-skill').textContent,81
hidden: document.getElementById('offline-hud') && document.getElementById('offline-hud').hidden,82
bots: app.battle && app.battle.bots.length,83
schedule: app.battle && app.battle.schedule,84
jump: app.planet && app.planet.baseJumpHeight,85
fall: app.planet && app.planet.fallSpeed,86
})""")87
print("HUD", hud)88
check(hud["hidden"] is False, f"{tag}: offline HUD visible")89
check(hud["round"] == "Ronde 1", f"{tag}: round is Ronde 1 ({hud['round']})")90
check("1 tegenstander" in (hud["opponents"] or ""), f"{tag}: one opponent ({hud['opponents']})")91
check(hud["skill"] == "Skill 5%", f"{tag}: skill 5% ({hud['skill']})")92
check(hud["bots"] == 1, f"{tag}: one bot field")93
check(abs(hud["jump"] - 1.5 * 13 / 2) < 1e-9, f"{tag}: +50% jump height ({hud['jump']})")94
check(abs(hud["fall"] - 0.5 * 13 / 3) < 1e-9, f"{tag}: halved fallSpeed ({hud['fall']})")95
mini = page.locator("#minis .mini")96
check(mini.count() >= 1, f"{tag}: at least one bot mini")97
name = mini.first.locator(".mini-name").inner_text()98
check(name.startswith("Bot 1"), f"{tag}: mini named {name!r}")99
shot(page, f"t1119-offline-ronde1-{tag}.png")100
101
# Many opponents: jump to a high-N schedule and check minis stay cheap.102
info = page.evaluate("""() => {103
app.battle.advanceRound(); // 2104
app.battle.advanceRound(); // 3, 3 opponents after two advances from 1? 105
// From round 1, advance → 2 (2 bots), advance → 3 (3 bots).106
// Call more to get 6 opponents (round 12 starts 6? let's set round).107
const Offline = window.Offline;108
app.battle.round = 8;109
app.battle.schedule = Offline.scheduleForRound(8);110
app.battle._initBots();111
if (typeof renderOfflineMinis === 'function') renderOfflineMinis();112
else if (app.battle) { /* tick will render */ }113
return { round: app.battle.round, n: app.battle.bots.length, skill: app.battle.schedule.skill };114
}""")115
print("many", info)116
page.wait_for_timeout(200)117
page.evaluate("() => { if (typeof renderOfflineMinis === 'function') renderOfflineMinis(); }")118
page.wait_for_timeout(150)119
nmini = page.locator("#minis .mini").count()120
check(nmini == info["n"], f"{tag}: {nmini} minis for {info['n']} bots")121
shot(page, f"t1119-offline-many-{tag}.png")122
123
# Column warn: 10 grounded in column 0, pulse visible on the player field.124
page.evaluate("""() => {125
const g = app.core;126
// Clear and fill column 0 with 10 still blocks.127
for (let i = g.blocks.length - 1; i >= 0; i--) {128
try { g.removeBlock(g.blocks[i]); } catch (e) {}129
}130
for (let r = 0; r < 10; r++) g.place(0, r, r % 5);131
if (typeof updateColumnWarn === 'function') updateColumnWarn(0.4);132
}""")133
page.wait_for_timeout(200)134
warn = page.evaluate("""() => ({135
needs: app.core.columnNeedsWarn(0),136
count: app.core.groundedCount(0),137
visible: !!(app.columnWarn && app.columnWarn[0] && app.columnWarn[0].renderer.visible),138
alpha: app.columnWarn && app.columnWarn[0] && app.columnWarn[0].renderer.alpha,139
})""")140
print("warn", warn)141
check(warn["needs"] is True and warn["count"] >= 10, f"{tag}: column 0 needs warn")142
check(warn["visible"] is True and warn["alpha"] > 0, f"{tag}: warn quad visible alpha={warn['alpha']}")143
shot(page, f"t1123-column-warn-{tag}.png")144
145
# Result screen.146
page.evaluate("""() => {147
app.core.state = 'gameover';148
app.battle.state = 'lost';149
if (typeof showOfflineResult === 'function') showOfflineResult();150
}""")151
page.wait_for_selector("#offline-result:not([hidden])", timeout=5000)152
reached = page.locator("#offline-reached").inner_text()153
check(reached.isdigit() and int(reached) >= 1, f"{tag}: reached round shown ({reached})")154
shot(page, f"t1119-offline-result-{tag}.png")155
156
157
def main():158
# Ensure a fresh build is what we serve.159
port = free_port()160
proc = start_http(port)161
url = f"http://127.0.0.1:{port}/index.html"162
try:163
with sync_playwright() as p:164
browser = p.chromium.launch(executable_path=CHROME, args=CHROME_ARGS)165
# desktop166
ctx = browser.new_context(viewport={"width": 1280, "height": 900})167
page = ctx.new_page()168
open_offline(page, url)169
run(page, "desktop")170
ctx.close()171
# mobile172
ctx = browser.new_context(173
viewport={"width": 393, "height": 851},174
device_scale_factor=2,175
is_mobile=True,176
has_touch=True,177
)178
page = ctx.new_page()179
open_offline(page, url)180
run(page, "mobile")181
ctx.close()182
browser.close()183
finally:184
proc.terminate()185
try:186
proc.wait(timeout=2)187
except Exception:188
proc.kill()189
190
if FAILURES:191
print(f"\n{len(FAILURES)} FAILURES:")192
for f in FAILURES:193
print(" -", f)194
sys.exit(1)195
print("\nall offline playwright checks passed")196
197
198
if __name__ == "__main__":199
main()@@ -0,0 +1,208 @@
1
'use strict';
2
3
const { describe, it } = require('node:test');
4
const assert = require('node:assert/strict');
5
const { makeGame, Planet, Rng, GameCore } = require('./helpers.js');
6
const Offline = require('../src/offline.js');
7
8
describe('Offline Strijd progression (t1119)', () =>
9
{
10
it('one opponent for one round, then N opponents for N-1 rounds', () =>
11
{
12
assert.equal(Offline.roundsAtOpponentCount(1), 1);
13
assert.equal(Offline.roundsAtOpponentCount(2), 1);
14
assert.equal(Offline.roundsAtOpponentCount(3), 2);
15
assert.equal(Offline.roundsAtOpponentCount(6), 5);
16
17
const expect = {
18
1: { opponents: 1 },
19
2: { opponents: 2 },
20
3: { opponents: 3 },
21
4: { opponents: 3 },
22
5: { opponents: 4 },
23
6: { opponents: 4 },
24
7: { opponents: 4 },
25
8: { opponents: 5 }
26
};
27
for (const [round, exp] of Object.entries(expect))
28
{
29
const s = Offline.scheduleForRound(Number(round));
30
assert.equal(s.opponents, exp.opponents, 'round ' + round + ' opponents=' + s.opponents);
31
assert.equal(s.round, Number(round));
32
}
33
});
34
35
it('skill starts at 5% and rises 1% per round, capped at 100%', () =>
36
{
37
assert.equal(Offline.skillForRound(1), 0.05);
38
assert.equal(Offline.skillForRound(2), 0.06);
39
assert.equal(Offline.skillForRound(96), 1);
40
assert.equal(Offline.skillForRound(97), 1);
41
assert.equal(Offline.skillForRound(200), 1);
42
assert.equal(Offline.scheduleForRound(1).skill, 0.05);
43
assert.equal(Offline.scheduleForRound(10).skill, 0.14);
44
});
45
});
46
47
describe('Bot move finder and roll (t1119)', () =>
48
{
49
it('finds the shortest vertical move that creates a match', () =>
50
{
51
const g = makeGame({ noSpawn: true });
52
// Column 0: [0, 0, 1, 0] — moving the 1 up (or the top 0 down) makes [0,0,0,1].
53
g.place(0, 0, 0);
54
g.place(0, 1, 0);
55
g.place(0, 2, 1);
56
g.place(0, 3, 0);
57
const move = Offline.findBotMove(g);
58
assert.ok(move, 'expected a move');
59
assert.equal(move.col, 0);
60
assert.equal(move.dist, 1);
61
assert.ok(
62
(move.fromY === 2 && move.toY === 3) || (move.fromY === 3 && move.toY === 2),
63
'from=' + move.fromY + ' to=' + move.toY
64
);
65
assert.ok(Offline.executeBotMove(g, move));
66
const launched = g.resolveMatches();
67
assert.ok(launched.length >= 1, 'the move must create a match');
68
});
69
70
it('returns null when no vertical move creates a match', () =>
71
{
72
const g = makeGame({ noSpawn: true });
73
g.place(0, 0, 0);
74
g.place(0, 1, 1);
75
g.place(0, 2, 2);
76
g.place(1, 0, 3);
77
g.place(1, 1, 4);
78
assert.equal(Offline.findBotMove(g), null);
79
});
80
81
it('a roll at skill 0 never moves, skill 1 always tries', () =>
82
{
83
const setup = () =>
84
{
85
const g = makeGame({ noSpawn: true });
86
g.place(0, 0, 0);
87
g.place(0, 1, 0);
88
g.place(0, 2, 1);
89
g.place(0, 3, 0);
90
return g;
91
};
92
const g0 = setup();
93
const r0 = Offline.tryBotRoll(g0, 0, () => 0);
94
assert.equal(r0.success, false);
95
assert.equal(r0.moved, false);
96
assert.equal(g0.blocks[2].y, 2, 'nothing moved at skill 0 even with roll 0');
97
98
const g1 = setup();
99
const r1 = Offline.tryBotRoll(g1, 1, () => 0.999);
100
assert.equal(r1.success, true);
101
assert.equal(r1.moved, true);
102
assert.ok(r1.move);
103
104
// roll == skill is a failure (success only when roll < skill)
105
const g2 = setup();
106
const r2 = Offline.tryBotRoll(g2, 0.05, () => 0.05);
107
assert.equal(r2.success, false);
108
assert.equal(r2.moved, false);
109
});
110
});
111
112
describe('Offline battle flow (t1119)', () =>
113
{
114
it('starts a round with the scheduled number of bots, each a random planet', () =>
115
{
116
const rng = Rng.create(42);
117
const battle = Offline.createBattle({
118
playerPlanet: Planet.defaultPlanet(),
119
rng: rng,
120
round: 5
121
});
122
assert.equal(battle.schedule.opponents, 4);
123
assert.equal(battle.bots.length, 4);
124
assert.equal(battle.schedule.skill, Offline.skillForRound(5));
125
for (const bot of battle.bots)
126
{
127
assert.ok(bot.planet && bot.planet.id);
128
assert.ok(bot.core instanceof GameCore);
129
assert.equal(bot.eliminated, false);
130
}
131
const ids = new Set(battle.bots.map((b) => b.planet.id));
132
// With 12 planets and 4 bots, seed 42 is very likely to vary; just
133
// assert they are real catalogue planets.
134
const catalogue = new Set(Planet.allPlanets().map((p) => p.id));
135
for (const id of ids)
136
{ assert.ok(catalogue.has(id), 'unknown planet ' + id); }
137
});
138
139
it('a forced miss never delivers garbage; a forced hit does', () =>
140
{
141
const player = makeGame({ noSpawn: true });
142
// Forced miss: rng always returns 0 for pick? miss if rng() < missChance.
143
// Use a planet with 60% miss (power 0) and rng that always returns 0
144
// → always miss? 0 < 0.60 is true, so miss. Wait, I used rng() < missChance
145
// in battle... _dispatchShots: miss = targets.length===0 || this.rng() < missChance
146
// Yes 0 < 0.60 → miss.
147
const easy = Planet.createPlanet({ jumpsToClear: 1, fallTime: 5, riseTime: 3, id: 'easy' });
148
let n = 0;
149
const missRng = () => { n++; return 0; }; // always miss (0 < 0.60)
150
const battle = Offline.createBattle({ playerPlanet: easy, rng: missRng, round: 1 });
151
// Give the player an outgoing shot without actually flying.
152
player.outgoingShots.push({ id: 99, color: 1, col: 0, y: 13 });
153
battle.tick(0.01, player);
154
assert.ok(battle.flightResults.length >= 1);
155
assert.equal(battle.flightResults[0].miss, true);
156
assert.equal(battle.pending.length, 0);
157
158
// Forced hit: rng always 0.99, missChance 0.60, 0.99 < 0.60 is false.
159
const hitRng = () => 0.99;
160
const battle2 = Offline.createBattle({ playerPlanet: easy, rng: hitRng, round: 1 });
161
const player2 = makeGame({ noSpawn: true });
162
player2.outgoingShots.push({ id: 7, color: 2, col: 1, y: 13 });
163
const botBlocksBefore = battle2.bots[0].core.blocks.length;
164
battle2.tick(0.01, player2);
165
assert.equal(battle2.flightResults[0].miss, false);
166
assert.equal(battle2.pending.length, 1);
167
// Deliver after the flight duration.
168
battle2.tick(Offline.FLIGHT_DURATION + 0.05, player2);
169
assert.equal(battle2.pending.length, 0);
170
assert.ok(battle2.bots[0].core.blocks.length > botBlocksBefore,
171
'garbage was ingested by the bot');
172
});
173
174
it('winning a round means every bot is defeated, then advanceRound grows the field', () =>
175
{
176
const rng = Rng.create(7);
177
const battle = Offline.createBattle({
178
playerPlanet: Planet.defaultPlanet(),
179
rng,
180
round: 1
181
});
182
assert.equal(battle.bots.length, 1);
183
const player = makeGame({ noSpawn: true });
184
battle.bots[0].core.state = 'gameover';
185
battle.tick(0.05, player);
186
assert.equal(battle.state, 'round_won');
187
assert.equal(battle.aliveBots().length, 0);
188
battle.advanceRound();
189
assert.equal(battle.round, 2);
190
assert.equal(battle.state, 'playing');
191
assert.equal(battle.bots.length, 2);
192
assert.equal(battle.schedule.skill, 0.06);
193
});
194
195
it('the player losing sets state to lost at the current round', () =>
196
{
197
const battle = Offline.createBattle({
198
playerPlanet: Planet.defaultPlanet(),
199
rng: Rng.create(1),
200
round: 3
201
});
202
const player = makeGame({ noSpawn: true });
203
player.state = 'gameover';
204
battle.tick(0.05, player);
205
assert.equal(battle.state, 'lost');
206
assert.equal(battle.round, 3);
207
});
208
});
@@ -0,0 +1,208 @@1
'use strict';2
3
const { describe, it } = require('node:test');4
const assert = require('node:assert/strict');5
const { makeGame, Planet, Rng, GameCore } = require('./helpers.js');6
const Offline = require('../src/offline.js');7
8
describe('Offline Strijd progression (t1119)', () =>9
{10
it('one opponent for one round, then N opponents for N-1 rounds', () =>11
{12
assert.equal(Offline.roundsAtOpponentCount(1), 1);13
assert.equal(Offline.roundsAtOpponentCount(2), 1);14
assert.equal(Offline.roundsAtOpponentCount(3), 2);15
assert.equal(Offline.roundsAtOpponentCount(6), 5);16
17
const expect = {18
1: { opponents: 1 },19
2: { opponents: 2 },20
3: { opponents: 3 },21
4: { opponents: 3 },22
5: { opponents: 4 },23
6: { opponents: 4 },24
7: { opponents: 4 },25
8: { opponents: 5 }26
};27
for (const [round, exp] of Object.entries(expect))28
{29
const s = Offline.scheduleForRound(Number(round));30
assert.equal(s.opponents, exp.opponents, 'round ' + round + ' opponents=' + s.opponents);31
assert.equal(s.round, Number(round));32
}33
});34
35
it('skill starts at 5% and rises 1% per round, capped at 100%', () =>36
{37
assert.equal(Offline.skillForRound(1), 0.05);38
assert.equal(Offline.skillForRound(2), 0.06);39
assert.equal(Offline.skillForRound(96), 1);40
assert.equal(Offline.skillForRound(97), 1);41
assert.equal(Offline.skillForRound(200), 1);42
assert.equal(Offline.scheduleForRound(1).skill, 0.05);43
assert.equal(Offline.scheduleForRound(10).skill, 0.14);44
});45
});46
47
describe('Bot move finder and roll (t1119)', () =>48
{49
it('finds the shortest vertical move that creates a match', () =>50
{51
const g = makeGame({ noSpawn: true });52
// Column 0: [0, 0, 1, 0] — moving the 1 up (or the top 0 down) makes [0,0,0,1].53
g.place(0, 0, 0);54
g.place(0, 1, 0);55
g.place(0, 2, 1);56
g.place(0, 3, 0);57
const move = Offline.findBotMove(g);58
assert.ok(move, 'expected a move');59
assert.equal(move.col, 0);60
assert.equal(move.dist, 1);61
assert.ok(62
(move.fromY === 2 && move.toY === 3) || (move.fromY === 3 && move.toY === 2),63
'from=' + move.fromY + ' to=' + move.toY64
);65
assert.ok(Offline.executeBotMove(g, move));66
const launched = g.resolveMatches();67
assert.ok(launched.length >= 1, 'the move must create a match');68
});69
70
it('returns null when no vertical move creates a match', () =>71
{72
const g = makeGame({ noSpawn: true });73
g.place(0, 0, 0);74
g.place(0, 1, 1);75
g.place(0, 2, 2);76
g.place(1, 0, 3);77
g.place(1, 1, 4);78
assert.equal(Offline.findBotMove(g), null);79
});80
81
it('a roll at skill 0 never moves, skill 1 always tries', () =>82
{83
const setup = () =>84
{85
const g = makeGame({ noSpawn: true });86
g.place(0, 0, 0);87
g.place(0, 1, 0);88
g.place(0, 2, 1);89
g.place(0, 3, 0);90
return g;91
};92
const g0 = setup();93
const r0 = Offline.tryBotRoll(g0, 0, () => 0);94
assert.equal(r0.success, false);95
assert.equal(r0.moved, false);96
assert.equal(g0.blocks[2].y, 2, 'nothing moved at skill 0 even with roll 0');97
98
const g1 = setup();99
const r1 = Offline.tryBotRoll(g1, 1, () => 0.999);100
assert.equal(r1.success, true);101
assert.equal(r1.moved, true);102
assert.ok(r1.move);103
104
// roll == skill is a failure (success only when roll < skill)105
const g2 = setup();106
const r2 = Offline.tryBotRoll(g2, 0.05, () => 0.05);107
assert.equal(r2.success, false);108
assert.equal(r2.moved, false);109
});110
});111
112
describe('Offline battle flow (t1119)', () =>113
{114
it('starts a round with the scheduled number of bots, each a random planet', () =>115
{116
const rng = Rng.create(42);117
const battle = Offline.createBattle({118
playerPlanet: Planet.defaultPlanet(),119
rng: rng,120
round: 5121
});122
assert.equal(battle.schedule.opponents, 4);123
assert.equal(battle.bots.length, 4);124
assert.equal(battle.schedule.skill, Offline.skillForRound(5));125
for (const bot of battle.bots)126
{127
assert.ok(bot.planet && bot.planet.id);128
assert.ok(bot.core instanceof GameCore);129
assert.equal(bot.eliminated, false);130
}131
const ids = new Set(battle.bots.map((b) => b.planet.id));132
// With 12 planets and 4 bots, seed 42 is very likely to vary; just133
// assert they are real catalogue planets.134
const catalogue = new Set(Planet.allPlanets().map((p) => p.id));135
for (const id of ids)136
{ assert.ok(catalogue.has(id), 'unknown planet ' + id); }137
});138
139
it('a forced miss never delivers garbage; a forced hit does', () =>140
{141
const player = makeGame({ noSpawn: true });142
// Forced miss: rng always returns 0 for pick? miss if rng() < missChance.143
// Use a planet with 60% miss (power 0) and rng that always returns 0144
// → always miss? 0 < 0.60 is true, so miss. Wait, I used rng() < missChance145
// in battle... _dispatchShots: miss = targets.length===0 || this.rng() < missChance146
// Yes 0 < 0.60 → miss.147
const easy = Planet.createPlanet({ jumpsToClear: 1, fallTime: 5, riseTime: 3, id: 'easy' });148
let n = 0;149
const missRng = () => { n++; return 0; }; // always miss (0 < 0.60)150
const battle = Offline.createBattle({ playerPlanet: easy, rng: missRng, round: 1 });151
// Give the player an outgoing shot without actually flying.152
player.outgoingShots.push({ id: 99, color: 1, col: 0, y: 13 });153
battle.tick(0.01, player);154
assert.ok(battle.flightResults.length >= 1);155
assert.equal(battle.flightResults[0].miss, true);156
assert.equal(battle.pending.length, 0);157
158
// Forced hit: rng always 0.99, missChance 0.60, 0.99 < 0.60 is false.159
const hitRng = () => 0.99;160
const battle2 = Offline.createBattle({ playerPlanet: easy, rng: hitRng, round: 1 });161
const player2 = makeGame({ noSpawn: true });162
player2.outgoingShots.push({ id: 7, color: 2, col: 1, y: 13 });163
const botBlocksBefore = battle2.bots[0].core.blocks.length;164
battle2.tick(0.01, player2);165
assert.equal(battle2.flightResults[0].miss, false);166
assert.equal(battle2.pending.length, 1);167
// Deliver after the flight duration.168
battle2.tick(Offline.FLIGHT_DURATION + 0.05, player2);169
assert.equal(battle2.pending.length, 0);170
assert.ok(battle2.bots[0].core.blocks.length > botBlocksBefore,171
'garbage was ingested by the bot');172
});173
174
it('winning a round means every bot is defeated, then advanceRound grows the field', () =>175
{176
const rng = Rng.create(7);177
const battle = Offline.createBattle({178
playerPlanet: Planet.defaultPlanet(),179
rng,180
round: 1181
});182
assert.equal(battle.bots.length, 1);183
const player = makeGame({ noSpawn: true });184
battle.bots[0].core.state = 'gameover';185
battle.tick(0.05, player);186
assert.equal(battle.state, 'round_won');187
assert.equal(battle.aliveBots().length, 0);188
battle.advanceRound();189
assert.equal(battle.round, 2);190
assert.equal(battle.state, 'playing');191
assert.equal(battle.bots.length, 2);192
assert.equal(battle.schedule.skill, 0.06);193
});194
195
it('the player losing sets state to lost at the current round', () =>196
{197
const battle = Offline.createBattle({198
playerPlanet: Planet.defaultPlanet(),199
rng: Rng.create(1),200
round: 3201
});202
const player = makeGame({ noSpawn: true });203
player.state = 'gameover';204
battle.tick(0.05, player);205
assert.equal(battle.state, 'lost');206
assert.equal(battle.round, 3);207
});208
});@@ -21,8 +21,8 @@ describe('Planet field and defaults', () =>
21
21
assert.equal(p.fallTime, 3);
22
22
assert.equal(p.riseTime, 1.5);
23
23
assert.equal(p.colors.length, 5);
24
assert.equal(p.baseJumpHeight, 13 / 2);
25
assert.equal(p.fallSpeed, 13 / 3);
24
assert.equal(p.baseJumpHeight, 1.5 * 13 / 2);
25
assert.equal(p.fallSpeed, 0.5 * 13 / 3);
26
26
});
27
27
28
28
it('clamps gravity, air and mass to the stage-3 ranges', () =>
@@ -78,16 +78,17 @@ describe('Jump height rules', () =>
78
78
assert.ok(Math.abs(Planet.jumpHeight(planet, 6, true) - base * (1.2 + 0.15)) < 1e-12);
79
79
});
80
80
81
it('at min gravity one horizontal-3 jump equals the field height', () =>
81
it('at min gravity one horizontal-3 jump is 50% taller than the field', () =>
82
82
{
83
83
const easy = Planet.createPlanet({ jumpsToClear: 1 });
84
assert.equal(Planet.jumpHeight(easy, 3, false), 13);
84
assert.equal(Planet.jumpHeight(easy, 3, false), 1.5 * 13);
85
assert.equal(Planet.JUMP_HEIGHT_SCALE, 1.5);
85
86
});
86
87
87
it('at max gravity four horizontal-3 jumps equal the field height', () =>
88
it('at max gravity four horizontal-3 jumps equal 1.5 times the field height', () =>
88
89
{
89
90
const hard = Planet.createPlanet({ jumpsToClear: 4 });
90
assert.equal(Planet.jumpHeight(hard, 3, false) * 4, 13);
91
assert.equal(Planet.jumpHeight(hard, 3, false) * 4, 1.5 * 13);
91
92
});
92
93
});
93
94
@@ -118,13 +119,16 @@ describe('Launch and fall physics parameters', () =>
118
119
assert.ok(Math.abs(v2 / a2 - p.riseTime) < 1e-12);
119
120
});
120
121
121
it('fall speed is field height over fallTime (air resistance)', () =>
122
it('fall speed is half the field height over fallTime (t1122), ratios kept', () =>
122
123
{
123
124
const slow = Planet.createPlanet({ fallTime: 5 });
124
125
const fast = Planet.createPlanet({ fallTime: 1 });
125
assert.equal(slow.fallSpeed, 13 / 5);
126
assert.equal(fast.fallSpeed, 13);
126
assert.equal(Planet.DESCENT_SPEED_SCALE, 0.5);
127
assert.equal(slow.fallSpeed, 0.5 * 13 / 5);
128
assert.equal(fast.fallSpeed, 0.5 * 13);
127
129
assert.ok(fast.fallSpeed > slow.fallSpeed);
130
// Relative difference between planets is unchanged (1 / fallTime).
131
assert.ok(Math.abs(fast.fallSpeed / slow.fallSpeed - 5) < 1e-12);
128
132
});
129
133
});
130
134
@@ -21,8 +21,8 @@ describe('Planet field and defaults', () =>21
assert.equal(p.fallTime, 3);21
assert.equal(p.fallTime, 3);22
assert.equal(p.riseTime, 1.5);22
assert.equal(p.riseTime, 1.5);23
assert.equal(p.colors.length, 5);23
assert.equal(p.colors.length, 5);24
assert.equal(p.baseJumpHeight, 13 / 2);24
assert.equal(p.baseJumpHeight, 1.5 * 13 / 2);25
assert.equal(p.fallSpeed, 13 / 3);25
assert.equal(p.fallSpeed, 0.5 * 13 / 3);26
});26
});27
27
28
it('clamps gravity, air and mass to the stage-3 ranges', () =>28
it('clamps gravity, air and mass to the stage-3 ranges', () =>@@ -78,16 +78,17 @@ describe('Jump height rules', () =>78
assert.ok(Math.abs(Planet.jumpHeight(planet, 6, true) - base * (1.2 + 0.15)) < 1e-12);78
assert.ok(Math.abs(Planet.jumpHeight(planet, 6, true) - base * (1.2 + 0.15)) < 1e-12);79
});79
});80
80
81
it('at min gravity one horizontal-3 jump equals the field height', () =>81
it('at min gravity one horizontal-3 jump is 50% taller than the field', () =>82
{82
{83
const easy = Planet.createPlanet({ jumpsToClear: 1 });83
const easy = Planet.createPlanet({ jumpsToClear: 1 });84
assert.equal(Planet.jumpHeight(easy, 3, false), 13);84
assert.equal(Planet.jumpHeight(easy, 3, false), 1.5 * 13);85
assert.equal(Planet.JUMP_HEIGHT_SCALE, 1.5);85
});86
});86
87
87
it('at max gravity four horizontal-3 jumps equal the field height', () =>88
it('at max gravity four horizontal-3 jumps equal 1.5 times the field height', () =>88
{89
{89
const hard = Planet.createPlanet({ jumpsToClear: 4 });90
const hard = Planet.createPlanet({ jumpsToClear: 4 });90
assert.equal(Planet.jumpHeight(hard, 3, false) * 4, 13);91
assert.equal(Planet.jumpHeight(hard, 3, false) * 4, 1.5 * 13);91
});92
});92
});93
});93
94
@@ -118,13 +119,16 @@ describe('Launch and fall physics parameters', () =>118
assert.ok(Math.abs(v2 / a2 - p.riseTime) < 1e-12);119
assert.ok(Math.abs(v2 / a2 - p.riseTime) < 1e-12);119
});120
});120
121
121
it('fall speed is field height over fallTime (air resistance)', () =>122
it('fall speed is half the field height over fallTime (t1122), ratios kept', () =>122
{123
{123
const slow = Planet.createPlanet({ fallTime: 5 });124
const slow = Planet.createPlanet({ fallTime: 5 });124
const fast = Planet.createPlanet({ fallTime: 1 });125
const fast = Planet.createPlanet({ fallTime: 1 });125
assert.equal(slow.fallSpeed, 13 / 5);126
assert.equal(Planet.DESCENT_SPEED_SCALE, 0.5);126
assert.equal(fast.fallSpeed, 13);127
assert.equal(slow.fallSpeed, 0.5 * 13 / 5);128
assert.equal(fast.fallSpeed, 0.5 * 13);127
assert.ok(fast.fallSpeed > slow.fallSpeed);129
assert.ok(fast.fallSpeed > slow.fallSpeed);130
// Relative difference between planets is unchanged (1 / fallTime).131
assert.ok(Math.abs(fast.fallSpeed / slow.fallSpeed - 5) < 1e-12);128
});132
});129
});133
});130
134
@@ -2,7 +2,7 @@
2
2
3
3
const { describe, it } = require('node:test');
4
4
const assert = require('node:assert/strict');
5
const { makeGame, placeRow, GameCore, Planet } = require('./helpers.js');
5
const { makeGame, placeRow, almost, GameCore, Planet } = require('./helpers.js');
6
6
7
7
describe('Points, landing and recolor', () =>
8
8
{
@@ -94,7 +94,7 @@ describe('Points, landing and recolor', () =>
94
94
assert.equal(carried.color, 4);
95
95
assert.equal(carried.state, 'still');
96
96
assert.equal(carried.clusterId, null);
97
assert.equal(carried.y, 1);
97
assert.ok(almost(carried.y, 1, 1e-6), 'y=' + carried.y);
98
98
});
99
99
100
100
it('spawn drops a random color into a random open column every second', () =>
@@ -111,7 +111,7 @@ describe('Points, landing and recolor', () =>
111
111
g.step(1);
112
112
assert.equal(g.blocks.length, 2);
113
113
// Let the first one land.
114
g.step(g.planet.fallTime + 0.2);
114
g.step(g.planet.fallTime / Planet.DESCENT_SPEED_SCALE + 0.5);
115
115
const landed = g.blocks.filter((b) => b.state === 'still');
116
116
assert.ok(landed.length >= 1);
117
117
for (const b of landed)
@@ -2,7 +2,7 @@2
2
3
const { describe, it } = require('node:test');3
const { describe, it } = require('node:test');4
const assert = require('node:assert/strict');4
const assert = require('node:assert/strict');5
const { makeGame, placeRow, GameCore, Planet } = require('./helpers.js');5
const { makeGame, placeRow, almost, GameCore, Planet } = require('./helpers.js');6
6
7
describe('Points, landing and recolor', () =>7
describe('Points, landing and recolor', () =>8
{8
{@@ -94,7 +94,7 @@ describe('Points, landing and recolor', () =>94
assert.equal(carried.color, 4);94
assert.equal(carried.color, 4);95
assert.equal(carried.state, 'still');95
assert.equal(carried.state, 'still');96
assert.equal(carried.clusterId, null);96
assert.equal(carried.clusterId, null);97
assert.equal(carried.y, 1);97
assert.ok(almost(carried.y, 1, 1e-6), 'y=' + carried.y);98
});98
});99
99
100
it('spawn drops a random color into a random open column every second', () =>100
it('spawn drops a random color into a random open column every second', () =>@@ -111,7 +111,7 @@ describe('Points, landing and recolor', () =>111
g.step(1);111
g.step(1);112
assert.equal(g.blocks.length, 2);112
assert.equal(g.blocks.length, 2);113
// Let the first one land.113
// Let the first one land.114
g.step(g.planet.fallTime + 0.2);114
g.step(g.planet.fallTime / Planet.DESCENT_SPEED_SCALE + 0.5);115
const landed = g.blocks.filter((b) => b.state === 'still');115
const landed = g.blocks.filter((b) => b.state === 'still');116
assert.ok(landed.length >= 1);116
assert.ok(landed.length >= 1);117
for (const b of landed)117
for (const b of landed)@@ -0,0 +1,52 @@
1
'use strict';
2
3
const { describe, it } = require('node:test');
4
const assert = require('node:assert/strict');
5
const { makeGame } = require('./helpers.js');
6
7
describe('Swap events (t1121)', () =>
8
{
9
it('swapBlocks records visual events and consumeSwapEvents clears them', () =>
10
{
11
const g = makeGame({ noSpawn: true });
12
const a = g.place(0, 0, 1);
13
const b = g.place(0, 1, 2);
14
g.swapBlocks(a, b);
15
assert.equal(a.y, 1);
16
assert.equal(b.y, 0);
17
const ev = g.consumeSwapEvents();
18
assert.equal(ev.length, 2);
19
assert.equal(ev[0].id, a.id);
20
assert.equal(ev[0].fromY, 0);
21
assert.equal(ev[0].toY, 1);
22
assert.equal(ev[1].id, b.id);
23
assert.equal(ev[1].fromY, 1);
24
assert.equal(ev[1].toY, 0);
25
assert.equal(g.consumeSwapEvents().length, 0);
26
});
27
28
it('rapid multi-cell swapToward records a chain of events (logic already at the final cell)', () =>
29
{
30
const g = makeGame({ noSpawn: true });
31
const a = g.place(1, 0, 0);
32
g.place(1, 1, 1);
33
g.place(1, 2, 2);
34
g.swapToward(a, 2);
35
assert.equal(a.y, 2);
36
const ev = g.consumeSwapEvents();
37
// Two pairwise swaps (0↔1, then 1↔2) → 4 events, final toY of a is 2.
38
assert.ok(ev.length >= 4, 'events=' + ev.length);
39
const aEvents = ev.filter((e) => e.id === a.id);
40
assert.equal(aEvents[aEvents.length - 1].toY, 2);
41
});
42
43
it('the invariant checker is unaffected by swap events (grid is already updated)', () =>
44
{
45
const g = makeGame({ noSpawn: true });
46
g.place(2, 0, 0);
47
g.place(2, 1, 1);
48
g.swapToward(g.blocks[0], 1);
49
g.assertInvariants('after-swap');
50
assert.equal(g.lastInvariantViolations.length, 0);
51
});
52
});
@@ -0,0 +1,52 @@1
'use strict';2
3
const { describe, it } = require('node:test');4
const assert = require('node:assert/strict');5
const { makeGame } = require('./helpers.js');6
7
describe('Swap events (t1121)', () =>8
{9
it('swapBlocks records visual events and consumeSwapEvents clears them', () =>10
{11
const g = makeGame({ noSpawn: true });12
const a = g.place(0, 0, 1);13
const b = g.place(0, 1, 2);14
g.swapBlocks(a, b);15
assert.equal(a.y, 1);16
assert.equal(b.y, 0);17
const ev = g.consumeSwapEvents();18
assert.equal(ev.length, 2);19
assert.equal(ev[0].id, a.id);20
assert.equal(ev[0].fromY, 0);21
assert.equal(ev[0].toY, 1);22
assert.equal(ev[1].id, b.id);23
assert.equal(ev[1].fromY, 1);24
assert.equal(ev[1].toY, 0);25
assert.equal(g.consumeSwapEvents().length, 0);26
});27
28
it('rapid multi-cell swapToward records a chain of events (logic already at the final cell)', () =>29
{30
const g = makeGame({ noSpawn: true });31
const a = g.place(1, 0, 0);32
g.place(1, 1, 1);33
g.place(1, 2, 2);34
g.swapToward(a, 2);35
assert.equal(a.y, 2);36
const ev = g.consumeSwapEvents();37
// Two pairwise swaps (0↔1, then 1↔2) → 4 events, final toY of a is 2.38
assert.ok(ev.length >= 4, 'events=' + ev.length);39
const aEvents = ev.filter((e) => e.id === a.id);40
assert.equal(aEvents[aEvents.length - 1].toY, 2);41
});42
43
it('the invariant checker is unaffected by swap events (grid is already updated)', () =>44
{45
const g = makeGame({ noSpawn: true });46
g.place(2, 0, 0);47
g.place(2, 1, 1);48
g.swapToward(g.blocks[0], 1);49
g.assertInvariants('after-swap');50
assert.equal(g.lastInvariantViolations.length, 0);51
});52
});