Merge branch 'feature/stage1-t1102'
@@ -390,6 +390,13 @@ var SUBSTEP = 1 / 120;
390
390
var DRAG_LAUNCH_SLACK = 0.65;
391
391
// Upward pull (tiles past the press point) that launches an already-topmost block.
392
392
var LAUNCH_PULL = 0.35;
393
// Minimal accumulated vertical pointer travel (tiles) to swap one step.
394
// No hold delay: the first swap fires as soon as this distance is reached.
395
var SWAP_DISTANCE = 0.25;
396
// Grab a still block if the pointer is at most this far (tiles) from it.
397
var SNAP_Y = 0.65;
398
// Horizontal slop (tiles) for snapping to a neighbouring column on press.
399
var HORIZONTAL_SLOP = 0.35;
393
400
394
401
function UnionFind ()
395
402
{
@@ -440,6 +447,9 @@ function GameCore (planet, rng)
440
447
441
448
GameCore.COLOR_GRAY = COLOR_GRAY;
442
449
GameCore.LAUNCH_PULL = LAUNCH_PULL;
450
GameCore.SWAP_DISTANCE = SWAP_DISTANCE;
451
GameCore.SNAP_Y = SNAP_Y;
452
GameCore.HORIZONTAL_SLOP = HORIZONTAL_SLOP;
443
453
GameCore.STATE_STILL = STATE_STILL;
444
454
GameCore.STATE_FALLING = STATE_FALLING;
445
455
GameCore.STATE_FLYING = STATE_FLYING;
@@ -698,6 +708,21 @@ GameCore.prototype.highestFallingBelow = function (block)
698
708
* Make an unsupported still block start falling from rest, so it eases
699
709
* into fallSpeed under normal gravity. Skips the block being dragged.
700
710
*/
711
/**
712
* Strip leftover launch / manual kinematics so a block that has just
713
* become still or falling starts from rest. Used after a landed grey
714
* cluster recolors, and whenever an unsupported still block drops.
715
*/
716
GameCore.prototype.clearFlightState = function (block)
717
{
718
block.vy = 0;
719
block.flame = false;
720
block.manualPhase = null;
721
block.manualTarget = null;
722
block.manualDecel = 0;
723
block.pushedClusters = null;
724
};
725
701
726
GameCore.prototype.releaseUnsupported = function ()
702
727
{
703
728
for (var i = 0; i < this.blocks.length; i++)
@@ -709,10 +734,9 @@ GameCore.prototype.releaseUnsupported = function ()
709
734
{ continue; }
710
735
if (this.hasSupport(block))
711
736
{ continue; }
712
block.state = STATE_FALLING;
713
block.vy = 0;
714
block.flame = false;
715
737
this.leaveCluster(block);
738
this.clearFlightState(block);
739
block.state = STATE_FALLING;
716
740
}
717
741
};
718
742
@@ -824,6 +848,7 @@ GameCore.prototype.tick = function (dt)
824
848
var step = Math.min(SUBSTEP, left);
825
849
this.integrateFalling(step);
826
850
this.integrateClusters(step);
851
this.mergeFlyingClusters();
827
852
this.integrateManual(step);
828
853
this.cullOffTop();
829
854
left -= step;
@@ -831,6 +856,11 @@ GameCore.prototype.tick = function (dt)
831
856
832
857
this.releaseUnsupported();
833
858
this.advanceSettle(dt);
859
// After a landed grey group is released, blocks that were sitting on
860
// hanging members are still STILL (the earlier pass ran while those
861
// members counted as support). Drop them from rest before matching,
862
// so they cannot form a mid-air match and shoot off the top.
863
this.releaseUnsupported();
834
864
this.advanceBounces(dt);
835
865
if (!this.drag)
836
866
{ this.resolveMatches(); }
@@ -1035,6 +1065,139 @@ GameCore.prototype.integrateClusters = function (dt)
1035
1065
}
1036
1066
};
1037
1067
1068
1069
/**
1070
* If two or more flying clusters overlap in the same column, merge them
1071
* into one cluster. Velocity (and deceleration and jumpHeight) is the
1072
* mass-weighted average by block count. Phase is 'up' when the merged
1073
* vy is positive, otherwise 'down'. Overlapping members in a column
1074
* are packed so the higher one sits flush on the lower.
1075
*/
1076
GameCore.prototype.mergeFlyingClusters = function ()
1077
{
1078
var flying = [];
1079
var ids = Object.keys(this.clusters);
1080
for (var n = 0; n < ids.length; n++)
1081
{
1082
var cluster = this.clusters[ids[n]];
1083
if (!cluster)
1084
{ continue; }
1085
if (cluster.phase === 'landed' || cluster.phase === 'hold')
1086
{ continue; }
1087
flying.push(cluster);
1088
}
1089
if (flying.length < 2)
1090
{ return; }
1091
1092
var uf = new UnionFind();
1093
for (var i = 0; i < flying.length; i++)
1094
{ uf.add(flying[i].id); }
1095
for (var i = 0; i < flying.length; i++)
1096
{
1097
for (var j = i + 1; j < flying.length; j++)
1098
{
1099
if (this.flyingClustersOverlap(flying[i], flying[j]))
1100
{ uf.union(flying[i].id, flying[j].id); }
1101
}
1102
}
1103
1104
var groups = Object.create(null);
1105
for (var i = 0; i < flying.length; i++)
1106
{
1107
var root = uf.find(flying[i].id);
1108
if (!groups[root])
1109
{ groups[root] = []; }
1110
groups[root].push(flying[i]);
1111
}
1112
for (var root in groups)
1113
{
1114
if (groups[root].length >= 2)
1115
{ this.mergeClusterGroup(groups[root]); }
1116
}
1117
};
1118
1119
GameCore.prototype.flyingClustersOverlap = function (a, b)
1120
{
1121
var ma = this.clusterMembers(a.id);
1122
var mb = this.clusterMembers(b.id);
1123
for (var i = 0; i < ma.length; i++)
1124
{
1125
for (var j = 0; j < mb.length; j++)
1126
{
1127
if (ma[i].col !== mb[j].col)
1128
{ continue; }
1129
if (ma[i].y < mb[j].y + 1 - 1e-9 && mb[j].y < ma[i].y + 1 - 1e-9)
1130
{ return true; }
1131
}
1132
}
1133
return false;
1134
};
1135
1136
GameCore.prototype.mergeClusterGroup = function (clusters)
1137
{
1138
clusters.sort(function (a, b) { return a.id - b.id; });
1139
var keep = clusters[0];
1140
var n = 0;
1141
var vySum = 0;
1142
var decelSum = 0;
1143
var hSum = 0;
1144
for (var c = 0; c < clusters.length; c++)
1145
{
1146
var mem = this.clusterMembers(clusters[c].id);
1147
var m = mem.length;
1148
n += m;
1149
vySum += clusters[c].vy * m;
1150
decelSum += (clusters[c].decel || 0) * m;
1151
hSum += (clusters[c].jumpHeight || 0) * m;
1152
}
1153
if (n === 0)
1154
{ return; }
1155
keep.vy = vySum / n;
1156
keep.decel = decelSum / n;
1157
keep.jumpHeight = hSum / n;
1158
keep.phase = keep.vy > 1e-10 ? 'up' : 'down';
1159
for (var c = 0; c < clusters.length; c++)
1160
{
1161
var mem = this.clusterMembers(clusters[c].id);
1162
for (var i = 0; i < mem.length; i++)
1163
{
1164
mem[i].clusterId = keep.id;
1165
mem[i].vy = keep.vy;
1166
mem[i].state = STATE_FLYING;
1167
}
1168
if (clusters[c] !== keep)
1169
{ delete this.clusters[clusters[c].id]; }
1170
}
1171
this.packClusterOverlaps(keep);
1172
if (keep.phase === 'down')
1173
{ this.tryLandCluster(keep, this.clusterMembers(keep.id)); }
1174
};
1175
1176
GameCore.prototype.packClusterOverlaps = function (cluster)
1177
{
1178
var members = this.clusterMembers(cluster.id);
1179
var byCol = Object.create(null);
1180
for (var i = 0; i < members.length; i++)
1181
{
1182
var col = members[i].col;
1183
if (!byCol[col])
1184
{ byCol[col] = []; }
1185
byCol[col].push(members[i]);
1186
}
1187
var cols = Object.keys(byCol);
1188
for (var c = 0; c < cols.length; c++)
1189
{
1190
var list = byCol[cols[c]];
1191
list.sort(function (a, b) { return a.y - b.y; });
1192
for (var i = 1; i < list.length; i++)
1193
{
1194
var minY = list[i - 1].y + 1;
1195
if (list[i].y < minY - 1e-12)
1196
{ list[i].y = minY; }
1197
}
1198
}
1199
};
1200
1038
1201
GameCore.prototype.tryLandCluster = function (cluster, members)
1039
1202
{
1040
1203
if (!members.length)
@@ -1115,22 +1278,16 @@ GameCore.prototype.releaseLandedCluster = function (cluster)
1115
1278
block.color = this.randomColor();
1116
1279
block.settleTime = 0;
1117
1280
}
1118
block.flame = false;
1119
1281
this.leaveCluster(block);
1282
// Always drop leftover launch / manual velocity. A stale upward
1283
// vy here is what sends blocks off the top "very fast" after
1284
// a grey group recolors.
1285
this.clearFlightState(block);
1120
1286
// Support from outside the group (floor or a foreign block). Fellow
1121
1287
// members that will also fall do not count, so a hanging stack
1122
1288
// drops together without the top one staying put.
1123
1289
var supported = this.hasSupportOutside(block, releasing);
1124
if (supported)
1125
{
1126
block.state = STATE_STILL;
1127
block.vy = 0;
1128
}
1129
else
1130
{
1131
block.state = STATE_FALLING;
1132
block.vy = 0;
1133
}
1290
block.state = supported ? STATE_STILL : STATE_FALLING;
1134
1291
}
1135
1292
delete this.clusters[cluster.id];
1136
1293
};
@@ -1382,27 +1539,18 @@ GameCore.prototype.advanceSettle = function (dt)
1382
1539
else
1383
1540
{
1384
1541
this.leaveCluster(block);
1385
if (this.hasSupport(block))
1386
{
1387
block.state = STATE_STILL;
1388
block.vy = 0;
1389
}
1390
else
1391
{
1392
block.state = STATE_FALLING;
1393
block.vy = 0;
1394
}
1542
this.clearFlightState(block);
1543
block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING;
1395
1544
}
1396
1545
}
1397
1546
}
1398
1547
else if (!inLanded)
1399
1548
{
1400
1549
// Coloured settling that is not in a landed cluster (shouldn't
1401
// normally happen): just become still or fall.
1550
// normally happen): just become still or fall, from rest.
1402
1551
this.leaveCluster(block);
1552
this.clearFlightState(block);
1403
1553
block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING;
1404
if (block.state === STATE_FALLING)
1405
{ block.vy = 0; }
1406
1554
}
1407
1555
}
1408
1556
@@ -1723,29 +1871,88 @@ GameCore.prototype.beginDrag = function (col, y)
1723
1871
{
1724
1872
if (this.state !== 'playing')
1725
1873
{ return false; }
1726
col = col | 0;
1727
if (col < 0 || col >= this.width)
1728
{ return false; }
1729
if (!this.isColumnStill(col))
1730
{ return false; }
1731
var row = Math.floor(y + 1e-6);
1732
if (row < 0)
1733
{ return false; }
1734
var block = this.blockAt(col, row);
1735
if (!block || block.state !== STATE_STILL || block.color < 0)
1874
var block = this.snapDragBlock(col, y);
1875
if (!block)
1736
1876
{ return false; }
1737
var top = this.columnStackTopRow(col);
1877
var top = this.columnStackTopRow(block.col);
1738
1878
var startedAsTop = Math.abs(block.y - top) < ALIGN_EPS;
1739
1879
this.drag = {
1740
1880
blockId: block.id,
1741
1881
pointerY: y,
1742
1882
startY: y,
1883
accum: 0,
1743
1884
launchIntent: false,
1744
1885
startedAsTop: startedAsTop
1745
1886
};
1746
1887
return true;
1747
1888
};
1748
1889
1890
/**
1891
* Instant grab: the nearest still, coloured block to (col, y), allowing
1892
* a small vertical miss and a horizontal slop into a neighbouring
1893
* column. `col` may be fractional (pointer x in tiles). No hold delay.
1894
*/
1895
GameCore.prototype.snapDragBlock = function (col, y)
1896
{
1897
var raw = col;
1898
var c0 = Math.floor(raw + 1e-9);
1899
var frac = raw - c0;
1900
var candidates = [];
1901
if (c0 >= 0 && c0 < this.width)
1902
{ candidates.push(c0); }
1903
// Only consult a neighbour when the pointer is actually near the edge
1904
// (a whole-number col, as in unit tests, stays in that column).
1905
if (frac > 1e-9 && frac < HORIZONTAL_SLOP && c0 - 1 >= 0)
1906
{ candidates.push(c0 - 1); }
1907
if (frac > 1 - HORIZONTAL_SLOP && frac < 1 - 1e-9 && c0 + 1 < this.width)
1908
{ candidates.push(c0 + 1); }
1909
1910
var best = null;
1911
var bestDist = Infinity;
1912
for (var c = 0; c < candidates.length; c++)
1913
{
1914
var cc = candidates[c];
1915
if (!this.isColumnStill(cc))
1916
{ continue; }
1917
var list = this.blocksInColumn(cc);
1918
for (var i = 0; i < list.length; i++)
1919
{
1920
var block = list[i];
1921
if (block.state !== STATE_STILL || block.color < 0)
1922
{ continue; }
1923
var dist = this.pointerDistToBlock(block, raw, y);
1924
// Prefer the column the pointer is actually in on a tie.
1925
if (dist < bestDist - 1e-12 || (Math.abs(dist - bestDist) < 1e-12 && cc === c0))
1926
{
1927
bestDist = dist;
1928
best = block;
1929
}
1930
}
1931
}
1932
if (!best || bestDist > SNAP_Y)
1933
{ return null; }
1934
return best;
1935
};
1936
1937
GameCore.prototype.pointerDistToBlock = function (block, col, y)
1938
{
1939
var dx;
1940
if (col >= block.col && col < block.col + 1)
1941
{ dx = 0; }
1942
else if (col < block.col)
1943
{ dx = block.col - col; }
1944
else
1945
{ dx = col - (block.col + 1); }
1946
var dy;
1947
if (y >= block.y && y < block.y + 1)
1948
{ dy = 0; }
1949
else if (y < block.y)
1950
{ dy = block.y - y; }
1951
else
1952
{ dy = y - (block.y + 1); }
1953
return Math.sqrt(dx * dx + dy * dy);
1954
};
1955
1749
1956
GameCore.prototype.moveDrag = function (y)
1750
1957
{
1751
1958
if (!this.drag)
@@ -1761,8 +1968,37 @@ GameCore.prototype.moveDrag = function (y)
1761
1968
this.drag = null;
1762
1969
return;
1763
1970
}
1971
var dy = y - this.drag.pointerY;
1764
1972
this.drag.pointerY = y;
1765
this.swapToward(block, y);
1973
if (this.drag.accum == null)
1974
{ this.drag.accum = 0; }
1975
this.drag.accum += dy;
1976
// One swap per tile of travel, triggered after a minimal SWAP_DISTANCE.
1977
// A single large move (fast swipe) walks every tile; none are skipped.
1978
var guard = 0;
1979
while (guard++ < this.height + 2
1980
&& (this.drag.accum >= SWAP_DISTANCE || this.drag.accum <= -SWAP_DISTANCE))
1981
{
1982
var dir = this.drag.accum > 0 ? 1 : -1;
1983
if (!this.swapOne(block, dir))
1984
{
1985
if (dir > 0)
1986
{ this.drag.accum = Math.min(this.drag.accum, SWAP_DISTANCE - 1e-9); }
1987
else
1988
{ this.drag.accum = Math.max(this.drag.accum, -(SWAP_DISTANCE - 1e-9)); }
1989
break;
1990
}
1991
this.drag.accum -= dir;
1992
// A short move (SWAP_DISTANCE < 1) leaves a negative leftover;
1993
// do not let that immediately swap back the other way.
1994
if ((dir > 0 && this.drag.accum < 0) || (dir < 0 && this.drag.accum > 0))
1995
{ this.drag.accum = 0; }
1996
if (!this.isColumnStill(block.col))
1997
{
1998
this.drag = null;
1999
return;
2000
}
2001
}
1766
2002
var top = this.columnStackTopRow(block.col);
1767
2003
var isTop = Math.abs(block.y - top) < ALIGN_EPS;
1768
2004
if (this.drag.startedAsTop)
@@ -1779,6 +2015,18 @@ GameCore.prototype.moveDrag = function (y)
1779
2015
}
1780
2016
};
1781
2017
2018
/** Swap `block` one tile up (dir=+1) or down (dir=-1). Returns true if swapped. */
2019
GameCore.prototype.swapOne = function (block, dir)
2020
{
2021
var neighbor = this.blockAt(block.col, block.y + dir);
2022
if (neighbor && this.isGrounded(neighbor) && neighbor !== block)
2023
{
2024
this.swapBlocks(block, neighbor);
2025
return true;
2026
}
2027
return false;
2028
};
2029
1782
2030
GameCore.prototype.endDrag = function ()
1783
2031
{
1784
2032
if (!this.drag)
@@ -2362,9 +2610,9 @@ function addWindowPointer ()
2362
2610
{
2363
2611
if (windowListening)
2364
2612
{ return; }
2365
window.addEventListener('pointermove', onPointerMove, true);
2366
window.addEventListener('pointerup', onPointerUp, true);
2367
window.addEventListener('pointercancel', onPointerUp, true);
2613
window.addEventListener('pointermove', onPointerMove, { capture: true, passive: false });
2614
window.addEventListener('pointerup', onPointerUp, { capture: true, passive: false });
2615
window.addEventListener('pointercancel', onPointerUp, { capture: true, passive: false });
2368
2616
windowListening = true;
2369
2617
}
2370
2618
@@ -2372,9 +2620,9 @@ function removeWindowPointer ()
2372
2620
{
2373
2621
if (!windowListening)
2374
2622
{ return; }
2375
window.removeEventListener('pointermove', onPointerMove, true);
2376
window.removeEventListener('pointerup', onPointerUp, true);
2377
window.removeEventListener('pointercancel', onPointerUp, true);
2623
window.removeEventListener('pointermove', onPointerMove, { capture: true });
2624
window.removeEventListener('pointerup', onPointerUp, { capture: true });
2625
window.removeEventListener('pointercancel', onPointerUp, { capture: true });
2378
2626
windowListening = false;
2379
2627
}
2380
2628
@@ -2382,9 +2630,11 @@ function bindPointer (canvas)
2382
2630
{
2383
2631
unbindPointer();
2384
2632
boundCanvas = canvas;
2385
canvas.addEventListener('pointerdown', onPointerDown);
2633
canvas.addEventListener('pointerdown', onPointerDown, { passive: false });
2386
2634
canvas.style.touchAction = 'none';
2387
2635
canvas.style.cursor = 'pointer';
2636
canvas.style.webkitUserSelect = 'none';
2637
canvas.style.userSelect = 'none';
2388
2638
}
2389
2639
2390
2640
function unbindPointer ()
@@ -2406,7 +2656,8 @@ function fieldFromEvent (e)
2406
2656
{ return null; }
2407
2657
var x = (e.clientX - rect.left) * (canvas.width / rect.width);
2408
2658
var y = (e.clientY - rect.top) * (canvas.height / rect.height);
2409
var col = Math.floor(x / app.tile);
2659
// Fractional column so beginDrag can snap across a nearby edge.
2660
var col = x / app.tile;
2410
2661
var fieldY = (canvas.height - y) / app.tile;
2411
2662
return { col: col, y: fieldY };
2412
2663
}
@@ -2424,6 +2675,8 @@ function onPointerDown (e)
2424
2675
catch (err) { /* ignore */ }
2425
2676
addWindowPointer();
2426
2677
var pos = fieldFromEvent(e);
2678
// Instant grab, no long-press or hold delay: the block is taken on
2679
// pointerdown and the click tween starts in the same moment.
2427
2680
if (pos && app.core.beginDrag(pos.col, pos.y) && app.core.drag)
2428
2681
{ startPressTween(app.core.drag.blockId); }
2429
2682
}
@@ -390,6 +390,13 @@ var SUBSTEP = 1 / 120;390
var DRAG_LAUNCH_SLACK = 0.65;390
var DRAG_LAUNCH_SLACK = 0.65;391
// Upward pull (tiles past the press point) that launches an already-topmost block.391
// Upward pull (tiles past the press point) that launches an already-topmost block.392
var LAUNCH_PULL = 0.35;392
var LAUNCH_PULL = 0.35;393
// Minimal accumulated vertical pointer travel (tiles) to swap one step.394
// No hold delay: the first swap fires as soon as this distance is reached.395
var SWAP_DISTANCE = 0.25;396
// Grab a still block if the pointer is at most this far (tiles) from it.397
var SNAP_Y = 0.65;398
// Horizontal slop (tiles) for snapping to a neighbouring column on press.399
var HORIZONTAL_SLOP = 0.35;393
400
394
function UnionFind ()401
function UnionFind ()395
{402
{@@ -440,6 +447,9 @@ function GameCore (planet, rng)440
447
441
GameCore.COLOR_GRAY = COLOR_GRAY;448
GameCore.COLOR_GRAY = COLOR_GRAY;442
GameCore.LAUNCH_PULL = LAUNCH_PULL;449
GameCore.LAUNCH_PULL = LAUNCH_PULL;450
GameCore.SWAP_DISTANCE = SWAP_DISTANCE;451
GameCore.SNAP_Y = SNAP_Y;452
GameCore.HORIZONTAL_SLOP = HORIZONTAL_SLOP;443
GameCore.STATE_STILL = STATE_STILL;453
GameCore.STATE_STILL = STATE_STILL;444
GameCore.STATE_FALLING = STATE_FALLING;454
GameCore.STATE_FALLING = STATE_FALLING;445
GameCore.STATE_FLYING = STATE_FLYING;455
GameCore.STATE_FLYING = STATE_FLYING;@@ -698,6 +708,21 @@ GameCore.prototype.highestFallingBelow = function (block)698
* Make an unsupported still block start falling from rest, so it eases708
* Make an unsupported still block start falling from rest, so it eases699
* into fallSpeed under normal gravity. Skips the block being dragged.709
* into fallSpeed under normal gravity. Skips the block being dragged.700
*/710
*/711
/**712
* Strip leftover launch / manual kinematics so a block that has just713
* become still or falling starts from rest. Used after a landed grey714
* cluster recolors, and whenever an unsupported still block drops.715
*/716
GameCore.prototype.clearFlightState = function (block)717
{718
block.vy = 0;719
block.flame = false;720
block.manualPhase = null;721
block.manualTarget = null;722
block.manualDecel = 0;723
block.pushedClusters = null;724
};725
701
GameCore.prototype.releaseUnsupported = function ()726
GameCore.prototype.releaseUnsupported = function ()702
{727
{703
for (var i = 0; i < this.blocks.length; i++)728
for (var i = 0; i < this.blocks.length; i++)@@ -709,10 +734,9 @@ GameCore.prototype.releaseUnsupported = function ()709
{ continue; }734
{ continue; }710
if (this.hasSupport(block))735
if (this.hasSupport(block))711
{ continue; }736
{ continue; }712
block.state = STATE_FALLING;713
block.vy = 0;714
block.flame = false;715
this.leaveCluster(block);737
this.leaveCluster(block);738
this.clearFlightState(block);739
block.state = STATE_FALLING;716
}740
}717
};741
};718
742
@@ -824,6 +848,7 @@ GameCore.prototype.tick = function (dt)824
var step = Math.min(SUBSTEP, left);848
var step = Math.min(SUBSTEP, left);825
this.integrateFalling(step);849
this.integrateFalling(step);826
this.integrateClusters(step);850
this.integrateClusters(step);851
this.mergeFlyingClusters();827
this.integrateManual(step);852
this.integrateManual(step);828
this.cullOffTop();853
this.cullOffTop();829
left -= step;854
left -= step;@@ -831,6 +856,11 @@ GameCore.prototype.tick = function (dt)831
856
832
this.releaseUnsupported();857
this.releaseUnsupported();833
this.advanceSettle(dt);858
this.advanceSettle(dt);859
// After a landed grey group is released, blocks that were sitting on860
// hanging members are still STILL (the earlier pass ran while those861
// members counted as support). Drop them from rest before matching,862
// so they cannot form a mid-air match and shoot off the top.863
this.releaseUnsupported();834
this.advanceBounces(dt);864
this.advanceBounces(dt);835
if (!this.drag)865
if (!this.drag)836
{ this.resolveMatches(); }866
{ this.resolveMatches(); }@@ -1035,6 +1065,139 @@ GameCore.prototype.integrateClusters = function (dt)1035
}1065
}1036
};1066
};1037
1067
1068
1069
/**1070
* If two or more flying clusters overlap in the same column, merge them1071
* into one cluster. Velocity (and deceleration and jumpHeight) is the1072
* mass-weighted average by block count. Phase is 'up' when the merged1073
* vy is positive, otherwise 'down'. Overlapping members in a column1074
* are packed so the higher one sits flush on the lower.1075
*/1076
GameCore.prototype.mergeFlyingClusters = function ()1077
{1078
var flying = [];1079
var ids = Object.keys(this.clusters);1080
for (var n = 0; n < ids.length; n++)1081
{1082
var cluster = this.clusters[ids[n]];1083
if (!cluster)1084
{ continue; }1085
if (cluster.phase === 'landed' || cluster.phase === 'hold')1086
{ continue; }1087
flying.push(cluster);1088
}1089
if (flying.length < 2)1090
{ return; }1091
1092
var uf = new UnionFind();1093
for (var i = 0; i < flying.length; i++)1094
{ uf.add(flying[i].id); }1095
for (var i = 0; i < flying.length; i++)1096
{1097
for (var j = i + 1; j < flying.length; j++)1098
{1099
if (this.flyingClustersOverlap(flying[i], flying[j]))1100
{ uf.union(flying[i].id, flying[j].id); }1101
}1102
}1103
1104
var groups = Object.create(null);1105
for (var i = 0; i < flying.length; i++)1106
{1107
var root = uf.find(flying[i].id);1108
if (!groups[root])1109
{ groups[root] = []; }1110
groups[root].push(flying[i]);1111
}1112
for (var root in groups)1113
{1114
if (groups[root].length >= 2)1115
{ this.mergeClusterGroup(groups[root]); }1116
}1117
};1118
1119
GameCore.prototype.flyingClustersOverlap = function (a, b)1120
{1121
var ma = this.clusterMembers(a.id);1122
var mb = this.clusterMembers(b.id);1123
for (var i = 0; i < ma.length; i++)1124
{1125
for (var j = 0; j < mb.length; j++)1126
{1127
if (ma[i].col !== mb[j].col)1128
{ continue; }1129
if (ma[i].y < mb[j].y + 1 - 1e-9 && mb[j].y < ma[i].y + 1 - 1e-9)1130
{ return true; }1131
}1132
}1133
return false;1134
};1135
1136
GameCore.prototype.mergeClusterGroup = function (clusters)1137
{1138
clusters.sort(function (a, b) { return a.id - b.id; });1139
var keep = clusters[0];1140
var n = 0;1141
var vySum = 0;1142
var decelSum = 0;1143
var hSum = 0;1144
for (var c = 0; c < clusters.length; c++)1145
{1146
var mem = this.clusterMembers(clusters[c].id);1147
var m = mem.length;1148
n += m;1149
vySum += clusters[c].vy * m;1150
decelSum += (clusters[c].decel || 0) * m;1151
hSum += (clusters[c].jumpHeight || 0) * m;1152
}1153
if (n === 0)1154
{ return; }1155
keep.vy = vySum / n;1156
keep.decel = decelSum / n;1157
keep.jumpHeight = hSum / n;1158
keep.phase = keep.vy > 1e-10 ? 'up' : 'down';1159
for (var c = 0; c < clusters.length; c++)1160
{1161
var mem = this.clusterMembers(clusters[c].id);1162
for (var i = 0; i < mem.length; i++)1163
{1164
mem[i].clusterId = keep.id;1165
mem[i].vy = keep.vy;1166
mem[i].state = STATE_FLYING;1167
}1168
if (clusters[c] !== keep)1169
{ delete this.clusters[clusters[c].id]; }1170
}1171
this.packClusterOverlaps(keep);1172
if (keep.phase === 'down')1173
{ this.tryLandCluster(keep, this.clusterMembers(keep.id)); }1174
};1175
1176
GameCore.prototype.packClusterOverlaps = function (cluster)1177
{1178
var members = this.clusterMembers(cluster.id);1179
var byCol = Object.create(null);1180
for (var i = 0; i < members.length; i++)1181
{1182
var col = members[i].col;1183
if (!byCol[col])1184
{ byCol[col] = []; }1185
byCol[col].push(members[i]);1186
}1187
var cols = Object.keys(byCol);1188
for (var c = 0; c < cols.length; c++)1189
{1190
var list = byCol[cols[c]];1191
list.sort(function (a, b) { return a.y - b.y; });1192
for (var i = 1; i < list.length; i++)1193
{1194
var minY = list[i - 1].y + 1;1195
if (list[i].y < minY - 1e-12)1196
{ list[i].y = minY; }1197
}1198
}1199
};1200
1038
GameCore.prototype.tryLandCluster = function (cluster, members)1201
GameCore.prototype.tryLandCluster = function (cluster, members)1039
{1202
{1040
if (!members.length)1203
if (!members.length)@@ -1115,22 +1278,16 @@ GameCore.prototype.releaseLandedCluster = function (cluster)1115
block.color = this.randomColor();1278
block.color = this.randomColor();1116
block.settleTime = 0;1279
block.settleTime = 0;1117
}1280
}1118
block.flame = false;1119
this.leaveCluster(block);1281
this.leaveCluster(block);1282
// Always drop leftover launch / manual velocity. A stale upward1283
// vy here is what sends blocks off the top "very fast" after1284
// a grey group recolors.1285
this.clearFlightState(block);1120
// Support from outside the group (floor or a foreign block). Fellow1286
// Support from outside the group (floor or a foreign block). Fellow1121
// members that will also fall do not count, so a hanging stack1287
// members that will also fall do not count, so a hanging stack1122
// drops together without the top one staying put.1288
// drops together without the top one staying put.1123
var supported = this.hasSupportOutside(block, releasing);1289
var supported = this.hasSupportOutside(block, releasing);1124
if (supported)1290
block.state = supported ? STATE_STILL : STATE_FALLING;1125
{1126
block.state = STATE_STILL;1127
block.vy = 0;1128
}1129
else1130
{1131
block.state = STATE_FALLING;1132
block.vy = 0;1133
}1134
}1291
}1135
delete this.clusters[cluster.id];1292
delete this.clusters[cluster.id];1136
};1293
};@@ -1382,27 +1539,18 @@ GameCore.prototype.advanceSettle = function (dt)1382
else1539
else1383
{1540
{1384
this.leaveCluster(block);1541
this.leaveCluster(block);1385
if (this.hasSupport(block))1542
this.clearFlightState(block);1386
{1543
block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING;1387
block.state = STATE_STILL;1388
block.vy = 0;1389
}1390
else1391
{1392
block.state = STATE_FALLING;1393
block.vy = 0;1394
}1395
}1544
}1396
}1545
}1397
}1546
}1398
else if (!inLanded)1547
else if (!inLanded)1399
{1548
{1400
// Coloured settling that is not in a landed cluster (shouldn't1549
// Coloured settling that is not in a landed cluster (shouldn't1401
// normally happen): just become still or fall.1550
// normally happen): just become still or fall, from rest.1402
this.leaveCluster(block);1551
this.leaveCluster(block);1552
this.clearFlightState(block);1403
block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING;1553
block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING;1404
if (block.state === STATE_FALLING)1405
{ block.vy = 0; }1406
}1554
}1407
}1555
}1408
1556
@@ -1723,29 +1871,88 @@ GameCore.prototype.beginDrag = function (col, y)1723
{1871
{1724
if (this.state !== 'playing')1872
if (this.state !== 'playing')1725
{ return false; }1873
{ return false; }1726
col = col | 0;1874
var block = this.snapDragBlock(col, y);1727
if (col < 0 || col >= this.width)1875
if (!block)1728
{ return false; }1729
if (!this.isColumnStill(col))1730
{ return false; }1731
var row = Math.floor(y + 1e-6);1732
if (row < 0)1733
{ return false; }1734
var block = this.blockAt(col, row);1735
if (!block || block.state !== STATE_STILL || block.color < 0)1736
{ return false; }1876
{ return false; }1737
var top = this.columnStackTopRow(col);1877
var top = this.columnStackTopRow(block.col);1738
var startedAsTop = Math.abs(block.y - top) < ALIGN_EPS;1878
var startedAsTop = Math.abs(block.y - top) < ALIGN_EPS;1739
this.drag = {1879
this.drag = {1740
blockId: block.id,1880
blockId: block.id,1741
pointerY: y,1881
pointerY: y,1742
startY: y,1882
startY: y,1883
accum: 0,1743
launchIntent: false,1884
launchIntent: false,1744
startedAsTop: startedAsTop1885
startedAsTop: startedAsTop1745
};1886
};1746
return true;1887
return true;1747
};1888
};1748
1889
1890
/**1891
* Instant grab: the nearest still, coloured block to (col, y), allowing1892
* a small vertical miss and a horizontal slop into a neighbouring1893
* column. `col` may be fractional (pointer x in tiles). No hold delay.1894
*/1895
GameCore.prototype.snapDragBlock = function (col, y)1896
{1897
var raw = col;1898
var c0 = Math.floor(raw + 1e-9);1899
var frac = raw - c0;1900
var candidates = [];1901
if (c0 >= 0 && c0 < this.width)1902
{ candidates.push(c0); }1903
// Only consult a neighbour when the pointer is actually near the edge1904
// (a whole-number col, as in unit tests, stays in that column).1905
if (frac > 1e-9 && frac < HORIZONTAL_SLOP && c0 - 1 >= 0)1906
{ candidates.push(c0 - 1); }1907
if (frac > 1 - HORIZONTAL_SLOP && frac < 1 - 1e-9 && c0 + 1 < this.width)1908
{ candidates.push(c0 + 1); }1909
1910
var best = null;1911
var bestDist = Infinity;1912
for (var c = 0; c < candidates.length; c++)1913
{1914
var cc = candidates[c];1915
if (!this.isColumnStill(cc))1916
{ continue; }1917
var list = this.blocksInColumn(cc);1918
for (var i = 0; i < list.length; i++)1919
{1920
var block = list[i];1921
if (block.state !== STATE_STILL || block.color < 0)1922
{ continue; }1923
var dist = this.pointerDistToBlock(block, raw, y);1924
// Prefer the column the pointer is actually in on a tie.1925
if (dist < bestDist - 1e-12 || (Math.abs(dist - bestDist) < 1e-12 && cc === c0))1926
{1927
bestDist = dist;1928
best = block;1929
}1930
}1931
}1932
if (!best || bestDist > SNAP_Y)1933
{ return null; }1934
return best;1935
};1936
1937
GameCore.prototype.pointerDistToBlock = function (block, col, y)1938
{1939
var dx;1940
if (col >= block.col && col < block.col + 1)1941
{ dx = 0; }1942
else if (col < block.col)1943
{ dx = block.col - col; }1944
else1945
{ dx = col - (block.col + 1); }1946
var dy;1947
if (y >= block.y && y < block.y + 1)1948
{ dy = 0; }1949
else if (y < block.y)1950
{ dy = block.y - y; }1951
else1952
{ dy = y - (block.y + 1); }1953
return Math.sqrt(dx * dx + dy * dy);1954
};1955
1749
GameCore.prototype.moveDrag = function (y)1956
GameCore.prototype.moveDrag = function (y)1750
{1957
{1751
if (!this.drag)1958
if (!this.drag)@@ -1761,8 +1968,37 @@ GameCore.prototype.moveDrag = function (y)1761
this.drag = null;1968
this.drag = null;1762
return;1969
return;1763
}1970
}1971
var dy = y - this.drag.pointerY;1764
this.drag.pointerY = y;1972
this.drag.pointerY = y;1765
this.swapToward(block, y);1973
if (this.drag.accum == null)1974
{ this.drag.accum = 0; }1975
this.drag.accum += dy;1976
// One swap per tile of travel, triggered after a minimal SWAP_DISTANCE.1977
// A single large move (fast swipe) walks every tile; none are skipped.1978
var guard = 0;1979
while (guard++ < this.height + 21980
&& (this.drag.accum >= SWAP_DISTANCE || this.drag.accum <= -SWAP_DISTANCE))1981
{1982
var dir = this.drag.accum > 0 ? 1 : -1;1983
if (!this.swapOne(block, dir))1984
{1985
if (dir > 0)1986
{ this.drag.accum = Math.min(this.drag.accum, SWAP_DISTANCE - 1e-9); }1987
else1988
{ this.drag.accum = Math.max(this.drag.accum, -(SWAP_DISTANCE - 1e-9)); }1989
break;1990
}1991
this.drag.accum -= dir;1992
// A short move (SWAP_DISTANCE < 1) leaves a negative leftover;1993
// do not let that immediately swap back the other way.1994
if ((dir > 0 && this.drag.accum < 0) || (dir < 0 && this.drag.accum > 0))1995
{ this.drag.accum = 0; }1996
if (!this.isColumnStill(block.col))1997
{1998
this.drag = null;1999
return;2000
}2001
}1766
var top = this.columnStackTopRow(block.col);2002
var top = this.columnStackTopRow(block.col);1767
var isTop = Math.abs(block.y - top) < ALIGN_EPS;2003
var isTop = Math.abs(block.y - top) < ALIGN_EPS;1768
if (this.drag.startedAsTop)2004
if (this.drag.startedAsTop)@@ -1779,6 +2015,18 @@ GameCore.prototype.moveDrag = function (y)1779
}2015
}1780
};2016
};1781
2017
2018
/** Swap `block` one tile up (dir=+1) or down (dir=-1). Returns true if swapped. */2019
GameCore.prototype.swapOne = function (block, dir)2020
{2021
var neighbor = this.blockAt(block.col, block.y + dir);2022
if (neighbor && this.isGrounded(neighbor) && neighbor !== block)2023
{2024
this.swapBlocks(block, neighbor);2025
return true;2026
}2027
return false;2028
};2029
1782
GameCore.prototype.endDrag = function ()2030
GameCore.prototype.endDrag = function ()1783
{2031
{1784
if (!this.drag)2032
if (!this.drag)@@ -2362,9 +2610,9 @@ function addWindowPointer ()2362
{2610
{2363
if (windowListening)2611
if (windowListening)2364
{ return; }2612
{ return; }2365
window.addEventListener('pointermove', onPointerMove, true);2613
window.addEventListener('pointermove', onPointerMove, { capture: true, passive: false });2366
window.addEventListener('pointerup', onPointerUp, true);2614
window.addEventListener('pointerup', onPointerUp, { capture: true, passive: false });2367
window.addEventListener('pointercancel', onPointerUp, true);2615
window.addEventListener('pointercancel', onPointerUp, { capture: true, passive: false });2368
windowListening = true;2616
windowListening = true;2369
}2617
}2370
2618
@@ -2372,9 +2620,9 @@ function removeWindowPointer ()2372
{2620
{2373
if (!windowListening)2621
if (!windowListening)2374
{ return; }2622
{ return; }2375
window.removeEventListener('pointermove', onPointerMove, true);2623
window.removeEventListener('pointermove', onPointerMove, { capture: true });2376
window.removeEventListener('pointerup', onPointerUp, true);2624
window.removeEventListener('pointerup', onPointerUp, { capture: true });2377
window.removeEventListener('pointercancel', onPointerUp, true);2625
window.removeEventListener('pointercancel', onPointerUp, { capture: true });2378
windowListening = false;2626
windowListening = false;2379
}2627
}2380
2628
@@ -2382,9 +2630,11 @@ function bindPointer (canvas)2382
{2630
{2383
unbindPointer();2631
unbindPointer();2384
boundCanvas = canvas;2632
boundCanvas = canvas;2385
canvas.addEventListener('pointerdown', onPointerDown);2633
canvas.addEventListener('pointerdown', onPointerDown, { passive: false });2386
canvas.style.touchAction = 'none';2634
canvas.style.touchAction = 'none';2387
canvas.style.cursor = 'pointer';2635
canvas.style.cursor = 'pointer';2636
canvas.style.webkitUserSelect = 'none';2637
canvas.style.userSelect = 'none';2388
}2638
}2389
2639
2390
function unbindPointer ()2640
function unbindPointer ()@@ -2406,7 +2656,8 @@ function fieldFromEvent (e)2406
{ return null; }2656
{ return null; }2407
var x = (e.clientX - rect.left) * (canvas.width / rect.width);2657
var x = (e.clientX - rect.left) * (canvas.width / rect.width);2408
var y = (e.clientY - rect.top) * (canvas.height / rect.height);2658
var y = (e.clientY - rect.top) * (canvas.height / rect.height);2409
var col = Math.floor(x / app.tile);2659
// Fractional column so beginDrag can snap across a nearby edge.2660
var col = x / app.tile;2410
var fieldY = (canvas.height - y) / app.tile;2661
var fieldY = (canvas.height - y) / app.tile;2411
return { col: col, y: fieldY };2662
return { col: col, y: fieldY };2412
}2663
}@@ -2424,6 +2675,8 @@ function onPointerDown (e)2424
catch (err) { /* ignore */ }2675
catch (err) { /* ignore */ }2425
addWindowPointer();2676
addWindowPointer();2426
var pos = fieldFromEvent(e);2677
var pos = fieldFromEvent(e);2678
// Instant grab, no long-press or hold delay: the block is taken on2679
// pointerdown and the click tween starts in the same moment.2427
if (pos && app.core.beginDrag(pos.col, pos.y) && app.core.drag)2680
if (pos && app.core.beginDrag(pos.col, pos.y) && app.core.drag)2428
{ startPressTween(app.core.drag.blockId); }2681
{ startPressTween(app.core.drag.blockId); }2429
}2682
}@@ -133,3 +133,68 @@ nooit `--delete`, dus ze blijven staan en zijn onschadelijk.
133
133
`favicon.ico` op de server wordt niet overschreven en niet verwijderd
134
134
(mogelijk van Tim of de host). De deploy sluit dat bestand uit van de
135
135
upload, ook als er lokaal een `build/favicon.ico` staat voor eigen gebruik.
136
137
### 7. Recolor stuurt blokken niet extra hard naar boven (t1102)
138
139
Na het herkleuren van een gelande grijze groep schoten blokken erboven
140
soms heel hard van de bovenkant af. Oorzaak: een restant van de
141
lanceringssnelheid (`vy` omhoog) of van een handmatige sprong, dat
142
na de release in `integrateFalling` alsnog werd gebruikt. Daarnaast
143
telde `releaseUnsupported` in dezelfde tick nog de hangende leden als
144
steun, zodat blokken die erop stonden `still` bleven en in
145
`resolveMatches` een match in de lucht konden vormen.
146
147
Aanname / aanpak:
148
149
- Bij elke overgang naar `still` of `falling` na release (en bij het
150
loslaten van ongesteunde still-blokken) wordt `clearFlightState`
151
aangeroepen: `vy = 0`, geen vlam, geen restant van een handmatige
152
sprong.
153
- `releaseUnsupported` draait opnieuw ná `advanceSettle`, zodat
154
blokken op zojuist losgelaten hangende leden vanaf rust vallen
155
voordat er gematcht wordt.
156
- Een échte nieuwe match na herkleuren is toegestaan en gebruikt de
157
normale sprong: `launchVelocity(planet, jumpHeight)` en de bijbehorende
158
deceleratie, niet een opgetelde of achtergebleven `vy`. Dat zit in
159
een regressietest (inclusief een kunstmatig achtergebleven `vy = 40`).
160
161
### 8. Botsende vliegende clusters smelten samen (t1102)
162
163
Twee (of meer) vliegende clusters die in dezelfde kolom in Y
164
overlappen, worden één cluster.
165
166
Aanname: de nieuwe snelheid is het **massagewogen gemiddelde op
167
blok-aantal** (niet het eenvoudige gemiddelde van de twee
168
clustersnelheden):
169
170
vy = (n1·vy1 + n2·vy2) / (n1 + n2)
171
172
Hetzelfde gewogen gemiddelde geldt voor `decel` en `jumpHeight`.
173
De fase is `up` als de samengevoegde `vy > 0`, anders `down`.
174
Overlappende leden in één kolom worden van onder naar boven
175
aangepakt, zodat de hogere strak op de lagere rust (geen twee
176
blokken in dezelfde cel). Keuze vastgelegd: gewogen op blok-aantal.
177
178
### 9. Direct vastpakken, geen long-press (t1102 / t1103)
179
180
Er is **geen** long-press en **geen** wachttijd. Een blok wordt op
181
`pointerdown` (tap of klik) meteen vastgepakt en blijft in de sleep
182
zolang de vinger of muisknop omlaag is; loslaten beëindigt de sleep.
183
De click-tween start in hetzelfde moment als `pointerdown`.
184
185
Aanname:
186
187
- Verticaal: snap naar het dichtstbijzijnde still-blok in de kolom,
188
tot `SNAP_Y = 0,65` tegel (een iets misplaatste druk pakt nog).
189
- Horizontaal: op de druk, als de aanwijzer binnen
190
`HORIZONTAL_SLOP = 0,35` tegel van de kolomrand zit, mag het
191
buurblok gepakt worden. Tijdens de sleep blijft de startkolom
192
vast, ook bij een iets diagonale beweging.
193
- Wisselen: alleen een **minimale** opgetelde verticale afstand
194
`SWAP_DISTANCE = 0,25` tegel per stap, zonder vertraging vóór de
195
sleep. Een enkele grote `pointermove` (snelle swipe) loopt alle
196
tegels langs (één wissel per tegel, geen overslaan). Er is geen
197
extra drempel of hold voordat de sleep begint.
198
- `touch-action: none` op canvas en pagina, `preventDefault` op
199
pointer-events met `{ passive: false }`, `setPointerCapture`,
200
en window-listeners voor move/up (zoals al bij t1100).
@@ -133,3 +133,68 @@ nooit `--delete`, dus ze blijven staan en zijn onschadelijk.133
`favicon.ico` op de server wordt niet overschreven en niet verwijderd133
`favicon.ico` op de server wordt niet overschreven en niet verwijderd134
(mogelijk van Tim of de host). De deploy sluit dat bestand uit van de134
(mogelijk van Tim of de host). De deploy sluit dat bestand uit van de135
upload, ook als er lokaal een `build/favicon.ico` staat voor eigen gebruik.135
upload, ook als er lokaal een `build/favicon.ico` staat voor eigen gebruik.136
137
### 7. Recolor stuurt blokken niet extra hard naar boven (t1102)138
139
Na het herkleuren van een gelande grijze groep schoten blokken erboven140
soms heel hard van de bovenkant af. Oorzaak: een restant van de141
lanceringssnelheid (`vy` omhoog) of van een handmatige sprong, dat142
na de release in `integrateFalling` alsnog werd gebruikt. Daarnaast143
telde `releaseUnsupported` in dezelfde tick nog de hangende leden als144
steun, zodat blokken die erop stonden `still` bleven en in145
`resolveMatches` een match in de lucht konden vormen.146
147
Aanname / aanpak:148
149
- Bij elke overgang naar `still` of `falling` na release (en bij het150
loslaten van ongesteunde still-blokken) wordt `clearFlightState`151
aangeroepen: `vy = 0`, geen vlam, geen restant van een handmatige152
sprong.153
- `releaseUnsupported` draait opnieuw ná `advanceSettle`, zodat154
blokken op zojuist losgelaten hangende leden vanaf rust vallen155
voordat er gematcht wordt.156
- Een échte nieuwe match na herkleuren is toegestaan en gebruikt de157
normale sprong: `launchVelocity(planet, jumpHeight)` en de bijbehorende158
deceleratie, niet een opgetelde of achtergebleven `vy`. Dat zit in159
een regressietest (inclusief een kunstmatig achtergebleven `vy = 40`).160
161
### 8. Botsende vliegende clusters smelten samen (t1102)162
163
Twee (of meer) vliegende clusters die in dezelfde kolom in Y164
overlappen, worden één cluster.165
166
Aanname: de nieuwe snelheid is het **massagewogen gemiddelde op167
blok-aantal** (niet het eenvoudige gemiddelde van de twee168
clustersnelheden):169
170
vy = (n1·vy1 + n2·vy2) / (n1 + n2)171
172
Hetzelfde gewogen gemiddelde geldt voor `decel` en `jumpHeight`.173
De fase is `up` als de samengevoegde `vy > 0`, anders `down`.174
Overlappende leden in één kolom worden van onder naar boven175
aangepakt, zodat de hogere strak op de lagere rust (geen twee176
blokken in dezelfde cel). Keuze vastgelegd: gewogen op blok-aantal.177
178
### 9. Direct vastpakken, geen long-press (t1102 / t1103)179
180
Er is **geen** long-press en **geen** wachttijd. Een blok wordt op181
`pointerdown` (tap of klik) meteen vastgepakt en blijft in de sleep182
zolang de vinger of muisknop omlaag is; loslaten beëindigt de sleep.183
De click-tween start in hetzelfde moment als `pointerdown`.184
185
Aanname:186
187
- Verticaal: snap naar het dichtstbijzijnde still-blok in de kolom,188
tot `SNAP_Y = 0,65` tegel (een iets misplaatste druk pakt nog).189
- Horizontaal: op de druk, als de aanwijzer binnen190
`HORIZONTAL_SLOP = 0,35` tegel van de kolomrand zit, mag het191
buurblok gepakt worden. Tijdens de sleep blijft de startkolom192
vast, ook bij een iets diagonale beweging.193
- Wisselen: alleen een **minimale** opgetelde verticale afstand194
`SWAP_DISTANCE = 0,25` tegel per stap, zonder vertraging vóór de195
sleep. Een enkele grote `pointermove` (snelle swipe) loopt alle196
tegels langs (één wissel per tegel, geen overslaan). Er is geen197
extra drempel of hold voordat de sleep begint.198
- `touch-action: none` op canvas en pagina, `preventDefault` op199
pointer-events met `{ passive: false }`, `setPointerCapture`,200
en window-listeners voor move/up (zoals al bij t1100).@@ -24,6 +24,13 @@ var SUBSTEP = 1 / 120;
24
24
var DRAG_LAUNCH_SLACK = 0.65;
25
25
// Upward pull (tiles past the press point) that launches an already-topmost block.
26
26
var LAUNCH_PULL = 0.35;
27
// Minimal accumulated vertical pointer travel (tiles) to swap one step.
28
// No hold delay: the first swap fires as soon as this distance is reached.
29
var SWAP_DISTANCE = 0.25;
30
// Grab a still block if the pointer is at most this far (tiles) from it.
31
var SNAP_Y = 0.65;
32
// Horizontal slop (tiles) for snapping to a neighbouring column on press.
33
var HORIZONTAL_SLOP = 0.35;
27
34
28
35
function UnionFind ()
29
36
{
@@ -74,6 +81,9 @@ function GameCore (planet, rng)
74
81
75
82
GameCore.COLOR_GRAY = COLOR_GRAY;
76
83
GameCore.LAUNCH_PULL = LAUNCH_PULL;
84
GameCore.SWAP_DISTANCE = SWAP_DISTANCE;
85
GameCore.SNAP_Y = SNAP_Y;
86
GameCore.HORIZONTAL_SLOP = HORIZONTAL_SLOP;
77
87
GameCore.STATE_STILL = STATE_STILL;
78
88
GameCore.STATE_FALLING = STATE_FALLING;
79
89
GameCore.STATE_FLYING = STATE_FLYING;
@@ -332,6 +342,21 @@ GameCore.prototype.highestFallingBelow = function (block)
332
342
* Make an unsupported still block start falling from rest, so it eases
333
343
* into fallSpeed under normal gravity. Skips the block being dragged.
334
344
*/
345
/**
346
* Strip leftover launch / manual kinematics so a block that has just
347
* become still or falling starts from rest. Used after a landed grey
348
* cluster recolors, and whenever an unsupported still block drops.
349
*/
350
GameCore.prototype.clearFlightState = function (block)
351
{
352
block.vy = 0;
353
block.flame = false;
354
block.manualPhase = null;
355
block.manualTarget = null;
356
block.manualDecel = 0;
357
block.pushedClusters = null;
358
};
359
335
360
GameCore.prototype.releaseUnsupported = function ()
336
361
{
337
362
for (var i = 0; i < this.blocks.length; i++)
@@ -343,10 +368,9 @@ GameCore.prototype.releaseUnsupported = function ()
343
368
{ continue; }
344
369
if (this.hasSupport(block))
345
370
{ continue; }
346
block.state = STATE_FALLING;
347
block.vy = 0;
348
block.flame = false;
349
371
this.leaveCluster(block);
372
this.clearFlightState(block);
373
block.state = STATE_FALLING;
350
374
}
351
375
};
352
376
@@ -458,6 +482,7 @@ GameCore.prototype.tick = function (dt)
458
482
var step = Math.min(SUBSTEP, left);
459
483
this.integrateFalling(step);
460
484
this.integrateClusters(step);
485
this.mergeFlyingClusters();
461
486
this.integrateManual(step);
462
487
this.cullOffTop();
463
488
left -= step;
@@ -465,6 +490,11 @@ GameCore.prototype.tick = function (dt)
465
490
466
491
this.releaseUnsupported();
467
492
this.advanceSettle(dt);
493
// After a landed grey group is released, blocks that were sitting on
494
// hanging members are still STILL (the earlier pass ran while those
495
// members counted as support). Drop them from rest before matching,
496
// so they cannot form a mid-air match and shoot off the top.
497
this.releaseUnsupported();
468
498
this.advanceBounces(dt);
469
499
if (!this.drag)
470
500
{ this.resolveMatches(); }
@@ -669,6 +699,139 @@ GameCore.prototype.integrateClusters = function (dt)
669
699
}
670
700
};
671
701
702
703
/**
704
* If two or more flying clusters overlap in the same column, merge them
705
* into one cluster. Velocity (and deceleration and jumpHeight) is the
706
* mass-weighted average by block count. Phase is 'up' when the merged
707
* vy is positive, otherwise 'down'. Overlapping members in a column
708
* are packed so the higher one sits flush on the lower.
709
*/
710
GameCore.prototype.mergeFlyingClusters = function ()
711
{
712
var flying = [];
713
var ids = Object.keys(this.clusters);
714
for (var n = 0; n < ids.length; n++)
715
{
716
var cluster = this.clusters[ids[n]];
717
if (!cluster)
718
{ continue; }
719
if (cluster.phase === 'landed' || cluster.phase === 'hold')
720
{ continue; }
721
flying.push(cluster);
722
}
723
if (flying.length < 2)
724
{ return; }
725
726
var uf = new UnionFind();
727
for (var i = 0; i < flying.length; i++)
728
{ uf.add(flying[i].id); }
729
for (var i = 0; i < flying.length; i++)
730
{
731
for (var j = i + 1; j < flying.length; j++)
732
{
733
if (this.flyingClustersOverlap(flying[i], flying[j]))
734
{ uf.union(flying[i].id, flying[j].id); }
735
}
736
}
737
738
var groups = Object.create(null);
739
for (var i = 0; i < flying.length; i++)
740
{
741
var root = uf.find(flying[i].id);
742
if (!groups[root])
743
{ groups[root] = []; }
744
groups[root].push(flying[i]);
745
}
746
for (var root in groups)
747
{
748
if (groups[root].length >= 2)
749
{ this.mergeClusterGroup(groups[root]); }
750
}
751
};
752
753
GameCore.prototype.flyingClustersOverlap = function (a, b)
754
{
755
var ma = this.clusterMembers(a.id);
756
var mb = this.clusterMembers(b.id);
757
for (var i = 0; i < ma.length; i++)
758
{
759
for (var j = 0; j < mb.length; j++)
760
{
761
if (ma[i].col !== mb[j].col)
762
{ continue; }
763
if (ma[i].y < mb[j].y + 1 - 1e-9 && mb[j].y < ma[i].y + 1 - 1e-9)
764
{ return true; }
765
}
766
}
767
return false;
768
};
769
770
GameCore.prototype.mergeClusterGroup = function (clusters)
771
{
772
clusters.sort(function (a, b) { return a.id - b.id; });
773
var keep = clusters[0];
774
var n = 0;
775
var vySum = 0;
776
var decelSum = 0;
777
var hSum = 0;
778
for (var c = 0; c < clusters.length; c++)
779
{
780
var mem = this.clusterMembers(clusters[c].id);
781
var m = mem.length;
782
n += m;
783
vySum += clusters[c].vy * m;
784
decelSum += (clusters[c].decel || 0) * m;
785
hSum += (clusters[c].jumpHeight || 0) * m;
786
}
787
if (n === 0)
788
{ return; }
789
keep.vy = vySum / n;
790
keep.decel = decelSum / n;
791
keep.jumpHeight = hSum / n;
792
keep.phase = keep.vy > 1e-10 ? 'up' : 'down';
793
for (var c = 0; c < clusters.length; c++)
794
{
795
var mem = this.clusterMembers(clusters[c].id);
796
for (var i = 0; i < mem.length; i++)
797
{
798
mem[i].clusterId = keep.id;
799
mem[i].vy = keep.vy;
800
mem[i].state = STATE_FLYING;
801
}
802
if (clusters[c] !== keep)
803
{ delete this.clusters[clusters[c].id]; }
804
}
805
this.packClusterOverlaps(keep);
806
if (keep.phase === 'down')
807
{ this.tryLandCluster(keep, this.clusterMembers(keep.id)); }
808
};
809
810
GameCore.prototype.packClusterOverlaps = function (cluster)
811
{
812
var members = this.clusterMembers(cluster.id);
813
var byCol = Object.create(null);
814
for (var i = 0; i < members.length; i++)
815
{
816
var col = members[i].col;
817
if (!byCol[col])
818
{ byCol[col] = []; }
819
byCol[col].push(members[i]);
820
}
821
var cols = Object.keys(byCol);
822
for (var c = 0; c < cols.length; c++)
823
{
824
var list = byCol[cols[c]];
825
list.sort(function (a, b) { return a.y - b.y; });
826
for (var i = 1; i < list.length; i++)
827
{
828
var minY = list[i - 1].y + 1;
829
if (list[i].y < minY - 1e-12)
830
{ list[i].y = minY; }
831
}
832
}
833
};
834
672
835
GameCore.prototype.tryLandCluster = function (cluster, members)
673
836
{
674
837
if (!members.length)
@@ -749,22 +912,16 @@ GameCore.prototype.releaseLandedCluster = function (cluster)
749
912
block.color = this.randomColor();
750
913
block.settleTime = 0;
751
914
}
752
block.flame = false;
753
915
this.leaveCluster(block);
916
// Always drop leftover launch / manual velocity. A stale upward
917
// vy here is what sends blocks off the top "very fast" after
918
// a grey group recolors.
919
this.clearFlightState(block);
754
920
// Support from outside the group (floor or a foreign block). Fellow
755
921
// members that will also fall do not count, so a hanging stack
756
922
// drops together without the top one staying put.
757
923
var supported = this.hasSupportOutside(block, releasing);
758
if (supported)
759
{
760
block.state = STATE_STILL;
761
block.vy = 0;
762
}
763
else
764
{
765
block.state = STATE_FALLING;
766
block.vy = 0;
767
}
924
block.state = supported ? STATE_STILL : STATE_FALLING;
768
925
}
769
926
delete this.clusters[cluster.id];
770
927
};
@@ -1016,27 +1173,18 @@ GameCore.prototype.advanceSettle = function (dt)
1016
1173
else
1017
1174
{
1018
1175
this.leaveCluster(block);
1019
if (this.hasSupport(block))
1020
{
1021
block.state = STATE_STILL;
1022
block.vy = 0;
1023
}
1024
else
1025
{
1026
block.state = STATE_FALLING;
1027
block.vy = 0;
1028
}
1176
this.clearFlightState(block);
1177
block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING;
1029
1178
}
1030
1179
}
1031
1180
}
1032
1181
else if (!inLanded)
1033
1182
{
1034
1183
// Coloured settling that is not in a landed cluster (shouldn't
1035
// normally happen): just become still or fall.
1184
// normally happen): just become still or fall, from rest.
1036
1185
this.leaveCluster(block);
1186
this.clearFlightState(block);
1037
1187
block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING;
1038
if (block.state === STATE_FALLING)
1039
{ block.vy = 0; }
1040
1188
}
1041
1189
}
1042
1190
@@ -1357,29 +1505,88 @@ GameCore.prototype.beginDrag = function (col, y)
1357
1505
{
1358
1506
if (this.state !== 'playing')
1359
1507
{ return false; }
1360
col = col | 0;
1361
if (col < 0 || col >= this.width)
1362
{ return false; }
1363
if (!this.isColumnStill(col))
1364
{ return false; }
1365
var row = Math.floor(y + 1e-6);
1366
if (row < 0)
1367
{ return false; }
1368
var block = this.blockAt(col, row);
1369
if (!block || block.state !== STATE_STILL || block.color < 0)
1508
var block = this.snapDragBlock(col, y);
1509
if (!block)
1370
1510
{ return false; }
1371
var top = this.columnStackTopRow(col);
1511
var top = this.columnStackTopRow(block.col);
1372
1512
var startedAsTop = Math.abs(block.y - top) < ALIGN_EPS;
1373
1513
this.drag = {
1374
1514
blockId: block.id,
1375
1515
pointerY: y,
1376
1516
startY: y,
1517
accum: 0,
1377
1518
launchIntent: false,
1378
1519
startedAsTop: startedAsTop
1379
1520
};
1380
1521
return true;
1381
1522
};
1382
1523
1524
/**
1525
* Instant grab: the nearest still, coloured block to (col, y), allowing
1526
* a small vertical miss and a horizontal slop into a neighbouring
1527
* column. `col` may be fractional (pointer x in tiles). No hold delay.
1528
*/
1529
GameCore.prototype.snapDragBlock = function (col, y)
1530
{
1531
var raw = col;
1532
var c0 = Math.floor(raw + 1e-9);
1533
var frac = raw - c0;
1534
var candidates = [];
1535
if (c0 >= 0 && c0 < this.width)
1536
{ candidates.push(c0); }
1537
// Only consult a neighbour when the pointer is actually near the edge
1538
// (a whole-number col, as in unit tests, stays in that column).
1539
if (frac > 1e-9 && frac < HORIZONTAL_SLOP && c0 - 1 >= 0)
1540
{ candidates.push(c0 - 1); }
1541
if (frac > 1 - HORIZONTAL_SLOP && frac < 1 - 1e-9 && c0 + 1 < this.width)
1542
{ candidates.push(c0 + 1); }
1543
1544
var best = null;
1545
var bestDist = Infinity;
1546
for (var c = 0; c < candidates.length; c++)
1547
{
1548
var cc = candidates[c];
1549
if (!this.isColumnStill(cc))
1550
{ continue; }
1551
var list = this.blocksInColumn(cc);
1552
for (var i = 0; i < list.length; i++)
1553
{
1554
var block = list[i];
1555
if (block.state !== STATE_STILL || block.color < 0)
1556
{ continue; }
1557
var dist = this.pointerDistToBlock(block, raw, y);
1558
// Prefer the column the pointer is actually in on a tie.
1559
if (dist < bestDist - 1e-12 || (Math.abs(dist - bestDist) < 1e-12 && cc === c0))
1560
{
1561
bestDist = dist;
1562
best = block;
1563
}
1564
}
1565
}
1566
if (!best || bestDist > SNAP_Y)
1567
{ return null; }
1568
return best;
1569
};
1570
1571
GameCore.prototype.pointerDistToBlock = function (block, col, y)
1572
{
1573
var dx;
1574
if (col >= block.col && col < block.col + 1)
1575
{ dx = 0; }
1576
else if (col < block.col)
1577
{ dx = block.col - col; }
1578
else
1579
{ dx = col - (block.col + 1); }
1580
var dy;
1581
if (y >= block.y && y < block.y + 1)
1582
{ dy = 0; }
1583
else if (y < block.y)
1584
{ dy = block.y - y; }
1585
else
1586
{ dy = y - (block.y + 1); }
1587
return Math.sqrt(dx * dx + dy * dy);
1588
};
1589
1383
1590
GameCore.prototype.moveDrag = function (y)
1384
1591
{
1385
1592
if (!this.drag)
@@ -1395,8 +1602,37 @@ GameCore.prototype.moveDrag = function (y)
1395
1602
this.drag = null;
1396
1603
return;
1397
1604
}
1605
var dy = y - this.drag.pointerY;
1398
1606
this.drag.pointerY = y;
1399
this.swapToward(block, y);
1607
if (this.drag.accum == null)
1608
{ this.drag.accum = 0; }
1609
this.drag.accum += dy;
1610
// One swap per tile of travel, triggered after a minimal SWAP_DISTANCE.
1611
// A single large move (fast swipe) walks every tile; none are skipped.
1612
var guard = 0;
1613
while (guard++ < this.height + 2
1614
&& (this.drag.accum >= SWAP_DISTANCE || this.drag.accum <= -SWAP_DISTANCE))
1615
{
1616
var dir = this.drag.accum > 0 ? 1 : -1;
1617
if (!this.swapOne(block, dir))
1618
{
1619
if (dir > 0)
1620
{ this.drag.accum = Math.min(this.drag.accum, SWAP_DISTANCE - 1e-9); }
1621
else
1622
{ this.drag.accum = Math.max(this.drag.accum, -(SWAP_DISTANCE - 1e-9)); }
1623
break;
1624
}
1625
this.drag.accum -= dir;
1626
// A short move (SWAP_DISTANCE < 1) leaves a negative leftover;
1627
// do not let that immediately swap back the other way.
1628
if ((dir > 0 && this.drag.accum < 0) || (dir < 0 && this.drag.accum > 0))
1629
{ this.drag.accum = 0; }
1630
if (!this.isColumnStill(block.col))
1631
{
1632
this.drag = null;
1633
return;
1634
}
1635
}
1400
1636
var top = this.columnStackTopRow(block.col);
1401
1637
var isTop = Math.abs(block.y - top) < ALIGN_EPS;
1402
1638
if (this.drag.startedAsTop)
@@ -1413,6 +1649,18 @@ GameCore.prototype.moveDrag = function (y)
1413
1649
}
1414
1650
};
1415
1651
1652
/** Swap `block` one tile up (dir=+1) or down (dir=-1). Returns true if swapped. */
1653
GameCore.prototype.swapOne = function (block, dir)
1654
{
1655
var neighbor = this.blockAt(block.col, block.y + dir);
1656
if (neighbor && this.isGrounded(neighbor) && neighbor !== block)
1657
{
1658
this.swapBlocks(block, neighbor);
1659
return true;
1660
}
1661
return false;
1662
};
1663
1416
1664
GameCore.prototype.endDrag = function ()
1417
1665
{
1418
1666
if (!this.drag)
@@ -24,6 +24,13 @@ var SUBSTEP = 1 / 120;24
var DRAG_LAUNCH_SLACK = 0.65;24
var DRAG_LAUNCH_SLACK = 0.65;25
// Upward pull (tiles past the press point) that launches an already-topmost block.25
// Upward pull (tiles past the press point) that launches an already-topmost block.26
var LAUNCH_PULL = 0.35;26
var LAUNCH_PULL = 0.35;27
// Minimal accumulated vertical pointer travel (tiles) to swap one step.28
// No hold delay: the first swap fires as soon as this distance is reached.29
var SWAP_DISTANCE = 0.25;30
// Grab a still block if the pointer is at most this far (tiles) from it.31
var SNAP_Y = 0.65;32
// Horizontal slop (tiles) for snapping to a neighbouring column on press.33
var HORIZONTAL_SLOP = 0.35;27
34
28
function UnionFind ()35
function UnionFind ()29
{36
{@@ -74,6 +81,9 @@ function GameCore (planet, rng)74
81
75
GameCore.COLOR_GRAY = COLOR_GRAY;82
GameCore.COLOR_GRAY = COLOR_GRAY;76
GameCore.LAUNCH_PULL = LAUNCH_PULL;83
GameCore.LAUNCH_PULL = LAUNCH_PULL;84
GameCore.SWAP_DISTANCE = SWAP_DISTANCE;85
GameCore.SNAP_Y = SNAP_Y;86
GameCore.HORIZONTAL_SLOP = HORIZONTAL_SLOP;77
GameCore.STATE_STILL = STATE_STILL;87
GameCore.STATE_STILL = STATE_STILL;78
GameCore.STATE_FALLING = STATE_FALLING;88
GameCore.STATE_FALLING = STATE_FALLING;79
GameCore.STATE_FLYING = STATE_FLYING;89
GameCore.STATE_FLYING = STATE_FLYING;@@ -332,6 +342,21 @@ GameCore.prototype.highestFallingBelow = function (block)332
* Make an unsupported still block start falling from rest, so it eases342
* Make an unsupported still block start falling from rest, so it eases333
* into fallSpeed under normal gravity. Skips the block being dragged.343
* into fallSpeed under normal gravity. Skips the block being dragged.334
*/344
*/345
/**346
* Strip leftover launch / manual kinematics so a block that has just347
* become still or falling starts from rest. Used after a landed grey348
* cluster recolors, and whenever an unsupported still block drops.349
*/350
GameCore.prototype.clearFlightState = function (block)351
{352
block.vy = 0;353
block.flame = false;354
block.manualPhase = null;355
block.manualTarget = null;356
block.manualDecel = 0;357
block.pushedClusters = null;358
};359
335
GameCore.prototype.releaseUnsupported = function ()360
GameCore.prototype.releaseUnsupported = function ()336
{361
{337
for (var i = 0; i < this.blocks.length; i++)362
for (var i = 0; i < this.blocks.length; i++)@@ -343,10 +368,9 @@ GameCore.prototype.releaseUnsupported = function ()343
{ continue; }368
{ continue; }344
if (this.hasSupport(block))369
if (this.hasSupport(block))345
{ continue; }370
{ continue; }346
block.state = STATE_FALLING;347
block.vy = 0;348
block.flame = false;349
this.leaveCluster(block);371
this.leaveCluster(block);372
this.clearFlightState(block);373
block.state = STATE_FALLING;350
}374
}351
};375
};352
376
@@ -458,6 +482,7 @@ GameCore.prototype.tick = function (dt)458
var step = Math.min(SUBSTEP, left);482
var step = Math.min(SUBSTEP, left);459
this.integrateFalling(step);483
this.integrateFalling(step);460
this.integrateClusters(step);484
this.integrateClusters(step);485
this.mergeFlyingClusters();461
this.integrateManual(step);486
this.integrateManual(step);462
this.cullOffTop();487
this.cullOffTop();463
left -= step;488
left -= step;@@ -465,6 +490,11 @@ GameCore.prototype.tick = function (dt)465
490
466
this.releaseUnsupported();491
this.releaseUnsupported();467
this.advanceSettle(dt);492
this.advanceSettle(dt);493
// After a landed grey group is released, blocks that were sitting on494
// hanging members are still STILL (the earlier pass ran while those495
// members counted as support). Drop them from rest before matching,496
// so they cannot form a mid-air match and shoot off the top.497
this.releaseUnsupported();468
this.advanceBounces(dt);498
this.advanceBounces(dt);469
if (!this.drag)499
if (!this.drag)470
{ this.resolveMatches(); }500
{ this.resolveMatches(); }@@ -669,6 +699,139 @@ GameCore.prototype.integrateClusters = function (dt)669
}699
}670
};700
};671
701
702
703
/**704
* If two or more flying clusters overlap in the same column, merge them705
* into one cluster. Velocity (and deceleration and jumpHeight) is the706
* mass-weighted average by block count. Phase is 'up' when the merged707
* vy is positive, otherwise 'down'. Overlapping members in a column708
* are packed so the higher one sits flush on the lower.709
*/710
GameCore.prototype.mergeFlyingClusters = function ()711
{712
var flying = [];713
var ids = Object.keys(this.clusters);714
for (var n = 0; n < ids.length; n++)715
{716
var cluster = this.clusters[ids[n]];717
if (!cluster)718
{ continue; }719
if (cluster.phase === 'landed' || cluster.phase === 'hold')720
{ continue; }721
flying.push(cluster);722
}723
if (flying.length < 2)724
{ return; }725
726
var uf = new UnionFind();727
for (var i = 0; i < flying.length; i++)728
{ uf.add(flying[i].id); }729
for (var i = 0; i < flying.length; i++)730
{731
for (var j = i + 1; j < flying.length; j++)732
{733
if (this.flyingClustersOverlap(flying[i], flying[j]))734
{ uf.union(flying[i].id, flying[j].id); }735
}736
}737
738
var groups = Object.create(null);739
for (var i = 0; i < flying.length; i++)740
{741
var root = uf.find(flying[i].id);742
if (!groups[root])743
{ groups[root] = []; }744
groups[root].push(flying[i]);745
}746
for (var root in groups)747
{748
if (groups[root].length >= 2)749
{ this.mergeClusterGroup(groups[root]); }750
}751
};752
753
GameCore.prototype.flyingClustersOverlap = function (a, b)754
{755
var ma = this.clusterMembers(a.id);756
var mb = this.clusterMembers(b.id);757
for (var i = 0; i < ma.length; i++)758
{759
for (var j = 0; j < mb.length; j++)760
{761
if (ma[i].col !== mb[j].col)762
{ continue; }763
if (ma[i].y < mb[j].y + 1 - 1e-9 && mb[j].y < ma[i].y + 1 - 1e-9)764
{ return true; }765
}766
}767
return false;768
};769
770
GameCore.prototype.mergeClusterGroup = function (clusters)771
{772
clusters.sort(function (a, b) { return a.id - b.id; });773
var keep = clusters[0];774
var n = 0;775
var vySum = 0;776
var decelSum = 0;777
var hSum = 0;778
for (var c = 0; c < clusters.length; c++)779
{780
var mem = this.clusterMembers(clusters[c].id);781
var m = mem.length;782
n += m;783
vySum += clusters[c].vy * m;784
decelSum += (clusters[c].decel || 0) * m;785
hSum += (clusters[c].jumpHeight || 0) * m;786
}787
if (n === 0)788
{ return; }789
keep.vy = vySum / n;790
keep.decel = decelSum / n;791
keep.jumpHeight = hSum / n;792
keep.phase = keep.vy > 1e-10 ? 'up' : 'down';793
for (var c = 0; c < clusters.length; c++)794
{795
var mem = this.clusterMembers(clusters[c].id);796
for (var i = 0; i < mem.length; i++)797
{798
mem[i].clusterId = keep.id;799
mem[i].vy = keep.vy;800
mem[i].state = STATE_FLYING;801
}802
if (clusters[c] !== keep)803
{ delete this.clusters[clusters[c].id]; }804
}805
this.packClusterOverlaps(keep);806
if (keep.phase === 'down')807
{ this.tryLandCluster(keep, this.clusterMembers(keep.id)); }808
};809
810
GameCore.prototype.packClusterOverlaps = function (cluster)811
{812
var members = this.clusterMembers(cluster.id);813
var byCol = Object.create(null);814
for (var i = 0; i < members.length; i++)815
{816
var col = members[i].col;817
if (!byCol[col])818
{ byCol[col] = []; }819
byCol[col].push(members[i]);820
}821
var cols = Object.keys(byCol);822
for (var c = 0; c < cols.length; c++)823
{824
var list = byCol[cols[c]];825
list.sort(function (a, b) { return a.y - b.y; });826
for (var i = 1; i < list.length; i++)827
{828
var minY = list[i - 1].y + 1;829
if (list[i].y < minY - 1e-12)830
{ list[i].y = minY; }831
}832
}833
};834
672
GameCore.prototype.tryLandCluster = function (cluster, members)835
GameCore.prototype.tryLandCluster = function (cluster, members)673
{836
{674
if (!members.length)837
if (!members.length)@@ -749,22 +912,16 @@ GameCore.prototype.releaseLandedCluster = function (cluster)749
block.color = this.randomColor();912
block.color = this.randomColor();750
block.settleTime = 0;913
block.settleTime = 0;751
}914
}752
block.flame = false;753
this.leaveCluster(block);915
this.leaveCluster(block);916
// Always drop leftover launch / manual velocity. A stale upward917
// vy here is what sends blocks off the top "very fast" after918
// a grey group recolors.919
this.clearFlightState(block);754
// Support from outside the group (floor or a foreign block). Fellow920
// Support from outside the group (floor or a foreign block). Fellow755
// members that will also fall do not count, so a hanging stack921
// members that will also fall do not count, so a hanging stack756
// drops together without the top one staying put.922
// drops together without the top one staying put.757
var supported = this.hasSupportOutside(block, releasing);923
var supported = this.hasSupportOutside(block, releasing);758
if (supported)924
block.state = supported ? STATE_STILL : STATE_FALLING;759
{760
block.state = STATE_STILL;761
block.vy = 0;762
}763
else764
{765
block.state = STATE_FALLING;766
block.vy = 0;767
}768
}925
}769
delete this.clusters[cluster.id];926
delete this.clusters[cluster.id];770
};927
};@@ -1016,27 +1173,18 @@ GameCore.prototype.advanceSettle = function (dt)1016
else1173
else1017
{1174
{1018
this.leaveCluster(block);1175
this.leaveCluster(block);1019
if (this.hasSupport(block))1176
this.clearFlightState(block);1020
{1177
block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING;1021
block.state = STATE_STILL;1022
block.vy = 0;1023
}1024
else1025
{1026
block.state = STATE_FALLING;1027
block.vy = 0;1028
}1029
}1178
}1030
}1179
}1031
}1180
}1032
else if (!inLanded)1181
else if (!inLanded)1033
{1182
{1034
// Coloured settling that is not in a landed cluster (shouldn't1183
// Coloured settling that is not in a landed cluster (shouldn't1035
// normally happen): just become still or fall.1184
// normally happen): just become still or fall, from rest.1036
this.leaveCluster(block);1185
this.leaveCluster(block);1186
this.clearFlightState(block);1037
block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING;1187
block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING;1038
if (block.state === STATE_FALLING)1039
{ block.vy = 0; }1040
}1188
}1041
}1189
}1042
1190
@@ -1357,29 +1505,88 @@ GameCore.prototype.beginDrag = function (col, y)1357
{1505
{1358
if (this.state !== 'playing')1506
if (this.state !== 'playing')1359
{ return false; }1507
{ return false; }1360
col = col | 0;1508
var block = this.snapDragBlock(col, y);1361
if (col < 0 || col >= this.width)1509
if (!block)1362
{ return false; }1363
if (!this.isColumnStill(col))1364
{ return false; }1365
var row = Math.floor(y + 1e-6);1366
if (row < 0)1367
{ return false; }1368
var block = this.blockAt(col, row);1369
if (!block || block.state !== STATE_STILL || block.color < 0)1370
{ return false; }1510
{ return false; }1371
var top = this.columnStackTopRow(col);1511
var top = this.columnStackTopRow(block.col);1372
var startedAsTop = Math.abs(block.y - top) < ALIGN_EPS;1512
var startedAsTop = Math.abs(block.y - top) < ALIGN_EPS;1373
this.drag = {1513
this.drag = {1374
blockId: block.id,1514
blockId: block.id,1375
pointerY: y,1515
pointerY: y,1376
startY: y,1516
startY: y,1517
accum: 0,1377
launchIntent: false,1518
launchIntent: false,1378
startedAsTop: startedAsTop1519
startedAsTop: startedAsTop1379
};1520
};1380
return true;1521
return true;1381
};1522
};1382
1523
1524
/**1525
* Instant grab: the nearest still, coloured block to (col, y), allowing1526
* a small vertical miss and a horizontal slop into a neighbouring1527
* column. `col` may be fractional (pointer x in tiles). No hold delay.1528
*/1529
GameCore.prototype.snapDragBlock = function (col, y)1530
{1531
var raw = col;1532
var c0 = Math.floor(raw + 1e-9);1533
var frac = raw - c0;1534
var candidates = [];1535
if (c0 >= 0 && c0 < this.width)1536
{ candidates.push(c0); }1537
// Only consult a neighbour when the pointer is actually near the edge1538
// (a whole-number col, as in unit tests, stays in that column).1539
if (frac > 1e-9 && frac < HORIZONTAL_SLOP && c0 - 1 >= 0)1540
{ candidates.push(c0 - 1); }1541
if (frac > 1 - HORIZONTAL_SLOP && frac < 1 - 1e-9 && c0 + 1 < this.width)1542
{ candidates.push(c0 + 1); }1543
1544
var best = null;1545
var bestDist = Infinity;1546
for (var c = 0; c < candidates.length; c++)1547
{1548
var cc = candidates[c];1549
if (!this.isColumnStill(cc))1550
{ continue; }1551
var list = this.blocksInColumn(cc);1552
for (var i = 0; i < list.length; i++)1553
{1554
var block = list[i];1555
if (block.state !== STATE_STILL || block.color < 0)1556
{ continue; }1557
var dist = this.pointerDistToBlock(block, raw, y);1558
// Prefer the column the pointer is actually in on a tie.1559
if (dist < bestDist - 1e-12 || (Math.abs(dist - bestDist) < 1e-12 && cc === c0))1560
{1561
bestDist = dist;1562
best = block;1563
}1564
}1565
}1566
if (!best || bestDist > SNAP_Y)1567
{ return null; }1568
return best;1569
};1570
1571
GameCore.prototype.pointerDistToBlock = function (block, col, y)1572
{1573
var dx;1574
if (col >= block.col && col < block.col + 1)1575
{ dx = 0; }1576
else if (col < block.col)1577
{ dx = block.col - col; }1578
else1579
{ dx = col - (block.col + 1); }1580
var dy;1581
if (y >= block.y && y < block.y + 1)1582
{ dy = 0; }1583
else if (y < block.y)1584
{ dy = block.y - y; }1585
else1586
{ dy = y - (block.y + 1); }1587
return Math.sqrt(dx * dx + dy * dy);1588
};1589
1383
GameCore.prototype.moveDrag = function (y)1590
GameCore.prototype.moveDrag = function (y)1384
{1591
{1385
if (!this.drag)1592
if (!this.drag)@@ -1395,8 +1602,37 @@ GameCore.prototype.moveDrag = function (y)1395
this.drag = null;1602
this.drag = null;1396
return;1603
return;1397
}1604
}1605
var dy = y - this.drag.pointerY;1398
this.drag.pointerY = y;1606
this.drag.pointerY = y;1399
this.swapToward(block, y);1607
if (this.drag.accum == null)1608
{ this.drag.accum = 0; }1609
this.drag.accum += dy;1610
// One swap per tile of travel, triggered after a minimal SWAP_DISTANCE.1611
// A single large move (fast swipe) walks every tile; none are skipped.1612
var guard = 0;1613
while (guard++ < this.height + 21614
&& (this.drag.accum >= SWAP_DISTANCE || this.drag.accum <= -SWAP_DISTANCE))1615
{1616
var dir = this.drag.accum > 0 ? 1 : -1;1617
if (!this.swapOne(block, dir))1618
{1619
if (dir > 0)1620
{ this.drag.accum = Math.min(this.drag.accum, SWAP_DISTANCE - 1e-9); }1621
else1622
{ this.drag.accum = Math.max(this.drag.accum, -(SWAP_DISTANCE - 1e-9)); }1623
break;1624
}1625
this.drag.accum -= dir;1626
// A short move (SWAP_DISTANCE < 1) leaves a negative leftover;1627
// do not let that immediately swap back the other way.1628
if ((dir > 0 && this.drag.accum < 0) || (dir < 0 && this.drag.accum > 0))1629
{ this.drag.accum = 0; }1630
if (!this.isColumnStill(block.col))1631
{1632
this.drag = null;1633
return;1634
}1635
}1400
var top = this.columnStackTopRow(block.col);1636
var top = this.columnStackTopRow(block.col);1401
var isTop = Math.abs(block.y - top) < ALIGN_EPS;1637
var isTop = Math.abs(block.y - top) < ALIGN_EPS;1402
if (this.drag.startedAsTop)1638
if (this.drag.startedAsTop)@@ -1413,6 +1649,18 @@ GameCore.prototype.moveDrag = function (y)1413
}1649
}1414
};1650
};1415
1651
1652
/** Swap `block` one tile up (dir=+1) or down (dir=-1). Returns true if swapped. */1653
GameCore.prototype.swapOne = function (block, dir)1654
{1655
var neighbor = this.blockAt(block.col, block.y + dir);1656
if (neighbor && this.isGrounded(neighbor) && neighbor !== block)1657
{1658
this.swapBlocks(block, neighbor);1659
return true;1660
}1661
return false;1662
};1663
1416
GameCore.prototype.endDrag = function ()1664
GameCore.prototype.endDrag = function ()1417
{1665
{1418
if (!this.drag)1666
if (!this.drag)@@ -416,9 +416,9 @@ function addWindowPointer ()
416
416
{
417
417
if (windowListening)
418
418
{ return; }
419
window.addEventListener('pointermove', onPointerMove, true);
420
window.addEventListener('pointerup', onPointerUp, true);
421
window.addEventListener('pointercancel', onPointerUp, true);
419
window.addEventListener('pointermove', onPointerMove, { capture: true, passive: false });
420
window.addEventListener('pointerup', onPointerUp, { capture: true, passive: false });
421
window.addEventListener('pointercancel', onPointerUp, { capture: true, passive: false });
422
422
windowListening = true;
423
423
}
424
424
@@ -426,9 +426,9 @@ function removeWindowPointer ()
426
426
{
427
427
if (!windowListening)
428
428
{ return; }
429
window.removeEventListener('pointermove', onPointerMove, true);
430
window.removeEventListener('pointerup', onPointerUp, true);
431
window.removeEventListener('pointercancel', onPointerUp, true);
429
window.removeEventListener('pointermove', onPointerMove, { capture: true });
430
window.removeEventListener('pointerup', onPointerUp, { capture: true });
431
window.removeEventListener('pointercancel', onPointerUp, { capture: true });
432
432
windowListening = false;
433
433
}
434
434
@@ -436,9 +436,11 @@ function bindPointer (canvas)
436
436
{
437
437
unbindPointer();
438
438
boundCanvas = canvas;
439
canvas.addEventListener('pointerdown', onPointerDown);
439
canvas.addEventListener('pointerdown', onPointerDown, { passive: false });
440
440
canvas.style.touchAction = 'none';
441
441
canvas.style.cursor = 'pointer';
442
canvas.style.webkitUserSelect = 'none';
443
canvas.style.userSelect = 'none';
442
444
}
443
445
444
446
function unbindPointer ()
@@ -460,7 +462,8 @@ function fieldFromEvent (e)
460
462
{ return null; }
461
463
var x = (e.clientX - rect.left) * (canvas.width / rect.width);
462
464
var y = (e.clientY - rect.top) * (canvas.height / rect.height);
463
var col = Math.floor(x / app.tile);
465
// Fractional column so beginDrag can snap across a nearby edge.
466
var col = x / app.tile;
464
467
var fieldY = (canvas.height - y) / app.tile;
465
468
return { col: col, y: fieldY };
466
469
}
@@ -478,6 +481,8 @@ function onPointerDown (e)
478
481
catch (err) { /* ignore */ }
479
482
addWindowPointer();
480
483
var pos = fieldFromEvent(e);
484
// Instant grab, no long-press or hold delay: the block is taken on
485
// pointerdown and the click tween starts in the same moment.
481
486
if (pos && app.core.beginDrag(pos.col, pos.y) && app.core.drag)
482
487
{ startPressTween(app.core.drag.blockId); }
483
488
}
@@ -416,9 +416,9 @@ function addWindowPointer ()416
{416
{417
if (windowListening)417
if (windowListening)418
{ return; }418
{ return; }419
window.addEventListener('pointermove', onPointerMove, true);419
window.addEventListener('pointermove', onPointerMove, { capture: true, passive: false });420
window.addEventListener('pointerup', onPointerUp, true);420
window.addEventListener('pointerup', onPointerUp, { capture: true, passive: false });421
window.addEventListener('pointercancel', onPointerUp, true);421
window.addEventListener('pointercancel', onPointerUp, { capture: true, passive: false });422
windowListening = true;422
windowListening = true;423
}423
}424
424
@@ -426,9 +426,9 @@ function removeWindowPointer ()426
{426
{427
if (!windowListening)427
if (!windowListening)428
{ return; }428
{ return; }429
window.removeEventListener('pointermove', onPointerMove, true);429
window.removeEventListener('pointermove', onPointerMove, { capture: true });430
window.removeEventListener('pointerup', onPointerUp, true);430
window.removeEventListener('pointerup', onPointerUp, { capture: true });431
window.removeEventListener('pointercancel', onPointerUp, true);431
window.removeEventListener('pointercancel', onPointerUp, { capture: true });432
windowListening = false;432
windowListening = false;433
}433
}434
434
@@ -436,9 +436,11 @@ function bindPointer (canvas)436
{436
{437
unbindPointer();437
unbindPointer();438
boundCanvas = canvas;438
boundCanvas = canvas;439
canvas.addEventListener('pointerdown', onPointerDown);439
canvas.addEventListener('pointerdown', onPointerDown, { passive: false });440
canvas.style.touchAction = 'none';440
canvas.style.touchAction = 'none';441
canvas.style.cursor = 'pointer';441
canvas.style.cursor = 'pointer';442
canvas.style.webkitUserSelect = 'none';443
canvas.style.userSelect = 'none';442
}444
}443
445
444
function unbindPointer ()446
function unbindPointer ()@@ -460,7 +462,8 @@ function fieldFromEvent (e)460
{ return null; }462
{ return null; }461
var x = (e.clientX - rect.left) * (canvas.width / rect.width);463
var x = (e.clientX - rect.left) * (canvas.width / rect.width);462
var y = (e.clientY - rect.top) * (canvas.height / rect.height);464
var y = (e.clientY - rect.top) * (canvas.height / rect.height);463
var col = Math.floor(x / app.tile);465
// Fractional column so beginDrag can snap across a nearby edge.466
var col = x / app.tile;464
var fieldY = (canvas.height - y) / app.tile;467
var fieldY = (canvas.height - y) / app.tile;465
return { col: col, y: fieldY };468
return { col: col, y: fieldY };466
}469
}@@ -478,6 +481,8 @@ function onPointerDown (e)478
catch (err) { /* ignore */ }481
catch (err) { /* ignore */ }479
addWindowPointer();482
addWindowPointer();480
var pos = fieldFromEvent(e);483
var pos = fieldFromEvent(e);484
// Instant grab, no long-press or hold delay: the block is taken on485
// pointerdown and the click tween starts in the same moment.481
if (pos && app.core.beginDrag(pos.col, pos.y) && app.core.drag)486
if (pos && app.core.beginDrag(pos.col, pos.y) && app.core.drag)482
{ startPressTween(app.core.drag.blockId); }487
{ startPressTween(app.core.drag.blockId); }483
}488
}@@ -0,0 +1,121 @@
1
'use strict';
2
3
const { describe, it } = require('node:test');
4
const assert = require('node:assert/strict');
5
const { makeGame, almost, GameCore } = 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('Flying cluster merge (t1102)', () =>
31
{
32
it('merges two overlapping flying clusters and averages vy by block count', () =>
33
{
34
const g = makeGame({ noSpawn: true });
35
// 3-block cluster going up, 1-block cluster going down, same column, overlapping.
36
const a = flyingCluster(g, [[3, 5], [3, 6], [3, 7]], { vy: 6, decel: 4, jumpHeight: 4, phase: 'up' });
37
const b = flyingCluster(g, [[3, 6.5]], { vy: -2, decel: 0, jumpHeight: 2, phase: 'down' });
38
assert.ok(a.cluster.id !== b.cluster.id);
39
40
g.mergeFlyingClusters();
41
42
const ids = Object.keys(g.clusters);
43
assert.equal(ids.length, 1, 'one cluster remains');
44
const merged = g.clusters[ids[0]];
45
assert.equal(g.clusterMembers(merged.id).length, 4);
46
// Mass-weighted: (3*6 + 1*(-2)) / 4 = 16/4 = 4
47
assert.ok(almost(merged.vy, 4, 1e-12), 'vy=' + merged.vy);
48
assert.equal(merged.phase, 'up', 'positive vy keeps phase up');
49
// decel (3*4 + 1*0)/4 = 3, jumpHeight (3*4 + 1*2)/4 = 3.5
50
assert.ok(almost(merged.decel, 3, 1e-12), 'decel=' + merged.decel);
51
assert.ok(almost(merged.jumpHeight, 3.5, 1e-12), 'jumpHeight=' + merged.jumpHeight);
52
for (const block of g.blocks)
53
{
54
assert.equal(block.clusterId, merged.id);
55
assert.ok(almost(block.vy, 4, 1e-12));
56
assert.equal(block.state, 'flying');
57
}
58
// Overlap in col 3 is packed: four blocks stacked flush from the lowest (y=5).
59
const ys = g.blocks.filter((bl) => bl.col === 3).map((bl) => bl.y).sort((x, y) => x - y);
60
assert.ok(almost(ys[0], 5, 1e-9));
61
for (let i = 1; i < ys.length; i++)
62
{ assert.ok(almost(ys[i], ys[i - 1] + 1, 1e-9), 'packed ys=' + ys); }
63
});
64
65
it('merged cluster then moves as one with the averaged velocity', () =>
66
{
67
const g = makeGame({ noSpawn: true });
68
flyingCluster(g, [[1, 4], [1, 5]], { vy: 8, decel: 0, phase: 'up' });
69
flyingCluster(g, [[1, 4.5], [2, 4.5]], { vy: 2, decel: 0, phase: 'up' });
70
g.mergeFlyingClusters();
71
const merged = Object.values(g.clusters)[0];
72
// (2*8 + 2*2)/4 = 5
73
assert.ok(almost(merged.vy, 5, 1e-12), 'vy=' + merged.vy);
74
const before = g.blocks.map((b) => ({ id: b.id, y: b.y, col: b.col }));
75
g.integrateClusters(0.1);
76
// decel 0, phase up: they rise by vy*dt = 0.5
77
for (const prev of before)
78
{
79
const block = g.blockById(prev.id);
80
assert.ok(almost(block.y - prev.y, 5 * 0.1, 1e-9), 'id=' + prev.id + ' dy=' + (block.y - prev.y));
81
assert.ok(almost(block.vy, 5, 1e-12));
82
}
83
});
84
85
it('merged vy <= 0 sets phase to down', () =>
86
{
87
const g = makeGame({ noSpawn: true });
88
flyingCluster(g, [[0, 8]], { vy: 1, phase: 'up' });
89
flyingCluster(g, [[0, 8]], { vy: -5, phase: 'down' });
90
g.mergeFlyingClusters();
91
const merged = Object.values(g.clusters)[0];
92
assert.ok(almost(merged.vy, (1 + -5) / 2, 1e-12));
93
assert.equal(merged.phase, 'down');
94
});
95
96
it('does not merge clusters that do not overlap', () =>
97
{
98
const g = makeGame({ noSpawn: true });
99
flyingCluster(g, [[0, 3]], { vy: 4, phase: 'up' });
100
flyingCluster(g, [[5, 8]], { vy: -3, phase: 'down' });
101
g.mergeFlyingClusters();
102
assert.equal(Object.keys(g.clusters).length, 2);
103
});
104
105
it('two approaching clusters merge mid-flight during a tick', () =>
106
{
107
const g = makeGame({ noSpawn: true, planetOpts: { fallTime: 3, riseTime: 1.5, jumpsToClear: 2 } });
108
// Lower cluster going up quickly, upper one going down, same column, a gap
109
// that closes within a short step.
110
flyingCluster(g, [[4, 3]], { vy: 8, decel: 0, phase: 'up' });
111
flyingCluster(g, [[4, 6]], { vy: -8, decel: 0, phase: 'down' });
112
assert.equal(Object.keys(g.clusters).length, 2);
113
g.step(0.3, 1 / 120);
114
assert.equal(Object.keys(g.clusters).length, 1, 'they must have merged once their y-ranges overlapped');
115
const merged = Object.values(g.clusters)[0];
116
const members = g.clusterMembers(merged.id);
117
assert.equal(members.length, 2);
118
assert.equal(members[0].clusterId, members[1].clusterId);
119
assert.ok(almost(members[0].vy, members[1].vy, 1e-12));
120
});
121
});
@@ -0,0 +1,121 @@1
'use strict';2
3
const { describe, it } = require('node:test');4
const assert = require('node:assert/strict');5
const { makeGame, almost, GameCore } = 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('Flying cluster merge (t1102)', () =>31
{32
it('merges two overlapping flying clusters and averages vy by block count', () =>33
{34
const g = makeGame({ noSpawn: true });35
// 3-block cluster going up, 1-block cluster going down, same column, overlapping.36
const a = flyingCluster(g, [[3, 5], [3, 6], [3, 7]], { vy: 6, decel: 4, jumpHeight: 4, phase: 'up' });37
const b = flyingCluster(g, [[3, 6.5]], { vy: -2, decel: 0, jumpHeight: 2, phase: 'down' });38
assert.ok(a.cluster.id !== b.cluster.id);39
40
g.mergeFlyingClusters();41
42
const ids = Object.keys(g.clusters);43
assert.equal(ids.length, 1, 'one cluster remains');44
const merged = g.clusters[ids[0]];45
assert.equal(g.clusterMembers(merged.id).length, 4);46
// Mass-weighted: (3*6 + 1*(-2)) / 4 = 16/4 = 447
assert.ok(almost(merged.vy, 4, 1e-12), 'vy=' + merged.vy);48
assert.equal(merged.phase, 'up', 'positive vy keeps phase up');49
// decel (3*4 + 1*0)/4 = 3, jumpHeight (3*4 + 1*2)/4 = 3.550
assert.ok(almost(merged.decel, 3, 1e-12), 'decel=' + merged.decel);51
assert.ok(almost(merged.jumpHeight, 3.5, 1e-12), 'jumpHeight=' + merged.jumpHeight);52
for (const block of g.blocks)53
{54
assert.equal(block.clusterId, merged.id);55
assert.ok(almost(block.vy, 4, 1e-12));56
assert.equal(block.state, 'flying');57
}58
// Overlap in col 3 is packed: four blocks stacked flush from the lowest (y=5).59
const ys = g.blocks.filter((bl) => bl.col === 3).map((bl) => bl.y).sort((x, y) => x - y);60
assert.ok(almost(ys[0], 5, 1e-9));61
for (let i = 1; i < ys.length; i++)62
{ assert.ok(almost(ys[i], ys[i - 1] + 1, 1e-9), 'packed ys=' + ys); }63
});64
65
it('merged cluster then moves as one with the averaged velocity', () =>66
{67
const g = makeGame({ noSpawn: true });68
flyingCluster(g, [[1, 4], [1, 5]], { vy: 8, decel: 0, phase: 'up' });69
flyingCluster(g, [[1, 4.5], [2, 4.5]], { vy: 2, decel: 0, phase: 'up' });70
g.mergeFlyingClusters();71
const merged = Object.values(g.clusters)[0];72
// (2*8 + 2*2)/4 = 573
assert.ok(almost(merged.vy, 5, 1e-12), 'vy=' + merged.vy);74
const before = g.blocks.map((b) => ({ id: b.id, y: b.y, col: b.col }));75
g.integrateClusters(0.1);76
// decel 0, phase up: they rise by vy*dt = 0.577
for (const prev of before)78
{79
const block = g.blockById(prev.id);80
assert.ok(almost(block.y - prev.y, 5 * 0.1, 1e-9), 'id=' + prev.id + ' dy=' + (block.y - prev.y));81
assert.ok(almost(block.vy, 5, 1e-12));82
}83
});84
85
it('merged vy <= 0 sets phase to down', () =>86
{87
const g = makeGame({ noSpawn: true });88
flyingCluster(g, [[0, 8]], { vy: 1, phase: 'up' });89
flyingCluster(g, [[0, 8]], { vy: -5, phase: 'down' });90
g.mergeFlyingClusters();91
const merged = Object.values(g.clusters)[0];92
assert.ok(almost(merged.vy, (1 + -5) / 2, 1e-12));93
assert.equal(merged.phase, 'down');94
});95
96
it('does not merge clusters that do not overlap', () =>97
{98
const g = makeGame({ noSpawn: true });99
flyingCluster(g, [[0, 3]], { vy: 4, phase: 'up' });100
flyingCluster(g, [[5, 8]], { vy: -3, phase: 'down' });101
g.mergeFlyingClusters();102
assert.equal(Object.keys(g.clusters).length, 2);103
});104
105
it('two approaching clusters merge mid-flight during a tick', () =>106
{107
const g = makeGame({ noSpawn: true, planetOpts: { fallTime: 3, riseTime: 1.5, jumpsToClear: 2 } });108
// Lower cluster going up quickly, upper one going down, same column, a gap109
// that closes within a short step.110
flyingCluster(g, [[4, 3]], { vy: 8, decel: 0, phase: 'up' });111
flyingCluster(g, [[4, 6]], { vy: -8, decel: 0, phase: 'down' });112
assert.equal(Object.keys(g.clusters).length, 2);113
g.step(0.3, 1 / 120);114
assert.equal(Object.keys(g.clusters).length, 1, 'they must have merged once their y-ranges overlapped');115
const merged = Object.values(g.clusters)[0];116
const members = g.clusterMembers(merged.id);117
assert.equal(members.length, 2);118
assert.equal(members[0].clusterId, members[1].clusterId);119
assert.ok(almost(members[0].vy, members[1].vy, 1e-12));120
});121
});@@ -233,3 +233,142 @@ describe('Landing bounce planet parameter', () =>
233
233
assert.equal(left.bouncing, false, 'the hanging member does not bounce');
234
234
});
235
235
});
236
237
function landUntilSettling (g, minGrey)
238
{
239
minGrey = minGrey || 3;
240
let landed = false;
241
for (let i = 0; i < 4000; i++)
242
{
243
g.tick(1 / 120);
244
const greys = g.blocks.filter((b) => b.color === GameCore.COLOR_GRAY);
245
const cluster = Object.values(g.clusters)[0];
246
if (greys.length >= minGrey && greys.every((b) => b.state === 'settling')
247
&& cluster && cluster.phase === 'landed')
248
{
249
landed = true;
250
break;
251
}
252
}
253
assert.ok(landed, 'cluster should have landed as a settling group\n' + g.snapshot().picture);
254
}
255
256
describe('Recolor must not shoot blocks off the top (t1102)', () =>
257
{
258
it('clears leftover upward velocity: hanging cargo falls from rest after recolor, and does not fly off', () =>
259
{
260
const g = makeGame({
261
noSpawn: true,
262
planetOpts: { jumpsToClear: 4, fallTime: 2, riseTime: 0.5 },
263
seed: 3
264
});
265
// Pedestal in col 1, hanging sides; cargo stacked on the left hang
266
// and on the middle (in-cluster riders).
267
g.place(1, 0, 4);
268
placeRow(g, 1, [0, 1, 2], 0);
269
g.place(0, 2, 3);
270
g.place(0, 3, 4);
271
g.place(1, 2, 3);
272
g.resolveMatches();
273
landUntilSettling(g, 3);
274
275
const cargo = g.blocks.filter((b) => b.color >= 0 && b.state === 'settling');
276
assert.ok(cargo.length >= 2, 'expected in-cluster cargo, got ' + cargo.length);
277
const yBefore = {};
278
const members = g.blocks.filter((b) => b.state === 'settling');
279
for (const b of members)
280
{
281
// Inject a leftover upward launch velocity — the kind that
282
// would shoot blocks off the top if it survived recolor.
283
b.vy = 40;
284
yBefore[b.id] = b.y;
285
}
286
for (const id of Object.keys(g.clusters))
287
{ g.clusters[id].vy = 40; }
288
289
// Force non-matching recolor (0,1,2 cycling) so any upward motion
290
// is a leftover-velocity bug, not a new match.
291
let n = 0;
292
g.randomColor = () => (n++ % 3);
293
294
g.step(g.settleTime + 0.05, 1 / 120);
295
296
for (const b of g.blocks)
297
{
298
assert.notEqual(b.state, 'flying', 'no new launch without a match, id=' + b.id);
299
}
300
for (const b of members)
301
{
302
assert.ok(b.vy <= 1e-9, 'vy must not stay upward after recolor, vy=' + b.vy + ' id=' + b.id + ' state=' + b.state);
303
}
304
assert.equal(g.score, 0, 'nothing should have been culled off the top');
305
assert.equal(Object.keys(g.clusters).length, 0, 'landed cluster is released');
306
307
// Hanging left cargo (and the left grey) must start falling down,
308
// never climb above their pre-recolor height.
309
g.step(0.3, 1 / 120);
310
const lefts = g.blocks.filter((b) => b.col === 0);
311
assert.ok(lefts.length >= 2, 'left column still has blocks');
312
for (const b of lefts)
313
{
314
assert.ok(b.y <= yBefore[b.id] + 0.02, 'left block must not rise, y=' + b.y + ' from ' + yBefore[b.id]);
315
assert.ok(b.vy <= 1e-9, 'falling from rest, vy=' + b.vy);
316
assert.ok(b.y > -0.05, 'must stay in the field, y=' + b.y);
317
}
318
const maxY = Math.max(...g.blocks.map((b) => b.y));
319
assert.ok(maxY < 8, 'nothing raced toward the top, maxY=' + maxY);
320
assert.equal(g.score, 0);
321
});
322
323
it('a genuine match after recolor launches with normal jump physics, not leftover speed', () =>
324
{
325
const planetOpts = { jumpsToClear: 2, fallTime: 3, riseTime: 1.5 };
326
const g = makeGame({ noSpawn: true, planetOpts, seed: 1 });
327
// Full support under a 3-wide match so all three stay still after recolor.
328
g.place(0, 0, 4);
329
g.place(1, 0, 4);
330
g.place(2, 0, 4);
331
placeRow(g, 1, [0, 1, 2], 0);
332
const cargoA = g.place(1, 2, 3);
333
const cargoB = g.place(1, 3, 2);
334
g.resolveMatches();
335
landUntilSettling(g, 3);
336
337
for (const b of g.blocks)
338
{ b.vy = 40; }
339
for (const id of Object.keys(g.clusters))
340
{ g.clusters[id].vy = 40; }
341
342
// Recolor every grey to color 0: the three supported blocks match.
343
g.randomColor = () => 0;
344
const yCargo = cargoB.y;
345
346
g.step(g.settleTime + 0.02, 1 / 120);
347
348
const cluster = Object.values(g.clusters).find((c) => c.phase === 'up');
349
assert.ok(cluster, 'a new match must launch\n' + g.snapshot().picture + '\nair=' + JSON.stringify(g.snapshot().airborne));
350
const expectedH = Planet.jumpHeight(g.planet, 3, false);
351
const expectedVy = Planet.launchVelocity(g.planet, expectedH);
352
const expectedDecel = Planet.launchDeceleration(g.planet, expectedH);
353
assert.ok(almost(cluster.jumpHeight, expectedH, 1e-9), 'jumpHeight=' + cluster.jumpHeight + ' expected ' + expectedH);
354
assert.ok(almost(cluster.vy, expectedVy, 0.15), 'vy must be the normal launch speed ' + expectedVy + ', got ' + cluster.vy + ' (leftover 40 would be wrong)');
355
assert.ok(almost(cluster.decel, expectedDecel, 0.15), 'decel=' + cluster.decel);
356
assert.ok(cluster.vy < 40, 'must not keep the leftover vy');
357
// Riders share the same (normal) velocity.
358
assert.equal(cargoA.state, 'flying');
359
assert.equal(cargoB.state, 'flying');
360
assert.ok(almost(cargoA.vy, cluster.vy, 1e-9));
361
assert.ok(almost(cargoB.vy, cluster.vy, 1e-9));
362
363
// Apex of a normal jump from the pre-launch y, not a double or leftover boost.
364
const startY = yCargo;
365
let apex = Math.max(cargoA.y, cargoB.y);
366
for (let i = 0; i < 800; i++)
367
{
368
g.tick(1 / 240);
369
apex = Math.max(apex, cargoA.y, cargoB.y);
370
}
371
assert.ok(apex <= startY + expectedH + 0.35, 'apex must follow normal jump height, apex=' + apex + ' start=' + startY + ' H=' + expectedH);
372
assert.ok(apex >= startY + expectedH - 0.85, 'should actually reach the jump, apex=' + apex);
373
});
374
});
@@ -233,3 +233,142 @@ describe('Landing bounce planet parameter', () =>233
assert.equal(left.bouncing, false, 'the hanging member does not bounce');233
assert.equal(left.bouncing, false, 'the hanging member does not bounce');234
});234
});235
});235
});236
237
function landUntilSettling (g, minGrey)238
{239
minGrey = minGrey || 3;240
let landed = false;241
for (let i = 0; i < 4000; i++)242
{243
g.tick(1 / 120);244
const greys = g.blocks.filter((b) => b.color === GameCore.COLOR_GRAY);245
const cluster = Object.values(g.clusters)[0];246
if (greys.length >= minGrey && greys.every((b) => b.state === 'settling')247
&& cluster && cluster.phase === 'landed')248
{249
landed = true;250
break;251
}252
}253
assert.ok(landed, 'cluster should have landed as a settling group\n' + g.snapshot().picture);254
}255
256
describe('Recolor must not shoot blocks off the top (t1102)', () =>257
{258
it('clears leftover upward velocity: hanging cargo falls from rest after recolor, and does not fly off', () =>259
{260
const g = makeGame({261
noSpawn: true,262
planetOpts: { jumpsToClear: 4, fallTime: 2, riseTime: 0.5 },263
seed: 3264
});265
// Pedestal in col 1, hanging sides; cargo stacked on the left hang266
// and on the middle (in-cluster riders).267
g.place(1, 0, 4);268
placeRow(g, 1, [0, 1, 2], 0);269
g.place(0, 2, 3);270
g.place(0, 3, 4);271
g.place(1, 2, 3);272
g.resolveMatches();273
landUntilSettling(g, 3);274
275
const cargo = g.blocks.filter((b) => b.color >= 0 && b.state === 'settling');276
assert.ok(cargo.length >= 2, 'expected in-cluster cargo, got ' + cargo.length);277
const yBefore = {};278
const members = g.blocks.filter((b) => b.state === 'settling');279
for (const b of members)280
{281
// Inject a leftover upward launch velocity — the kind that282
// would shoot blocks off the top if it survived recolor.283
b.vy = 40;284
yBefore[b.id] = b.y;285
}286
for (const id of Object.keys(g.clusters))287
{ g.clusters[id].vy = 40; }288
289
// Force non-matching recolor (0,1,2 cycling) so any upward motion290
// is a leftover-velocity bug, not a new match.291
let n = 0;292
g.randomColor = () => (n++ % 3);293
294
g.step(g.settleTime + 0.05, 1 / 120);295
296
for (const b of g.blocks)297
{298
assert.notEqual(b.state, 'flying', 'no new launch without a match, id=' + b.id);299
}300
for (const b of members)301
{302
assert.ok(b.vy <= 1e-9, 'vy must not stay upward after recolor, vy=' + b.vy + ' id=' + b.id + ' state=' + b.state);303
}304
assert.equal(g.score, 0, 'nothing should have been culled off the top');305
assert.equal(Object.keys(g.clusters).length, 0, 'landed cluster is released');306
307
// Hanging left cargo (and the left grey) must start falling down,308
// never climb above their pre-recolor height.309
g.step(0.3, 1 / 120);310
const lefts = g.blocks.filter((b) => b.col === 0);311
assert.ok(lefts.length >= 2, 'left column still has blocks');312
for (const b of lefts)313
{314
assert.ok(b.y <= yBefore[b.id] + 0.02, 'left block must not rise, y=' + b.y + ' from ' + yBefore[b.id]);315
assert.ok(b.vy <= 1e-9, 'falling from rest, vy=' + b.vy);316
assert.ok(b.y > -0.05, 'must stay in the field, y=' + b.y);317
}318
const maxY = Math.max(...g.blocks.map((b) => b.y));319
assert.ok(maxY < 8, 'nothing raced toward the top, maxY=' + maxY);320
assert.equal(g.score, 0);321
});322
323
it('a genuine match after recolor launches with normal jump physics, not leftover speed', () =>324
{325
const planetOpts = { jumpsToClear: 2, fallTime: 3, riseTime: 1.5 };326
const g = makeGame({ noSpawn: true, planetOpts, seed: 1 });327
// Full support under a 3-wide match so all three stay still after recolor.328
g.place(0, 0, 4);329
g.place(1, 0, 4);330
g.place(2, 0, 4);331
placeRow(g, 1, [0, 1, 2], 0);332
const cargoA = g.place(1, 2, 3);333
const cargoB = g.place(1, 3, 2);334
g.resolveMatches();335
landUntilSettling(g, 3);336
337
for (const b of g.blocks)338
{ b.vy = 40; }339
for (const id of Object.keys(g.clusters))340
{ g.clusters[id].vy = 40; }341
342
// Recolor every grey to color 0: the three supported blocks match.343
g.randomColor = () => 0;344
const yCargo = cargoB.y;345
346
g.step(g.settleTime + 0.02, 1 / 120);347
348
const cluster = Object.values(g.clusters).find((c) => c.phase === 'up');349
assert.ok(cluster, 'a new match must launch\n' + g.snapshot().picture + '\nair=' + JSON.stringify(g.snapshot().airborne));350
const expectedH = Planet.jumpHeight(g.planet, 3, false);351
const expectedVy = Planet.launchVelocity(g.planet, expectedH);352
const expectedDecel = Planet.launchDeceleration(g.planet, expectedH);353
assert.ok(almost(cluster.jumpHeight, expectedH, 1e-9), 'jumpHeight=' + cluster.jumpHeight + ' expected ' + expectedH);354
assert.ok(almost(cluster.vy, expectedVy, 0.15), 'vy must be the normal launch speed ' + expectedVy + ', got ' + cluster.vy + ' (leftover 40 would be wrong)');355
assert.ok(almost(cluster.decel, expectedDecel, 0.15), 'decel=' + cluster.decel);356
assert.ok(cluster.vy < 40, 'must not keep the leftover vy');357
// Riders share the same (normal) velocity.358
assert.equal(cargoA.state, 'flying');359
assert.equal(cargoB.state, 'flying');360
assert.ok(almost(cargoA.vy, cluster.vy, 1e-9));361
assert.ok(almost(cargoB.vy, cluster.vy, 1e-9));362
363
// Apex of a normal jump from the pre-launch y, not a double or leftover boost.364
const startY = yCargo;365
let apex = Math.max(cargoA.y, cargoB.y);366
for (let i = 0; i < 800; i++)367
{368
g.tick(1 / 240);369
apex = Math.max(apex, cargoA.y, cargoB.y);370
}371
assert.ok(apex <= startY + expectedH + 0.35, 'apex must follow normal jump height, apex=' + apex + ' start=' + startY + ' H=' + expectedH);372
assert.ok(apex >= startY + expectedH - 0.85, 'should actually reach the jump, apex=' + apex);373
});374
});@@ -185,3 +185,104 @@ describe('Manual launch of the already-topmost block', () =>
185
185
assert.equal(bottom.state, 'manual');
186
186
});
187
187
});
188
189
describe('Instant grab, snap and accumulated swaps (t1102/t1103)', () =>
190
{
191
it('grabs instantly on beginDrag with no hold delay or elapsed time', () =>
192
{
193
const g = makeGame({ noSpawn: true });
194
const block = g.place(2, 1, 1);
195
g.place(2, 0, 0);
196
// No tick between "pointerdown" and the grab — there is no long press.
197
assert.ok(g.beginDrag(2, 1.4));
198
assert.ok(g.drag);
199
assert.equal(g.drag.blockId, block.id);
200
assert.equal(g.drag.accum, 0);
201
assert.equal(block.state, 'still');
202
});
203
204
it('snaps to the nearest still block when the press is slightly outside it', () =>
205
{
206
const g = makeGame({ noSpawn: true });
207
const bottom = g.place(1, 0, 0);
208
g.place(1, 1, 1);
209
const top = g.place(1, 2, 2);
210
// Just below the bottom block (occupies [0, 1)).
211
assert.ok(g.beginDrag(1, -0.2));
212
assert.equal(g.blockById(g.drag.blockId).id, bottom.id);
213
g.endDrag();
214
// Just above the top block (occupies [2, 3)).
215
assert.ok(g.beginDrag(1, 3.2));
216
assert.equal(g.blockById(g.drag.blockId).id, top.id);
217
g.endDrag();
218
// A miss further than SNAP_Y does not grab.
219
assert.equal(g.beginDrag(1, 3.2 + GameCore.SNAP_Y + 0.1), false);
220
});
221
222
it('horizontal slop grabs a neighbouring column when the press is near the edge', () =>
223
{
224
const g = makeGame({ noSpawn: true });
225
const block = g.place(2, 1, 3);
226
g.place(2, 0, 0);
227
// Pointer is in column 3, 0.2 tiles from the left edge — close to col 2.
228
assert.ok(g.beginDrag(3.2, 1.5));
229
assert.equal(g.blockById(g.drag.blockId).id, block.id);
230
assert.equal(g.blockById(g.drag.blockId).col, 2);
231
g.endDrag();
232
// An integer column 3 (no slop — used by existing tests) does not jump left.
233
assert.equal(g.beginDrag(3, 1.5), false);
234
});
235
236
it('a slightly diagonal drag stays in the starting column', () =>
237
{
238
const g = makeGame({ noSpawn: true });
239
const a = g.place(4, 0, 0);
240
g.place(4, 1, 1);
241
g.place(4, 2, 2);
242
g.place(5, 0, 3);
243
g.place(5, 1, 4);
244
g.place(5, 2, 0);
245
assert.ok(g.beginDrag(4.85, 0.4));
246
assert.equal(g.blockById(g.drag.blockId).col, 4);
247
// moveDrag only takes y — column is locked for the whole press.
248
g.moveDrag(2.2);
249
g.endDrag();
250
assert.equal(a.col, 4);
251
assert.equal(a.y, 2);
252
assert.equal(g.blockAt(5, 0).color, 3, 'neighbour column is untouched');
253
});
254
255
it('minimal accumulated travel swaps one step, with no delay before the drag starts', () =>
256
{
257
const g = makeGame({ noSpawn: true });
258
const a = g.place(0, 0, 0);
259
g.place(0, 1, 1);
260
g.place(0, 2, 2);
261
assert.ok(g.beginDrag(0, 0.5));
262
// Immediately, without ticking, a small upward move of SWAP_DISTANCE swaps once.
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');
266
g.endDrag();
267
});
268
269
it('a fast swipe of several tiles swaps through every block and does not skip', () =>
270
{
271
const g = makeGame({ noSpawn: true });
272
const a = g.place(6, 0, 0);
273
const b = g.place(6, 1, 1);
274
const c = g.place(6, 2, 2);
275
const d = g.place(6, 3, 3);
276
const e = g.place(6, 4, 4);
277
assert.ok(g.beginDrag(6, 0.5));
278
// One large move event, as a fast swipe that only reports the end point.
279
g.moveDrag(0.5 + 4);
280
g.endDrag();
281
assert.equal(a.y, 4, 'bottom block walked all four steps, y=' + a.y);
282
assert.equal(b.y, 0, 'each neighbour was swapped, not skipped: b at ' + b.y);
283
assert.equal(c.y, 1);
284
assert.equal(d.y, 2);
285
assert.equal(e.y, 3);
286
assert.equal(g.blockAt(6, 4).id, a.id);
287
});
288
});
@@ -185,3 +185,104 @@ describe('Manual launch of the already-topmost block', () =>185
assert.equal(bottom.state, 'manual');185
assert.equal(bottom.state, 'manual');186
});186
});187
});187
});188
189
describe('Instant grab, snap and accumulated swaps (t1102/t1103)', () =>190
{191
it('grabs instantly on beginDrag with no hold delay or elapsed time', () =>192
{193
const g = makeGame({ noSpawn: true });194
const block = g.place(2, 1, 1);195
g.place(2, 0, 0);196
// No tick between "pointerdown" and the grab — there is no long press.197
assert.ok(g.beginDrag(2, 1.4));198
assert.ok(g.drag);199
assert.equal(g.drag.blockId, block.id);200
assert.equal(g.drag.accum, 0);201
assert.equal(block.state, 'still');202
});203
204
it('snaps to the nearest still block when the press is slightly outside it', () =>205
{206
const g = makeGame({ noSpawn: true });207
const bottom = g.place(1, 0, 0);208
g.place(1, 1, 1);209
const top = g.place(1, 2, 2);210
// Just below the bottom block (occupies [0, 1)).211
assert.ok(g.beginDrag(1, -0.2));212
assert.equal(g.blockById(g.drag.blockId).id, bottom.id);213
g.endDrag();214
// Just above the top block (occupies [2, 3)).215
assert.ok(g.beginDrag(1, 3.2));216
assert.equal(g.blockById(g.drag.blockId).id, top.id);217
g.endDrag();218
// A miss further than SNAP_Y does not grab.219
assert.equal(g.beginDrag(1, 3.2 + GameCore.SNAP_Y + 0.1), false);220
});221
222
it('horizontal slop grabs a neighbouring column when the press is near the edge', () =>223
{224
const g = makeGame({ noSpawn: true });225
const block = g.place(2, 1, 3);226
g.place(2, 0, 0);227
// Pointer is in column 3, 0.2 tiles from the left edge — close to col 2.228
assert.ok(g.beginDrag(3.2, 1.5));229
assert.equal(g.blockById(g.drag.blockId).id, block.id);230
assert.equal(g.blockById(g.drag.blockId).col, 2);231
g.endDrag();232
// An integer column 3 (no slop — used by existing tests) does not jump left.233
assert.equal(g.beginDrag(3, 1.5), false);234
});235
236
it('a slightly diagonal drag stays in the starting column', () =>237
{238
const g = makeGame({ noSpawn: true });239
const a = g.place(4, 0, 0);240
g.place(4, 1, 1);241
g.place(4, 2, 2);242
g.place(5, 0, 3);243
g.place(5, 1, 4);244
g.place(5, 2, 0);245
assert.ok(g.beginDrag(4.85, 0.4));246
assert.equal(g.blockById(g.drag.blockId).col, 4);247
// moveDrag only takes y — column is locked for the whole press.248
g.moveDrag(2.2);249
g.endDrag();250
assert.equal(a.col, 4);251
assert.equal(a.y, 2);252
assert.equal(g.blockAt(5, 0).color, 3, 'neighbour column is untouched');253
});254
255
it('minimal accumulated travel swaps one step, with no delay before the drag starts', () =>256
{257
const g = makeGame({ noSpawn: true });258
const a = g.place(0, 0, 0);259
g.place(0, 1, 1);260
g.place(0, 2, 2);261
assert.ok(g.beginDrag(0, 0.5));262
// Immediately, without ticking, a small upward move of SWAP_DISTANCE swaps once.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');266
g.endDrag();267
});268
269
it('a fast swipe of several tiles swaps through every block and does not skip', () =>270
{271
const g = makeGame({ noSpawn: true });272
const a = g.place(6, 0, 0);273
const b = g.place(6, 1, 1);274
const c = g.place(6, 2, 2);275
const d = g.place(6, 3, 3);276
const e = g.place(6, 4, 4);277
assert.ok(g.beginDrag(6, 0.5));278
// One large move event, as a fast swipe that only reports the end point.279
g.moveDrag(0.5 + 4);280
g.endDrag();281
assert.equal(a.y, 4, 'bottom block walked all four steps, y=' + a.y);282
assert.equal(b.y, 0, 'each neighbour was swapped, not skipped: b at ' + b.y);283
assert.equal(c.y, 1);284
assert.equal(d.y, 2);285
assert.equal(e.y, 3);286
assert.equal(g.blockAt(6, 4).id, a.id);287
});288
});@@ -0,0 +1,353 @@
1
#!/usr/bin/env python3
2
"""Touch input for Meteors: real touch sequences on Android- and iOS-like viewports."""
3
from __future__ import annotations
4
5
import json
6
import sys
7
import time
8
import subprocess
9
import socket
10
from pathlib import Path
11
12
from playwright.sync_api import sync_playwright
13
14
OUT = Path("/workspace/meteors-shots")
15
OUT.mkdir(parents=True, exist_ok=True)
16
ROOT = Path("/workspace/meteors")
17
CHROME = "/usr/bin/google-chrome"
18
CHROME_ARGS = [
19
"--use-gl=angle",
20
"--use-angle=swiftshader",
21
"--no-sandbox",
22
"--disable-dev-shm-usage",
23
"--disable-gpu-sandbox",
24
]
25
26
ANDROID = {
27
"name": "android-chrome",
28
"viewport": {"width": 393, "height": 851},
29
"device_scale_factor": 2,
30
"is_mobile": True,
31
"has_touch": True,
32
"user_agent": (
33
"Mozilla/5.0 (Linux; Android 14; Pixel 7) AppleWebKit/537.36 "
34
"(KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36"
35
),
36
}
37
IOS = {
38
"name": "ios-safari",
39
"viewport": {"width": 390, "height": 844},
40
"device_scale_factor": 2,
41
"is_mobile": True,
42
"has_touch": True,
43
"user_agent": (
44
"Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) "
45
"AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 "
46
"Mobile/15E148 Safari/604.1"
47
),
48
}
49
50
FAILURES = []
51
LOG = []
52
53
54
def free_port():
55
s = socket.socket()
56
s.bind(("127.0.0.1", 0))
57
port = s.getsockname()[1]
58
s.close()
59
return port
60
61
62
def field_to_client(page, col, field_y):
63
return page.evaluate(
64
"""([col, fieldY]) => {
65
const c = app.scene.canvas;
66
const r = c.getBoundingClientRect();
67
const x = (col + 0.5) * app.tile;
68
const y = c.height - fieldY * app.tile;
69
return {
70
x: r.left + x * (r.width / c.width),
71
y: r.top + y * (r.height / c.height)
72
};
73
}""",
74
[col, field_y],
75
)
76
77
78
def touch_start(cdp, x, y):
79
cdp.send(
80
"Input.dispatchTouchEvent",
81
{"type": "touchStart", "touchPoints": [{"x": x, "y": y, "id": 0, "force": 1.0}]},
82
)
83
84
85
def touch_move(cdp, x, y):
86
cdp.send(
87
"Input.dispatchTouchEvent",
88
{"type": "touchMove", "touchPoints": [{"x": x, "y": y, "id": 0, "force": 1.0}]},
89
)
90
91
92
def touch_end(cdp):
93
cdp.send("Input.dispatchTouchEvent", {"type": "touchEnd", "touchPoints": []})
94
95
96
def touch_drag(cdp, x1, y1, x2, y2, steps=16):
97
touch_start(cdp, x1, y1)
98
for i in range(1, steps + 1):
99
t = i / steps
100
touch_move(cdp, x1 + (x2 - x1) * t, y1 + (y2 - y1) * t)
101
touch_end(cdp)
102
103
104
def reset_board(page, stacks):
105
"""stacks: {col: [colors from bottom]}"""
106
page.evaluate(
107
"""(stacks) => {
108
const g = app.core;
109
g.spawnInterval = 1e9;
110
g.spawnTimer = 0;
111
g.blocks.length = 0;
112
g.clusters = Object.create(null);
113
g.score = 0;
114
g.drag = null;
115
g.state = 'playing';
116
g.nextBlockId = 1;
117
g.nextClusterId = 1;
118
app.selectTween = null;
119
for (const [col, colors] of Object.entries(stacks)) {
120
colors.forEach((color, row) => g.place(+col, row, color));
121
}
122
}""",
123
stacks,
124
)
125
page.evaluate("() => { if (typeof syncSprites === 'function') { /* maybe closed */ } }")
126
# Give the view one frame to draw.
127
page.wait_for_timeout(80)
128
129
130
def board(page):
131
return page.evaluate(
132
"""() => app.core.blocks.map((b) => ({
133
id: b.id, col: b.col, y: b.y, color: b.color, state: b.state
134
}))"""
135
)
136
137
138
def grab_state(page):
139
return page.evaluate(
140
"""() => ({
141
drag: app.core.drag && {
142
blockId: app.core.drag.blockId,
143
accum: app.core.drag.accum,
144
startedAsTop: app.core.drag.startedAsTop
145
},
146
tween: app.selectTween && {
147
phase: app.selectTween.phase,
148
scale: app.selectTween.scale,
149
t: app.selectTween.t,
150
blockId: app.selectTween.blockId
151
}
152
})"""
153
)
154
155
156
def check(cond, msg, device):
157
if not cond:
158
FAILURES.append(f"[{device}] {msg}")
159
print(f"FAIL [{device}] {msg}")
160
else:
161
print(f"OK [{device}] {msg}")
162
return cond
163
164
165
def shot(page, name):
166
path = OUT / name
167
page.screenshot(path=str(path), full_page=False)
168
print(f"wrote {path} ({path.stat().st_size} bytes)")
169
return path
170
171
172
def start_play(page):
173
page.goto(URL, wait_until="networkidle", timeout=20000)
174
page.wait_for_timeout(400)
175
btn = page.locator("#btn-play")
176
btn.wait_for(state="visible", timeout=5000)
177
# Real touch tap on the Play button (mobile browsers may swallow click).
178
box = btn.bounding_box()
179
cdp = page.context.new_cdp_session(page)
180
touch_drag(
181
cdp,
182
box["x"] + box["width"] / 2,
183
box["y"] + box["height"] / 2,
184
box["x"] + box["width"] / 2,
185
box["y"] + box["height"] / 2,
186
steps=1,
187
)
188
page.wait_for_timeout(400)
189
# Fallback if the touch didn't start the game (desktop-like click path).
190
if page.evaluate("() => app.mode") != "playing":
191
btn.click()
192
page.wait_for_timeout(400)
193
page.wait_for_function("() => app && app.mode === 'playing' && app.core && app.scene", timeout=8000)
194
page.wait_for_selector("canvas", state="visible", timeout=5000)
195
return cdp
196
197
198
def run_device(browser, device):
199
name = device["name"]
200
print(f"\n======== {name} ========")
201
context = browser.new_context(
202
viewport=device["viewport"],
203
device_scale_factor=device["device_scale_factor"],
204
is_mobile=device["is_mobile"],
205
has_touch=device["has_touch"],
206
user_agent=device["user_agent"],
207
)
208
page = context.new_page()
209
bag = []
210
page.on("console", lambda m: bag.append(f"{m.type}: {m.text}"))
211
page.on("pageerror", lambda e: bag.append(f"pageerror: {e}"))
212
cdp = start_play(page)
213
check(page.evaluate("() => app.mode") == "playing", "play started", name)
214
shot(page, f"t1102-touch-{name}-play.png")
215
216
# --- Instant grab + click tween starts on pointerdown, no hold delay ---
217
reset_board(page, {"2": [0, 1, 2, 3, 4]})
218
page.wait_for_timeout(120)
219
pos = field_to_client(page, 2, 1.5) # centre of the block at y=1
220
touch_start(cdp, pos["x"], pos["y"])
221
# No wait-for-hold: inspect immediately, then after one frame.
222
page.wait_for_timeout(16)
223
st = grab_state(page)
224
check(st.get("drag") is not None, f"instant grab on pointerdown, state={st}", name)
225
tw = st.get("tween") or {}
226
check(
227
tw.get("phase") in ("press", "hold") and tw.get("blockId") is not None,
228
f"click tween starts immediately on pointerdown, tween={tw}",
229
name,
230
)
231
# Drag without any extra hold delay: swipe up two tiles.
232
dest = field_to_client(page, 2, 1.5 + 2)
233
for i in range(1, 9):
234
t = i / 8
235
touch_move(cdp, pos["x"], pos["y"] + (dest["y"] - pos["y"]) * t)
236
page.wait_for_timeout(40)
237
mid = board(page)
238
# The grabbed block (color 1 at y=1) should have moved up.
239
grabbed = [b for b in mid if b["color"] == 1]
240
check(
241
grabbed and grabbed[0]["y"] >= 2.9,
242
f"immediate drag (no hold) swaps upward, grabbed={grabbed}",
243
name,
244
)
245
touch_end(cdp)
246
page.wait_for_timeout(80)
247
248
# --- Fast swipe: several tiles in a short sequence, no skip ---
249
reset_board(page, {"3": [0, 1, 2, 3, 4]})
250
page.wait_for_timeout(80)
251
p0 = field_to_client(page, 3, 0.5)
252
p1 = field_to_client(page, 3, 0.5 + 4)
253
# Few steps: a fast swipe that jumps a long way between events.
254
touch_drag(cdp, p0["x"], p0["y"], p1["x"], p1["y"], steps=3)
255
page.wait_for_timeout(80)
256
after = {b["color"]: b["y"] for b in board(page) if b["col"] == 3}
257
check(
258
after.get(0) == 4,
259
f"fast swipe walks every tile (bottom ends at top), after={after}",
260
name,
261
)
262
check(
263
after.get(1) == 0 and after.get(2) == 1 and after.get(3) == 2 and after.get(4) == 3,
264
f"fast swipe does not skip neighbours, after={after}",
265
name,
266
)
267
shot(page, f"t1102-touch-{name}-after-swipe.png")
268
269
# --- Horizontal slop: slightly diagonal swipe stays in column ---
270
reset_board(page, {"4": [0, 1, 2, 3], "5": [3, 4, 0, 1]})
271
page.wait_for_timeout(80)
272
q0 = field_to_client(page, 4, 0.5)
273
q1 = field_to_client(page, 4.4, 0.5 + 3) # drift 0.4 tiles toward col 5
274
# field_to_client uses (col+0.5)*tile, so 4.4 means 0.4 into the slop visually.
275
q1 = field_to_client(page, 4.4, 3.5)
276
colors_before_5 = [b["color"] for b in sorted(board(page), key=lambda b: b["y"]) if b["col"] == 5]
277
touch_drag(cdp, q0["x"], q0["y"], q1["x"], q1["y"], steps=10)
278
page.wait_for_timeout(80)
279
col4 = {b["color"]: (b["y"], b["col"]) for b in board(page) if b["color"] == 0 and b["state"] == "still"}
280
moved = [b for b in board(page) if b["color"] == 0 and b.get("id") is not None]
281
# The bottom block of col 4 (color 0) should be at the top of col 4, not in col 5.
282
bottoms = [b for b in board(page) if b["col"] == 4]
283
top4 = max(bottoms, key=lambda b: b["y"]) if bottoms else None
284
colors_after_5 = [b["color"] for b in sorted(board(page), key=lambda b: b["y"]) if b["col"] == 5]
285
check(
286
top4 and top4["color"] == 0 and top4["col"] == 4,
287
f"diagonal drag stays in starting column, top4={top4}, col5={colors_after_5}",
288
name,
289
)
290
check(
291
colors_after_5 == colors_before_5,
292
f"neighbour column untouched, before={colors_before_5} after={colors_after_5}",
293
name,
294
)
295
shot(page, f"t1102-touch-{name}-diagonal.png")
296
297
# --- Snap: press slightly above the top block still grabs it ---
298
reset_board(page, {"1": [2, 3]})
299
page.wait_for_timeout(80)
300
# Top block occupies [1, 2); press at 2.25 (0.25 above).
301
s = field_to_client(page, 1, 2.25)
302
touch_start(cdp, s["x"], s["y"])
303
page.wait_for_timeout(16)
304
st = grab_state(page)
305
check(st.get("drag") is not None, f"snap-grab slightly above the block, state={st}", name)
306
touch_end(cdp)
307
page.wait_for_timeout(50)
308
309
if bag:
310
print(f"console [{name}]: {bag[:8]}")
311
context.close()
312
313
314
def main():
315
global URL
316
port = free_port()
317
URL = f"http://127.0.0.1:{port}/"
318
print("serving", URL, "from", ROOT / "build")
319
httpd = subprocess.Popen(
320
["python3", "-m", "http.server", str(port), "--bind", "127.0.0.1", "--directory", str(ROOT / "build")],
321
stdout=subprocess.DEVNULL,
322
stderr=subprocess.DEVNULL,
323
)
324
try:
325
time.sleep(0.4)
326
with sync_playwright() as p:
327
browser = p.chromium.launch(
328
executable_path=CHROME,
329
args=CHROME_ARGS,
330
headless=True,
331
)
332
for device in (ANDROID, IOS):
333
run_device(browser, device)
334
browser.close()
335
finally:
336
httpd.terminate()
337
try:
338
httpd.wait(timeout=3)
339
except Exception:
340
httpd.kill()
341
342
print("\n======== summary ========")
343
if FAILURES:
344
print(f"{len(FAILURES)} failure(s):")
345
for f in FAILURES:
346
print(" -", f)
347
return 1
348
print("all touch tests passed")
349
return 0
350
351
352
if __name__ == "__main__":
353
sys.exit(main())
@@ -0,0 +1,353 @@1
#!/usr/bin/env python32
"""Touch input for Meteors: real touch sequences on Android- and iOS-like viewports."""3
from __future__ import annotations4
5
import json6
import sys7
import time8
import subprocess9
import socket10
from pathlib import Path11
12
from playwright.sync_api import sync_playwright13
14
OUT = Path("/workspace/meteors-shots")15
OUT.mkdir(parents=True, exist_ok=True)16
ROOT = Path("/workspace/meteors")17
CHROME = "/usr/bin/google-chrome"18
CHROME_ARGS = [19
"--use-gl=angle",20
"--use-angle=swiftshader",21
"--no-sandbox",22
"--disable-dev-shm-usage",23
"--disable-gpu-sandbox",24
]25
26
ANDROID = {27
"name": "android-chrome",28
"viewport": {"width": 393, "height": 851},29
"device_scale_factor": 2,30
"is_mobile": True,31
"has_touch": True,32
"user_agent": (33
"Mozilla/5.0 (Linux; Android 14; Pixel 7) AppleWebKit/537.36 "34
"(KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36"35
),36
}37
IOS = {38
"name": "ios-safari",39
"viewport": {"width": 390, "height": 844},40
"device_scale_factor": 2,41
"is_mobile": True,42
"has_touch": True,43
"user_agent": (44
"Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) "45
"AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 "46
"Mobile/15E148 Safari/604.1"47
),48
}49
50
FAILURES = []51
LOG = []52
53
54
def free_port():55
s = socket.socket()56
s.bind(("127.0.0.1", 0))57
port = s.getsockname()[1]58
s.close()59
return port60
61
62
def field_to_client(page, col, field_y):63
return page.evaluate(64
"""([col, fieldY]) => {65
const c = app.scene.canvas;66
const r = c.getBoundingClientRect();67
const x = (col + 0.5) * app.tile;68
const y = c.height - fieldY * app.tile;69
return {70
x: r.left + x * (r.width / c.width),71
y: r.top + y * (r.height / c.height)72
};73
}""",74
[col, field_y],75
)76
77
78
def touch_start(cdp, x, y):79
cdp.send(80
"Input.dispatchTouchEvent",81
{"type": "touchStart", "touchPoints": [{"x": x, "y": y, "id": 0, "force": 1.0}]},82
)83
84
85
def touch_move(cdp, x, y):86
cdp.send(87
"Input.dispatchTouchEvent",88
{"type": "touchMove", "touchPoints": [{"x": x, "y": y, "id": 0, "force": 1.0}]},89
)90
91
92
def touch_end(cdp):93
cdp.send("Input.dispatchTouchEvent", {"type": "touchEnd", "touchPoints": []})94
95
96
def touch_drag(cdp, x1, y1, x2, y2, steps=16):97
touch_start(cdp, x1, y1)98
for i in range(1, steps + 1):99
t = i / steps100
touch_move(cdp, x1 + (x2 - x1) * t, y1 + (y2 - y1) * t)101
touch_end(cdp)102
103
104
def reset_board(page, stacks):105
"""stacks: {col: [colors from bottom]}"""106
page.evaluate(107
"""(stacks) => {108
const g = app.core;109
g.spawnInterval = 1e9;110
g.spawnTimer = 0;111
g.blocks.length = 0;112
g.clusters = Object.create(null);113
g.score = 0;114
g.drag = null;115
g.state = 'playing';116
g.nextBlockId = 1;117
g.nextClusterId = 1;118
app.selectTween = null;119
for (const [col, colors] of Object.entries(stacks)) {120
colors.forEach((color, row) => g.place(+col, row, color));121
}122
}""",123
stacks,124
)125
page.evaluate("() => { if (typeof syncSprites === 'function') { /* maybe closed */ } }")126
# Give the view one frame to draw.127
page.wait_for_timeout(80)128
129
130
def board(page):131
return page.evaluate(132
"""() => app.core.blocks.map((b) => ({133
id: b.id, col: b.col, y: b.y, color: b.color, state: b.state134
}))"""135
)136
137
138
def grab_state(page):139
return page.evaluate(140
"""() => ({141
drag: app.core.drag && {142
blockId: app.core.drag.blockId,143
accum: app.core.drag.accum,144
startedAsTop: app.core.drag.startedAsTop145
},146
tween: app.selectTween && {147
phase: app.selectTween.phase,148
scale: app.selectTween.scale,149
t: app.selectTween.t,150
blockId: app.selectTween.blockId151
}152
})"""153
)154
155
156
def check(cond, msg, device):157
if not cond:158
FAILURES.append(f"[{device}] {msg}")159
print(f"FAIL [{device}] {msg}")160
else:161
print(f"OK [{device}] {msg}")162
return cond163
164
165
def shot(page, name):166
path = OUT / name167
page.screenshot(path=str(path), full_page=False)168
print(f"wrote {path} ({path.stat().st_size} bytes)")169
return path170
171
172
def start_play(page):173
page.goto(URL, wait_until="networkidle", timeout=20000)174
page.wait_for_timeout(400)175
btn = page.locator("#btn-play")176
btn.wait_for(state="visible", timeout=5000)177
# Real touch tap on the Play button (mobile browsers may swallow click).178
box = btn.bounding_box()179
cdp = page.context.new_cdp_session(page)180
touch_drag(181
cdp,182
box["x"] + box["width"] / 2,183
box["y"] + box["height"] / 2,184
box["x"] + box["width"] / 2,185
box["y"] + box["height"] / 2,186
steps=1,187
)188
page.wait_for_timeout(400)189
# Fallback if the touch didn't start the game (desktop-like click path).190
if page.evaluate("() => app.mode") != "playing":191
btn.click()192
page.wait_for_timeout(400)193
page.wait_for_function("() => app && app.mode === 'playing' && app.core && app.scene", timeout=8000)194
page.wait_for_selector("canvas", state="visible", timeout=5000)195
return cdp196
197
198
def run_device(browser, device):199
name = device["name"]200
print(f"\n======== {name} ========")201
context = browser.new_context(202
viewport=device["viewport"],203
device_scale_factor=device["device_scale_factor"],204
is_mobile=device["is_mobile"],205
has_touch=device["has_touch"],206
user_agent=device["user_agent"],207
)208
page = context.new_page()209
bag = []210
page.on("console", lambda m: bag.append(f"{m.type}: {m.text}"))211
page.on("pageerror", lambda e: bag.append(f"pageerror: {e}"))212
cdp = start_play(page)213
check(page.evaluate("() => app.mode") == "playing", "play started", name)214
shot(page, f"t1102-touch-{name}-play.png")215
216
# --- Instant grab + click tween starts on pointerdown, no hold delay ---217
reset_board(page, {"2": [0, 1, 2, 3, 4]})218
page.wait_for_timeout(120)219
pos = field_to_client(page, 2, 1.5) # centre of the block at y=1220
touch_start(cdp, pos["x"], pos["y"])221
# No wait-for-hold: inspect immediately, then after one frame.222
page.wait_for_timeout(16)223
st = grab_state(page)224
check(st.get("drag") is not None, f"instant grab on pointerdown, state={st}", name)225
tw = st.get("tween") or {}226
check(227
tw.get("phase") in ("press", "hold") and tw.get("blockId") is not None,228
f"click tween starts immediately on pointerdown, tween={tw}",229
name,230
)231
# Drag without any extra hold delay: swipe up two tiles.232
dest = field_to_client(page, 2, 1.5 + 2)233
for i in range(1, 9):234
t = i / 8235
touch_move(cdp, pos["x"], pos["y"] + (dest["y"] - pos["y"]) * t)236
page.wait_for_timeout(40)237
mid = board(page)238
# The grabbed block (color 1 at y=1) should have moved up.239
grabbed = [b for b in mid if b["color"] == 1]240
check(241
grabbed and grabbed[0]["y"] >= 2.9,242
f"immediate drag (no hold) swaps upward, grabbed={grabbed}",243
name,244
)245
touch_end(cdp)246
page.wait_for_timeout(80)247
248
# --- Fast swipe: several tiles in a short sequence, no skip ---249
reset_board(page, {"3": [0, 1, 2, 3, 4]})250
page.wait_for_timeout(80)251
p0 = field_to_client(page, 3, 0.5)252
p1 = field_to_client(page, 3, 0.5 + 4)253
# Few steps: a fast swipe that jumps a long way between events.254
touch_drag(cdp, p0["x"], p0["y"], p1["x"], p1["y"], steps=3)255
page.wait_for_timeout(80)256
after = {b["color"]: b["y"] for b in board(page) if b["col"] == 3}257
check(258
after.get(0) == 4,259
f"fast swipe walks every tile (bottom ends at top), after={after}",260
name,261
)262
check(263
after.get(1) == 0 and after.get(2) == 1 and after.get(3) == 2 and after.get(4) == 3,264
f"fast swipe does not skip neighbours, after={after}",265
name,266
)267
shot(page, f"t1102-touch-{name}-after-swipe.png")268
269
# --- Horizontal slop: slightly diagonal swipe stays in column ---270
reset_board(page, {"4": [0, 1, 2, 3], "5": [3, 4, 0, 1]})271
page.wait_for_timeout(80)272
q0 = field_to_client(page, 4, 0.5)273
q1 = field_to_client(page, 4.4, 0.5 + 3) # drift 0.4 tiles toward col 5274
# field_to_client uses (col+0.5)*tile, so 4.4 means 0.4 into the slop visually.275
q1 = field_to_client(page, 4.4, 3.5)276
colors_before_5 = [b["color"] for b in sorted(board(page), key=lambda b: b["y"]) if b["col"] == 5]277
touch_drag(cdp, q0["x"], q0["y"], q1["x"], q1["y"], steps=10)278
page.wait_for_timeout(80)279
col4 = {b["color"]: (b["y"], b["col"]) for b in board(page) if b["color"] == 0 and b["state"] == "still"}280
moved = [b for b in board(page) if b["color"] == 0 and b.get("id") is not None]281
# The bottom block of col 4 (color 0) should be at the top of col 4, not in col 5.282
bottoms = [b for b in board(page) if b["col"] == 4]283
top4 = max(bottoms, key=lambda b: b["y"]) if bottoms else None284
colors_after_5 = [b["color"] for b in sorted(board(page), key=lambda b: b["y"]) if b["col"] == 5]285
check(286
top4 and top4["color"] == 0 and top4["col"] == 4,287
f"diagonal drag stays in starting column, top4={top4}, col5={colors_after_5}",288
name,289
)290
check(291
colors_after_5 == colors_before_5,292
f"neighbour column untouched, before={colors_before_5} after={colors_after_5}",293
name,294
)295
shot(page, f"t1102-touch-{name}-diagonal.png")296
297
# --- Snap: press slightly above the top block still grabs it ---298
reset_board(page, {"1": [2, 3]})299
page.wait_for_timeout(80)300
# Top block occupies [1, 2); press at 2.25 (0.25 above).301
s = field_to_client(page, 1, 2.25)302
touch_start(cdp, s["x"], s["y"])303
page.wait_for_timeout(16)304
st = grab_state(page)305
check(st.get("drag") is not None, f"snap-grab slightly above the block, state={st}", name)306
touch_end(cdp)307
page.wait_for_timeout(50)308
309
if bag:310
print(f"console [{name}]: {bag[:8]}")311
context.close()312
313
314
def main():315
global URL316
port = free_port()317
URL = f"http://127.0.0.1:{port}/"318
print("serving", URL, "from", ROOT / "build")319
httpd = subprocess.Popen(320
["python3", "-m", "http.server", str(port), "--bind", "127.0.0.1", "--directory", str(ROOT / "build")],321
stdout=subprocess.DEVNULL,322
stderr=subprocess.DEVNULL,323
)324
try:325
time.sleep(0.4)326
with sync_playwright() as p:327
browser = p.chromium.launch(328
executable_path=CHROME,329
args=CHROME_ARGS,330
headless=True,331
)332
for device in (ANDROID, IOS):333
run_device(browser, device)334
browser.close()335
finally:336
httpd.terminate()337
try:338
httpd.wait(timeout=3)339
except Exception:340
httpd.kill()341
342
print("\n======== summary ========")343
if FAILURES:344
print(f"{len(FAILURES)} failure(s):")345
for f in FAILURES:346
print(" -", f)347
return 1348
print("all touch tests passed")349
return 0350
351
352
if __name__ == "__main__":353
sys.exit(main())