Merge branch 'feature/t1104-drag-matches-power'
@@ -80,12 +80,17 @@ is een planeet met een volk, vijf eigen kleuren/vormen, en drie natuurwetten:
80
80
- luchtweerstand — hoe snel blokjes weer vallen (`d`)
81
81
- massa — hoe snel de sprong omhoog gaat (`F`, newton)
82
82
83
Power is het gemiddelde van die drie, als percentage. Hoe hoger de Power,
84
hoe kleiner de kans dat een afgeschoten blokje een andere speler mist.
85
In een online wedstrijd telt **jouw** planeet voor de blokjes die jij
86
verstuurt. De twaalf werelden en hun getallen staan in
87
`server/lib/planets.json`. De blokplaatjes zijn unieke placeholders
88
(`build/images/block-{planeet}-{kleur}.png`); Tim kan ze zelf vervangen.
83
Die drie waarden bepalen een interne moeilijkheids-Power (0–1). De
84
miss-kans van een afgeschoten blokje is `0,60 − 0,55 × Power` (60 % op
85
het makkelijkste veld, 5 % op het moeilijkste). De **getoonde** Power in
86
de kiezer, de HUD en de lobby is het omgekeerde daarvan:
87
`1 − miss / 0,60` als percentage. 0 % miss is 100 % Power; 60 % miss is
88
0 % Power. Aurel toont 0 %, Terra 44 %, Cinder 92 % (de bodem is 5 %
89
miss, dus niet 100 %). In een online wedstrijd telt **jouw** planeet
90
voor de blokjes die jij verstuurt. De twaalf werelden en hun getallen
91
staan in `server/lib/planets.json`. De blokplaatjes zijn unieke
92
placeholders (`build/images/block-{planeet}-{kleur}.png`); Tim kan ze
93
zelf vervangen.
89
94
90
95
## Deploy
91
96
@@ -80,12 +80,17 @@ is een planeet met een volk, vijf eigen kleuren/vormen, en drie natuurwetten:80
- luchtweerstand — hoe snel blokjes weer vallen (`d`)80
- luchtweerstand — hoe snel blokjes weer vallen (`d`)81
- massa — hoe snel de sprong omhoog gaat (`F`, newton)81
- massa — hoe snel de sprong omhoog gaat (`F`, newton)82
82
83
Power is het gemiddelde van die drie, als percentage. Hoe hoger de Power,83
Die drie waarden bepalen een interne moeilijkheids-Power (0–1). De84
hoe kleiner de kans dat een afgeschoten blokje een andere speler mist.84
miss-kans van een afgeschoten blokje is `0,60 − 0,55 × Power` (60 % op85
In een online wedstrijd telt **jouw** planeet voor de blokjes die jij85
het makkelijkste veld, 5 % op het moeilijkste). De **getoonde** Power in86
verstuurt. De twaalf werelden en hun getallen staan in86
de kiezer, de HUD en de lobby is het omgekeerde daarvan:87
`server/lib/planets.json`. De blokplaatjes zijn unieke placeholders87
`1 − miss / 0,60` als percentage. 0 % miss is 100 % Power; 60 % miss is88
(`build/images/block-{planeet}-{kleur}.png`); Tim kan ze zelf vervangen.88
0 % Power. Aurel toont 0 %, Terra 44 %, Cinder 92 % (de bodem is 5 %89
miss, dus niet 100 %). In een online wedstrijd telt **jouw** planeet90
voor de blokjes die jij verstuurt. De twaalf werelden en hun getallen91
staan in `server/lib/planets.json`. De blokplaatjes zijn unieke92
placeholders (`build/images/block-{planeet}-{kleur}.png`); Tim kan ze93
zelf vervangen.89
94
90
## Deploy95
## Deploy91
96
@@ -438,16 +438,30 @@ function power (planet)
438
438
return (gravity + air + mass) / 3;
439
439
}
440
440
441
/** Maximum miss chance, used by the gameplay formula and the displayed Power. */
442
var MAX_MISS_CHANCE = 0.60;
443
var MIN_MISS_CHANCE = 0.05;
444
441
445
/** Stage-2 miss chance, 0.60 at power 0 down to 0.05 at power 1. */
442
446
function missChance (planet)
443
447
{
444
return 0.60 - 0.55 * power(planet);
448
return MAX_MISS_CHANCE - (MAX_MISS_CHANCE - MIN_MISS_CHANCE) * power(planet);
449
}
450
451
/**
452
* Displayed Power, as a 0–100 percentage. This is the complement of the
453
* miss chance against the maximum (60%): 0% miss → 100% Power, 60% miss
454
* → 0% Power. The gameplay power() and missChance() formulas are unchanged.
455
*/
456
function displayPower (planet)
457
{
458
return Math.round((1 - missChance(planet) / MAX_MISS_CHANCE) * 100);
445
459
}
446
460
447
461
/**
448
462
* Numeric HUD values: a gravity-like constant (m/s²), air density (kg/m³),
449
* launch force (N), and power as a percentage. The numbers do not have to
450
* explain themselves.
463
* launch force (N), and displayed Power as a percentage. The numbers do
464
* not have to explain themselves.
451
465
*/
452
466
function displayValues (planet)
453
467
{
@@ -458,7 +472,7 @@ function displayValues (planet)
458
472
gravity: gravity,
459
473
density: density,
460
474
newtons: newtons,
461
power: Math.round(power(planet) * 100),
475
power: displayPower(planet),
462
476
missChance: missChance(planet)
463
477
};
464
478
}
@@ -482,8 +496,11 @@ var Planet = {
482
496
jumpHeight: jumpHeight,
483
497
launchVelocity: launchVelocity,
484
498
launchDeceleration: launchDeceleration,
499
MAX_MISS_CHANCE: MAX_MISS_CHANCE,
500
MIN_MISS_CHANCE: MIN_MISS_CHANCE,
485
501
power: power,
486
502
missChance: missChance,
503
displayPower: displayPower,
487
504
displayValues: displayValues
488
505
};
489
506
@@ -1120,6 +1137,7 @@ GameCore.prototype.tick = function (dt)
1120
1137
{
1121
1138
var step = Math.min(SUBSTEP, left);
1122
1139
this.integrateFalling(step);
1140
this.resolveFlyingMatches();
1123
1141
this.integrateClusters(step);
1124
1142
this.mergeFlyingClusters();
1125
1143
this.integrateManual(step);
@@ -1332,8 +1350,9 @@ GameCore.prototype.integrateClusters = function (dt)
1332
1350
}
1333
1351
1334
1352
this.catchFallingOntoCluster(cluster, members);
1353
this.checkChainRelaunch(cluster);
1335
1354
1336
if (cluster.phase === 'down')
1355
if (cluster.phase === 'down' && this.clusters[cluster.id])
1337
1356
{ this.tryLandCluster(cluster, this.clusterMembers(cluster.id)); }
1338
1357
}
1339
1358
};
@@ -1442,7 +1461,8 @@ GameCore.prototype.mergeClusterGroup = function (clusters)
1442
1461
{ delete this.clusters[clusters[c].id]; }
1443
1462
}
1444
1463
this.packClusterOverlaps(keep);
1445
if (keep.phase === 'down')
1464
this.checkChainRelaunch(keep);
1465
if (keep.phase === 'down' && this.clusters[keep.id])
1446
1466
{ this.tryLandCluster(keep, this.clusterMembers(keep.id)); }
1447
1467
};
1448
1468
@@ -1702,6 +1722,24 @@ GameCore.prototype.pushClusterColumn = function (clusterId, col)
1702
1722
return true;
1703
1723
};
1704
1724
1725
/**
1726
* After a cargo attach or a cluster merge (or any other mid-air state
1727
* change), turn spontaneous lines of 3+ into rockets and give the whole
1728
* already-flying cluster an extra launch from its current position —
1729
* the same re-launch as a player push that completes a row.
1730
*/
1731
GameCore.prototype.resolveFlyingMatches = function ()
1732
{
1733
var ids = Object.keys(this.clusters);
1734
for (var n = 0; n < ids.length; n++)
1735
{
1736
var cluster = this.clusters[ids[n]];
1737
if (!cluster || cluster.phase === 'landed')
1738
{ continue; }
1739
this.checkChainRelaunch(cluster);
1740
}
1741
};
1742
1705
1743
GameCore.prototype.checkChainRelaunch = function (cluster)
1706
1744
{
1707
1745
if (!this.clusters[cluster.id])
@@ -2320,38 +2358,25 @@ GameCore.prototype.moveDrag = function (y)
2320
2358
this.drag = null;
2321
2359
return;
2322
2360
}
2323
var dy = y - this.drag.pointerY;
2324
2361
this.drag.pointerY = y;
2325
if (this.drag.accum == null)
2326
{ this.drag.accum = 0; }
2327
this.drag.accum += dy;
2328
// One swap per tile of travel, triggered after a minimal SWAP_DISTANCE.
2329
// A single large move (fast swipe) walks every tile; none are skipped.
2330
var guard = 0;
2331
while (guard++ < this.height + 2
2332
&& (this.drag.accum >= SWAP_DISTANCE || this.drag.accum <= -SWAP_DISTANCE))
2333
{
2334
var dir = this.drag.accum > 0 ? 1 : -1;
2335
if (!this.swapOne(block, dir))
2336
{
2337
if (dir > 0)
2338
{ this.drag.accum = Math.min(this.drag.accum, SWAP_DISTANCE - 1e-9); }
2339
else
2340
{ this.drag.accum = Math.max(this.drag.accum, -(SWAP_DISTANCE - 1e-9)); }
2341
break;
2342
}
2343
this.drag.accum -= dir;
2344
// A short move (SWAP_DISTANCE < 1) leaves a negative leftover;
2345
// do not let that immediately swap back the other way.
2346
if ((dir > 0 && this.drag.accum < 0) || (dir < 0 && this.drag.accum > 0))
2347
{ this.drag.accum = 0; }
2348
if (!this.isColumnStill(block.col))
2349
{
2350
this.drag = null;
2351
return;
2352
}
2353
}
2362
// 1:1 tracking: the target row is the one under the pointer, clamped
2363
// to the still stack. Swap step by step with each neighbour, and stop
2364
// exactly there. When the pointer stops, nothing else moves.
2365
// Accumulated deltas are not used: a SWAP_DISTANCE (0.25) threshold
2366
// used to jump a full cell on a short pull, and one large event
2367
// could walk the entire column (the "jumps all the way" bug).
2354
2368
var top = this.columnStackTopRow(block.col);
2369
var bottom = this.columnStackBottomRow(block.col);
2370
var target = Math.floor(y + 1e-12);
2371
if (bottom < 0)
2372
{ bottom = 0; }
2373
if (target < bottom)
2374
{ target = bottom; }
2375
if (target > top)
2376
{ target = top; }
2377
this.swapToward(block, target);
2378
2379
top = this.columnStackTopRow(block.col);
2355
2380
var isTop = Math.abs(block.y - top) < ALIGN_EPS;
2356
2381
if (this.drag.startedAsTop)
2357
2382
{
@@ -2414,6 +2439,18 @@ GameCore.prototype.columnStackTopRow = function (col)
2414
2439
return top;
2415
2440
};
2416
2441
2442
GameCore.prototype.columnStackBottomRow = function (col)
2443
{
2444
var bottom = Infinity;
2445
var list = this.blocksInColumn(col);
2446
for (var i = 0; i < list.length; i++)
2447
{
2448
if (this.isGrounded(list[i]) && list[i].y < bottom)
2449
{ bottom = list[i].y; }
2450
}
2451
return bottom === Infinity ? 0 : bottom;
2452
};
2453
2417
2454
GameCore.prototype.swapToward = function (block, targetY)
2418
2455
{
2419
2456
var guard = 0;
@@ -3640,11 +3677,14 @@ function fieldFromEvent (e)
3640
3677
var rect = canvas.getBoundingClientRect();
3641
3678
if (rect.width <= 0 || rect.height <= 0)
3642
3679
{ return null; }
3643
var x = (e.clientX - rect.left) * (canvas.width / rect.width);
3644
var y = (e.clientY - rect.top) * (canvas.height / rect.height);
3645
// Fractional column so beginDrag can snap across a nearby edge.
3646
var col = x / app.tile;
3647
var fieldY = (canvas.height - y) / app.tile;
3680
// Map through the CSS box only. Using canvas.width / app.tile would
3681
// scale the pointer by the backing-store ratio whenever that differs
3682
// from the layout size (high-DPR devices), so a short finger move
3683
// would look like a long swipe.
3684
var width = Planet.FIELD_WIDTH;
3685
var height = Planet.FIELD_HEIGHT;
3686
var col = ((e.clientX - rect.left) / rect.width) * width;
3687
var fieldY = (1 - (e.clientY - rect.top) / rect.height) * height;
3648
3688
return { col: col, y: fieldY };
3649
3689
}
3650
3690
@@ -438,16 +438,30 @@ function power (planet)438
return (gravity + air + mass) / 3;438
return (gravity + air + mass) / 3;439
}439
}440
440
441
/** Maximum miss chance, used by the gameplay formula and the displayed Power. */442
var MAX_MISS_CHANCE = 0.60;443
var MIN_MISS_CHANCE = 0.05;444
441
/** Stage-2 miss chance, 0.60 at power 0 down to 0.05 at power 1. */445
/** Stage-2 miss chance, 0.60 at power 0 down to 0.05 at power 1. */442
function missChance (planet)446
function missChance (planet)443
{447
{444
return 0.60 - 0.55 * power(planet);448
return MAX_MISS_CHANCE - (MAX_MISS_CHANCE - MIN_MISS_CHANCE) * power(planet);449
}450
451
/**452
* Displayed Power, as a 0–100 percentage. This is the complement of the453
* miss chance against the maximum (60%): 0% miss → 100% Power, 60% miss454
* → 0% Power. The gameplay power() and missChance() formulas are unchanged.455
*/456
function displayPower (planet)457
{458
return Math.round((1 - missChance(planet) / MAX_MISS_CHANCE) * 100);445
}459
}446
460
447
/**461
/**448
* Numeric HUD values: a gravity-like constant (m/s²), air density (kg/m³),462
* Numeric HUD values: a gravity-like constant (m/s²), air density (kg/m³),449
* launch force (N), and power as a percentage. The numbers do not have to463
* launch force (N), and displayed Power as a percentage. The numbers do450
* explain themselves.464
* not have to explain themselves.451
*/465
*/452
function displayValues (planet)466
function displayValues (planet)453
{467
{@@ -458,7 +472,7 @@ function displayValues (planet)458
gravity: gravity,472
gravity: gravity,459
density: density,473
density: density,460
newtons: newtons,474
newtons: newtons,461
power: Math.round(power(planet) * 100),475
power: displayPower(planet),462
missChance: missChance(planet)476
missChance: missChance(planet)463
};477
};464
}478
}@@ -482,8 +496,11 @@ var Planet = {482
jumpHeight: jumpHeight,496
jumpHeight: jumpHeight,483
launchVelocity: launchVelocity,497
launchVelocity: launchVelocity,484
launchDeceleration: launchDeceleration,498
launchDeceleration: launchDeceleration,499
MAX_MISS_CHANCE: MAX_MISS_CHANCE,500
MIN_MISS_CHANCE: MIN_MISS_CHANCE,485
power: power,501
power: power,486
missChance: missChance,502
missChance: missChance,503
displayPower: displayPower,487
displayValues: displayValues504
displayValues: displayValues488
};505
};489
506
@@ -1120,6 +1137,7 @@ GameCore.prototype.tick = function (dt)1120
{1137
{1121
var step = Math.min(SUBSTEP, left);1138
var step = Math.min(SUBSTEP, left);1122
this.integrateFalling(step);1139
this.integrateFalling(step);1140
this.resolveFlyingMatches();1123
this.integrateClusters(step);1141
this.integrateClusters(step);1124
this.mergeFlyingClusters();1142
this.mergeFlyingClusters();1125
this.integrateManual(step);1143
this.integrateManual(step);@@ -1332,8 +1350,9 @@ GameCore.prototype.integrateClusters = function (dt)1332
}1350
}1333
1351
1334
this.catchFallingOntoCluster(cluster, members);1352
this.catchFallingOntoCluster(cluster, members);1353
this.checkChainRelaunch(cluster);1335
1354
1336
if (cluster.phase === 'down')1355
if (cluster.phase === 'down' && this.clusters[cluster.id])1337
{ this.tryLandCluster(cluster, this.clusterMembers(cluster.id)); }1356
{ this.tryLandCluster(cluster, this.clusterMembers(cluster.id)); }1338
}1357
}1339
};1358
};@@ -1442,7 +1461,8 @@ GameCore.prototype.mergeClusterGroup = function (clusters)1442
{ delete this.clusters[clusters[c].id]; }1461
{ delete this.clusters[clusters[c].id]; }1443
}1462
}1444
this.packClusterOverlaps(keep);1463
this.packClusterOverlaps(keep);1445
if (keep.phase === 'down')1464
this.checkChainRelaunch(keep);1465
if (keep.phase === 'down' && this.clusters[keep.id])1446
{ this.tryLandCluster(keep, this.clusterMembers(keep.id)); }1466
{ this.tryLandCluster(keep, this.clusterMembers(keep.id)); }1447
};1467
};1448
1468
@@ -1702,6 +1722,24 @@ GameCore.prototype.pushClusterColumn = function (clusterId, col)1702
return true;1722
return true;1703
};1723
};1704
1724
1725
/**1726
* After a cargo attach or a cluster merge (or any other mid-air state1727
* change), turn spontaneous lines of 3+ into rockets and give the whole1728
* already-flying cluster an extra launch from its current position —1729
* the same re-launch as a player push that completes a row.1730
*/1731
GameCore.prototype.resolveFlyingMatches = function ()1732
{1733
var ids = Object.keys(this.clusters);1734
for (var n = 0; n < ids.length; n++)1735
{1736
var cluster = this.clusters[ids[n]];1737
if (!cluster || cluster.phase === 'landed')1738
{ continue; }1739
this.checkChainRelaunch(cluster);1740
}1741
};1742
1705
GameCore.prototype.checkChainRelaunch = function (cluster)1743
GameCore.prototype.checkChainRelaunch = function (cluster)1706
{1744
{1707
if (!this.clusters[cluster.id])1745
if (!this.clusters[cluster.id])@@ -2320,38 +2358,25 @@ GameCore.prototype.moveDrag = function (y)2320
this.drag = null;2358
this.drag = null;2321
return;2359
return;2322
}2360
}2323
var dy = y - this.drag.pointerY;2324
this.drag.pointerY = y;2361
this.drag.pointerY = y;2325
if (this.drag.accum == null)2362
// 1:1 tracking: the target row is the one under the pointer, clamped2326
{ this.drag.accum = 0; }2363
// to the still stack. Swap step by step with each neighbour, and stop2327
this.drag.accum += dy;2364
// exactly there. When the pointer stops, nothing else moves.2328
// One swap per tile of travel, triggered after a minimal SWAP_DISTANCE.2365
// Accumulated deltas are not used: a SWAP_DISTANCE (0.25) threshold2329
// A single large move (fast swipe) walks every tile; none are skipped.2366
// used to jump a full cell on a short pull, and one large event2330
var guard = 0;2367
// could walk the entire column (the "jumps all the way" bug).2331
while (guard++ < this.height + 22332
&& (this.drag.accum >= SWAP_DISTANCE || this.drag.accum <= -SWAP_DISTANCE))2333
{2334
var dir = this.drag.accum > 0 ? 1 : -1;2335
if (!this.swapOne(block, dir))2336
{2337
if (dir > 0)2338
{ this.drag.accum = Math.min(this.drag.accum, SWAP_DISTANCE - 1e-9); }2339
else2340
{ this.drag.accum = Math.max(this.drag.accum, -(SWAP_DISTANCE - 1e-9)); }2341
break;2342
}2343
this.drag.accum -= dir;2344
// A short move (SWAP_DISTANCE < 1) leaves a negative leftover;2345
// do not let that immediately swap back the other way.2346
if ((dir > 0 && this.drag.accum < 0) || (dir < 0 && this.drag.accum > 0))2347
{ this.drag.accum = 0; }2348
if (!this.isColumnStill(block.col))2349
{2350
this.drag = null;2351
return;2352
}2353
}2354
var top = this.columnStackTopRow(block.col);2368
var top = this.columnStackTopRow(block.col);2369
var bottom = this.columnStackBottomRow(block.col);2370
var target = Math.floor(y + 1e-12);2371
if (bottom < 0)2372
{ bottom = 0; }2373
if (target < bottom)2374
{ target = bottom; }2375
if (target > top)2376
{ target = top; }2377
this.swapToward(block, target);2378
2379
top = this.columnStackTopRow(block.col);2355
var isTop = Math.abs(block.y - top) < ALIGN_EPS;2380
var isTop = Math.abs(block.y - top) < ALIGN_EPS;2356
if (this.drag.startedAsTop)2381
if (this.drag.startedAsTop)2357
{2382
{@@ -2414,6 +2439,18 @@ GameCore.prototype.columnStackTopRow = function (col)2414
return top;2439
return top;2415
};2440
};2416
2441
2442
GameCore.prototype.columnStackBottomRow = function (col)2443
{2444
var bottom = Infinity;2445
var list = this.blocksInColumn(col);2446
for (var i = 0; i < list.length; i++)2447
{2448
if (this.isGrounded(list[i]) && list[i].y < bottom)2449
{ bottom = list[i].y; }2450
}2451
return bottom === Infinity ? 0 : bottom;2452
};2453
2417
GameCore.prototype.swapToward = function (block, targetY)2454
GameCore.prototype.swapToward = function (block, targetY)2418
{2455
{2419
var guard = 0;2456
var guard = 0;@@ -3640,11 +3677,14 @@ function fieldFromEvent (e)3640
var rect = canvas.getBoundingClientRect();3677
var rect = canvas.getBoundingClientRect();3641
if (rect.width <= 0 || rect.height <= 0)3678
if (rect.width <= 0 || rect.height <= 0)3642
{ return null; }3679
{ return null; }3643
var x = (e.clientX - rect.left) * (canvas.width / rect.width);3680
// Map through the CSS box only. Using canvas.width / app.tile would3644
var y = (e.clientY - rect.top) * (canvas.height / rect.height);3681
// scale the pointer by the backing-store ratio whenever that differs3645
// Fractional column so beginDrag can snap across a nearby edge.3682
// from the layout size (high-DPR devices), so a short finger move3646
var col = x / app.tile;3683
// would look like a long swipe.3647
var fieldY = (canvas.height - y) / app.tile;3684
var width = Planet.FIELD_WIDTH;3685
var height = Planet.FIELD_HEIGHT;3686
var col = ((e.clientX - rect.left) / rect.width) * width;3687
var fieldY = (1 - (e.clientY - rect.top) / rect.height) * height;3648
return { col: col, y: fieldY };3688
return { col: col, y: fieldY };3649
}3689
}3650
3690
@@ -253,22 +253,28 @@ Aanname:
253
253
254
254
- Een veld is een planeet, met een naam voor de planeet en voor het volk.
255
255
De catalogus staat in `server/lib/planets.json` (bron voor JS én PHP) en
256
telt **12** werelden, van makkelijk (Aurel: Power 0 %, 60 % miss) tot
257
moeilijk (Cinder: Power 100 %, 5 % miss). Terra blijft de standaard.
256
telt **12** werelden, van makkelijk (Aurel: gameplay-Power 0, 60 % miss,
257
getoonde Power 0 %) tot moeilijk (Cinder: gameplay-Power 1, 5 % miss,
258
getoonde Power 92 %). Terra (44 % getoonde Power) blijft de standaard.
258
259
- Zwaartekracht (`jumpsToClear` 1–4): één sprong haalt `1/jumpsToClear` van
259
260
de veldhoogte. Luchtweerstand (`fallTime` 1–5 s tot de bodem). Massa
260
261
(`riseTime` 0,5–3 s tot de apex). Lage massa en lage luchtweerstand en
261
262
hoge zwaartekracht zijn moeilijker. Bounce-duur en apex-ease schalen al
262
263
met `fallTime` (gebouwd in stage 1).
263
- Power is het gemiddelde van die drie assen, genormaliseerd 0–1, getoond
264
als percentage. Miss-kans = `0,60 − 0,55 × Power` (60 % bij Power 0,
265
5 % bij Power 1). In multiplayer gebruikt de **server** de Power van
266
**jouw** planeet voor de blokjes die jij afschiet (niet de lobby-waarde,
267
niet de planeet van het doel). De client kan dat niet vervalsen.
264
- De interne (gameplay-)Power is het gemiddelde van die drie assen,
265
genormaliseerd 0–1. Miss-kans = `0,60 − 0,55 × Power` (60 % bij 0,
266
5 % bij 1). Dat formule blijft de gameplay: schoten en de server
267
gebruiken hem onveranderd. De **getoonde** Power in kiezer, HUD en
268
lobby is `1 − miss / 0,60` als percentage (0 % miss → 100 % Power,
269
60 % miss → 0 % Power). Dat is alleen weergave (t1105). In
270
multiplayer gebruikt de **server** de gameplay-Power van **jouw**
271
planeet voor de blokjes die jij afschiet (niet de lobby-waarde, niet
272
de planeet van het doel). De client kan dat niet vervalsen.
268
273
- De vier getallen op de kiezers en in de HUD: `g` als
269
274
zwaartekrachtsconstante (m/s²), `d` als luchtdichtheid, `F` in newton,
270
Power als percentage. Alleen de getallen, zonder uitleg. Verticale match
271
van 3 = 120 % sprong, +5 % per extra blokje (al gebouwd, nergens uitgelegd).
275
getoonde Power als percentage. Alleen de getallen, zonder uitleg.
276
Verticale match van 3 = 120 % sprong, +5 % per extra blokje (al
277
gebouwd, nergens uitgelegd).
272
278
- Elk veld heeft een eigen set van 5 kleuren, elk met een uniek vormpje
273
279
en een uniek placeholder-PNG (`build/images/block-{planeet}-{kleur}.png`).
274
280
Tim kan die bestanden zelf vervangen; de namen blijven gelijk. Te
@@ -277,3 +283,38 @@ Aanname:
277
283
lobby (iedereen kiest zelf; zichtbaar voor de anderen). De keuze wordt
278
284
onthouden in `localStorage` (`meteors-planet`). Na de start van een
279
285
wedstrijd kun je niet meer wisselen.
286
287
## t1104 — 1:1-slepen en spontane raketten
288
289
- Oorzaak van de sleepbug: `moveDrag` werkte met een opgetelde
290
pointer-delta en een drempel van `SWAP_DISTANCE` (0,25 tegel). Een
291
klein stukje sleep deed daardoor al een hele tegel, en één grote
292
`pointermove` (typisch op touch) kon de rest van de kolom aflopen —
293
precies “meestal gelijk helemaal omlaag of omhoog”. De doelrij was
294
niet de rij onder de vinger, dus als de vinger stopte kon het blokje
295
al aan de top of de bodem zitten. Daarnaast liep de pointer-mapping
296
via `canvas.width` / `app.tile`, wat deltas zou vermenigvuldigen met
297
de devicePixelRatio als de backing-store en de CSS-maat ooit
298
uit elkaar lopen.
299
- Nu: de doelrij is `floor(pointerY)`, geklemd op de still-stapel van
300
de kolom. `swapToward` wisselt stap voor stap met elke buur, en stopt
301
precies daar. Als de pointer stilstaat, beweegt er niets meer.
302
Optrekken-boven-de-top om te lanceren blijft. Coordinaten komen uit
303
`getBoundingClientRect` en de veldgrootte (10×13), zonder
304
canvas-backing of `app.tile`.
305
- Spontane rijen (na vallen, settle/recolor, cargo-attach op een
306
vliegende cluster, cluster-merge) worden altijd raketten, net als
307
wanneer de speler ze maakt. In een al vliegende cluster geeft dat
308
een extra sprong vanaf de huidige positie (`checkChainRelaunch`,
309
dezelfde hoogte als bij een player-push). Mid-air hangend cargo na
310
recolor valt nog steeds vanuit stilstand (t1102), geen launch.
311
312
## t1105 — getoonde Power omgekeerd
313
314
- Alleen de weergave. Gameplay `power()` en `missChance()` zijn
315
onveranderd (`miss = 0,60 − 0,55 × power`). Getoonde Power =
316
`1 − missChance / 0,60`, afgerond als percentage, in JS
317
(`Planet.displayValues` / `formatStats`) en PHP (`Planets::displayValues`),
318
dus op de planeetkiezer, in de HUD en in de lobby. 0 % miss is 100 %
319
Power; Aurel 0 %, Terra 44 %, Cinder 92 %.
320
@@ -253,22 +253,28 @@ Aanname:253
253
254
- Een veld is een planeet, met een naam voor de planeet en voor het volk.254
- Een veld is een planeet, met een naam voor de planeet en voor het volk.255
De catalogus staat in `server/lib/planets.json` (bron voor JS én PHP) en255
De catalogus staat in `server/lib/planets.json` (bron voor JS én PHP) en256
telt **12** werelden, van makkelijk (Aurel: Power 0 %, 60 % miss) tot256
telt **12** werelden, van makkelijk (Aurel: gameplay-Power 0, 60 % miss,257
moeilijk (Cinder: Power 100 %, 5 % miss). Terra blijft de standaard.257
getoonde Power 0 %) tot moeilijk (Cinder: gameplay-Power 1, 5 % miss,258
getoonde Power 92 %). Terra (44 % getoonde Power) blijft de standaard.258
- Zwaartekracht (`jumpsToClear` 1–4): één sprong haalt `1/jumpsToClear` van259
- Zwaartekracht (`jumpsToClear` 1–4): één sprong haalt `1/jumpsToClear` van259
de veldhoogte. Luchtweerstand (`fallTime` 1–5 s tot de bodem). Massa260
de veldhoogte. Luchtweerstand (`fallTime` 1–5 s tot de bodem). Massa260
(`riseTime` 0,5–3 s tot de apex). Lage massa en lage luchtweerstand en261
(`riseTime` 0,5–3 s tot de apex). Lage massa en lage luchtweerstand en261
hoge zwaartekracht zijn moeilijker. Bounce-duur en apex-ease schalen al262
hoge zwaartekracht zijn moeilijker. Bounce-duur en apex-ease schalen al262
met `fallTime` (gebouwd in stage 1).263
met `fallTime` (gebouwd in stage 1).263
- Power is het gemiddelde van die drie assen, genormaliseerd 0–1, getoond264
- De interne (gameplay-)Power is het gemiddelde van die drie assen,264
als percentage. Miss-kans = `0,60 − 0,55 × Power` (60 % bij Power 0,265
genormaliseerd 0–1. Miss-kans = `0,60 − 0,55 × Power` (60 % bij 0,265
5 % bij Power 1). In multiplayer gebruikt de **server** de Power van266
5 % bij 1). Dat formule blijft de gameplay: schoten en de server266
**jouw** planeet voor de blokjes die jij afschiet (niet de lobby-waarde,267
gebruiken hem onveranderd. De **getoonde** Power in kiezer, HUD en267
niet de planeet van het doel). De client kan dat niet vervalsen.268
lobby is `1 − miss / 0,60` als percentage (0 % miss → 100 % Power,269
60 % miss → 0 % Power). Dat is alleen weergave (t1105). In270
multiplayer gebruikt de **server** de gameplay-Power van **jouw**271
planeet voor de blokjes die jij afschiet (niet de lobby-waarde, niet272
de planeet van het doel). De client kan dat niet vervalsen.268
- De vier getallen op de kiezers en in de HUD: `g` als273
- De vier getallen op de kiezers en in de HUD: `g` als269
zwaartekrachtsconstante (m/s²), `d` als luchtdichtheid, `F` in newton,274
zwaartekrachtsconstante (m/s²), `d` als luchtdichtheid, `F` in newton,270
Power als percentage. Alleen de getallen, zonder uitleg. Verticale match275
getoonde Power als percentage. Alleen de getallen, zonder uitleg.271
van 3 = 120 % sprong, +5 % per extra blokje (al gebouwd, nergens uitgelegd).276
Verticale match van 3 = 120 % sprong, +5 % per extra blokje (al277
gebouwd, nergens uitgelegd).272
- Elk veld heeft een eigen set van 5 kleuren, elk met een uniek vormpje278
- Elk veld heeft een eigen set van 5 kleuren, elk met een uniek vormpje273
en een uniek placeholder-PNG (`build/images/block-{planeet}-{kleur}.png`).279
en een uniek placeholder-PNG (`build/images/block-{planeet}-{kleur}.png`).274
Tim kan die bestanden zelf vervangen; de namen blijven gelijk. Te280
Tim kan die bestanden zelf vervangen; de namen blijven gelijk. Te@@ -277,3 +283,38 @@ Aanname:277
lobby (iedereen kiest zelf; zichtbaar voor de anderen). De keuze wordt283
lobby (iedereen kiest zelf; zichtbaar voor de anderen). De keuze wordt278
onthouden in `localStorage` (`meteors-planet`). Na de start van een284
onthouden in `localStorage` (`meteors-planet`). Na de start van een279
wedstrijd kun je niet meer wisselen.285
wedstrijd kun je niet meer wisselen.286
287
## t1104 — 1:1-slepen en spontane raketten288
289
- Oorzaak van de sleepbug: `moveDrag` werkte met een opgetelde290
pointer-delta en een drempel van `SWAP_DISTANCE` (0,25 tegel). Een291
klein stukje sleep deed daardoor al een hele tegel, en één grote292
`pointermove` (typisch op touch) kon de rest van de kolom aflopen —293
precies “meestal gelijk helemaal omlaag of omhoog”. De doelrij was294
niet de rij onder de vinger, dus als de vinger stopte kon het blokje295
al aan de top of de bodem zitten. Daarnaast liep de pointer-mapping296
via `canvas.width` / `app.tile`, wat deltas zou vermenigvuldigen met297
de devicePixelRatio als de backing-store en de CSS-maat ooit298
uit elkaar lopen.299
- Nu: de doelrij is `floor(pointerY)`, geklemd op de still-stapel van300
de kolom. `swapToward` wisselt stap voor stap met elke buur, en stopt301
precies daar. Als de pointer stilstaat, beweegt er niets meer.302
Optrekken-boven-de-top om te lanceren blijft. Coordinaten komen uit303
`getBoundingClientRect` en de veldgrootte (10×13), zonder304
canvas-backing of `app.tile`.305
- Spontane rijen (na vallen, settle/recolor, cargo-attach op een306
vliegende cluster, cluster-merge) worden altijd raketten, net als307
wanneer de speler ze maakt. In een al vliegende cluster geeft dat308
een extra sprong vanaf de huidige positie (`checkChainRelaunch`,309
dezelfde hoogte als bij een player-push). Mid-air hangend cargo na310
recolor valt nog steeds vanuit stilstand (t1102), geen launch.311
312
## t1105 — getoonde Power omgekeerd313
314
- Alleen de weergave. Gameplay `power()` en `missChance()` zijn315
onveranderd (`miss = 0,60 − 0,55 × power`). Getoonde Power =316
`1 − missChance / 0,60`, afgerond als percentage, in JS317
(`Planet.displayValues` / `formatStats`) en PHP (`Planets::displayValues`),318
dus op de planeetkiezer, in de HUD en in de lobby. 0 % miss is 100 %319
Power; Aurel 0 %, Terra 44 %, Cinder 92 %.320
@@ -75,10 +75,20 @@ final class Planets
75
75
return ($gravity + $air + $mass) / 3;
76
76
}
77
77
78
/** Miss chance: 0.60 at power 0, 0.05 at power 1. */
78
/** Maximum miss chance; displayed Power is 1 − miss / MAX_MISS_CHANCE. */
79
public const MAX_MISS_CHANCE = 0.60;
80
public const MIN_MISS_CHANCE = 0.05;
81
82
/** Miss chance: 0.60 at power 0, 0.05 at power 1. Unchanged gameplay formula. */
79
83
public static function missChance(array $planet): float
80
84
{
81
return 0.60 - 0.55 * self::power($planet);
85
return self::MAX_MISS_CHANCE - (self::MAX_MISS_CHANCE - self::MIN_MISS_CHANCE) * self::power($planet);
86
}
87
88
/** Displayed Power 0–100: 0% miss → 100% Power, 60% miss → 0% Power. */
89
public static function displayPower(array $planet): int
90
{
91
return (int) round((1 - self::missChance($planet) / self::MAX_MISS_CHANCE) * 100);
82
92
}
83
93
84
94
public static function missChanceForId(string $id): float
@@ -96,13 +106,12 @@ final class Planets
96
106
$j = self::clamp((float) ($planet['jumpsToClear'] ?? 2), 1, 4);
97
107
$f = self::clamp((float) ($planet['fallTime'] ?? 3), 1, 5);
98
108
$r = self::clamp((float) ($planet['riseTime'] ?? 1.5), 0.5, 3);
99
$power = self::power($planet);
100
109
return [
101
110
'gravity' => 9.81 * $j / 2,
102
111
'density' => 0.25 + ((5 - $f) / 4) * 1.60,
103
112
'newtons' => 40 + (($r - 0.5) / 2.5) * 160,
104
'power' => (int) round($power * 100),
105
'missChance' => 0.60 - 0.55 * $power,
113
'power' => self::displayPower($planet),
114
'missChance' => self::missChance($planet),
106
115
];
107
116
}
108
117
@@ -75,10 +75,20 @@ final class Planets75
return ($gravity + $air + $mass) / 3;75
return ($gravity + $air + $mass) / 3;76
}76
}77
77
78
/** Miss chance: 0.60 at power 0, 0.05 at power 1. */78
/** Maximum miss chance; displayed Power is 1 − miss / MAX_MISS_CHANCE. */79
public const MAX_MISS_CHANCE = 0.60;80
public const MIN_MISS_CHANCE = 0.05;81
82
/** Miss chance: 0.60 at power 0, 0.05 at power 1. Unchanged gameplay formula. */79
public static function missChance(array $planet): float83
public static function missChance(array $planet): float80
{84
{81
return 0.60 - 0.55 * self::power($planet);85
return self::MAX_MISS_CHANCE - (self::MAX_MISS_CHANCE - self::MIN_MISS_CHANCE) * self::power($planet);86
}87
88
/** Displayed Power 0–100: 0% miss → 100% Power, 60% miss → 0% Power. */89
public static function displayPower(array $planet): int90
{91
return (int) round((1 - self::missChance($planet) / self::MAX_MISS_CHANCE) * 100);82
}92
}83
93
84
public static function missChanceForId(string $id): float94
public static function missChanceForId(string $id): float@@ -96,13 +106,12 @@ final class Planets96
$j = self::clamp((float) ($planet['jumpsToClear'] ?? 2), 1, 4);106
$j = self::clamp((float) ($planet['jumpsToClear'] ?? 2), 1, 4);97
$f = self::clamp((float) ($planet['fallTime'] ?? 3), 1, 5);107
$f = self::clamp((float) ($planet['fallTime'] ?? 3), 1, 5);98
$r = self::clamp((float) ($planet['riseTime'] ?? 1.5), 0.5, 3);108
$r = self::clamp((float) ($planet['riseTime'] ?? 1.5), 0.5, 3);99
$power = self::power($planet);100
return [109
return [101
'gravity' => 9.81 * $j / 2,110
'gravity' => 9.81 * $j / 2,102
'density' => 0.25 + ((5 - $f) / 4) * 1.60,111
'density' => 0.25 + ((5 - $f) / 4) * 1.60,103
'newtons' => 40 + (($r - 0.5) / 2.5) * 160,112
'newtons' => 40 + (($r - 0.5) / 2.5) * 160,104
'power' => (int) round($power * 100),113
'power' => self::displayPower($planet),105
'missChance' => 0.60 - 0.55 * $power,114
'missChance' => self::missChance($planet),106
];115
];107
}116
}108
117
@@ -187,7 +187,10 @@ expect(almostEqual(Planets::missChance(Planets::byId('aurel')), 0.60), 'Aurel mi
187
187
expect(almostEqual(Planets::power(Planets::byId('cinder')), 1.0), 'Cinder power 1');
188
188
expect(almostEqual(Planets::missChance(Planets::byId('cinder')), 0.05), 'Cinder miss 5%');
189
189
$td = Planets::displayValues(Planets::byId('terra'));
190
expect(almostEqual($td['gravity'], 9.81) && almostEqual($td['density'], 1.05) && (int) round($td['newtons']) === 104 && $td['power'] === 48, 'Terra display g/d/F/Power');
190
expect(almostEqual($td['gravity'], 9.81) && almostEqual($td['density'], 1.05) && (int) round($td['newtons']) === 104 && $td['power'] === 44, 'Terra display g/d/F/Power');
191
expect(Planets::displayPower(Planets::byId('aurel')) === 0, 'Aurel displayed Power 0');
192
expect(Planets::displayPower(Planets::byId('cinder')) === 92, 'Cinder displayed Power 92 (5% miss)');
193
expect(Planets::displayValues(Planets::byId('cinder'))['power'] === 92, 'Cinder displayValues Power 92');
191
194
192
195
$store->leaveLobby('local:test_user_1');
193
196
$store->leaveLobby('local:test_user_2');
@@ -187,7 +187,10 @@ expect(almostEqual(Planets::missChance(Planets::byId('aurel')), 0.60), 'Aurel mi187
expect(almostEqual(Planets::power(Planets::byId('cinder')), 1.0), 'Cinder power 1');187
expect(almostEqual(Planets::power(Planets::byId('cinder')), 1.0), 'Cinder power 1');188
expect(almostEqual(Planets::missChance(Planets::byId('cinder')), 0.05), 'Cinder miss 5%');188
expect(almostEqual(Planets::missChance(Planets::byId('cinder')), 0.05), 'Cinder miss 5%');189
$td = Planets::displayValues(Planets::byId('terra'));189
$td = Planets::displayValues(Planets::byId('terra'));190
expect(almostEqual($td['gravity'], 9.81) && almostEqual($td['density'], 1.05) && (int) round($td['newtons']) === 104 && $td['power'] === 48, 'Terra display g/d/F/Power');190
expect(almostEqual($td['gravity'], 9.81) && almostEqual($td['density'], 1.05) && (int) round($td['newtons']) === 104 && $td['power'] === 44, 'Terra display g/d/F/Power');191
expect(Planets::displayPower(Planets::byId('aurel')) === 0, 'Aurel displayed Power 0');192
expect(Planets::displayPower(Planets::byId('cinder')) === 92, 'Cinder displayed Power 92 (5% miss)');193
expect(Planets::displayValues(Planets::byId('cinder'))['power'] === 92, 'Cinder displayValues Power 92');191
194
192
$store->leaveLobby('local:test_user_1');195
$store->leaveLobby('local:test_user_1');193
$store->leaveLobby('local:test_user_2');196
$store->leaveLobby('local:test_user_2');@@ -496,6 +496,7 @@ GameCore.prototype.tick = function (dt)
496
496
{
497
497
var step = Math.min(SUBSTEP, left);
498
498
this.integrateFalling(step);
499
this.resolveFlyingMatches();
499
500
this.integrateClusters(step);
500
501
this.mergeFlyingClusters();
501
502
this.integrateManual(step);
@@ -708,8 +709,9 @@ GameCore.prototype.integrateClusters = function (dt)
708
709
}
709
710
710
711
this.catchFallingOntoCluster(cluster, members);
712
this.checkChainRelaunch(cluster);
711
713
712
if (cluster.phase === 'down')
714
if (cluster.phase === 'down' && this.clusters[cluster.id])
713
715
{ this.tryLandCluster(cluster, this.clusterMembers(cluster.id)); }
714
716
}
715
717
};
@@ -818,7 +820,8 @@ GameCore.prototype.mergeClusterGroup = function (clusters)
818
820
{ delete this.clusters[clusters[c].id]; }
819
821
}
820
822
this.packClusterOverlaps(keep);
821
if (keep.phase === 'down')
823
this.checkChainRelaunch(keep);
824
if (keep.phase === 'down' && this.clusters[keep.id])
822
825
{ this.tryLandCluster(keep, this.clusterMembers(keep.id)); }
823
826
};
824
827
@@ -1078,6 +1081,24 @@ GameCore.prototype.pushClusterColumn = function (clusterId, col)
1078
1081
return true;
1079
1082
};
1080
1083
1084
/**
1085
* After a cargo attach or a cluster merge (or any other mid-air state
1086
* change), turn spontaneous lines of 3+ into rockets and give the whole
1087
* already-flying cluster an extra launch from its current position —
1088
* the same re-launch as a player push that completes a row.
1089
*/
1090
GameCore.prototype.resolveFlyingMatches = function ()
1091
{
1092
var ids = Object.keys(this.clusters);
1093
for (var n = 0; n < ids.length; n++)
1094
{
1095
var cluster = this.clusters[ids[n]];
1096
if (!cluster || cluster.phase === 'landed')
1097
{ continue; }
1098
this.checkChainRelaunch(cluster);
1099
}
1100
};
1101
1081
1102
GameCore.prototype.checkChainRelaunch = function (cluster)
1082
1103
{
1083
1104
if (!this.clusters[cluster.id])
@@ -1696,38 +1717,25 @@ GameCore.prototype.moveDrag = function (y)
1696
1717
this.drag = null;
1697
1718
return;
1698
1719
}
1699
var dy = y - this.drag.pointerY;
1700
1720
this.drag.pointerY = y;
1701
if (this.drag.accum == null)
1702
{ this.drag.accum = 0; }
1703
this.drag.accum += dy;
1704
// One swap per tile of travel, triggered after a minimal SWAP_DISTANCE.
1705
// A single large move (fast swipe) walks every tile; none are skipped.
1706
var guard = 0;
1707
while (guard++ < this.height + 2
1708
&& (this.drag.accum >= SWAP_DISTANCE || this.drag.accum <= -SWAP_DISTANCE))
1709
{
1710
var dir = this.drag.accum > 0 ? 1 : -1;
1711
if (!this.swapOne(block, dir))
1712
{
1713
if (dir > 0)
1714
{ this.drag.accum = Math.min(this.drag.accum, SWAP_DISTANCE - 1e-9); }
1715
else
1716
{ this.drag.accum = Math.max(this.drag.accum, -(SWAP_DISTANCE - 1e-9)); }
1717
break;
1718
}
1719
this.drag.accum -= dir;
1720
// A short move (SWAP_DISTANCE < 1) leaves a negative leftover;
1721
// do not let that immediately swap back the other way.
1722
if ((dir > 0 && this.drag.accum < 0) || (dir < 0 && this.drag.accum > 0))
1723
{ this.drag.accum = 0; }
1724
if (!this.isColumnStill(block.col))
1725
{
1726
this.drag = null;
1727
return;
1728
}
1729
}
1721
// 1:1 tracking: the target row is the one under the pointer, clamped
1722
// to the still stack. Swap step by step with each neighbour, and stop
1723
// exactly there. When the pointer stops, nothing else moves.
1724
// Accumulated deltas are not used: a SWAP_DISTANCE (0.25) threshold
1725
// used to jump a full cell on a short pull, and one large event
1726
// could walk the entire column (the "jumps all the way" bug).
1730
1727
var top = this.columnStackTopRow(block.col);
1728
var bottom = this.columnStackBottomRow(block.col);
1729
var target = Math.floor(y + 1e-12);
1730
if (bottom < 0)
1731
{ bottom = 0; }
1732
if (target < bottom)
1733
{ target = bottom; }
1734
if (target > top)
1735
{ target = top; }
1736
this.swapToward(block, target);
1737
1738
top = this.columnStackTopRow(block.col);
1731
1739
var isTop = Math.abs(block.y - top) < ALIGN_EPS;
1732
1740
if (this.drag.startedAsTop)
1733
1741
{
@@ -1790,6 +1798,18 @@ GameCore.prototype.columnStackTopRow = function (col)
1790
1798
return top;
1791
1799
};
1792
1800
1801
GameCore.prototype.columnStackBottomRow = function (col)
1802
{
1803
var bottom = Infinity;
1804
var list = this.blocksInColumn(col);
1805
for (var i = 0; i < list.length; i++)
1806
{
1807
if (this.isGrounded(list[i]) && list[i].y < bottom)
1808
{ bottom = list[i].y; }
1809
}
1810
return bottom === Infinity ? 0 : bottom;
1811
};
1812
1793
1813
GameCore.prototype.swapToward = function (block, targetY)
1794
1814
{
1795
1815
var guard = 0;
@@ -496,6 +496,7 @@ GameCore.prototype.tick = function (dt)496
{496
{497
var step = Math.min(SUBSTEP, left);497
var step = Math.min(SUBSTEP, left);498
this.integrateFalling(step);498
this.integrateFalling(step);499
this.resolveFlyingMatches();499
this.integrateClusters(step);500
this.integrateClusters(step);500
this.mergeFlyingClusters();501
this.mergeFlyingClusters();501
this.integrateManual(step);502
this.integrateManual(step);@@ -708,8 +709,9 @@ GameCore.prototype.integrateClusters = function (dt)708
}709
}709
710
710
this.catchFallingOntoCluster(cluster, members);711
this.catchFallingOntoCluster(cluster, members);712
this.checkChainRelaunch(cluster);711
713
712
if (cluster.phase === 'down')714
if (cluster.phase === 'down' && this.clusters[cluster.id])713
{ this.tryLandCluster(cluster, this.clusterMembers(cluster.id)); }715
{ this.tryLandCluster(cluster, this.clusterMembers(cluster.id)); }714
}716
}715
};717
};@@ -818,7 +820,8 @@ GameCore.prototype.mergeClusterGroup = function (clusters)818
{ delete this.clusters[clusters[c].id]; }820
{ delete this.clusters[clusters[c].id]; }819
}821
}820
this.packClusterOverlaps(keep);822
this.packClusterOverlaps(keep);821
if (keep.phase === 'down')823
this.checkChainRelaunch(keep);824
if (keep.phase === 'down' && this.clusters[keep.id])822
{ this.tryLandCluster(keep, this.clusterMembers(keep.id)); }825
{ this.tryLandCluster(keep, this.clusterMembers(keep.id)); }823
};826
};824
827
@@ -1078,6 +1081,24 @@ GameCore.prototype.pushClusterColumn = function (clusterId, col)1078
return true;1081
return true;1079
};1082
};1080
1083
1084
/**1085
* After a cargo attach or a cluster merge (or any other mid-air state1086
* change), turn spontaneous lines of 3+ into rockets and give the whole1087
* already-flying cluster an extra launch from its current position —1088
* the same re-launch as a player push that completes a row.1089
*/1090
GameCore.prototype.resolveFlyingMatches = function ()1091
{1092
var ids = Object.keys(this.clusters);1093
for (var n = 0; n < ids.length; n++)1094
{1095
var cluster = this.clusters[ids[n]];1096
if (!cluster || cluster.phase === 'landed')1097
{ continue; }1098
this.checkChainRelaunch(cluster);1099
}1100
};1101
1081
GameCore.prototype.checkChainRelaunch = function (cluster)1102
GameCore.prototype.checkChainRelaunch = function (cluster)1082
{1103
{1083
if (!this.clusters[cluster.id])1104
if (!this.clusters[cluster.id])@@ -1696,38 +1717,25 @@ GameCore.prototype.moveDrag = function (y)1696
this.drag = null;1717
this.drag = null;1697
return;1718
return;1698
}1719
}1699
var dy = y - this.drag.pointerY;1700
this.drag.pointerY = y;1720
this.drag.pointerY = y;1701
if (this.drag.accum == null)1721
// 1:1 tracking: the target row is the one under the pointer, clamped1702
{ this.drag.accum = 0; }1722
// to the still stack. Swap step by step with each neighbour, and stop1703
this.drag.accum += dy;1723
// exactly there. When the pointer stops, nothing else moves.1704
// One swap per tile of travel, triggered after a minimal SWAP_DISTANCE.1724
// Accumulated deltas are not used: a SWAP_DISTANCE (0.25) threshold1705
// A single large move (fast swipe) walks every tile; none are skipped.1725
// used to jump a full cell on a short pull, and one large event1706
var guard = 0;1726
// could walk the entire column (the "jumps all the way" bug).1707
while (guard++ < this.height + 21708
&& (this.drag.accum >= SWAP_DISTANCE || this.drag.accum <= -SWAP_DISTANCE))1709
{1710
var dir = this.drag.accum > 0 ? 1 : -1;1711
if (!this.swapOne(block, dir))1712
{1713
if (dir > 0)1714
{ this.drag.accum = Math.min(this.drag.accum, SWAP_DISTANCE - 1e-9); }1715
else1716
{ this.drag.accum = Math.max(this.drag.accum, -(SWAP_DISTANCE - 1e-9)); }1717
break;1718
}1719
this.drag.accum -= dir;1720
// A short move (SWAP_DISTANCE < 1) leaves a negative leftover;1721
// do not let that immediately swap back the other way.1722
if ((dir > 0 && this.drag.accum < 0) || (dir < 0 && this.drag.accum > 0))1723
{ this.drag.accum = 0; }1724
if (!this.isColumnStill(block.col))1725
{1726
this.drag = null;1727
return;1728
}1729
}1730
var top = this.columnStackTopRow(block.col);1727
var top = this.columnStackTopRow(block.col);1728
var bottom = this.columnStackBottomRow(block.col);1729
var target = Math.floor(y + 1e-12);1730
if (bottom < 0)1731
{ bottom = 0; }1732
if (target < bottom)1733
{ target = bottom; }1734
if (target > top)1735
{ target = top; }1736
this.swapToward(block, target);1737
1738
top = this.columnStackTopRow(block.col);1731
var isTop = Math.abs(block.y - top) < ALIGN_EPS;1739
var isTop = Math.abs(block.y - top) < ALIGN_EPS;1732
if (this.drag.startedAsTop)1740
if (this.drag.startedAsTop)1733
{1741
{@@ -1790,6 +1798,18 @@ GameCore.prototype.columnStackTopRow = function (col)1790
return top;1798
return top;1791
};1799
};1792
1800
1801
GameCore.prototype.columnStackBottomRow = function (col)1802
{1803
var bottom = Infinity;1804
var list = this.blocksInColumn(col);1805
for (var i = 0; i < list.length; i++)1806
{1807
if (this.isGrounded(list[i]) && list[i].y < bottom)1808
{ bottom = list[i].y; }1809
}1810
return bottom === Infinity ? 0 : bottom;1811
};1812
1793
GameCore.prototype.swapToward = function (block, targetY)1813
GameCore.prototype.swapToward = function (block, targetY)1794
{1814
{1795
var guard = 0;1815
var guard = 0;@@ -539,11 +539,14 @@ function fieldFromEvent (e)
539
539
var rect = canvas.getBoundingClientRect();
540
540
if (rect.width <= 0 || rect.height <= 0)
541
541
{ return null; }
542
var x = (e.clientX - rect.left) * (canvas.width / rect.width);
543
var y = (e.clientY - rect.top) * (canvas.height / rect.height);
544
// Fractional column so beginDrag can snap across a nearby edge.
545
var col = x / app.tile;
546
var fieldY = (canvas.height - y) / app.tile;
542
// Map through the CSS box only. Using canvas.width / app.tile would
543
// scale the pointer by the backing-store ratio whenever that differs
544
// from the layout size (high-DPR devices), so a short finger move
545
// would look like a long swipe.
546
var width = Planet.FIELD_WIDTH;
547
var height = Planet.FIELD_HEIGHT;
548
var col = ((e.clientX - rect.left) / rect.width) * width;
549
var fieldY = (1 - (e.clientY - rect.top) / rect.height) * height;
547
550
return { col: col, y: fieldY };
548
551
}
549
552
@@ -539,11 +539,14 @@ function fieldFromEvent (e)539
var rect = canvas.getBoundingClientRect();539
var rect = canvas.getBoundingClientRect();540
if (rect.width <= 0 || rect.height <= 0)540
if (rect.width <= 0 || rect.height <= 0)541
{ return null; }541
{ return null; }542
var x = (e.clientX - rect.left) * (canvas.width / rect.width);542
// Map through the CSS box only. Using canvas.width / app.tile would543
var y = (e.clientY - rect.top) * (canvas.height / rect.height);543
// scale the pointer by the backing-store ratio whenever that differs544
// Fractional column so beginDrag can snap across a nearby edge.544
// from the layout size (high-DPR devices), so a short finger move545
var col = x / app.tile;545
// would look like a long swipe.546
var fieldY = (canvas.height - y) / app.tile;546
var width = Planet.FIELD_WIDTH;547
var height = Planet.FIELD_HEIGHT;548
var col = ((e.clientX - rect.left) / rect.width) * width;549
var fieldY = (1 - (e.clientY - rect.top) / rect.height) * height;547
return { col: col, y: fieldY };550
return { col: col, y: fieldY };548
}551
}549
552
@@ -190,16 +190,30 @@ function power (planet)
190
190
return (gravity + air + mass) / 3;
191
191
}
192
192
193
/** Maximum miss chance, used by the gameplay formula and the displayed Power. */
194
var MAX_MISS_CHANCE = 0.60;
195
var MIN_MISS_CHANCE = 0.05;
196
193
197
/** Stage-2 miss chance, 0.60 at power 0 down to 0.05 at power 1. */
194
198
function missChance (planet)
195
199
{
196
return 0.60 - 0.55 * power(planet);
200
return MAX_MISS_CHANCE - (MAX_MISS_CHANCE - MIN_MISS_CHANCE) * power(planet);
201
}
202
203
/**
204
* Displayed Power, as a 0–100 percentage. This is the complement of the
205
* miss chance against the maximum (60%): 0% miss → 100% Power, 60% miss
206
* → 0% Power. The gameplay power() and missChance() formulas are unchanged.
207
*/
208
function displayPower (planet)
209
{
210
return Math.round((1 - missChance(planet) / MAX_MISS_CHANCE) * 100);
197
211
}
198
212
199
213
/**
200
214
* Numeric HUD values: a gravity-like constant (m/s²), air density (kg/m³),
201
* launch force (N), and power as a percentage. The numbers do not have to
202
* explain themselves.
215
* launch force (N), and displayed Power as a percentage. The numbers do
216
* not have to explain themselves.
203
217
*/
204
218
function displayValues (planet)
205
219
{
@@ -210,7 +224,7 @@ function displayValues (planet)
210
224
gravity: gravity,
211
225
density: density,
212
226
newtons: newtons,
213
power: Math.round(power(planet) * 100),
227
power: displayPower(planet),
214
228
missChance: missChance(planet)
215
229
};
216
230
}
@@ -234,8 +248,11 @@ var Planet = {
234
248
jumpHeight: jumpHeight,
235
249
launchVelocity: launchVelocity,
236
250
launchDeceleration: launchDeceleration,
251
MAX_MISS_CHANCE: MAX_MISS_CHANCE,
252
MIN_MISS_CHANCE: MIN_MISS_CHANCE,
237
253
power: power,
238
254
missChance: missChance,
255
displayPower: displayPower,
239
256
displayValues: displayValues
240
257
};
241
258
@@ -190,16 +190,30 @@ function power (planet)190
return (gravity + air + mass) / 3;190
return (gravity + air + mass) / 3;191
}191
}192
192
193
/** Maximum miss chance, used by the gameplay formula and the displayed Power. */194
var MAX_MISS_CHANCE = 0.60;195
var MIN_MISS_CHANCE = 0.05;196
193
/** Stage-2 miss chance, 0.60 at power 0 down to 0.05 at power 1. */197
/** Stage-2 miss chance, 0.60 at power 0 down to 0.05 at power 1. */194
function missChance (planet)198
function missChance (planet)195
{199
{196
return 0.60 - 0.55 * power(planet);200
return MAX_MISS_CHANCE - (MAX_MISS_CHANCE - MIN_MISS_CHANCE) * power(planet);201
}202
203
/**204
* Displayed Power, as a 0–100 percentage. This is the complement of the205
* miss chance against the maximum (60%): 0% miss → 100% Power, 60% miss206
* → 0% Power. The gameplay power() and missChance() formulas are unchanged.207
*/208
function displayPower (planet)209
{210
return Math.round((1 - missChance(planet) / MAX_MISS_CHANCE) * 100);197
}211
}198
212
199
/**213
/**200
* Numeric HUD values: a gravity-like constant (m/s²), air density (kg/m³),214
* Numeric HUD values: a gravity-like constant (m/s²), air density (kg/m³),201
* launch force (N), and power as a percentage. The numbers do not have to215
* launch force (N), and displayed Power as a percentage. The numbers do202
* explain themselves.216
* not have to explain themselves.203
*/217
*/204
function displayValues (planet)218
function displayValues (planet)205
{219
{@@ -210,7 +224,7 @@ function displayValues (planet)210
gravity: gravity,224
gravity: gravity,211
density: density,225
density: density,212
newtons: newtons,226
newtons: newtons,213
power: Math.round(power(planet) * 100),227
power: displayPower(planet),214
missChance: missChance(planet)228
missChance: missChance(planet)215
};229
};216
}230
}@@ -234,8 +248,11 @@ var Planet = {234
jumpHeight: jumpHeight,248
jumpHeight: jumpHeight,235
launchVelocity: launchVelocity,249
launchVelocity: launchVelocity,236
launchDeceleration: launchDeceleration,250
launchDeceleration: launchDeceleration,251
MAX_MISS_CHANCE: MAX_MISS_CHANCE,252
MIN_MISS_CHANCE: MIN_MISS_CHANCE,237
power: power,253
power: power,238
missChance: missChance,254
missChance: missChance,255
displayPower: displayPower,239
displayValues: displayValues256
displayValues: displayValues240
};257
};241
258
@@ -0,0 +1,346 @@
1
#!/usr/bin/env python3
2
"""1:1 drag tracking (t1104): mouse and real touch, including a high-DPR mobile viewport."""
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
OUT = Path("/workspace/meteors-shots")
14
OUT.mkdir(parents=True, exist_ok=True)
15
ROOT = Path("/workspace/meteors")
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
25
DESKTOP = {
26
"name": "desktop-mouse",
27
"viewport": {"width": 1280, "height": 900},
28
"device_scale_factor": 1,
29
"is_mobile": False,
30
"has_touch": False,
31
"user_agent": None,
32
"input": "mouse",
33
}
34
ANDROID = {
35
"name": "android-touch",
36
"viewport": {"width": 393, "height": 851},
37
"device_scale_factor": 2,
38
"is_mobile": True,
39
"has_touch": True,
40
"user_agent": (
41
"Mozilla/5.0 (Linux; Android 14; Pixel 7) AppleWebKit/537.36 "
42
"(KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36"
43
),
44
"input": "touch",
45
}
46
ANDROID_DPR3 = {
47
"name": "android-dpr3",
48
"viewport": {"width": 393, "height": 851},
49
"device_scale_factor": 3,
50
"is_mobile": True,
51
"has_touch": True,
52
"user_agent": (
53
"Mozilla/5.0 (Linux; Android 14; Pixel 7) AppleWebKit/537.36 "
54
"(KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36"
55
),
56
"input": "touch",
57
}
58
IOS = {
59
"name": "ios-touch",
60
"viewport": {"width": 390, "height": 844},
61
"device_scale_factor": 2,
62
"is_mobile": True,
63
"has_touch": True,
64
"user_agent": (
65
"Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) "
66
"AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 "
67
"Mobile/15E148 Safari/604.1"
68
),
69
"input": "touch",
70
}
71
72
FAILURES = []
73
URL = None
74
75
76
def free_port():
77
s = socket.socket()
78
s.bind(("127.0.0.1", 0))
79
port = s.getsockname()[1]
80
s.close()
81
return port
82
83
84
def field_to_client(page, col, field_y):
85
return page.evaluate(
86
"""([col, fieldY]) => {
87
const c = app.scene.canvas;
88
const r = c.getBoundingClientRect();
89
const w = Planet.FIELD_WIDTH;
90
const h = Planet.FIELD_HEIGHT;
91
return {
92
x: r.left + ((col + 0.5) / w) * r.width,
93
y: r.top + (1 - fieldY / h) * r.height
94
};
95
}""",
96
[col, field_y],
97
)
98
99
100
def touch_start(cdp, x, y):
101
cdp.send(
102
"Input.dispatchTouchEvent",
103
{"type": "touchStart", "touchPoints": [{"x": x, "y": y, "id": 1}]},
104
)
105
106
107
def touch_move(cdp, x, y):
108
cdp.send(
109
"Input.dispatchTouchEvent",
110
{"type": "touchMove", "touchPoints": [{"x": x, "y": y, "id": 1}]},
111
)
112
113
114
def touch_end(cdp):
115
cdp.send("Input.dispatchTouchEvent", {"type": "touchEnd", "touchPoints": []})
116
117
118
def pointer_down(page, cdp, kind, x, y):
119
if kind == "mouse":
120
page.mouse.move(x, y)
121
page.mouse.down()
122
else:
123
touch_start(cdp, x, y)
124
125
126
def pointer_move(page, cdp, kind, x, y):
127
if kind == "mouse":
128
page.mouse.move(x, y)
129
else:
130
touch_move(cdp, x, y)
131
132
133
def pointer_up(page, cdp, kind):
134
if kind == "mouse":
135
page.mouse.up()
136
else:
137
touch_end(cdp)
138
139
140
def drag_to(page, cdp, kind, x1, y1, x2, y2, steps=12, end=True):
141
pointer_down(page, cdp, kind, x1, y1)
142
for i in range(1, steps + 1):
143
t = i / steps
144
pointer_move(page, cdp, kind, x1 + (x2 - x1) * t, y1 + (y2 - y1) * t)
145
if end:
146
pointer_up(page, cdp, kind)
147
148
149
def reset_board(page, stacks):
150
page.evaluate(
151
"""(stacks) => {
152
const g = app.core;
153
g.spawnInterval = 1e9;
154
g.spawnTimer = 0;
155
g.blocks.length = 0;
156
g.clusters = Object.create(null);
157
g.score = 0;
158
g.drag = null;
159
g.state = 'playing';
160
g.nextBlockId = 1;
161
g.nextClusterId = 1;
162
app.selectTween = null;
163
for (const [col, colors] of Object.entries(stacks)) {
164
colors.forEach((color, row) => g.place(+col, row, color));
165
}
166
}""",
167
stacks,
168
)
169
page.wait_for_timeout(80)
170
171
172
def board(page):
173
return page.evaluate(
174
"""() => app.core.blocks.map((b) => ({
175
id: b.id, col: b.col, y: b.y, color: b.color, state: b.state
176
}))"""
177
)
178
179
180
def col_ys(page, col):
181
return {b["color"]: b["y"] for b in board(page) if b["col"] == col}
182
183
184
def check(cond, msg, device):
185
if not cond:
186
FAILURES.append(f"[{device}] {msg}")
187
print(f"FAIL [{device}] {msg}")
188
else:
189
print(f"OK [{device}] {msg}")
190
return cond
191
192
193
def shot(page, name):
194
path = OUT / name
195
page.screenshot(path=str(path), full_page=False)
196
print(f"wrote {path} ({path.stat().st_size} bytes)")
197
198
199
def start_play(page, kind):
200
page.goto(URL, wait_until="networkidle", timeout=20000)
201
page.wait_for_timeout(400)
202
btn = page.locator("#btn-play")
203
btn.wait_for(state="visible", timeout=5000)
204
if kind == "touch":
205
box = btn.bounding_box()
206
cdp = page.context.new_cdp_session(page)
207
touch_start(cdp, box["x"] + box["width"] / 2, box["y"] + box["height"] / 2)
208
touch_end(cdp)
209
page.wait_for_timeout(400)
210
else:
211
cdp = None
212
btn.click()
213
page.wait_for_timeout(400)
214
if page.evaluate("() => app && app.mode") == "planet-select":
215
go = page.locator("#btn-planet-go")
216
go.wait_for(state="visible", timeout=5000)
217
go.click()
218
page.wait_for_timeout(400)
219
if page.evaluate("() => app.mode") != "playing":
220
if page.locator("#btn-play").is_visible():
221
page.locator("#btn-play").click()
222
page.wait_for_timeout(400)
223
if page.locator("#btn-planet-go").is_visible():
224
page.locator("#btn-planet-go").click()
225
page.wait_for_timeout(400)
226
page.wait_for_function("() => app && app.mode === 'playing' && app.core && app.scene", timeout=8000)
227
page.wait_for_selector("canvas", state="visible", timeout=5000)
228
if cdp is None:
229
cdp = page.context.new_cdp_session(page)
230
return cdp
231
232
233
def nearly(a, b, eps=0.15):
234
return abs(a - b) <= eps
235
236
237
def run_device(browser, device):
238
name = device["name"]
239
kind = device["input"]
240
print(f"\n======== {name} ({kind}, dpr={device['device_scale_factor']}) ========")
241
kw = dict(
242
viewport=device["viewport"],
243
device_scale_factor=device["device_scale_factor"],
244
is_mobile=device["is_mobile"],
245
has_touch=device["has_touch"],
246
)
247
if device["user_agent"]:
248
kw["user_agent"] = device["user_agent"]
249
context = browser.new_context(**kw)
250
page = context.new_page()
251
bag = []
252
page.on("console", lambda m: bag.append(f"{m.type}: {m.text}"))
253
page.on("pageerror", lambda e: bag.append(f"pageerror: {e}"))
254
cdp = start_play(page, kind)
255
check(page.evaluate("() => app.mode") == "playing", "play started", name)
256
257
# --- 1 tile down ---
258
reset_board(page, {"2": [0, 1, 2, 3, 4]})
259
p0 = field_to_client(page, 2, 1.5)
260
p1 = field_to_client(page, 2, 0.5)
261
drag_to(page, cdp, kind, p0["x"], p0["y"], p1["x"], p1["y"], steps=10, end=True)
262
page.wait_for_timeout(60)
263
ys = col_ys(page, 2)
264
check(nearly(ys.get(1, -99), 0), f"1 tile down: grabbed color 1 at y=0, ys={ys}", name)
265
check(nearly(ys.get(0, -99), 1), f"1 tile down: swapped neighbour to y=1, ys={ys}", name)
266
check(nearly(ys.get(2, -99), 2) and nearly(ys.get(3, -99), 3) and nearly(ys.get(4, -99), 4),
267
f"1 tile down: rest of the stack unmoved, ys={ys}", name)
268
269
# --- 1 tile up ---
270
reset_board(page, {"3": [0, 1, 2, 3, 4]})
271
p0 = field_to_client(page, 3, 0.5)
272
p1 = field_to_client(page, 3, 1.5)
273
drag_to(page, cdp, kind, p0["x"], p0["y"], p1["x"], p1["y"], steps=10, end=True)
274
page.wait_for_timeout(60)
275
ys = col_ys(page, 3)
276
check(nearly(ys.get(0, -99), 1), f"1 tile up: grabbed color 0 at y=1, ys={ys}", name)
277
check(nearly(ys.get(1, -99), 0), f"1 tile up: neighbour at y=0, ys={ys}", name)
278
check(nearly(ys.get(2, -99), 2), f"1 tile up: rest unmoved, ys={ys}", name)
279
280
# --- 2 tiles, then stop: pointer held still, nothing else moves ---
281
reset_board(page, {"4": [0, 1, 2, 3, 4]})
282
p0 = field_to_client(page, 4, 0.5)
283
p1 = field_to_client(page, 4, 2.5)
284
drag_to(page, cdp, kind, p0["x"], p0["y"], p1["x"], p1["y"], steps=14, end=False)
285
page.wait_for_timeout(50)
286
mid = col_ys(page, 4)
287
check(nearly(mid.get(0, -99), 2), f"2 tiles: grabbed color 0 at y=2, ys={mid}", name)
288
check(nearly(mid.get(1, -99), 0) and nearly(mid.get(2, -99), 1) and nearly(mid.get(3, -99), 3),
289
f"2 tiles: walked both neighbours, ys={mid}", name)
290
# Pointer stops: more moves at the same point, then a short wait.
291
for _ in range(6):
292
pointer_move(page, cdp, kind, p1["x"], p1["y"])
293
page.wait_for_timeout(30)
294
after = col_ys(page, 4)
295
check(after == mid, f"pointer stopped: stack stays put, mid={mid} after={after}", name)
296
pointer_up(page, cdp, kind)
297
page.wait_for_timeout(80)
298
end = col_ys(page, 4)
299
check(end == mid, f"after release: still at the pointer row, mid={mid} end={end}", name)
300
shot(page, f"t1104-drag-{name}.png")
301
302
if bag:
303
print(f"console [{name}]: {bag[:8]}")
304
context.close()
305
306
307
def main():
308
global URL
309
port = free_port()
310
URL = f"http://127.0.0.1:{port}/"
311
print("serving", URL, "from", ROOT / "build")
312
httpd = subprocess.Popen(
313
["python3", "-m", "http.server", str(port), "--bind", "127.0.0.1", "--directory", str(ROOT / "build")],
314
stdout=subprocess.DEVNULL,
315
stderr=subprocess.DEVNULL,
316
)
317
try:
318
time.sleep(0.4)
319
with sync_playwright() as p:
320
browser = p.chromium.launch(
321
executable_path=CHROME,
322
args=CHROME_ARGS,
323
headless=True,
324
)
325
for device in (DESKTOP, ANDROID, ANDROID_DPR3, IOS):
326
run_device(browser, device)
327
browser.close()
328
finally:
329
httpd.terminate()
330
try:
331
httpd.wait(timeout=3)
332
except Exception:
333
httpd.kill()
334
335
print("\n======== summary ========")
336
if FAILURES:
337
print(f"{len(FAILURES)} failure(s):")
338
for f in FAILURES:
339
print(" -", f)
340
return 1
341
print("all 1:1 drag tests passed")
342
return 0
343
344
345
if __name__ == "__main__":
346
sys.exit(main())
@@ -0,0 +1,346 @@1
#!/usr/bin/env python32
"""1:1 drag tracking (t1104): mouse and real touch, including a high-DPR mobile viewport."""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
OUT = Path("/workspace/meteors-shots")14
OUT.mkdir(parents=True, exist_ok=True)15
ROOT = Path("/workspace/meteors")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
25
DESKTOP = {26
"name": "desktop-mouse",27
"viewport": {"width": 1280, "height": 900},28
"device_scale_factor": 1,29
"is_mobile": False,30
"has_touch": False,31
"user_agent": None,32
"input": "mouse",33
}34
ANDROID = {35
"name": "android-touch",36
"viewport": {"width": 393, "height": 851},37
"device_scale_factor": 2,38
"is_mobile": True,39
"has_touch": True,40
"user_agent": (41
"Mozilla/5.0 (Linux; Android 14; Pixel 7) AppleWebKit/537.36 "42
"(KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36"43
),44
"input": "touch",45
}46
ANDROID_DPR3 = {47
"name": "android-dpr3",48
"viewport": {"width": 393, "height": 851},49
"device_scale_factor": 3,50
"is_mobile": True,51
"has_touch": True,52
"user_agent": (53
"Mozilla/5.0 (Linux; Android 14; Pixel 7) AppleWebKit/537.36 "54
"(KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36"55
),56
"input": "touch",57
}58
IOS = {59
"name": "ios-touch",60
"viewport": {"width": 390, "height": 844},61
"device_scale_factor": 2,62
"is_mobile": True,63
"has_touch": True,64
"user_agent": (65
"Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) "66
"AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 "67
"Mobile/15E148 Safari/604.1"68
),69
"input": "touch",70
}71
72
FAILURES = []73
URL = None74
75
76
def free_port():77
s = socket.socket()78
s.bind(("127.0.0.1", 0))79
port = s.getsockname()[1]80
s.close()81
return port82
83
84
def field_to_client(page, col, field_y):85
return page.evaluate(86
"""([col, fieldY]) => {87
const c = app.scene.canvas;88
const r = c.getBoundingClientRect();89
const w = Planet.FIELD_WIDTH;90
const h = Planet.FIELD_HEIGHT;91
return {92
x: r.left + ((col + 0.5) / w) * r.width,93
y: r.top + (1 - fieldY / h) * r.height94
};95
}""",96
[col, field_y],97
)98
99
100
def touch_start(cdp, x, y):101
cdp.send(102
"Input.dispatchTouchEvent",103
{"type": "touchStart", "touchPoints": [{"x": x, "y": y, "id": 1}]},104
)105
106
107
def touch_move(cdp, x, y):108
cdp.send(109
"Input.dispatchTouchEvent",110
{"type": "touchMove", "touchPoints": [{"x": x, "y": y, "id": 1}]},111
)112
113
114
def touch_end(cdp):115
cdp.send("Input.dispatchTouchEvent", {"type": "touchEnd", "touchPoints": []})116
117
118
def pointer_down(page, cdp, kind, x, y):119
if kind == "mouse":120
page.mouse.move(x, y)121
page.mouse.down()122
else:123
touch_start(cdp, x, y)124
125
126
def pointer_move(page, cdp, kind, x, y):127
if kind == "mouse":128
page.mouse.move(x, y)129
else:130
touch_move(cdp, x, y)131
132
133
def pointer_up(page, cdp, kind):134
if kind == "mouse":135
page.mouse.up()136
else:137
touch_end(cdp)138
139
140
def drag_to(page, cdp, kind, x1, y1, x2, y2, steps=12, end=True):141
pointer_down(page, cdp, kind, x1, y1)142
for i in range(1, steps + 1):143
t = i / steps144
pointer_move(page, cdp, kind, x1 + (x2 - x1) * t, y1 + (y2 - y1) * t)145
if end:146
pointer_up(page, cdp, kind)147
148
149
def reset_board(page, stacks):150
page.evaluate(151
"""(stacks) => {152
const g = app.core;153
g.spawnInterval = 1e9;154
g.spawnTimer = 0;155
g.blocks.length = 0;156
g.clusters = Object.create(null);157
g.score = 0;158
g.drag = null;159
g.state = 'playing';160
g.nextBlockId = 1;161
g.nextClusterId = 1;162
app.selectTween = null;163
for (const [col, colors] of Object.entries(stacks)) {164
colors.forEach((color, row) => g.place(+col, row, color));165
}166
}""",167
stacks,168
)169
page.wait_for_timeout(80)170
171
172
def board(page):173
return page.evaluate(174
"""() => app.core.blocks.map((b) => ({175
id: b.id, col: b.col, y: b.y, color: b.color, state: b.state176
}))"""177
)178
179
180
def col_ys(page, col):181
return {b["color"]: b["y"] for b in board(page) if b["col"] == col}182
183
184
def check(cond, msg, device):185
if not cond:186
FAILURES.append(f"[{device}] {msg}")187
print(f"FAIL [{device}] {msg}")188
else:189
print(f"OK [{device}] {msg}")190
return cond191
192
193
def shot(page, name):194
path = OUT / name195
page.screenshot(path=str(path), full_page=False)196
print(f"wrote {path} ({path.stat().st_size} bytes)")197
198
199
def start_play(page, kind):200
page.goto(URL, wait_until="networkidle", timeout=20000)201
page.wait_for_timeout(400)202
btn = page.locator("#btn-play")203
btn.wait_for(state="visible", timeout=5000)204
if kind == "touch":205
box = btn.bounding_box()206
cdp = page.context.new_cdp_session(page)207
touch_start(cdp, box["x"] + box["width"] / 2, box["y"] + box["height"] / 2)208
touch_end(cdp)209
page.wait_for_timeout(400)210
else:211
cdp = None212
btn.click()213
page.wait_for_timeout(400)214
if page.evaluate("() => app && app.mode") == "planet-select":215
go = page.locator("#btn-planet-go")216
go.wait_for(state="visible", timeout=5000)217
go.click()218
page.wait_for_timeout(400)219
if page.evaluate("() => app.mode") != "playing":220
if page.locator("#btn-play").is_visible():221
page.locator("#btn-play").click()222
page.wait_for_timeout(400)223
if page.locator("#btn-planet-go").is_visible():224
page.locator("#btn-planet-go").click()225
page.wait_for_timeout(400)226
page.wait_for_function("() => app && app.mode === 'playing' && app.core && app.scene", timeout=8000)227
page.wait_for_selector("canvas", state="visible", timeout=5000)228
if cdp is None:229
cdp = page.context.new_cdp_session(page)230
return cdp231
232
233
def nearly(a, b, eps=0.15):234
return abs(a - b) <= eps235
236
237
def run_device(browser, device):238
name = device["name"]239
kind = device["input"]240
print(f"\n======== {name} ({kind}, dpr={device['device_scale_factor']}) ========")241
kw = dict(242
viewport=device["viewport"],243
device_scale_factor=device["device_scale_factor"],244
is_mobile=device["is_mobile"],245
has_touch=device["has_touch"],246
)247
if device["user_agent"]:248
kw["user_agent"] = device["user_agent"]249
context = browser.new_context(**kw)250
page = context.new_page()251
bag = []252
page.on("console", lambda m: bag.append(f"{m.type}: {m.text}"))253
page.on("pageerror", lambda e: bag.append(f"pageerror: {e}"))254
cdp = start_play(page, kind)255
check(page.evaluate("() => app.mode") == "playing", "play started", name)256
257
# --- 1 tile down ---258
reset_board(page, {"2": [0, 1, 2, 3, 4]})259
p0 = field_to_client(page, 2, 1.5)260
p1 = field_to_client(page, 2, 0.5)261
drag_to(page, cdp, kind, p0["x"], p0["y"], p1["x"], p1["y"], steps=10, end=True)262
page.wait_for_timeout(60)263
ys = col_ys(page, 2)264
check(nearly(ys.get(1, -99), 0), f"1 tile down: grabbed color 1 at y=0, ys={ys}", name)265
check(nearly(ys.get(0, -99), 1), f"1 tile down: swapped neighbour to y=1, ys={ys}", name)266
check(nearly(ys.get(2, -99), 2) and nearly(ys.get(3, -99), 3) and nearly(ys.get(4, -99), 4),267
f"1 tile down: rest of the stack unmoved, ys={ys}", name)268
269
# --- 1 tile up ---270
reset_board(page, {"3": [0, 1, 2, 3, 4]})271
p0 = field_to_client(page, 3, 0.5)272
p1 = field_to_client(page, 3, 1.5)273
drag_to(page, cdp, kind, p0["x"], p0["y"], p1["x"], p1["y"], steps=10, end=True)274
page.wait_for_timeout(60)275
ys = col_ys(page, 3)276
check(nearly(ys.get(0, -99), 1), f"1 tile up: grabbed color 0 at y=1, ys={ys}", name)277
check(nearly(ys.get(1, -99), 0), f"1 tile up: neighbour at y=0, ys={ys}", name)278
check(nearly(ys.get(2, -99), 2), f"1 tile up: rest unmoved, ys={ys}", name)279
280
# --- 2 tiles, then stop: pointer held still, nothing else moves ---281
reset_board(page, {"4": [0, 1, 2, 3, 4]})282
p0 = field_to_client(page, 4, 0.5)283
p1 = field_to_client(page, 4, 2.5)284
drag_to(page, cdp, kind, p0["x"], p0["y"], p1["x"], p1["y"], steps=14, end=False)285
page.wait_for_timeout(50)286
mid = col_ys(page, 4)287
check(nearly(mid.get(0, -99), 2), f"2 tiles: grabbed color 0 at y=2, ys={mid}", name)288
check(nearly(mid.get(1, -99), 0) and nearly(mid.get(2, -99), 1) and nearly(mid.get(3, -99), 3),289
f"2 tiles: walked both neighbours, ys={mid}", name)290
# Pointer stops: more moves at the same point, then a short wait.291
for _ in range(6):292
pointer_move(page, cdp, kind, p1["x"], p1["y"])293
page.wait_for_timeout(30)294
after = col_ys(page, 4)295
check(after == mid, f"pointer stopped: stack stays put, mid={mid} after={after}", name)296
pointer_up(page, cdp, kind)297
page.wait_for_timeout(80)298
end = col_ys(page, 4)299
check(end == mid, f"after release: still at the pointer row, mid={mid} end={end}", name)300
shot(page, f"t1104-drag-{name}.png")301
302
if bag:303
print(f"console [{name}]: {bag[:8]}")304
context.close()305
306
307
def main():308
global URL309
port = free_port()310
URL = f"http://127.0.0.1:{port}/"311
print("serving", URL, "from", ROOT / "build")312
httpd = subprocess.Popen(313
["python3", "-m", "http.server", str(port), "--bind", "127.0.0.1", "--directory", str(ROOT / "build")],314
stdout=subprocess.DEVNULL,315
stderr=subprocess.DEVNULL,316
)317
try:318
time.sleep(0.4)319
with sync_playwright() as p:320
browser = p.chromium.launch(321
executable_path=CHROME,322
args=CHROME_ARGS,323
headless=True,324
)325
for device in (DESKTOP, ANDROID, ANDROID_DPR3, IOS):326
run_device(browser, device)327
browser.close()328
finally:329
httpd.terminate()330
try:331
httpd.wait(timeout=3)332
except Exception:333
httpd.kill()334
335
print("\n======== summary ========")336
if FAILURES:337
print(f"{len(FAILURES)} failure(s):")338
for f in FAILURES:339
print(" -", f)340
return 1341
print("all 1:1 drag tests passed")342
return 0343
344
345
if __name__ == "__main__":346
sys.exit(main())@@ -96,11 +96,11 @@ def run_desktop(browser):
96
96
# Numeric stats, no long explanation — Terra mid values.
97
97
terra = next(t for t in texts if t.startswith("Terra"))
98
98
check("Terrans" in terra, "Terra people name")
99
check("g 9.81" in terra and "d 1.05" in terra and "F 104 N" in terra and "Power 48%" in terra,
99
check("g 9.81" in terra and "d 1.05" in terra and "F 104 N" in terra and "Power 44%" in terra,
100
100
"Terra numeric stats on the card")
101
101
cinder = next(t for t in texts if t.startswith("Cinder"))
102
check("Cindari" in cinder and "Power 100%" in cinder and "g 19.62" in cinder,
103
"Cinder is the hardest (Power 100%)")
102
check("Cindari" in cinder and "Power 92%" in cinder and "g 19.62" in cinder,
103
"Cinder is the hardest (Power 92%)")
104
104
aurel = next(t for t in texts if t.startswith("Aurel"))
105
105
check("Aurelians" in aurel and "Power 0%" in aurel, "Aurel is the easiest (Power 0%)")
106
106
# Each card has 5 unique placeholder images.
@@ -125,7 +125,7 @@ def run_desktop(browser):
125
125
print("HUD", hud)
126
126
check(hud["id"] == "cinder" and "Cinder" in hud["name"] and "Cindari" in hud["name"],
127
127
"HUD shows Cinder · Cindari")
128
check("Power 100%" in hud["stats"] and "g 19.62" in hud["stats"], "HUD shows Cinder numbers")
128
check("Power 92%" in hud["stats"] and "g 19.62" in hud["stats"], "HUD shows Cinder numbers")
129
129
check(abs(hud["miss"] - 0.05) < 1e-9, "GameCore missChance is Cinder's 5%")
130
130
shot(page, "stage3-play-cinder-desktop.png")
131
131
ctx.close()
@@ -96,11 +96,11 @@ def run_desktop(browser):96
# Numeric stats, no long explanation — Terra mid values.96
# Numeric stats, no long explanation — Terra mid values.97
terra = next(t for t in texts if t.startswith("Terra"))97
terra = next(t for t in texts if t.startswith("Terra"))98
check("Terrans" in terra, "Terra people name")98
check("Terrans" in terra, "Terra people name")99
check("g 9.81" in terra and "d 1.05" in terra and "F 104 N" in terra and "Power 48%" in terra,99
check("g 9.81" in terra and "d 1.05" in terra and "F 104 N" in terra and "Power 44%" in terra,100
"Terra numeric stats on the card")100
"Terra numeric stats on the card")101
cinder = next(t for t in texts if t.startswith("Cinder"))101
cinder = next(t for t in texts if t.startswith("Cinder"))102
check("Cindari" in cinder and "Power 100%" in cinder and "g 19.62" in cinder,102
check("Cindari" in cinder and "Power 92%" in cinder and "g 19.62" in cinder,103
"Cinder is the hardest (Power 100%)")103
"Cinder is the hardest (Power 92%)")104
aurel = next(t for t in texts if t.startswith("Aurel"))104
aurel = next(t for t in texts if t.startswith("Aurel"))105
check("Aurelians" in aurel and "Power 0%" in aurel, "Aurel is the easiest (Power 0%)")105
check("Aurelians" in aurel and "Power 0%" in aurel, "Aurel is the easiest (Power 0%)")106
# Each card has 5 unique placeholder images.106
# Each card has 5 unique placeholder images.@@ -125,7 +125,7 @@ def run_desktop(browser):125
print("HUD", hud)125
print("HUD", hud)126
check(hud["id"] == "cinder" and "Cinder" in hud["name"] and "Cindari" in hud["name"],126
check(hud["id"] == "cinder" and "Cinder" in hud["name"] and "Cindari" in hud["name"],127
"HUD shows Cinder · Cindari")127
"HUD shows Cinder · Cindari")128
check("Power 100%" in hud["stats"] and "g 19.62" in hud["stats"], "HUD shows Cinder numbers")128
check("Power 92%" in hud["stats"] and "g 19.62" in hud["stats"], "HUD shows Cinder numbers")129
check(abs(hud["miss"] - 0.05) < 1e-9, "GameCore missChance is Cinder's 5%")129
check(abs(hud["miss"] - 0.05) < 1e-9, "GameCore missChance is Cinder's 5%")130
shot(page, "stage3-play-cinder-desktop.png")130
shot(page, "stage3-play-cinder-desktop.png")131
ctx.close()131
ctx.close()@@ -156,6 +156,29 @@ describe('Power and display values', () =>
156
156
// Mid-range Terra (jumps=2) shows Earth-like 9.81
157
157
assert.ok(Math.abs(d.gravity - 9.81) < 1e-9);
158
158
});
159
160
it('displayed Power is 1 − missChance / 0.60, so 0% miss shows as 100% Power', () =>
161
{
162
const easy = Planet.createPlanet({ jumpsToClear: 1, fallTime: 5, riseTime: 3 });
163
const hard = Planet.createPlanet({ jumpsToClear: 4, fallTime: 1, riseTime: 0.5 });
164
const terra = Planet.defaultPlanet();
165
// 60% miss → 0% Power; 5% miss → 92% (not 100 — the floor is 5%, not 0).
166
assert.equal(Planet.displayPower(easy), 0);
167
assert.equal(Planet.displayValues(easy).power, 0);
168
assert.equal(Planet.displayPower(hard), Math.round((1 - 0.05 / 0.60) * 100));
169
assert.equal(Planet.displayPower(hard), 92);
170
const terraMiss = Planet.missChance(terra);
171
assert.equal(Planet.displayPower(terra), Math.round((1 - terraMiss / 0.60) * 100));
172
assert.equal(Planet.displayValues(terra).power, 44);
173
// Gameplay power() and missChance() are unchanged.
174
assert.equal(Planet.power(easy), 0);
175
assert.ok(Math.abs(Planet.power(hard) - 1) < 1e-12);
176
assert.equal(Planet.missChance(easy), 0.60);
177
assert.ok(Math.abs(Planet.missChance(hard) - 0.05) < 1e-12);
178
// Monotonic: a lower miss chance means a higher displayed Power.
179
assert.ok(Planet.displayPower(hard) > Planet.displayPower(terra));
180
assert.ok(Planet.displayPower(terra) > Planet.displayPower(easy));
181
});
159
182
});
160
183
161
184
describe('Planet catalog', () =>
@@ -189,7 +212,7 @@ describe('Planet catalog', () =>
189
212
assert.equal(Planet.planetById('cinder').name, 'Cinder');
190
213
});
191
214
192
it('Aurel is the easiest (Power 0, 60% miss) and Cinder the hardest (Power 1, 5% miss)', () =>
215
it('Aurel is the easiest (gameplay Power 0, 60% miss, shown as 0%) and Cinder the hardest (gameplay Power 1, 5% miss, shown as 92%)', () =>
193
216
{
194
217
const aurel = Planet.planetById('aurel');
195
218
const cinder = Planet.planetById('cinder');
@@ -198,6 +221,6 @@ describe('Planet catalog', () =>
198
221
assert.ok(Math.abs(Planet.power(cinder) - 1) < 1e-12);
199
222
assert.ok(Math.abs(Planet.missChance(cinder) - 0.05) < 1e-12);
200
223
assert.equal(Planet.displayValues(aurel).power, 0);
201
assert.equal(Planet.displayValues(cinder).power, 100);
224
assert.equal(Planet.displayValues(cinder).power, 92);
202
225
});
203
226
});
@@ -156,6 +156,29 @@ describe('Power and display values', () =>156
// Mid-range Terra (jumps=2) shows Earth-like 9.81156
// Mid-range Terra (jumps=2) shows Earth-like 9.81157
assert.ok(Math.abs(d.gravity - 9.81) < 1e-9);157
assert.ok(Math.abs(d.gravity - 9.81) < 1e-9);158
});158
});159
160
it('displayed Power is 1 − missChance / 0.60, so 0% miss shows as 100% Power', () =>161
{162
const easy = Planet.createPlanet({ jumpsToClear: 1, fallTime: 5, riseTime: 3 });163
const hard = Planet.createPlanet({ jumpsToClear: 4, fallTime: 1, riseTime: 0.5 });164
const terra = Planet.defaultPlanet();165
// 60% miss → 0% Power; 5% miss → 92% (not 100 — the floor is 5%, not 0).166
assert.equal(Planet.displayPower(easy), 0);167
assert.equal(Planet.displayValues(easy).power, 0);168
assert.equal(Planet.displayPower(hard), Math.round((1 - 0.05 / 0.60) * 100));169
assert.equal(Planet.displayPower(hard), 92);170
const terraMiss = Planet.missChance(terra);171
assert.equal(Planet.displayPower(terra), Math.round((1 - terraMiss / 0.60) * 100));172
assert.equal(Planet.displayValues(terra).power, 44);173
// Gameplay power() and missChance() are unchanged.174
assert.equal(Planet.power(easy), 0);175
assert.ok(Math.abs(Planet.power(hard) - 1) < 1e-12);176
assert.equal(Planet.missChance(easy), 0.60);177
assert.ok(Math.abs(Planet.missChance(hard) - 0.05) < 1e-12);178
// Monotonic: a lower miss chance means a higher displayed Power.179
assert.ok(Planet.displayPower(hard) > Planet.displayPower(terra));180
assert.ok(Planet.displayPower(terra) > Planet.displayPower(easy));181
});159
});182
});160
183
161
describe('Planet catalog', () =>184
describe('Planet catalog', () =>@@ -189,7 +212,7 @@ describe('Planet catalog', () =>189
assert.equal(Planet.planetById('cinder').name, 'Cinder');212
assert.equal(Planet.planetById('cinder').name, 'Cinder');190
});213
});191
214
192
it('Aurel is the easiest (Power 0, 60% miss) and Cinder the hardest (Power 1, 5% miss)', () =>215
it('Aurel is the easiest (gameplay Power 0, 60% miss, shown as 0%) and Cinder the hardest (gameplay Power 1, 5% miss, shown as 92%)', () =>193
{216
{194
const aurel = Planet.planetById('aurel');217
const aurel = Planet.planetById('aurel');195
const cinder = Planet.planetById('cinder');218
const cinder = Planet.planetById('cinder');@@ -198,6 +221,6 @@ describe('Planet catalog', () =>198
assert.ok(Math.abs(Planet.power(cinder) - 1) < 1e-12);221
assert.ok(Math.abs(Planet.power(cinder) - 1) < 1e-12);199
assert.ok(Math.abs(Planet.missChance(cinder) - 0.05) < 1e-12);222
assert.ok(Math.abs(Planet.missChance(cinder) - 0.05) < 1e-12);200
assert.equal(Planet.displayValues(aurel).power, 0);223
assert.equal(Planet.displayValues(aurel).power, 0);201
assert.equal(Planet.displayValues(cinder).power, 100);224
assert.equal(Planet.displayValues(cinder).power, 92);202
});225
});203
});226
});@@ -0,0 +1,149 @@
1
'use strict';
2
3
const { describe, it } = require('node:test');
4
const assert = require('node:assert/strict');
5
const { makeGame, placeRow, almost, GameCore, Planet } = require('./helpers.js');
6
7
function flyingCluster (game, colsAndY, opts)
8
{
9
opts = opts || {};
10
const cluster = {
11
id: game.nextClusterId++,
12
jumpHeight: opts.jumpHeight != null ? opts.jumpHeight : 3,
13
vy: opts.vy != null ? opts.vy : 4,
14
decel: opts.decel != null ? opts.decel : 2,
15
phase: opts.phase || (opts.vy > 0 ? 'up' : 'down')
16
};
17
game.clusters[cluster.id] = cluster;
18
const members = [];
19
for (const [col, y, color] of colsAndY)
20
{
21
const b = game.createBlock(col, y, color == null ? GameCore.COLOR_GRAY : color, 'flying');
22
b.clusterId = cluster.id;
23
b.vy = cluster.vy;
24
b.flame = color == null || color === GameCore.COLOR_GRAY;
25
members.push(b);
26
}
27
return { cluster, members };
28
}
29
30
describe('Spontaneous matches always become rockets (t1104)', () =>
31
{
32
it('a row that forms on the ground after a block falls launches like a player match', () =>
33
{
34
const g = makeGame({ noSpawn: true, planetOpts: { jumpsToClear: 2, fallTime: 3, riseTime: 1.5 } });
35
g.place(0, 0, 1);
36
g.place(1, 0, 1);
37
const falling = g.createBlock(2, 6, 1, 'falling');
38
falling.vy = -g.planet.fallSpeed;
39
let launched = false;
40
for (let i = 0; i < 800; i++)
41
{
42
g.tick(1 / 120);
43
const cluster = Object.values(g.clusters).find((c) => c.phase === 'up');
44
if (cluster && falling.color === GameCore.COLOR_GRAY)
45
{
46
launched = true;
47
break;
48
}
49
}
50
assert.ok(launched, 'falling block completing a ground row must become a rocket\n' + g.snapshot().picture);
51
assert.equal(g.blocks.filter((b) => b.color === GameCore.COLOR_GRAY).length, 3);
52
const cluster = Object.values(g.clusters).find((c) => c.phase === 'up');
53
assert.ok(cluster.vy > 0);
54
const expectedH = Planet.jumpHeight(g.planet, 3, false);
55
assert.ok(almost(cluster.jumpHeight, expectedH, 1e-9), 'jumpHeight=' + cluster.jumpHeight);
56
});
57
58
it('a row that appears after grey settle and recolor launches', () =>
59
{
60
const g = makeGame({ noSpawn: true, planetOpts: { jumpsToClear: 2, fallTime: 3, riseTime: 1.5 }, seed: 1 });
61
// Non-matching supports so only the recolored greys form a line.
62
g.place(0, 0, 4);
63
g.place(1, 0, 3);
64
g.place(2, 0, 2);
65
const greys = placeRow(g, 1, [0, 1, 2], GameCore.COLOR_GRAY);
66
for (const b of greys)
67
{
68
b.state = 'settling';
69
b.settleTime = 0;
70
b.flame = false;
71
}
72
g.randomColor = () => 0;
73
g.step(g.settleTime + 0.05, 1 / 120);
74
const cluster = Object.values(g.clusters).find((c) => c.phase === 'up');
75
assert.ok(cluster, 'recolored grounded row must launch\n' + g.snapshot().picture
76
+ '\nblocks=' + JSON.stringify(g.blocks.map((b) => ({ col: b.col, y: b.y, color: b.color, state: b.state }))));
77
assert.ok(cluster.vy > 0);
78
assert.ok(g.blocks.filter((b) => b.color === GameCore.COLOR_GRAY && b.flame).length >= 3);
79
});
80
81
it('a match after cargo attaches to a flying cluster greys the new line and re-launches the whole cluster', () =>
82
{
83
const g = makeGame({ noSpawn: true, planetOpts: { jumpsToClear: 2, fallTime: 3, riseTime: 1.5 } });
84
// Two color-1 blocks at y=6 with a platform in the gap column, plus a
85
// distant grey so the original cluster is already flying.
86
const { cluster, members } = flyingCluster(g, [
87
[0, 6, 1],
88
[1, 5, 2],
89
[2, 6, 1],
90
[4, 6, GameCore.COLOR_GRAY]
91
], { vy: 2, decel: 0, jumpHeight: 4, phase: 'up' });
92
const originalHeight = cluster.jumpHeight;
93
const originalVy = cluster.vy;
94
const falling = g.createBlock(1, 10, 1, 'falling');
95
falling.vy = -g.planet.fallSpeed;
96
let relaunched = false;
97
for (let i = 0; i < 800; i++)
98
{
99
g.tick(1 / 120);
100
if (falling.clusterId === cluster.id
101
&& falling.color === GameCore.COLOR_GRAY
102
&& cluster.phase === 'up'
103
&& cluster.vy > originalVy + 0.5)
104
{
105
relaunched = true;
106
break;
107
}
108
}
109
assert.ok(relaunched, 'cargo completing a flying row must re-launch, falling.color='
110
+ falling.color + ' state=' + falling.state + ' clusterId=' + falling.clusterId
111
+ ' phase=' + cluster.phase + ' vy=' + cluster.vy + '\n' + g.snapshot().picture);
112
assert.equal(members[0].color, GameCore.COLOR_GRAY);
113
assert.equal(members[2].color, GameCore.COLOR_GRAY);
114
assert.equal(falling.color, GameCore.COLOR_GRAY);
115
assert.equal(falling.clusterId, cluster.id);
116
assert.equal(members[3].clusterId, cluster.id, 'existing grey stays linked');
117
assert.equal(cluster.jumpHeight, originalHeight, 'same height as the player-push re-launch');
118
assert.ok(cluster.vy > 0);
119
});
120
121
it('a match that appears when two flying clusters merge greys the line and re-launches', () =>
122
{
123
const g = makeGame({ noSpawn: true, planetOpts: { jumpsToClear: 2, fallTime: 3, riseTime: 1.5 } });
124
const a = flyingCluster(g, [
125
[0, 6, 1],
126
[1, 6, 1],
127
[3, 6, GameCore.COLOR_GRAY]
128
], { vy: 5, decel: 2, jumpHeight: 4, phase: 'up' });
129
const b = flyingCluster(g, [
130
[3, 6.4, GameCore.COLOR_GRAY],
131
[2, 6.1, 1]
132
], { vy: 1, decel: 2, jumpHeight: 3, phase: 'up' });
133
assert.ok(a.cluster.id !== b.cluster.id);
134
const keepId = Math.min(a.cluster.id, b.cluster.id);
135
136
g.mergeFlyingClusters();
137
138
const merged = g.clusters[keepId] || Object.values(g.clusters)[0];
139
assert.ok(merged, 'clusters should have merged');
140
const color1 = g.blocks.filter((bl) => bl.col <= 2);
141
assert.ok(color1.every((bl) => bl.color === GameCore.COLOR_GRAY),
142
'the completed row must have turned grey: ' + color1.map((bl) => bl.color).join(','));
143
assert.ok(color1.every((bl) => bl.clusterId === merged.id));
144
assert.equal(merged.phase, 'up');
145
assert.ok(merged.vy > 1, 're-launched from the current position, vy=' + merged.vy);
146
const expectedVy = Planet.launchVelocity(g.planet, merged.jumpHeight);
147
assert.ok(almost(merged.vy, expectedVy, 0.15), 'vy=' + merged.vy + ' expected ' + expectedVy);
148
});
149
});
@@ -0,0 +1,149 @@1
'use strict';2
3
const { describe, it } = require('node:test');4
const assert = require('node:assert/strict');5
const { makeGame, placeRow, almost, GameCore, Planet } = require('./helpers.js');6
7
function flyingCluster (game, colsAndY, opts)8
{9
opts = opts || {};10
const cluster = {11
id: game.nextClusterId++,12
jumpHeight: opts.jumpHeight != null ? opts.jumpHeight : 3,13
vy: opts.vy != null ? opts.vy : 4,14
decel: opts.decel != null ? opts.decel : 2,15
phase: opts.phase || (opts.vy > 0 ? 'up' : 'down')16
};17
game.clusters[cluster.id] = cluster;18
const members = [];19
for (const [col, y, color] of colsAndY)20
{21
const b = game.createBlock(col, y, color == null ? GameCore.COLOR_GRAY : color, 'flying');22
b.clusterId = cluster.id;23
b.vy = cluster.vy;24
b.flame = color == null || color === GameCore.COLOR_GRAY;25
members.push(b);26
}27
return { cluster, members };28
}29
30
describe('Spontaneous matches always become rockets (t1104)', () =>31
{32
it('a row that forms on the ground after a block falls launches like a player match', () =>33
{34
const g = makeGame({ noSpawn: true, planetOpts: { jumpsToClear: 2, fallTime: 3, riseTime: 1.5 } });35
g.place(0, 0, 1);36
g.place(1, 0, 1);37
const falling = g.createBlock(2, 6, 1, 'falling');38
falling.vy = -g.planet.fallSpeed;39
let launched = false;40
for (let i = 0; i < 800; i++)41
{42
g.tick(1 / 120);43
const cluster = Object.values(g.clusters).find((c) => c.phase === 'up');44
if (cluster && falling.color === GameCore.COLOR_GRAY)45
{46
launched = true;47
break;48
}49
}50
assert.ok(launched, 'falling block completing a ground row must become a rocket\n' + g.snapshot().picture);51
assert.equal(g.blocks.filter((b) => b.color === GameCore.COLOR_GRAY).length, 3);52
const cluster = Object.values(g.clusters).find((c) => c.phase === 'up');53
assert.ok(cluster.vy > 0);54
const expectedH = Planet.jumpHeight(g.planet, 3, false);55
assert.ok(almost(cluster.jumpHeight, expectedH, 1e-9), 'jumpHeight=' + cluster.jumpHeight);56
});57
58
it('a row that appears after grey settle and recolor launches', () =>59
{60
const g = makeGame({ noSpawn: true, planetOpts: { jumpsToClear: 2, fallTime: 3, riseTime: 1.5 }, seed: 1 });61
// Non-matching supports so only the recolored greys form a line.62
g.place(0, 0, 4);63
g.place(1, 0, 3);64
g.place(2, 0, 2);65
const greys = placeRow(g, 1, [0, 1, 2], GameCore.COLOR_GRAY);66
for (const b of greys)67
{68
b.state = 'settling';69
b.settleTime = 0;70
b.flame = false;71
}72
g.randomColor = () => 0;73
g.step(g.settleTime + 0.05, 1 / 120);74
const cluster = Object.values(g.clusters).find((c) => c.phase === 'up');75
assert.ok(cluster, 'recolored grounded row must launch\n' + g.snapshot().picture76
+ '\nblocks=' + JSON.stringify(g.blocks.map((b) => ({ col: b.col, y: b.y, color: b.color, state: b.state }))));77
assert.ok(cluster.vy > 0);78
assert.ok(g.blocks.filter((b) => b.color === GameCore.COLOR_GRAY && b.flame).length >= 3);79
});80
81
it('a match after cargo attaches to a flying cluster greys the new line and re-launches the whole cluster', () =>82
{83
const g = makeGame({ noSpawn: true, planetOpts: { jumpsToClear: 2, fallTime: 3, riseTime: 1.5 } });84
// Two color-1 blocks at y=6 with a platform in the gap column, plus a85
// distant grey so the original cluster is already flying.86
const { cluster, members } = flyingCluster(g, [87
[0, 6, 1],88
[1, 5, 2],89
[2, 6, 1],90
[4, 6, GameCore.COLOR_GRAY]91
], { vy: 2, decel: 0, jumpHeight: 4, phase: 'up' });92
const originalHeight = cluster.jumpHeight;93
const originalVy = cluster.vy;94
const falling = g.createBlock(1, 10, 1, 'falling');95
falling.vy = -g.planet.fallSpeed;96
let relaunched = false;97
for (let i = 0; i < 800; i++)98
{99
g.tick(1 / 120);100
if (falling.clusterId === cluster.id101
&& falling.color === GameCore.COLOR_GRAY102
&& cluster.phase === 'up'103
&& cluster.vy > originalVy + 0.5)104
{105
relaunched = true;106
break;107
}108
}109
assert.ok(relaunched, 'cargo completing a flying row must re-launch, falling.color='110
+ falling.color + ' state=' + falling.state + ' clusterId=' + falling.clusterId111
+ ' phase=' + cluster.phase + ' vy=' + cluster.vy + '\n' + g.snapshot().picture);112
assert.equal(members[0].color, GameCore.COLOR_GRAY);113
assert.equal(members[2].color, GameCore.COLOR_GRAY);114
assert.equal(falling.color, GameCore.COLOR_GRAY);115
assert.equal(falling.clusterId, cluster.id);116
assert.equal(members[3].clusterId, cluster.id, 'existing grey stays linked');117
assert.equal(cluster.jumpHeight, originalHeight, 'same height as the player-push re-launch');118
assert.ok(cluster.vy > 0);119
});120
121
it('a match that appears when two flying clusters merge greys the line and re-launches', () =>122
{123
const g = makeGame({ noSpawn: true, planetOpts: { jumpsToClear: 2, fallTime: 3, riseTime: 1.5 } });124
const a = flyingCluster(g, [125
[0, 6, 1],126
[1, 6, 1],127
[3, 6, GameCore.COLOR_GRAY]128
], { vy: 5, decel: 2, jumpHeight: 4, phase: 'up' });129
const b = flyingCluster(g, [130
[3, 6.4, GameCore.COLOR_GRAY],131
[2, 6.1, 1]132
], { vy: 1, decel: 2, jumpHeight: 3, phase: 'up' });133
assert.ok(a.cluster.id !== b.cluster.id);134
const keepId = Math.min(a.cluster.id, b.cluster.id);135
136
g.mergeFlyingClusters();137
138
const merged = g.clusters[keepId] || Object.values(g.clusters)[0];139
assert.ok(merged, 'clusters should have merged');140
const color1 = g.blocks.filter((bl) => bl.col <= 2);141
assert.ok(color1.every((bl) => bl.color === GameCore.COLOR_GRAY),142
'the completed row must have turned grey: ' + color1.map((bl) => bl.color).join(','));143
assert.ok(color1.every((bl) => bl.clusterId === merged.id));144
assert.equal(merged.phase, 'up');145
assert.ok(merged.vy > 1, 're-launched from the current position, vy=' + merged.vy);146
const expectedVy = Planet.launchVelocity(g.planet, merged.jumpHeight);147
assert.ok(almost(merged.vy, expectedVy, 0.15), 'vy=' + merged.vy + ' expected ' + expectedVy);148
});149
});@@ -186,7 +186,7 @@ describe('Manual launch of the already-topmost block', () =>
186
186
});
187
187
});
188
188
189
describe('Instant grab, snap and accumulated swaps (t1102/t1103)', () =>
189
describe('Instant grab, snap and 1:1 pointer tracking (t1102/t1103/t1104)', () =>
190
190
{
191
191
it('grabs instantly on beginDrag with no hold delay or elapsed time', () =>
192
192
{
@@ -252,17 +252,76 @@ describe('Instant grab, snap and accumulated swaps (t1102/t1103)', () =>
252
252
assert.equal(g.blockAt(5, 0).color, 3, 'neighbour column is untouched');
253
253
});
254
254
255
it('minimal accumulated travel swaps one step, with no delay before the drag starts', () =>
255
it('a short move that stays inside the same cell does not swap', () =>
256
256
{
257
257
const g = makeGame({ noSpawn: true });
258
258
const a = g.place(0, 0, 0);
259
259
g.place(0, 1, 1);
260
260
g.place(0, 2, 2);
261
261
assert.ok(g.beginDrag(0, 0.5));
262
// Immediately, without ticking, a small upward move of SWAP_DISTANCE swaps once.
262
// Previously SWAP_DISTANCE (0.25) triggered a full-tile jump.
263
263
g.moveDrag(0.5 + GameCore.SWAP_DISTANCE);
264
assert.equal(a.y, 1, 'first swap at the minimal distance, y=' + a.y);
265
assert.ok(g.drag, 'drag is still active');
264
assert.equal(a.y, 0, 'still in the starting cell, y=' + a.y);
265
g.endDrag();
266
});
267
268
it('a 1-tile downward drag swaps exactly one step and stops when the pointer stops', () =>
269
{
270
const g = makeGame({ noSpawn: true });
271
const a = g.place(0, 0, 0);
272
const b = g.place(0, 1, 1);
273
const c = g.place(0, 2, 2);
274
assert.ok(g.beginDrag(0, 1.5));
275
g.moveDrag(0.5);
276
assert.equal(b.y, 0, 'grabbed block followed the pointer one tile down');
277
assert.equal(a.y, 1);
278
assert.equal(c.y, 2);
279
g.moveDrag(0.5);
280
assert.equal(b.y, 0, 'a stopped pointer moves nothing else');
281
assert.equal(a.y, 1);
282
assert.equal(c.y, 2);
283
g.endDrag();
284
});
285
286
it('a 1-tile upward drag swaps exactly one step and stops when the pointer stops', () =>
287
{
288
const g = makeGame({ noSpawn: true });
289
const a = g.place(0, 0, 0);
290
const b = g.place(0, 1, 1);
291
const c = g.place(0, 2, 2);
292
assert.ok(g.beginDrag(0, 0.5));
293
g.moveDrag(1.5);
294
assert.equal(a.y, 1, 'grabbed block followed the pointer one tile up');
295
assert.equal(b.y, 0);
296
assert.equal(c.y, 2);
297
g.moveDrag(1.5);
298
assert.equal(a.y, 1, 'a stopped pointer moves nothing else');
299
assert.equal(b.y, 0);
300
assert.equal(c.y, 2);
301
g.endDrag();
302
});
303
304
it('a 2-tile drag then stop leaves the block on the row under the pointer', () =>
305
{
306
const g = makeGame({ noSpawn: true });
307
const a = g.place(0, 0, 0);
308
const b = g.place(0, 1, 1);
309
const c = g.place(0, 2, 2);
310
const d = g.place(0, 3, 3);
311
assert.ok(g.beginDrag(0, 0.5));
312
g.moveDrag(2.5);
313
assert.equal(a.y, 2);
314
assert.equal(b.y, 0);
315
assert.equal(c.y, 1);
316
assert.equal(d.y, 3);
317
g.moveDrag(2.5);
318
assert.equal(a.y, 2, 'stopped pointer, no further movement');
319
assert.equal(b.y, 0);
320
assert.equal(c.y, 1);
321
assert.equal(d.y, 3);
322
// A twitch that stays in the same cell also leaves the stack alone.
323
g.moveDrag(2.7);
324
assert.equal(a.y, 2);
266
325
g.endDrag();
267
326
});
268
327
@@ -186,7 +186,7 @@ describe('Manual launch of the already-topmost block', () =>186
});186
});187
});187
});188
188
189
describe('Instant grab, snap and accumulated swaps (t1102/t1103)', () =>189
describe('Instant grab, snap and 1:1 pointer tracking (t1102/t1103/t1104)', () =>190
{190
{191
it('grabs instantly on beginDrag with no hold delay or elapsed time', () =>191
it('grabs instantly on beginDrag with no hold delay or elapsed time', () =>192
{192
{@@ -252,17 +252,76 @@ describe('Instant grab, snap and accumulated swaps (t1102/t1103)', () =>252
assert.equal(g.blockAt(5, 0).color, 3, 'neighbour column is untouched');252
assert.equal(g.blockAt(5, 0).color, 3, 'neighbour column is untouched');253
});253
});254
254
255
it('minimal accumulated travel swaps one step, with no delay before the drag starts', () =>255
it('a short move that stays inside the same cell does not swap', () =>256
{256
{257
const g = makeGame({ noSpawn: true });257
const g = makeGame({ noSpawn: true });258
const a = g.place(0, 0, 0);258
const a = g.place(0, 0, 0);259
g.place(0, 1, 1);259
g.place(0, 1, 1);260
g.place(0, 2, 2);260
g.place(0, 2, 2);261
assert.ok(g.beginDrag(0, 0.5));261
assert.ok(g.beginDrag(0, 0.5));262
// Immediately, without ticking, a small upward move of SWAP_DISTANCE swaps once.262
// Previously SWAP_DISTANCE (0.25) triggered a full-tile jump.263
g.moveDrag(0.5 + GameCore.SWAP_DISTANCE);263
g.moveDrag(0.5 + GameCore.SWAP_DISTANCE);264
assert.equal(a.y, 1, 'first swap at the minimal distance, y=' + a.y);264
assert.equal(a.y, 0, 'still in the starting cell, y=' + a.y);265
assert.ok(g.drag, 'drag is still active');265
g.endDrag();266
});267
268
it('a 1-tile downward drag swaps exactly one step and stops when the pointer stops', () =>269
{270
const g = makeGame({ noSpawn: true });271
const a = g.place(0, 0, 0);272
const b = g.place(0, 1, 1);273
const c = g.place(0, 2, 2);274
assert.ok(g.beginDrag(0, 1.5));275
g.moveDrag(0.5);276
assert.equal(b.y, 0, 'grabbed block followed the pointer one tile down');277
assert.equal(a.y, 1);278
assert.equal(c.y, 2);279
g.moveDrag(0.5);280
assert.equal(b.y, 0, 'a stopped pointer moves nothing else');281
assert.equal(a.y, 1);282
assert.equal(c.y, 2);283
g.endDrag();284
});285
286
it('a 1-tile upward drag swaps exactly one step and stops when the pointer stops', () =>287
{288
const g = makeGame({ noSpawn: true });289
const a = g.place(0, 0, 0);290
const b = g.place(0, 1, 1);291
const c = g.place(0, 2, 2);292
assert.ok(g.beginDrag(0, 0.5));293
g.moveDrag(1.5);294
assert.equal(a.y, 1, 'grabbed block followed the pointer one tile up');295
assert.equal(b.y, 0);296
assert.equal(c.y, 2);297
g.moveDrag(1.5);298
assert.equal(a.y, 1, 'a stopped pointer moves nothing else');299
assert.equal(b.y, 0);300
assert.equal(c.y, 2);301
g.endDrag();302
});303
304
it('a 2-tile drag then stop leaves the block on the row under the pointer', () =>305
{306
const g = makeGame({ noSpawn: true });307
const a = g.place(0, 0, 0);308
const b = g.place(0, 1, 1);309
const c = g.place(0, 2, 2);310
const d = g.place(0, 3, 3);311
assert.ok(g.beginDrag(0, 0.5));312
g.moveDrag(2.5);313
assert.equal(a.y, 2);314
assert.equal(b.y, 0);315
assert.equal(c.y, 1);316
assert.equal(d.y, 3);317
g.moveDrag(2.5);318
assert.equal(a.y, 2, 'stopped pointer, no further movement');319
assert.equal(b.y, 0);320
assert.equal(c.y, 1);321
assert.equal(d.y, 3);322
// A twitch that stays in the same cell also leaves the stack alone.323
g.moveDrag(2.7);324
assert.equal(a.y, 2);266
g.endDrag();325
g.endDrag();267
});326
});268
327
@@ -64,11 +64,11 @@ def field_to_client(page, col, field_y):
64
64
"""([col, fieldY]) => {
65
65
const c = app.scene.canvas;
66
66
const r = c.getBoundingClientRect();
67
const x = (col + 0.5) * app.tile;
68
const y = c.height - fieldY * app.tile;
67
const w = Planet.FIELD_WIDTH;
68
const h = Planet.FIELD_HEIGHT;
69
69
return {
70
x: r.left + x * (r.width / c.width),
71
y: r.top + y * (r.height / c.height)
70
x: r.left + ((col + 0.5) / w) * r.width,
71
y: r.top + (1 - fieldY / h) * r.height
72
72
};
73
73
}""",
74
74
[col, field_y],
@@ -64,11 +64,11 @@ def field_to_client(page, col, field_y):64
"""([col, fieldY]) => {64
"""([col, fieldY]) => {65
const c = app.scene.canvas;65
const c = app.scene.canvas;66
const r = c.getBoundingClientRect();66
const r = c.getBoundingClientRect();67
const x = (col + 0.5) * app.tile;67
const w = Planet.FIELD_WIDTH;68
const y = c.height - fieldY * app.tile;68
const h = Planet.FIELD_HEIGHT;69
return {69
return {70
x: r.left + x * (r.width / c.width),70
x: r.left + ((col + 0.5) / w) * r.width,71
y: r.top + y * (r.height / c.height)71
y: r.top + (1 - fieldY / h) * r.height72
};72
};73
}""",73
}""",74
[col, field_y],74
[col, field_y],