feat: Offline Strijd, taller jumps, slower falls, chain bonus, swap tween and column warn (t1119–t1123)
Add the Offline Strijd single-player mode: local bots with the same shot/miss mechanics as multiplayer, a 1-then-N-for-(N-1) opponent schedule, skill from 5% rising 1% per round, and a HUD plus final screen. Bot AI rolls every 0.5s and may make a vertical match-making move. Raise the minimum jump height by 50% and halve every descent speed, keeping planet ratios. Landing a cluster into a match adds a stacking +25% jump bonus. Block swaps tween visually in 100 ms with easeOutCubic. Columns with at least 10 grounded rows pulse red on the player field and on opponent/bot minis.
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
}@@ -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
});