Merge branch 'feature/t1111-physics-audit'
@@ -721,6 +721,11 @@ function GameCore (planet, rng)
721
721
this.outgoingShots = [];
722
722
// Stage-2 default; stage 3 replaces this with Planet.missChance (Power).
723
723
this.missChance = optsMissChance(arguments);
724
// t1112: invariant checker. strictInvariants throws (tests);
725
// debugInvariants records violations for the ?debug overlay.
726
this.strictInvariants = false;
727
this.debugInvariants = false;
728
this.lastInvariantViolations = [];
724
729
}
725
730
726
731
function optsMissChance (args)
@@ -820,7 +825,12 @@ GameCore.prototype.isGrounded = function (block)
820
825
|| block.state === STATE_LOCKED;
821
826
};
822
827
823
GameCore.prototype.stackTop = function (col, ignore)
828
/**
829
* Highest grounded landing surface in `col`. If `belowY` is given, only
830
* blocks strictly below that y count — a hanging still block above a
831
* gap must never pull a falling or thrown block upward through the gap.
832
*/
833
GameCore.prototype.stackTop = function (col, ignore, belowY)
824
834
{
825
835
var top = 0;
826
836
for (var i = 0; i < this.blocks.length; i++)
@@ -830,6 +840,8 @@ GameCore.prototype.stackTop = function (col, ignore)
830
840
{ continue; }
831
841
if (ignore && ignore(block))
832
842
{ continue; }
843
if (belowY != null && block.y + 1e-9 >= belowY)
844
{ continue; }
833
845
if (this.isGrounded(block))
834
846
{
835
847
var surface = block.y + 1;
@@ -1015,18 +1027,28 @@ GameCore.prototype.clearFlightState = function (block)
1015
1027
1016
1028
GameCore.prototype.releaseUnsupported = function ()
1017
1029
{
1018
for (var i = 0; i < this.blocks.length; i++)
1030
// Repeat until stable: a still sitting on a still that itself just
1031
// became falling must also drop. Two fixed passes are not enough
1032
// for a chain of hanging blocks (t1112).
1033
var guard = 0;
1034
var changed = true;
1035
while (changed && guard++ < this.height + 2)
1019
1036
{
1020
var block = this.blocks[i];
1021
if (block.state !== STATE_STILL)
1022
{ continue; }
1023
if (this.drag && this.drag.blockId === block.id)
1024
{ continue; }
1025
if (this.hasSupport(block))
1026
{ continue; }
1027
this.leaveCluster(block);
1028
this.clearFlightState(block);
1029
block.state = STATE_FALLING;
1037
changed = false;
1038
for (var i = 0; i < this.blocks.length; i++)
1039
{
1040
var block = this.blocks[i];
1041
if (block.state !== STATE_STILL)
1042
{ continue; }
1043
if (this.drag && this.drag.blockId === block.id)
1044
{ continue; }
1045
if (this.hasSupport(block))
1046
{ continue; }
1047
this.leaveCluster(block);
1048
this.clearFlightState(block);
1049
block.state = STATE_FALLING;
1050
changed = true;
1051
}
1030
1052
}
1031
1053
};
1032
1054
@@ -1062,24 +1084,29 @@ GameCore.prototype.attachToFlyingCluster = function (block, flyer)
1062
1084
var cluster = this.clusters[flyer.clusterId];
1063
1085
if (!cluster || cluster.phase === 'landed')
1064
1086
{ return false; }
1065
var roof = flyer.y + 1;
1066
for (var i = 0; i < this.blocks.length; i++)
1087
this.prepareClusterBody(cluster);
1088
var maxOff = null;
1089
var members = this.clusterMembers(cluster.id);
1090
for (var i = 0; i < members.length; i++)
1067
1091
{
1068
var other = this.blocks[i];
1069
if (other === block || other.col !== block.col)
1092
if (members[i].col !== block.col)
1070
1093
{ continue; }
1071
if (other.clusterId !== cluster.id)
1072
{ continue; }
1073
if (other.y + 1 > roof)
1074
{ roof = other.y + 1; }
1094
if (maxOff == null || members[i].clusterOffset > maxOff)
1095
{ maxOff = members[i].clusterOffset; }
1075
1096
}
1076
var oldN = this.clusterMembers(cluster.id).length;
1097
var oldN = members.length;
1077
1098
var fallingVy = block.vy;
1078
block.y = roof;
1099
if (block.clusterId != null && block.clusterId !== cluster.id)
1100
{ this.leaveCluster(block); }
1079
1101
block.state = STATE_FLYING;
1080
1102
block.clusterId = cluster.id;
1103
block.clusterOffset = (maxOff == null) ? 0 : maxOff + 1;
1081
1104
block.flame = false;
1082
1105
block.settleTime = 0;
1106
block.manualPhase = null;
1107
block.manualTarget = null;
1108
block.manualDecel = 0;
1109
block.pushedClusters = null;
1083
1110
// A cluster born from a thrown block averages in falling cargo
1084
1111
// the same way two flying clusters merge (t1108). Other rockets
1085
1112
// keep their velocity and just pick the cargo up.
@@ -1090,12 +1117,8 @@ GameCore.prototype.attachToFlyingCluster = function (block, flyer)
1090
1117
cluster.decel = ((cluster.decel || 0) * oldN) / newN;
1091
1118
cluster.jumpHeight = ((cluster.jumpHeight || 0) * oldN) / newN;
1092
1119
cluster.phase = cluster.vy > 1e-10 ? 'up' : 'down';
1093
var members = this.clusterMembers(cluster.id);
1094
for (var m = 0; m < members.length; m++)
1095
{ members[m].vy = cluster.vy; }
1096
1120
}
1097
else
1098
{ block.vy = cluster.vy; }
1121
this.syncClusterMembers(cluster);
1099
1122
return true;
1100
1123
};
1101
1124
@@ -1153,12 +1176,14 @@ GameCore.prototype.tick = function (dt)
1153
1176
while (left > 1e-12)
1154
1177
{
1155
1178
var step = Math.min(SUBSTEP, left);
1179
this.snapshotPrevY();
1156
1180
this.integrateFalling(step);
1157
1181
this.resolveFlyingMatches();
1158
1182
this.integrateClusters(step);
1159
1183
this.mergeFlyingClusters();
1160
1184
this.integrateManual(step);
1161
1185
this.mergeAnyManualFallingOverlaps();
1186
this.resolveAirborneCollisions();
1162
1187
this.cullOffTop();
1163
1188
left -= step;
1164
1189
}
@@ -1175,6 +1200,7 @@ GameCore.prototype.tick = function (dt)
1175
1200
{ this.resolveMatches(); }
1176
1201
this.checkLocks();
1177
1202
this.checkGameOver();
1203
this.assertInvariants('tick');
1178
1204
};
1179
1205
1180
1206
/** Step a stretch of time in fixed substeps. Useful for tests. */
@@ -1252,7 +1278,7 @@ GameCore.prototype.integrateFalling = function (dt)
1252
1278
if (this.attachToFlyingCluster(block, flyer))
1253
1279
{ continue; }
1254
1280
}
1255
var top = this.stackTop(block.col);
1281
var top = this.stackTop(block.col, null, block.y);
1256
1282
var below = this.highestFallingBelow(block);
1257
1283
if (below && below.y + 1 > top)
1258
1284
{ top = below.y + 1; }
@@ -1366,14 +1392,12 @@ GameCore.prototype.integrateClusters = function (dt)
1366
1392
if (cluster.phase === 'landed' || cluster.phase === 'hold')
1367
1393
{ continue; }
1368
1394
1395
this.prepareClusterBody(cluster);
1369
1396
var dy = this.advanceJump(cluster, dt);
1370
for (var i = 0; i < members.length; i++)
1371
{
1372
members[i].y += dy;
1373
members[i].vy = cluster.vy;
1374
}
1397
cluster.anchorY += dy;
1398
this.syncClusterMembers(cluster);
1375
1399
1376
this.catchFallingOntoCluster(cluster, members);
1400
this.catchFallingOntoCluster(cluster, this.clusterMembers(cluster.id));
1377
1401
this.checkChainRelaunch(cluster);
1378
1402
1379
1403
if (cluster.phase === 'down' && this.clusters[cluster.id])
@@ -1442,13 +1466,30 @@ GameCore.prototype.flyingClustersOverlap = function (a, b)
1442
1466
{
1443
1467
if (ma[i].col !== mb[j].col)
1444
1468
{ continue; }
1445
if (ma[i].y < mb[j].y + 1 - 1e-9 && mb[j].y < ma[i].y + 1 - 1e-9)
1469
if (this.sweptIntervalsOverlap(ma[i], mb[j]))
1446
1470
{ return true; }
1447
1471
}
1448
1472
}
1449
1473
return false;
1450
1474
};
1451
1475
1476
/**
1477
* Swept [y, y+1) of two blocks this substep, using _prevY when present.
1478
* Catches pairs that crossed without sharing a cell at either endpoint.
1479
*/
1480
GameCore.prototype.sweptIntervalsOverlap = function (a, b)
1481
{
1482
var a0 = (a._prevY != null) ? a._prevY : a.y;
1483
var a1 = a.y;
1484
var b0 = (b._prevY != null) ? b._prevY : b.y;
1485
var b1 = b.y;
1486
var aLo = Math.min(a0, a1);
1487
var aHi = Math.max(a0, a1) + 1;
1488
var bLo = Math.min(b0, b1);
1489
var bHi = Math.max(b0, b1) + 1;
1490
return aLo < bHi - 1e-9 && bLo < aHi - 1e-9;
1491
};
1492
1452
1493
GameCore.prototype.mergeClusterGroup = function (clusters)
1453
1494
{
1454
1495
clusters.sort(function (a, b) { return a.id - b.id; });
@@ -1484,7 +1525,7 @@ GameCore.prototype.mergeClusterGroup = function (clusters)
1484
1525
if (clusters[c] !== keep)
1485
1526
{ delete this.clusters[clusters[c].id]; }
1486
1527
}
1487
this.packClusterOverlaps(keep);
1528
this.prepareClusterBody(keep);
1488
1529
this.checkChainRelaunch(keep);
1489
1530
if (keep.phase === 'down' && this.clusters[keep.id])
1490
1531
{ this.tryLandCluster(keep, this.clusterMembers(keep.id)); }
@@ -1515,6 +1556,297 @@ GameCore.prototype.packClusterOverlaps = function (cluster)
1515
1556
}
1516
1557
};
1517
1558
1559
1560
/**
1561
* Derive integer cell offsets from current member positions and a
1562
* single anchorY, packing overlaps in each column while preserving
1563
* order (lower y stays lower; ties break on id). Then sync.
1564
* Flying clusters are one rigid body: one y, one vy, integer offsets.
1565
*/
1566
GameCore.prototype.prepareClusterBody = function (cluster)
1567
{
1568
if (!cluster)
1569
{ return; }
1570
var members = this.clusterMembers(cluster.id);
1571
if (!members.length)
1572
{ return; }
1573
this.rebuildClusterOffsets(cluster, members);
1574
};
1575
1576
GameCore.prototype.rebuildClusterOffsets = function (cluster, members)
1577
{
1578
members = members || this.clusterMembers(cluster.id);
1579
if (!members.length)
1580
{ return; }
1581
var byCol = Object.create(null);
1582
for (var i = 0; i < members.length; i++)
1583
{
1584
var col = members[i].col;
1585
if (!byCol[col])
1586
{ byCol[col] = []; }
1587
byCol[col].push(members[i]);
1588
}
1589
var minY = Infinity;
1590
for (var i = 0; i < members.length; i++)
1591
{
1592
if (members[i].y < minY)
1593
{ minY = members[i].y; }
1594
}
1595
if (cluster.anchorY == null || !isFinite(cluster.anchorY))
1596
{ cluster.anchorY = minY; }
1597
var cols = Object.keys(byCol);
1598
for (var c = 0; c < cols.length; c++)
1599
{
1600
var list = byCol[cols[c]];
1601
list.sort(function (a, b)
1602
{
1603
if (a.y !== b.y)
1604
{ return a.y - b.y; }
1605
return a.id - b.id;
1606
});
1607
var prevOff = -Infinity;
1608
for (var i = 0; i < list.length; i++)
1609
{
1610
var off = Math.round(list[i].y - cluster.anchorY);
1611
if (off <= prevOff)
1612
{ off = prevOff + 1; }
1613
list[i].clusterOffset = off;
1614
prevOff = off;
1615
}
1616
}
1617
// Re-base so the lowest offset is 0, keeping relative integers.
1618
var minOff = Infinity;
1619
for (var i = 0; i < members.length; i++)
1620
{
1621
if (members[i].clusterOffset < minOff)
1622
{ minOff = members[i].clusterOffset; }
1623
}
1624
if (minOff !== 0 && isFinite(minOff))
1625
{
1626
cluster.anchorY += minOff;
1627
for (var i = 0; i < members.length; i++)
1628
{ members[i].clusterOffset -= minOff; }
1629
}
1630
this.syncClusterMembers(cluster);
1631
};
1632
1633
GameCore.prototype.syncClusterMembers = function (cluster)
1634
{
1635
if (!cluster)
1636
{ return; }
1637
var members = this.clusterMembers(cluster.id);
1638
if (cluster.anchorY == null)
1639
{
1640
var minY = Infinity;
1641
for (var i = 0; i < members.length; i++)
1642
{
1643
if (members[i].y < minY)
1644
{ minY = members[i].y; }
1645
}
1646
cluster.anchorY = isFinite(minY) ? minY : 0;
1647
}
1648
for (var i = 0; i < members.length; i++)
1649
{
1650
var block = members[i];
1651
if (block.clusterOffset == null)
1652
{ block.clusterOffset = Math.round(block.y - cluster.anchorY); }
1653
block.y = cluster.anchorY + block.clusterOffset;
1654
if (cluster.phase !== 'landed')
1655
{ block.vy = cluster.vy; }
1656
}
1657
};
1658
1659
GameCore.prototype.snapshotPrevY = function ()
1660
{
1661
for (var i = 0; i < this.blocks.length; i++)
1662
{ this.blocks[i]._prevY = this.blocks[i].y; }
1663
};
1664
1665
/**
1666
* Safety net after the specific integrates: any remaining mid-air
1667
* overlap or swept crossing is resolved with the same rules, then
1668
* every flying cluster is rebuilt as a rigid body. Repeats a few
1669
* times because one attach can create a new contact.
1670
*/
1671
GameCore.prototype.resolveAirborneCollisions = function ()
1672
{
1673
var guard = 0;
1674
while (guard++ < this.height + 4)
1675
{
1676
var changed = false;
1677
1678
// Manual vs falling / cluster / manual.
1679
var manuals = [];
1680
for (var i = 0; i < this.blocks.length; i++)
1681
{
1682
if (this.blocks[i].state === STATE_MANUAL)
1683
{ manuals.push(this.blocks[i]); }
1684
}
1685
manuals.sort(function (a, b) { return b.y - a.y; });
1686
for (var m = 0; m < manuals.length; m++)
1687
{
1688
var manual = manuals[m];
1689
if (manual.state !== STATE_MANUAL)
1690
{ continue; }
1691
var oldY = (manual._prevY != null) ? manual._prevY : manual.y;
1692
if (this.resolveManualCollisions(manual, oldY, manual.y))
1693
{ changed = true; }
1694
}
1695
1696
// Falling vs flying (sit on the roof).
1697
for (var i = 0; i < this.blocks.length; i++)
1698
{
1699
var block = this.blocks[i];
1700
if (block.state !== STATE_FALLING)
1701
{ continue; }
1702
var flyer = this.highestFlyingBelow(block);
1703
if (!flyer)
1704
{
1705
// Also a flyer whose swept path crosses this falling block.
1706
flyer = this.flyingHitOnManualPath(block, (block._prevY != null) ? block._prevY : block.y, block.y);
1707
}
1708
if (flyer && this.sweptIntervalsOverlap(block, flyer))
1709
{
1710
if (this.attachToFlyingCluster(block, flyer))
1711
{ changed = true; }
1712
}
1713
}
1714
1715
// Cluster vs cluster (swept, including after a column push).
1716
var before = Object.keys(this.clusters).length;
1717
this.mergeFlyingClusters();
1718
if (Object.keys(this.clusters).length !== before)
1719
{ changed = true; }
1720
1721
// Rebuild every flying body so offsets stay integer and unique.
1722
var ids = Object.keys(this.clusters);
1723
for (var n = 0; n < ids.length; n++)
1724
{
1725
var cluster = this.clusters[ids[n]];
1726
if (!cluster || cluster.phase === 'landed' || cluster.phase === 'hold')
1727
{ continue; }
1728
this.prepareClusterBody(cluster);
1729
}
1730
1731
if (!changed)
1732
{ break; }
1733
}
1734
};
1735
1736
/**
1737
* Invariant checker (t1112). No two blocks occupy the same cell or
1738
* overlap their [y, y+1) intervals. Flying-cluster members are
1739
* grid-aligned to a single anchor. Returns a list of violation
1740
* strings (empty if clean).
1741
*/
1742
GameCore.prototype.checkInvariants = function ()
1743
{
1744
var issues = [];
1745
var byCol = Object.create(null);
1746
var ids = Object.create(null);
1747
for (var i = 0; i < this.blocks.length; i++)
1748
{
1749
var block = this.blocks[i];
1750
if (ids[block.id])
1751
{ issues.push('duplicate id ' + block.id); }
1752
ids[block.id] = true;
1753
if (!byCol[block.col])
1754
{ byCol[block.col] = []; }
1755
byCol[block.col].push(block);
1756
if (block.color < COLOR_GRAY || (block.color >= 0 && this.planet
1757
&& block.color >= this.planet.colors.length))
1758
{ issues.push('block ' + block.id + ' has invalid color ' + block.color); }
1759
}
1760
var cols = Object.keys(byCol);
1761
for (var c = 0; c < cols.length; c++)
1762
{
1763
var list = byCol[cols[c]];
1764
list.sort(function (a, b)
1765
{
1766
if (a.y !== b.y)
1767
{ return a.y - b.y; }
1768
return a.id - b.id;
1769
});
1770
for (var i = 0; i < list.length; i++)
1771
{
1772
var a = list[i];
1773
if (i > 0)
1774
{
1775
var prev = list[i - 1];
1776
if (a.y < prev.y + 1 - 1e-6)
1777
{
1778
issues.push('overlap col=' + a.col
1779
+ ' ' + this._invBlock(prev) + ' and ' + this._invBlock(a)
1780
+ ' gap=' + (a.y - prev.y));
1781
}
1782
var cellA = Math.floor(a.y + 1e-9);
1783
var cellP = Math.floor(prev.y + 1e-9);
1784
if (cellA === cellP)
1785
{
1786
issues.push('duplicate cell col=' + a.col + ' row=' + cellA
1787
+ ' ' + this._invBlock(prev) + ' and ' + this._invBlock(a));
1788
}
1789
}
1790
}
1791
}
1792
var cids = Object.keys(this.clusters);
1793
for (var n = 0; n < cids.length; n++)
1794
{
1795
var cluster = this.clusters[cids[n]];
1796
if (!cluster || cluster.phase === 'landed' || cluster.phase === 'hold')
1797
{ continue; }
1798
var mem = this.clusterMembers(cluster.id);
1799
var seenOff = Object.create(null);
1800
for (var i = 0; i < mem.length; i++)
1801
{
1802
var b = mem[i];
1803
if (cluster.anchorY != null && b.clusterOffset != null)
1804
{
1805
var expected = cluster.anchorY + b.clusterOffset;
1806
if (Math.abs(b.y - expected) > 1e-6)
1807
{
1808
issues.push('cluster ' + cluster.id + ' member ' + b.id
1809
+ ' y=' + b.y + ' != anchor+off ' + expected);
1810
}
1811
if (Math.abs(b.clusterOffset - Math.round(b.clusterOffset)) > 1e-9)
1812
{
1813
issues.push('cluster ' + cluster.id + ' member ' + b.id
1814
+ ' non-integer offset ' + b.clusterOffset);
1815
}
1816
var key = b.col + ':' + b.clusterOffset;
1817
if (seenOff[key])
1818
{
1819
issues.push('cluster ' + cluster.id + ' duplicate offset ' + key);
1820
}
1821
seenOff[key] = true;
1822
}
1823
}
1824
}
1825
return issues;
1826
};
1827
1828
GameCore.prototype._invBlock = function (b)
1829
{
1830
return '#' + b.id + '(' + b.state + ',c=' + b.color + ',y='
1831
+ (Math.round(b.y * 1000) / 1000) + ',cid=' + b.clusterId + ')';
1832
};
1833
1834
GameCore.prototype.assertInvariants = function (label)
1835
{
1836
if (!this.strictInvariants && !this.debugInvariants)
1837
{ return; }
1838
var issues = this.checkInvariants();
1839
this.lastInvariantViolations = issues;
1840
if (!issues.length)
1841
{ return; }
1842
var msg = 'physics invariants failed'
1843
+ (label ? ' at ' + label : '')
1844
+ ':\n ' + issues.join('\n ')
1845
+ '\n' + (this.snapshot ? this.snapshot().picture : '');
1846
if (this.strictInvariants)
1847
{ throw new Error(msg); }
1848
};
1849
1518
1850
GameCore.prototype.tryLandCluster = function (cluster, members)
1519
1851
{
1520
1852
if (!members.length)
@@ -1527,7 +1859,7 @@ GameCore.prototype.tryLandCluster = function (cluster, members)
1527
1859
var top = this.stackTop(block.col, function (other)
1528
1860
{
1529
1861
return other.clusterId === cluster.id;
1530
});
1862
}, block.y);
1531
1863
if (block.y <= top + 1e-9)
1532
1864
{
1533
1865
hit = true;
@@ -1539,9 +1871,10 @@ GameCore.prototype.tryLandCluster = function (cluster, members)
1539
1871
if (!hit)
1540
1872
{ return; }
1541
1873
// Lift the whole rigid body so the deepest contact sits flush.
1542
for (var i = 0; i < members.length; i++)
1543
{ members[i].y += shift; }
1544
this.landCluster(cluster, members);
1874
this.prepareClusterBody(cluster);
1875
cluster.anchorY += shift;
1876
this.syncClusterMembers(cluster);
1877
this.landCluster(cluster, this.clusterMembers(cluster.id));
1545
1878
};
1546
1879
1547
1880
/**
@@ -1642,12 +1975,11 @@ GameCore.prototype.integrateManual = function (dt)
1642
1975
var proxy = { phase: 'up', vy: block.vy, decel: block.manualDecel };
1643
1976
var dy = this.advanceJump(proxy, dt);
1644
1977
var nextY = oldY + dy;
1645
this.checkManualPush(block, oldY, Math.min(nextY, block.manualTarget));
1646
1978
block.vy = proxy.vy;
1647
1979
block.manualPhase = proxy.phase;
1648
block.y = Math.min(nextY, block.manualTarget);
1649
if (this.tryMergeManualWithFalling(block, oldY, block.y))
1980
if (this.resolveManualCollisions(block, oldY, Math.min(nextY, block.manualTarget)))
1650
1981
{ continue; }
1982
block.y = Math.min(nextY, block.manualTarget);
1651
1983
if (block.y >= block.manualTarget - 1e-12)
1652
1984
{
1653
1985
block.y = block.manualTarget;
@@ -1668,7 +2000,7 @@ GameCore.prototype.integrateManual = function (dt)
1668
2000
var dy = this.advanceJump(proxy, dt);
1669
2001
block.vy = proxy.vy;
1670
2002
var nextY = block.y + dy;
1671
var top = this.stackTop(block.col);
2003
var top = this.stackTop(block.col, null, block.y);
1672
2004
if (nextY <= top)
1673
2005
{
1674
2006
block.y = top;
@@ -1680,9 +2012,10 @@ GameCore.prototype.integrateManual = function (dt)
1680
2012
}
1681
2013
else
1682
2014
{
1683
block.y = Math.min(nextY, this.height - 1);
1684
if (this.tryMergeManualWithFalling(block, block.y - dy, block.y))
2015
var downNext = Math.min(nextY, this.height - 1);
2016
if (this.resolveManualCollisions(block, block.y, downNext))
1685
2017
{ continue; }
2018
block.y = downNext;
1686
2019
}
1687
2020
}
1688
2021
}
@@ -1857,7 +2190,7 @@ GameCore.prototype.mergeManualWithFalling = function (manual, fallingList)
1857
2190
}
1858
2191
if (this.drag && this.drag.blockId === manual.id)
1859
2192
{ this.drag = null; }
1860
this.packClusterOverlaps(cluster);
2193
this.prepareClusterBody(cluster);
1861
2194
this.checkChainRelaunch(cluster);
1862
2195
return cluster;
1863
2196
};
@@ -1882,40 +2215,217 @@ GameCore.prototype.mergeAnyManualFallingOverlaps = function ()
1882
2215
}
1883
2216
};
1884
2217
1885
GameCore.prototype.checkManualPush = function (manual, oldY, nextY)
2218
/**
2219
* Resolve collisions of a thrown (manual) block along [oldY, nextY].
2220
* Falling blocks merge (t1108). A flying cluster is pushed one cell up
2221
* in the hit column and the shot attaches at the bottom (t1111).
2222
* Another thrown block is promoted to a 1-block cluster and then the
2223
* same attach-at-bottom rule applies. Returns true if `manual` is no
2224
* longer in the MANUAL state.
2225
*/
2226
GameCore.prototype.resolveManualCollisions = function (manual, oldY, nextY)
1886
2227
{
1887
if (!manual.pushedClusters)
1888
{ manual.pushedClusters = Object.create(null); }
2228
if (!manual || manual.state !== STATE_MANUAL)
2229
{ return true; }
1889
2230
1890
var manualTopOld = oldY + 1;
1891
var manualTopNew = nextY + 1;
1892
var low = Math.min(oldY, nextY);
1893
var high = Math.max(oldY, nextY) + 1;
2231
var fallingHits = this.fallingHitsOnManualPath(manual, oldY, nextY);
2232
if (fallingHits.length)
2233
{
2234
this.mergeManualWithFalling(manual, fallingHits);
2235
return manual.state !== STATE_MANUAL;
2236
}
1894
2237
2238
var flyer = this.flyingHitOnManualPath(manual, oldY, nextY);
2239
if (flyer)
2240
{
2241
var cluster = this.clusters[flyer.clusterId];
2242
if (cluster && cluster.phase !== 'landed')
2243
{
2244
if (nextY + 1e-12 < oldY)
2245
{ this.attachToFlyingCluster(manual, flyer); }
2246
else
2247
{ this.attachShotUnderCluster(manual, cluster, manual.col); }
2248
return manual.state !== STATE_MANUAL;
2249
}
2250
}
2251
2252
var other = this.manualHitOnManualPath(manual, oldY, nextY);
2253
if (other)
2254
{
2255
var host = this.promoteManualToCluster(other);
2256
if (host)
2257
{
2258
if (nextY + 1e-12 < oldY)
2259
{ this.attachToFlyingCluster(manual, other); }
2260
else
2261
{ this.attachShotUnderCluster(manual, host, manual.col); }
2262
return manual.state !== STATE_MANUAL;
2263
}
2264
}
2265
return false;
2266
};
2267
2268
/** Closest flying cluster member in `manual`'s column on [oldY, nextY]. */
2269
GameCore.prototype.flyingHitOnManualPath = function (manual, oldY, nextY)
2270
{
2271
var lo = Math.min(oldY, nextY);
2272
var hi = Math.max(oldY, nextY) + 1;
2273
var best = null;
2274
var bestY = Infinity;
1895
2275
for (var i = 0; i < this.blocks.length; i++)
1896
2276
{
1897
2277
var other = this.blocks[i];
1898
if (other === manual)
1899
{ continue; }
1900
if (other.col !== manual.col)
2278
if (other === manual || other.col !== manual.col)
1901
2279
{ continue; }
1902
2280
if (other.state !== STATE_FLYING || other.clusterId == null)
1903
2281
{ continue; }
1904
if (manual.pushedClusters[other.clusterId])
2282
var cluster = this.clusters[other.clusterId];
2283
if (!cluster || cluster.phase === 'landed')
1905
2284
{ continue; }
1906
var otherBot = other.y;
1907
var otherTop = other.y + 1;
1908
var overlapping = otherBot < high + 1e-9 && otherTop > low - 1e-9;
1909
var crossing = manualTopOld <= otherBot + 1e-9 && manualTopNew >= otherBot - 1e-9;
1910
if (overlapping || crossing)
2285
var o0 = (other._prevY != null) ? other._prevY : other.y;
2286
var o1 = other.y;
2287
var oLo = Math.min(o0, o1);
2288
var oHi = Math.max(o0, o1) + 1;
2289
if (lo < oHi - 1e-9 && oLo < hi - 1e-9)
1911
2290
{
1912
if (this.pushClusterColumn(other.clusterId, manual.col))
2291
if (other.y < bestY)
1913
2292
{
1914
manual.pushedClusters[other.clusterId] = true;
1915
return;
2293
bestY = other.y;
2294
best = other;
1916
2295
}
1917
2296
}
1918
2297
}
2298
return best;
2299
};
2300
2301
/** Another thrown block in the same column on the path (prefer the lower). */
2302
GameCore.prototype.manualHitOnManualPath = function (manual, oldY, nextY)
2303
{
2304
var lo = Math.min(oldY, nextY);
2305
var hi = Math.max(oldY, nextY) + 1;
2306
var best = null;
2307
for (var i = 0; i < this.blocks.length; i++)
2308
{
2309
var other = this.blocks[i];
2310
if (other === manual || other.col !== manual.col)
2311
{ continue; }
2312
if (other.state !== STATE_MANUAL)
2313
{ continue; }
2314
var o0 = (other._prevY != null) ? other._prevY : other.y;
2315
var o1 = other.y;
2316
var oLo = Math.min(o0, o1);
2317
var oHi = Math.max(o0, o1) + 1;
2318
if (lo < oHi - 1e-9 && oLo < hi - 1e-9)
2319
{
2320
if (!best || other.y < best.y)
2321
{ best = other; }
2322
}
2323
}
2324
return best;
2325
};
2326
2327
/**
2328
* t1111: push every member of `cluster` in `col` up by one cell, then
2329
* attach `manual` at the bottom of that column, grid-aligned, as part
2330
* of the cluster. The cluster keeps its velocity; the shot takes it.
2331
* Other columns are untouched. Same rule for every successive shot.
2332
*/
2333
GameCore.prototype.attachShotUnderCluster = function (manual, cluster, col)
2334
{
2335
if (!manual || !cluster || !this.clusters[cluster.id])
2336
{ return false; }
2337
if (manual.state !== STATE_MANUAL && manual.clusterId !== cluster.id)
2338
{
2339
// Already belonging elsewhere: leave first.
2340
if (manual.clusterId != null)
2341
{ this.leaveCluster(manual); }
2342
}
2343
this.prepareClusterBody(cluster);
2344
var members = this.clusterMembers(cluster.id);
2345
var minOff = null;
2346
for (var i = 0; i < members.length; i++)
2347
{
2348
if (members[i].col !== col)
2349
{ continue; }
2350
if (minOff == null || members[i].clusterOffset < minOff)
2351
{ minOff = members[i].clusterOffset; }
2352
}
2353
if (minOff == null)
2354
{ minOff = 0; }
2355
else
2356
{
2357
for (var i = 0; i < members.length; i++)
2358
{
2359
if (members[i].col === col)
2360
{ members[i].clusterOffset += 1; }
2361
}
2362
}
2363
if (this.drag && this.drag.blockId === manual.id)
2364
{ this.drag = null; }
2365
manual.clusterId = cluster.id;
2366
manual.clusterOffset = minOff;
2367
manual.state = STATE_FLYING;
2368
manual.flame = manual.color === COLOR_GRAY;
2369
manual.settleTime = 0;
2370
manual.manualPhase = null;
2371
manual.manualTarget = null;
2372
manual.manualDecel = 0;
2373
manual.manualJumpHeight = 0;
2374
manual.pushedClusters = null;
2375
this.syncClusterMembers(cluster);
2376
this.cullOffTop();
2377
if (this.clusters[cluster.id])
2378
{ this.checkChainRelaunch(cluster); }
2379
return true;
2380
};
2381
2382
/**
2383
* Turn a lone thrown block into a 1-block flying cluster so a later
2384
* shot can use the t1111 attach-at-bottom rule. A single throw stays
2385
* MANUAL (and is capped at the top of the field) until it collides.
2386
*/
2387
GameCore.prototype.promoteManualToCluster = function (manual)
2388
{
2389
if (!manual)
2390
{ return null; }
2391
if (manual.state === STATE_FLYING && manual.clusterId != null)
2392
{
2393
var existing = this.clusters[manual.clusterId];
2394
if (existing && existing.phase !== 'landed')
2395
{ return existing; }
2396
}
2397
if (manual.state !== STATE_MANUAL)
2398
{ return null; }
2399
var height = manual.manualJumpHeight != null ? manual.manualJumpHeight
2400
: Math.max(0.05, (manual.manualTarget || this.height - 1) - manual.y);
2401
var cluster = {
2402
id: this.nextClusterId++,
2403
jumpHeight: height,
2404
vy: manual.vy,
2405
decel: manual.manualDecel || 0,
2406
phase: (manual.manualPhase === 'down' || manual.vy <= 1e-10) ? 'down' : 'up',
2407
fromManual: true,
2408
anchorY: manual.y
2409
};
2410
this.clusters[cluster.id] = cluster;
2411
manual.state = STATE_FLYING;
2412
manual.clusterId = cluster.id;
2413
manual.clusterOffset = 0;
2414
manual.flame = manual.color === COLOR_GRAY;
2415
manual.settleTime = 0;
2416
manual.manualPhase = null;
2417
manual.manualTarget = null;
2418
manual.manualDecel = 0;
2419
manual.manualJumpHeight = 0;
2420
manual.pushedClusters = null;
2421
this.syncClusterMembers(cluster);
2422
return cluster;
2423
};
2424
2425
/** Kept for older tests / call sites: push a cluster column by one cell. */
2426
GameCore.prototype.checkManualPush = function (manual, oldY, nextY)
2427
{
2428
return this.resolveManualCollisions(manual, oldY, nextY);
1919
2429
};
1920
2430
1921
2431
@@ -2428,6 +2938,7 @@ GameCore.prototype.launchCluster = function (matchedBlocks, height)
2428
2938
block.vy = cluster.vy;
2429
2939
block.settleTime = 0;
2430
2940
}
2941
this.prepareClusterBody(cluster);
2431
2942
return cluster;
2432
2943
};
2433
2944
@@ -3568,6 +4079,7 @@ var app = {
3568
4079
pointerType: null,
3569
4080
activeTouchId: null,
3570
4081
debugDrag: false,
4082
debugPhysics: false,
3571
4083
gameOverShown: false,
3572
4084
selectTween: null,
3573
4085
online: false,
@@ -3581,6 +4093,7 @@ var app = {
3581
4093
window.onload = function ()
3582
4094
{
3583
4095
app.debugDrag = isDragDebugEnabled();
4096
app.debugPhysics = isPhysicsDebugEnabled();
3584
4097
var play = document.getElementById('btn-play');
3585
4098
play.addEventListener('click', onPlay);
3586
4099
play.addEventListener('pointerup', function (e)
@@ -3629,6 +4142,8 @@ function startPlay (opts)
3629
4142
if (typeof miss !== 'number' || !isFinite(miss))
3630
4143
{ miss = planetMod.missChance(app.planet); }
3631
4144
app.core = new GameCore(app.planet, Math.random, miss);
4145
if (app.debugPhysics)
4146
{ app.core.debugInvariants = true; }
3632
4147
app.mode = 'playing';
3633
4148
app.online = !!opts.online;
3634
4149
app.gameOverShown = false;
@@ -4001,6 +4516,8 @@ function tickView (dt)
4001
4516
syncSprites();
4002
4517
refreshHud();
4003
4518
tickOnline(dt);
4519
if (app.debugPhysics)
4520
{ logPhysicsDebug(); }
4004
4521
4005
4522
if (app.core.state === 'gameover' && !app.gameOverShown)
4006
4523
{
@@ -4057,6 +4574,22 @@ function isDragDebugEnabled ()
4057
4574
return false;
4058
4575
}
4059
4576
4577
/** ?debug, ?debug=physics, ?debug=drag, or localStorage meteors-debug=1. */
4578
function isPhysicsDebugEnabled ()
4579
{
4580
try
4581
{
4582
var q = window.location && window.location.search;
4583
if (q && /(?:\?|&)debug(?:=|&|$)/.test(q))
4584
{ return true; }
4585
if (window.localStorage && (window.localStorage.getItem('meteors-debug') === '1'
4586
|| window.localStorage.getItem('meteors-debug-drag') === '1'))
4587
{ return true; }
4588
}
4589
catch (err) { /* ignore */ }
4590
return false;
4591
}
4592
4060
4593
function eventClient (e)
4061
4594
{
4062
4595
var t = null;
@@ -4366,6 +4899,42 @@ function onTouchCancel (e)
4366
4899
finishDrag({ noLaunch: true });
4367
4900
}
4368
4901
4902
function logPhysicsDebug ()
4903
{
4904
if (!app.debugPhysics || !app.core)
4905
{ return; }
4906
ensureDragDebugOverlay();
4907
var el = document.getElementById('drag-debug');
4908
if (!el)
4909
{ return; }
4910
var issues = app.core.lastInvariantViolations || [];
4911
var flying = 0;
4912
var manuals = 0;
4913
var clusters = app.core.clusters ? Object.keys(app.core.clusters).length : 0;
4914
for (var i = 0; i < app.core.blocks.length; i++)
4915
{
4916
if (app.core.blocks[i].state === 'flying')
4917
{ flying++; }
4918
if (app.core.blocks[i].state === 'manual')
4919
{ manuals++; }
4920
}
4921
var status = issues.length
4922
? ('PHYSICS FAIL x' + issues.length + '\n' + issues.slice(0, 6).join('\n'))
4923
: ('physics ok blocks=' + app.core.blocks.length
4924
+ ' fly=' + flying + ' man=' + manuals + ' cl=' + clusters);
4925
// Keep any live drag line above the physics status.
4926
var dragLine = '';
4927
if (app.debugDrag && lastDragDebug)
4928
{
4929
dragLine = el.textContent && el.textContent.indexOf('drag ') === 0
4930
? el.textContent.split('\n')[0] + '\n'
4931
: '';
4932
}
4933
el.textContent = dragLine + status;
4934
el.hidden = false;
4935
el.style.color = issues.length ? '#ffb4b4' : '#c6f6c8';
4936
}
4937
4369
4938
function ensureDragDebugOverlay ()
4370
4939
{
4371
4940
if (document.getElementById('drag-debug'))
@@ -721,6 +721,11 @@ function GameCore (planet, rng)721
this.outgoingShots = [];721
this.outgoingShots = [];722
// Stage-2 default; stage 3 replaces this with Planet.missChance (Power).722
// Stage-2 default; stage 3 replaces this with Planet.missChance (Power).723
this.missChance = optsMissChance(arguments);723
this.missChance = optsMissChance(arguments);724
// t1112: invariant checker. strictInvariants throws (tests);725
// debugInvariants records violations for the ?debug overlay.726
this.strictInvariants = false;727
this.debugInvariants = false;728
this.lastInvariantViolations = [];724
}729
}725
730
726
function optsMissChance (args)731
function optsMissChance (args)@@ -820,7 +825,12 @@ GameCore.prototype.isGrounded = function (block)820
|| block.state === STATE_LOCKED;825
|| block.state === STATE_LOCKED;821
};826
};822
827
823
GameCore.prototype.stackTop = function (col, ignore)828
/**829
* Highest grounded landing surface in `col`. If `belowY` is given, only830
* blocks strictly below that y count — a hanging still block above a831
* gap must never pull a falling or thrown block upward through the gap.832
*/833
GameCore.prototype.stackTop = function (col, ignore, belowY)824
{834
{825
var top = 0;835
var top = 0;826
for (var i = 0; i < this.blocks.length; i++)836
for (var i = 0; i < this.blocks.length; i++)@@ -830,6 +840,8 @@ GameCore.prototype.stackTop = function (col, ignore)830
{ continue; }840
{ continue; }831
if (ignore && ignore(block))841
if (ignore && ignore(block))832
{ continue; }842
{ continue; }843
if (belowY != null && block.y + 1e-9 >= belowY)844
{ continue; }833
if (this.isGrounded(block))845
if (this.isGrounded(block))834
{846
{835
var surface = block.y + 1;847
var surface = block.y + 1;@@ -1015,18 +1027,28 @@ GameCore.prototype.clearFlightState = function (block)1015
1027
1016
GameCore.prototype.releaseUnsupported = function ()1028
GameCore.prototype.releaseUnsupported = function ()1017
{1029
{1018
for (var i = 0; i < this.blocks.length; i++)1030
// Repeat until stable: a still sitting on a still that itself just1031
// became falling must also drop. Two fixed passes are not enough1032
// for a chain of hanging blocks (t1112).1033
var guard = 0;1034
var changed = true;1035
while (changed && guard++ < this.height + 2)1019
{1036
{1020
var block = this.blocks[i];1037
changed = false;1021
if (block.state !== STATE_STILL)1038
for (var i = 0; i < this.blocks.length; i++)1022
{ continue; }1039
{1023
if (this.drag && this.drag.blockId === block.id)1040
var block = this.blocks[i];1024
{ continue; }1041
if (block.state !== STATE_STILL)1025
if (this.hasSupport(block))1042
{ continue; }1026
{ continue; }1043
if (this.drag && this.drag.blockId === block.id)1027
this.leaveCluster(block);1044
{ continue; }1028
this.clearFlightState(block);1045
if (this.hasSupport(block))1029
block.state = STATE_FALLING;1046
{ continue; }1047
this.leaveCluster(block);1048
this.clearFlightState(block);1049
block.state = STATE_FALLING;1050
changed = true;1051
}1030
}1052
}1031
};1053
};1032
1054
@@ -1062,24 +1084,29 @@ GameCore.prototype.attachToFlyingCluster = function (block, flyer)1062
var cluster = this.clusters[flyer.clusterId];1084
var cluster = this.clusters[flyer.clusterId];1063
if (!cluster || cluster.phase === 'landed')1085
if (!cluster || cluster.phase === 'landed')1064
{ return false; }1086
{ return false; }1065
var roof = flyer.y + 1;1087
this.prepareClusterBody(cluster);1066
for (var i = 0; i < this.blocks.length; i++)1088
var maxOff = null;1089
var members = this.clusterMembers(cluster.id);1090
for (var i = 0; i < members.length; i++)1067
{1091
{1068
var other = this.blocks[i];1092
if (members[i].col !== block.col)1069
if (other === block || other.col !== block.col)1070
{ continue; }1093
{ continue; }1071
if (other.clusterId !== cluster.id)1094
if (maxOff == null || members[i].clusterOffset > maxOff)1072
{ continue; }1095
{ maxOff = members[i].clusterOffset; }1073
if (other.y + 1 > roof)1074
{ roof = other.y + 1; }1075
}1096
}1076
var oldN = this.clusterMembers(cluster.id).length;1097
var oldN = members.length;1077
var fallingVy = block.vy;1098
var fallingVy = block.vy;1078
block.y = roof;1099
if (block.clusterId != null && block.clusterId !== cluster.id)1100
{ this.leaveCluster(block); }1079
block.state = STATE_FLYING;1101
block.state = STATE_FLYING;1080
block.clusterId = cluster.id;1102
block.clusterId = cluster.id;1103
block.clusterOffset = (maxOff == null) ? 0 : maxOff + 1;1081
block.flame = false;1104
block.flame = false;1082
block.settleTime = 0;1105
block.settleTime = 0;1106
block.manualPhase = null;1107
block.manualTarget = null;1108
block.manualDecel = 0;1109
block.pushedClusters = null;1083
// A cluster born from a thrown block averages in falling cargo1110
// A cluster born from a thrown block averages in falling cargo1084
// the same way two flying clusters merge (t1108). Other rockets1111
// the same way two flying clusters merge (t1108). Other rockets1085
// keep their velocity and just pick the cargo up.1112
// keep their velocity and just pick the cargo up.@@ -1090,12 +1117,8 @@ GameCore.prototype.attachToFlyingCluster = function (block, flyer)1090
cluster.decel = ((cluster.decel || 0) * oldN) / newN;1117
cluster.decel = ((cluster.decel || 0) * oldN) / newN;1091
cluster.jumpHeight = ((cluster.jumpHeight || 0) * oldN) / newN;1118
cluster.jumpHeight = ((cluster.jumpHeight || 0) * oldN) / newN;1092
cluster.phase = cluster.vy > 1e-10 ? 'up' : 'down';1119
cluster.phase = cluster.vy > 1e-10 ? 'up' : 'down';1093
var members = this.clusterMembers(cluster.id);1094
for (var m = 0; m < members.length; m++)1095
{ members[m].vy = cluster.vy; }1096
}1120
}1097
else1121
this.syncClusterMembers(cluster);1098
{ block.vy = cluster.vy; }1099
return true;1122
return true;1100
};1123
};1101
1124
@@ -1153,12 +1176,14 @@ GameCore.prototype.tick = function (dt)1153
while (left > 1e-12)1176
while (left > 1e-12)1154
{1177
{1155
var step = Math.min(SUBSTEP, left);1178
var step = Math.min(SUBSTEP, left);1179
this.snapshotPrevY();1156
this.integrateFalling(step);1180
this.integrateFalling(step);1157
this.resolveFlyingMatches();1181
this.resolveFlyingMatches();1158
this.integrateClusters(step);1182
this.integrateClusters(step);1159
this.mergeFlyingClusters();1183
this.mergeFlyingClusters();1160
this.integrateManual(step);1184
this.integrateManual(step);1161
this.mergeAnyManualFallingOverlaps();1185
this.mergeAnyManualFallingOverlaps();1186
this.resolveAirborneCollisions();1162
this.cullOffTop();1187
this.cullOffTop();1163
left -= step;1188
left -= step;1164
}1189
}@@ -1175,6 +1200,7 @@ GameCore.prototype.tick = function (dt)1175
{ this.resolveMatches(); }1200
{ this.resolveMatches(); }1176
this.checkLocks();1201
this.checkLocks();1177
this.checkGameOver();1202
this.checkGameOver();1203
this.assertInvariants('tick');1178
};1204
};1179
1205
1180
/** Step a stretch of time in fixed substeps. Useful for tests. */1206
/** Step a stretch of time in fixed substeps. Useful for tests. */@@ -1252,7 +1278,7 @@ GameCore.prototype.integrateFalling = function (dt)1252
if (this.attachToFlyingCluster(block, flyer))1278
if (this.attachToFlyingCluster(block, flyer))1253
{ continue; }1279
{ continue; }1254
}1280
}1255
var top = this.stackTop(block.col);1281
var top = this.stackTop(block.col, null, block.y);1256
var below = this.highestFallingBelow(block);1282
var below = this.highestFallingBelow(block);1257
if (below && below.y + 1 > top)1283
if (below && below.y + 1 > top)1258
{ top = below.y + 1; }1284
{ top = below.y + 1; }@@ -1366,14 +1392,12 @@ GameCore.prototype.integrateClusters = function (dt)1366
if (cluster.phase === 'landed' || cluster.phase === 'hold')1392
if (cluster.phase === 'landed' || cluster.phase === 'hold')1367
{ continue; }1393
{ continue; }1368
1394
1395
this.prepareClusterBody(cluster);1369
var dy = this.advanceJump(cluster, dt);1396
var dy = this.advanceJump(cluster, dt);1370
for (var i = 0; i < members.length; i++)1397
cluster.anchorY += dy;1371
{1398
this.syncClusterMembers(cluster);1372
members[i].y += dy;1373
members[i].vy = cluster.vy;1374
}1375
1399
1376
this.catchFallingOntoCluster(cluster, members);1400
this.catchFallingOntoCluster(cluster, this.clusterMembers(cluster.id));1377
this.checkChainRelaunch(cluster);1401
this.checkChainRelaunch(cluster);1378
1402
1379
if (cluster.phase === 'down' && this.clusters[cluster.id])1403
if (cluster.phase === 'down' && this.clusters[cluster.id])@@ -1442,13 +1466,30 @@ GameCore.prototype.flyingClustersOverlap = function (a, b)1442
{1466
{1443
if (ma[i].col !== mb[j].col)1467
if (ma[i].col !== mb[j].col)1444
{ continue; }1468
{ continue; }1445
if (ma[i].y < mb[j].y + 1 - 1e-9 && mb[j].y < ma[i].y + 1 - 1e-9)1469
if (this.sweptIntervalsOverlap(ma[i], mb[j]))1446
{ return true; }1470
{ return true; }1447
}1471
}1448
}1472
}1449
return false;1473
return false;1450
};1474
};1451
1475
1476
/**1477
* Swept [y, y+1) of two blocks this substep, using _prevY when present.1478
* Catches pairs that crossed without sharing a cell at either endpoint.1479
*/1480
GameCore.prototype.sweptIntervalsOverlap = function (a, b)1481
{1482
var a0 = (a._prevY != null) ? a._prevY : a.y;1483
var a1 = a.y;1484
var b0 = (b._prevY != null) ? b._prevY : b.y;1485
var b1 = b.y;1486
var aLo = Math.min(a0, a1);1487
var aHi = Math.max(a0, a1) + 1;1488
var bLo = Math.min(b0, b1);1489
var bHi = Math.max(b0, b1) + 1;1490
return aLo < bHi - 1e-9 && bLo < aHi - 1e-9;1491
};1492
1452
GameCore.prototype.mergeClusterGroup = function (clusters)1493
GameCore.prototype.mergeClusterGroup = function (clusters)1453
{1494
{1454
clusters.sort(function (a, b) { return a.id - b.id; });1495
clusters.sort(function (a, b) { return a.id - b.id; });@@ -1484,7 +1525,7 @@ GameCore.prototype.mergeClusterGroup = function (clusters)1484
if (clusters[c] !== keep)1525
if (clusters[c] !== keep)1485
{ delete this.clusters[clusters[c].id]; }1526
{ delete this.clusters[clusters[c].id]; }1486
}1527
}1487
this.packClusterOverlaps(keep);1528
this.prepareClusterBody(keep);1488
this.checkChainRelaunch(keep);1529
this.checkChainRelaunch(keep);1489
if (keep.phase === 'down' && this.clusters[keep.id])1530
if (keep.phase === 'down' && this.clusters[keep.id])1490
{ this.tryLandCluster(keep, this.clusterMembers(keep.id)); }1531
{ this.tryLandCluster(keep, this.clusterMembers(keep.id)); }@@ -1515,6 +1556,297 @@ GameCore.prototype.packClusterOverlaps = function (cluster)1515
}1556
}1516
};1557
};1517
1558
1559
1560
/**1561
* Derive integer cell offsets from current member positions and a1562
* single anchorY, packing overlaps in each column while preserving1563
* order (lower y stays lower; ties break on id). Then sync.1564
* Flying clusters are one rigid body: one y, one vy, integer offsets.1565
*/1566
GameCore.prototype.prepareClusterBody = function (cluster)1567
{1568
if (!cluster)1569
{ return; }1570
var members = this.clusterMembers(cluster.id);1571
if (!members.length)1572
{ return; }1573
this.rebuildClusterOffsets(cluster, members);1574
};1575
1576
GameCore.prototype.rebuildClusterOffsets = function (cluster, members)1577
{1578
members = members || this.clusterMembers(cluster.id);1579
if (!members.length)1580
{ return; }1581
var byCol = Object.create(null);1582
for (var i = 0; i < members.length; i++)1583
{1584
var col = members[i].col;1585
if (!byCol[col])1586
{ byCol[col] = []; }1587
byCol[col].push(members[i]);1588
}1589
var minY = Infinity;1590
for (var i = 0; i < members.length; i++)1591
{1592
if (members[i].y < minY)1593
{ minY = members[i].y; }1594
}1595
if (cluster.anchorY == null || !isFinite(cluster.anchorY))1596
{ cluster.anchorY = minY; }1597
var cols = Object.keys(byCol);1598
for (var c = 0; c < cols.length; c++)1599
{1600
var list = byCol[cols[c]];1601
list.sort(function (a, b)1602
{1603
if (a.y !== b.y)1604
{ return a.y - b.y; }1605
return a.id - b.id;1606
});1607
var prevOff = -Infinity;1608
for (var i = 0; i < list.length; i++)1609
{1610
var off = Math.round(list[i].y - cluster.anchorY);1611
if (off <= prevOff)1612
{ off = prevOff + 1; }1613
list[i].clusterOffset = off;1614
prevOff = off;1615
}1616
}1617
// Re-base so the lowest offset is 0, keeping relative integers.1618
var minOff = Infinity;1619
for (var i = 0; i < members.length; i++)1620
{1621
if (members[i].clusterOffset < minOff)1622
{ minOff = members[i].clusterOffset; }1623
}1624
if (minOff !== 0 && isFinite(minOff))1625
{1626
cluster.anchorY += minOff;1627
for (var i = 0; i < members.length; i++)1628
{ members[i].clusterOffset -= minOff; }1629
}1630
this.syncClusterMembers(cluster);1631
};1632
1633
GameCore.prototype.syncClusterMembers = function (cluster)1634
{1635
if (!cluster)1636
{ return; }1637
var members = this.clusterMembers(cluster.id);1638
if (cluster.anchorY == null)1639
{1640
var minY = Infinity;1641
for (var i = 0; i < members.length; i++)1642
{1643
if (members[i].y < minY)1644
{ minY = members[i].y; }1645
}1646
cluster.anchorY = isFinite(minY) ? minY : 0;1647
}1648
for (var i = 0; i < members.length; i++)1649
{1650
var block = members[i];1651
if (block.clusterOffset == null)1652
{ block.clusterOffset = Math.round(block.y - cluster.anchorY); }1653
block.y = cluster.anchorY + block.clusterOffset;1654
if (cluster.phase !== 'landed')1655
{ block.vy = cluster.vy; }1656
}1657
};1658
1659
GameCore.prototype.snapshotPrevY = function ()1660
{1661
for (var i = 0; i < this.blocks.length; i++)1662
{ this.blocks[i]._prevY = this.blocks[i].y; }1663
};1664
1665
/**1666
* Safety net after the specific integrates: any remaining mid-air1667
* overlap or swept crossing is resolved with the same rules, then1668
* every flying cluster is rebuilt as a rigid body. Repeats a few1669
* times because one attach can create a new contact.1670
*/1671
GameCore.prototype.resolveAirborneCollisions = function ()1672
{1673
var guard = 0;1674
while (guard++ < this.height + 4)1675
{1676
var changed = false;1677
1678
// Manual vs falling / cluster / manual.1679
var manuals = [];1680
for (var i = 0; i < this.blocks.length; i++)1681
{1682
if (this.blocks[i].state === STATE_MANUAL)1683
{ manuals.push(this.blocks[i]); }1684
}1685
manuals.sort(function (a, b) { return b.y - a.y; });1686
for (var m = 0; m < manuals.length; m++)1687
{1688
var manual = manuals[m];1689
if (manual.state !== STATE_MANUAL)1690
{ continue; }1691
var oldY = (manual._prevY != null) ? manual._prevY : manual.y;1692
if (this.resolveManualCollisions(manual, oldY, manual.y))1693
{ changed = true; }1694
}1695
1696
// Falling vs flying (sit on the roof).1697
for (var i = 0; i < this.blocks.length; i++)1698
{1699
var block = this.blocks[i];1700
if (block.state !== STATE_FALLING)1701
{ continue; }1702
var flyer = this.highestFlyingBelow(block);1703
if (!flyer)1704
{1705
// Also a flyer whose swept path crosses this falling block.1706
flyer = this.flyingHitOnManualPath(block, (block._prevY != null) ? block._prevY : block.y, block.y);1707
}1708
if (flyer && this.sweptIntervalsOverlap(block, flyer))1709
{1710
if (this.attachToFlyingCluster(block, flyer))1711
{ changed = true; }1712
}1713
}1714
1715
// Cluster vs cluster (swept, including after a column push).1716
var before = Object.keys(this.clusters).length;1717
this.mergeFlyingClusters();1718
if (Object.keys(this.clusters).length !== before)1719
{ changed = true; }1720
1721
// Rebuild every flying body so offsets stay integer and unique.1722
var ids = Object.keys(this.clusters);1723
for (var n = 0; n < ids.length; n++)1724
{1725
var cluster = this.clusters[ids[n]];1726
if (!cluster || cluster.phase === 'landed' || cluster.phase === 'hold')1727
{ continue; }1728
this.prepareClusterBody(cluster);1729
}1730
1731
if (!changed)1732
{ break; }1733
}1734
};1735
1736
/**1737
* Invariant checker (t1112). No two blocks occupy the same cell or1738
* overlap their [y, y+1) intervals. Flying-cluster members are1739
* grid-aligned to a single anchor. Returns a list of violation1740
* strings (empty if clean).1741
*/1742
GameCore.prototype.checkInvariants = function ()1743
{1744
var issues = [];1745
var byCol = Object.create(null);1746
var ids = Object.create(null);1747
for (var i = 0; i < this.blocks.length; i++)1748
{1749
var block = this.blocks[i];1750
if (ids[block.id])1751
{ issues.push('duplicate id ' + block.id); }1752
ids[block.id] = true;1753
if (!byCol[block.col])1754
{ byCol[block.col] = []; }1755
byCol[block.col].push(block);1756
if (block.color < COLOR_GRAY || (block.color >= 0 && this.planet1757
&& block.color >= this.planet.colors.length))1758
{ issues.push('block ' + block.id + ' has invalid color ' + block.color); }1759
}1760
var cols = Object.keys(byCol);1761
for (var c = 0; c < cols.length; c++)1762
{1763
var list = byCol[cols[c]];1764
list.sort(function (a, b)1765
{1766
if (a.y !== b.y)1767
{ return a.y - b.y; }1768
return a.id - b.id;1769
});1770
for (var i = 0; i < list.length; i++)1771
{1772
var a = list[i];1773
if (i > 0)1774
{1775
var prev = list[i - 1];1776
if (a.y < prev.y + 1 - 1e-6)1777
{1778
issues.push('overlap col=' + a.col1779
+ ' ' + this._invBlock(prev) + ' and ' + this._invBlock(a)1780
+ ' gap=' + (a.y - prev.y));1781
}1782
var cellA = Math.floor(a.y + 1e-9);1783
var cellP = Math.floor(prev.y + 1e-9);1784
if (cellA === cellP)1785
{1786
issues.push('duplicate cell col=' + a.col + ' row=' + cellA1787
+ ' ' + this._invBlock(prev) + ' and ' + this._invBlock(a));1788
}1789
}1790
}1791
}1792
var cids = Object.keys(this.clusters);1793
for (var n = 0; n < cids.length; n++)1794
{1795
var cluster = this.clusters[cids[n]];1796
if (!cluster || cluster.phase === 'landed' || cluster.phase === 'hold')1797
{ continue; }1798
var mem = this.clusterMembers(cluster.id);1799
var seenOff = Object.create(null);1800
for (var i = 0; i < mem.length; i++)1801
{1802
var b = mem[i];1803
if (cluster.anchorY != null && b.clusterOffset != null)1804
{1805
var expected = cluster.anchorY + b.clusterOffset;1806
if (Math.abs(b.y - expected) > 1e-6)1807
{1808
issues.push('cluster ' + cluster.id + ' member ' + b.id1809
+ ' y=' + b.y + ' != anchor+off ' + expected);1810
}1811
if (Math.abs(b.clusterOffset - Math.round(b.clusterOffset)) > 1e-9)1812
{1813
issues.push('cluster ' + cluster.id + ' member ' + b.id1814
+ ' non-integer offset ' + b.clusterOffset);1815
}1816
var key = b.col + ':' + b.clusterOffset;1817
if (seenOff[key])1818
{1819
issues.push('cluster ' + cluster.id + ' duplicate offset ' + key);1820
}1821
seenOff[key] = true;1822
}1823
}1824
}1825
return issues;1826
};1827
1828
GameCore.prototype._invBlock = function (b)1829
{1830
return '#' + b.id + '(' + b.state + ',c=' + b.color + ',y='1831
+ (Math.round(b.y * 1000) / 1000) + ',cid=' + b.clusterId + ')';1832
};1833
1834
GameCore.prototype.assertInvariants = function (label)1835
{1836
if (!this.strictInvariants && !this.debugInvariants)1837
{ return; }1838
var issues = this.checkInvariants();1839
this.lastInvariantViolations = issues;1840
if (!issues.length)1841
{ return; }1842
var msg = 'physics invariants failed'1843
+ (label ? ' at ' + label : '')1844
+ ':\n ' + issues.join('\n ')1845
+ '\n' + (this.snapshot ? this.snapshot().picture : '');1846
if (this.strictInvariants)1847
{ throw new Error(msg); }1848
};1849
1518
GameCore.prototype.tryLandCluster = function (cluster, members)1850
GameCore.prototype.tryLandCluster = function (cluster, members)1519
{1851
{1520
if (!members.length)1852
if (!members.length)@@ -1527,7 +1859,7 @@ GameCore.prototype.tryLandCluster = function (cluster, members)1527
var top = this.stackTop(block.col, function (other)1859
var top = this.stackTop(block.col, function (other)1528
{1860
{1529
return other.clusterId === cluster.id;1861
return other.clusterId === cluster.id;1530
});1862
}, block.y);1531
if (block.y <= top + 1e-9)1863
if (block.y <= top + 1e-9)1532
{1864
{1533
hit = true;1865
hit = true;@@ -1539,9 +1871,10 @@ GameCore.prototype.tryLandCluster = function (cluster, members)1539
if (!hit)1871
if (!hit)1540
{ return; }1872
{ return; }1541
// Lift the whole rigid body so the deepest contact sits flush.1873
// Lift the whole rigid body so the deepest contact sits flush.1542
for (var i = 0; i < members.length; i++)1874
this.prepareClusterBody(cluster);1543
{ members[i].y += shift; }1875
cluster.anchorY += shift;1544
this.landCluster(cluster, members);1876
this.syncClusterMembers(cluster);1877
this.landCluster(cluster, this.clusterMembers(cluster.id));1545
};1878
};1546
1879
1547
/**1880
/**@@ -1642,12 +1975,11 @@ GameCore.prototype.integrateManual = function (dt)1642
var proxy = { phase: 'up', vy: block.vy, decel: block.manualDecel };1975
var proxy = { phase: 'up', vy: block.vy, decel: block.manualDecel };1643
var dy = this.advanceJump(proxy, dt);1976
var dy = this.advanceJump(proxy, dt);1644
var nextY = oldY + dy;1977
var nextY = oldY + dy;1645
this.checkManualPush(block, oldY, Math.min(nextY, block.manualTarget));1646
block.vy = proxy.vy;1978
block.vy = proxy.vy;1647
block.manualPhase = proxy.phase;1979
block.manualPhase = proxy.phase;1648
block.y = Math.min(nextY, block.manualTarget);1980
if (this.resolveManualCollisions(block, oldY, Math.min(nextY, block.manualTarget)))1649
if (this.tryMergeManualWithFalling(block, oldY, block.y))1650
{ continue; }1981
{ continue; }1982
block.y = Math.min(nextY, block.manualTarget);1651
if (block.y >= block.manualTarget - 1e-12)1983
if (block.y >= block.manualTarget - 1e-12)1652
{1984
{1653
block.y = block.manualTarget;1985
block.y = block.manualTarget;@@ -1668,7 +2000,7 @@ GameCore.prototype.integrateManual = function (dt)1668
var dy = this.advanceJump(proxy, dt);2000
var dy = this.advanceJump(proxy, dt);1669
block.vy = proxy.vy;2001
block.vy = proxy.vy;1670
var nextY = block.y + dy;2002
var nextY = block.y + dy;1671
var top = this.stackTop(block.col);2003
var top = this.stackTop(block.col, null, block.y);1672
if (nextY <= top)2004
if (nextY <= top)1673
{2005
{1674
block.y = top;2006
block.y = top;@@ -1680,9 +2012,10 @@ GameCore.prototype.integrateManual = function (dt)1680
}2012
}1681
else2013
else1682
{2014
{1683
block.y = Math.min(nextY, this.height - 1);2015
var downNext = Math.min(nextY, this.height - 1);1684
if (this.tryMergeManualWithFalling(block, block.y - dy, block.y))2016
if (this.resolveManualCollisions(block, block.y, downNext))1685
{ continue; }2017
{ continue; }2018
block.y = downNext;1686
}2019
}1687
}2020
}1688
}2021
}@@ -1857,7 +2190,7 @@ GameCore.prototype.mergeManualWithFalling = function (manual, fallingList)1857
}2190
}1858
if (this.drag && this.drag.blockId === manual.id)2191
if (this.drag && this.drag.blockId === manual.id)1859
{ this.drag = null; }2192
{ this.drag = null; }1860
this.packClusterOverlaps(cluster);2193
this.prepareClusterBody(cluster);1861
this.checkChainRelaunch(cluster);2194
this.checkChainRelaunch(cluster);1862
return cluster;2195
return cluster;1863
};2196
};@@ -1882,40 +2215,217 @@ GameCore.prototype.mergeAnyManualFallingOverlaps = function ()1882
}2215
}1883
};2216
};1884
2217
1885
GameCore.prototype.checkManualPush = function (manual, oldY, nextY)2218
/**2219
* Resolve collisions of a thrown (manual) block along [oldY, nextY].2220
* Falling blocks merge (t1108). A flying cluster is pushed one cell up2221
* in the hit column and the shot attaches at the bottom (t1111).2222
* Another thrown block is promoted to a 1-block cluster and then the2223
* same attach-at-bottom rule applies. Returns true if `manual` is no2224
* longer in the MANUAL state.2225
*/2226
GameCore.prototype.resolveManualCollisions = function (manual, oldY, nextY)1886
{2227
{1887
if (!manual.pushedClusters)2228
if (!manual || manual.state !== STATE_MANUAL)1888
{ manual.pushedClusters = Object.create(null); }2229
{ return true; }1889
2230
1890
var manualTopOld = oldY + 1;2231
var fallingHits = this.fallingHitsOnManualPath(manual, oldY, nextY);1891
var manualTopNew = nextY + 1;2232
if (fallingHits.length)1892
var low = Math.min(oldY, nextY);2233
{1893
var high = Math.max(oldY, nextY) + 1;2234
this.mergeManualWithFalling(manual, fallingHits);2235
return manual.state !== STATE_MANUAL;2236
}1894
2237
2238
var flyer = this.flyingHitOnManualPath(manual, oldY, nextY);2239
if (flyer)2240
{2241
var cluster = this.clusters[flyer.clusterId];2242
if (cluster && cluster.phase !== 'landed')2243
{2244
if (nextY + 1e-12 < oldY)2245
{ this.attachToFlyingCluster(manual, flyer); }2246
else2247
{ this.attachShotUnderCluster(manual, cluster, manual.col); }2248
return manual.state !== STATE_MANUAL;2249
}2250
}2251
2252
var other = this.manualHitOnManualPath(manual, oldY, nextY);2253
if (other)2254
{2255
var host = this.promoteManualToCluster(other);2256
if (host)2257
{2258
if (nextY + 1e-12 < oldY)2259
{ this.attachToFlyingCluster(manual, other); }2260
else2261
{ this.attachShotUnderCluster(manual, host, manual.col); }2262
return manual.state !== STATE_MANUAL;2263
}2264
}2265
return false;2266
};2267
2268
/** Closest flying cluster member in `manual`'s column on [oldY, nextY]. */2269
GameCore.prototype.flyingHitOnManualPath = function (manual, oldY, nextY)2270
{2271
var lo = Math.min(oldY, nextY);2272
var hi = Math.max(oldY, nextY) + 1;2273
var best = null;2274
var bestY = Infinity;1895
for (var i = 0; i < this.blocks.length; i++)2275
for (var i = 0; i < this.blocks.length; i++)1896
{2276
{1897
var other = this.blocks[i];2277
var other = this.blocks[i];1898
if (other === manual)2278
if (other === manual || other.col !== manual.col)1899
{ continue; }1900
if (other.col !== manual.col)1901
{ continue; }2279
{ continue; }1902
if (other.state !== STATE_FLYING || other.clusterId == null)2280
if (other.state !== STATE_FLYING || other.clusterId == null)1903
{ continue; }2281
{ continue; }1904
if (manual.pushedClusters[other.clusterId])2282
var cluster = this.clusters[other.clusterId];2283
if (!cluster || cluster.phase === 'landed')1905
{ continue; }2284
{ continue; }1906
var otherBot = other.y;2285
var o0 = (other._prevY != null) ? other._prevY : other.y;1907
var otherTop = other.y + 1;2286
var o1 = other.y;1908
var overlapping = otherBot < high + 1e-9 && otherTop > low - 1e-9;2287
var oLo = Math.min(o0, o1);1909
var crossing = manualTopOld <= otherBot + 1e-9 && manualTopNew >= otherBot - 1e-9;2288
var oHi = Math.max(o0, o1) + 1;1910
if (overlapping || crossing)2289
if (lo < oHi - 1e-9 && oLo < hi - 1e-9)1911
{2290
{1912
if (this.pushClusterColumn(other.clusterId, manual.col))2291
if (other.y < bestY)1913
{2292
{1914
manual.pushedClusters[other.clusterId] = true;2293
bestY = other.y;1915
return;2294
best = other;1916
}2295
}1917
}2296
}1918
}2297
}2298
return best;2299
};2300
2301
/** Another thrown block in the same column on the path (prefer the lower). */2302
GameCore.prototype.manualHitOnManualPath = function (manual, oldY, nextY)2303
{2304
var lo = Math.min(oldY, nextY);2305
var hi = Math.max(oldY, nextY) + 1;2306
var best = null;2307
for (var i = 0; i < this.blocks.length; i++)2308
{2309
var other = this.blocks[i];2310
if (other === manual || other.col !== manual.col)2311
{ continue; }2312
if (other.state !== STATE_MANUAL)2313
{ continue; }2314
var o0 = (other._prevY != null) ? other._prevY : other.y;2315
var o1 = other.y;2316
var oLo = Math.min(o0, o1);2317
var oHi = Math.max(o0, o1) + 1;2318
if (lo < oHi - 1e-9 && oLo < hi - 1e-9)2319
{2320
if (!best || other.y < best.y)2321
{ best = other; }2322
}2323
}2324
return best;2325
};2326
2327
/**2328
* t1111: push every member of `cluster` in `col` up by one cell, then2329
* attach `manual` at the bottom of that column, grid-aligned, as part2330
* of the cluster. The cluster keeps its velocity; the shot takes it.2331
* Other columns are untouched. Same rule for every successive shot.2332
*/2333
GameCore.prototype.attachShotUnderCluster = function (manual, cluster, col)2334
{2335
if (!manual || !cluster || !this.clusters[cluster.id])2336
{ return false; }2337
if (manual.state !== STATE_MANUAL && manual.clusterId !== cluster.id)2338
{2339
// Already belonging elsewhere: leave first.2340
if (manual.clusterId != null)2341
{ this.leaveCluster(manual); }2342
}2343
this.prepareClusterBody(cluster);2344
var members = this.clusterMembers(cluster.id);2345
var minOff = null;2346
for (var i = 0; i < members.length; i++)2347
{2348
if (members[i].col !== col)2349
{ continue; }2350
if (minOff == null || members[i].clusterOffset < minOff)2351
{ minOff = members[i].clusterOffset; }2352
}2353
if (minOff == null)2354
{ minOff = 0; }2355
else2356
{2357
for (var i = 0; i < members.length; i++)2358
{2359
if (members[i].col === col)2360
{ members[i].clusterOffset += 1; }2361
}2362
}2363
if (this.drag && this.drag.blockId === manual.id)2364
{ this.drag = null; }2365
manual.clusterId = cluster.id;2366
manual.clusterOffset = minOff;2367
manual.state = STATE_FLYING;2368
manual.flame = manual.color === COLOR_GRAY;2369
manual.settleTime = 0;2370
manual.manualPhase = null;2371
manual.manualTarget = null;2372
manual.manualDecel = 0;2373
manual.manualJumpHeight = 0;2374
manual.pushedClusters = null;2375
this.syncClusterMembers(cluster);2376
this.cullOffTop();2377
if (this.clusters[cluster.id])2378
{ this.checkChainRelaunch(cluster); }2379
return true;2380
};2381
2382
/**2383
* Turn a lone thrown block into a 1-block flying cluster so a later2384
* shot can use the t1111 attach-at-bottom rule. A single throw stays2385
* MANUAL (and is capped at the top of the field) until it collides.2386
*/2387
GameCore.prototype.promoteManualToCluster = function (manual)2388
{2389
if (!manual)2390
{ return null; }2391
if (manual.state === STATE_FLYING && manual.clusterId != null)2392
{2393
var existing = this.clusters[manual.clusterId];2394
if (existing && existing.phase !== 'landed')2395
{ return existing; }2396
}2397
if (manual.state !== STATE_MANUAL)2398
{ return null; }2399
var height = manual.manualJumpHeight != null ? manual.manualJumpHeight2400
: Math.max(0.05, (manual.manualTarget || this.height - 1) - manual.y);2401
var cluster = {2402
id: this.nextClusterId++,2403
jumpHeight: height,2404
vy: manual.vy,2405
decel: manual.manualDecel || 0,2406
phase: (manual.manualPhase === 'down' || manual.vy <= 1e-10) ? 'down' : 'up',2407
fromManual: true,2408
anchorY: manual.y2409
};2410
this.clusters[cluster.id] = cluster;2411
manual.state = STATE_FLYING;2412
manual.clusterId = cluster.id;2413
manual.clusterOffset = 0;2414
manual.flame = manual.color === COLOR_GRAY;2415
manual.settleTime = 0;2416
manual.manualPhase = null;2417
manual.manualTarget = null;2418
manual.manualDecel = 0;2419
manual.manualJumpHeight = 0;2420
manual.pushedClusters = null;2421
this.syncClusterMembers(cluster);2422
return cluster;2423
};2424
2425
/** Kept for older tests / call sites: push a cluster column by one cell. */2426
GameCore.prototype.checkManualPush = function (manual, oldY, nextY)2427
{2428
return this.resolveManualCollisions(manual, oldY, nextY);1919
};2429
};1920
2430
1921
2431
@@ -2428,6 +2938,7 @@ GameCore.prototype.launchCluster = function (matchedBlocks, height)2428
block.vy = cluster.vy;2938
block.vy = cluster.vy;2429
block.settleTime = 0;2939
block.settleTime = 0;2430
}2940
}2941
this.prepareClusterBody(cluster);2431
return cluster;2942
return cluster;2432
};2943
};2433
2944
@@ -3568,6 +4079,7 @@ var app = {3568
pointerType: null,4079
pointerType: null,3569
activeTouchId: null,4080
activeTouchId: null,3570
debugDrag: false,4081
debugDrag: false,4082
debugPhysics: false,3571
gameOverShown: false,4083
gameOverShown: false,3572
selectTween: null,4084
selectTween: null,3573
online: false,4085
online: false,@@ -3581,6 +4093,7 @@ var app = {3581
window.onload = function ()4093
window.onload = function ()3582
{4094
{3583
app.debugDrag = isDragDebugEnabled();4095
app.debugDrag = isDragDebugEnabled();4096
app.debugPhysics = isPhysicsDebugEnabled();3584
var play = document.getElementById('btn-play');4097
var play = document.getElementById('btn-play');3585
play.addEventListener('click', onPlay);4098
play.addEventListener('click', onPlay);3586
play.addEventListener('pointerup', function (e)4099
play.addEventListener('pointerup', function (e)@@ -3629,6 +4142,8 @@ function startPlay (opts)3629
if (typeof miss !== 'number' || !isFinite(miss))4142
if (typeof miss !== 'number' || !isFinite(miss))3630
{ miss = planetMod.missChance(app.planet); }4143
{ miss = planetMod.missChance(app.planet); }3631
app.core = new GameCore(app.planet, Math.random, miss);4144
app.core = new GameCore(app.planet, Math.random, miss);4145
if (app.debugPhysics)4146
{ app.core.debugInvariants = true; }3632
app.mode = 'playing';4147
app.mode = 'playing';3633
app.online = !!opts.online;4148
app.online = !!opts.online;3634
app.gameOverShown = false;4149
app.gameOverShown = false;@@ -4001,6 +4516,8 @@ function tickView (dt)4001
syncSprites();4516
syncSprites();4002
refreshHud();4517
refreshHud();4003
tickOnline(dt);4518
tickOnline(dt);4519
if (app.debugPhysics)4520
{ logPhysicsDebug(); }4004
4521
4005
if (app.core.state === 'gameover' && !app.gameOverShown)4522
if (app.core.state === 'gameover' && !app.gameOverShown)4006
{4523
{@@ -4057,6 +4574,22 @@ function isDragDebugEnabled ()4057
return false;4574
return false;4058
}4575
}4059
4576
4577
/** ?debug, ?debug=physics, ?debug=drag, or localStorage meteors-debug=1. */4578
function isPhysicsDebugEnabled ()4579
{4580
try4581
{4582
var q = window.location && window.location.search;4583
if (q && /(?:\?|&)debug(?:=|&|$)/.test(q))4584
{ return true; }4585
if (window.localStorage && (window.localStorage.getItem('meteors-debug') === '1'4586
|| window.localStorage.getItem('meteors-debug-drag') === '1'))4587
{ return true; }4588
}4589
catch (err) { /* ignore */ }4590
return false;4591
}4592
4060
function eventClient (e)4593
function eventClient (e)4061
{4594
{4062
var t = null;4595
var t = null;@@ -4366,6 +4899,42 @@ function onTouchCancel (e)4366
finishDrag({ noLaunch: true });4899
finishDrag({ noLaunch: true });4367
}4900
}4368
4901
4902
function logPhysicsDebug ()4903
{4904
if (!app.debugPhysics || !app.core)4905
{ return; }4906
ensureDragDebugOverlay();4907
var el = document.getElementById('drag-debug');4908
if (!el)4909
{ return; }4910
var issues = app.core.lastInvariantViolations || [];4911
var flying = 0;4912
var manuals = 0;4913
var clusters = app.core.clusters ? Object.keys(app.core.clusters).length : 0;4914
for (var i = 0; i < app.core.blocks.length; i++)4915
{4916
if (app.core.blocks[i].state === 'flying')4917
{ flying++; }4918
if (app.core.blocks[i].state === 'manual')4919
{ manuals++; }4920
}4921
var status = issues.length4922
? ('PHYSICS FAIL x' + issues.length + '\n' + issues.slice(0, 6).join('\n'))4923
: ('physics ok blocks=' + app.core.blocks.length4924
+ ' fly=' + flying + ' man=' + manuals + ' cl=' + clusters);4925
// Keep any live drag line above the physics status.4926
var dragLine = '';4927
if (app.debugDrag && lastDragDebug)4928
{4929
dragLine = el.textContent && el.textContent.indexOf('drag ') === 04930
? el.textContent.split('\n')[0] + '\n'4931
: '';4932
}4933
el.textContent = dragLine + status;4934
el.hidden = false;4935
el.style.color = issues.length ? '#ffb4b4' : '#c6f6c8';4936
}4937
4369
function ensureDragDebugOverlay ()4938
function ensureDragDebugOverlay ()4370
{4939
{4371
if (document.getElementById('drag-debug'))4940
if (document.getElementById('drag-debug'))@@ -434,3 +434,17 @@ Aanname:
434
434
- De vlam onder raketten is 3× zo groot, in lengte én breedte
435
435
(`0,85 × 3` tegels). De bovenkant van de vlam blijft op dezelfde
436
436
overlap in het blokje; de extra lengte steekt naar beneden uit.
437
438
## t1111 / t1112 — schot in een cluster, en physics-audit
439
440
- Zie `docs/PHYSICS.md` voor de volledige lijst van gevonden oorzaken
441
(video `t1111.webm`) en de herschreven regels.
442
- Schot in een vliegende cluster: de geraakte kolom 1 cel omhoog, het
443
schot sluit onderaan aan, rooster-uitgelijnd, als lid. Elke volgende
444
worp hetzelfde. Vliegende clusters zijn één star lichaam (één `y`/`vy`,
445
gehele offsets). Geen twee blokjes delen een cel of overlappen;
446
volgorde in een kolom blijft; verdwijnen/dupliceren/kleur veranderen
447
alleen via de bekende regels (match → grijs, grijs recolor, of
448
scoren over de bovenkant).
449
- `?debug` (of `?debug=physics` / `?debug=drag`) zet de
450
invariant-checker aan en toont overtredingen in de overlay.
@@ -434,3 +434,17 @@ Aanname:434
- De vlam onder raketten is 3× zo groot, in lengte én breedte434
- De vlam onder raketten is 3× zo groot, in lengte én breedte435
(`0,85 × 3` tegels). De bovenkant van de vlam blijft op dezelfde435
(`0,85 × 3` tegels). De bovenkant van de vlam blijft op dezelfde436
overlap in het blokje; de extra lengte steekt naar beneden uit.436
overlap in het blokje; de extra lengte steekt naar beneden uit.437
438
## t1111 / t1112 — schot in een cluster, en physics-audit439
440
- Zie `docs/PHYSICS.md` voor de volledige lijst van gevonden oorzaken441
(video `t1111.webm`) en de herschreven regels.442
- Schot in een vliegende cluster: de geraakte kolom 1 cel omhoog, het443
schot sluit onderaan aan, rooster-uitgelijnd, als lid. Elke volgende444
worp hetzelfde. Vliegende clusters zijn één star lichaam (één `y`/`vy`,445
gehele offsets). Geen twee blokjes delen een cel of overlappen;446
volgorde in een kolom blijft; verdwijnen/dupliceren/kleur veranderen447
alleen via de bekende regels (match → grijs, grijs recolor, of448
scoren over de bovenkant).449
- `?debug` (of `?debug=physics` / `?debug=drag`) zet de450
invariant-checker aan en toont overtredingen in de overlay.@@ -0,0 +1,117 @@
1
# Physics-audit (t1111 / t1112)
2
3
Problemen die we vonden in de vlucht-, bots-, merge-, landings-, settle-
4
en recolor-logica op master `1ede900`, nagegaan aan de hand van
5
`t1111.webm` en een gerandomiseerde soak. Daarna de herschrijving.
6
7
## Wat Tim zag (video, 3e kolom)
8
9
- Gegoide roze blokjes liepen een eerder gegooid roze blokje in en
10
overlapten in dezelfde cel.
11
- Een gegooid geel blokje ging door twee roze blokjes heen en overlapte
12
een vallend groen blokje.
13
- Bij de landing snapte de stapel, met een gat (geel, gat, roze, groen,
14
roze).
15
- Een blokje leek van kleur of type te veranderen.
16
- Nog een worp ging door het onderste blokje heen.
17
- De cluster stortte in tot 2 cellen met overlaps, alsof blokjes
18
verdwenen.
19
- Een worp liet de cluster in een gatloze 5-stapel teleporten, die
20
vervolgens tot 3 rijen met overlaps inzakte.
21
- De stapel spreidde zich daarna naar beneden uit, met gaten en
22
overlaps over meerdere frames.
23
24
## Gevonden oorzaken
25
26
1. **Een gegooid blokje duwde een cluster-kolom omhoog maar sloot niet
27
aan (t1111).** `checkManualPush` / `pushClusterColumn` schoof de
28
geraakte kolom 1 tegel op en zette `pushedClusters` zodat die worp
29
de cluster niet nóg eens duwde. Het gegoide blokje zelf bleef
30
MANUAL en vloog door de cluster heen. Elke volgende worp deed
31
hetzelfde: door elkaar, overlaps, daarna een late pack die alles
32
in één stapel duwde (“teleport naar een 5-stapel”).
33
34
2. **Twee gegooide (MANUAL) blokjes hadden geen botsing.** Een tweede
35
worp in dezelfde kolom liep de eerste in en deelde een cel. Precies
36
“roze haalt eerder roze in”.
37
38
3. **Een vliegende cluster was geen star lichaam.** Elk lid had een
39
eigen `y`. `integrateClusters` telde dezelfde `dy` op, maar duwen,
40
attach, merge en `packClusterOverlaps` werkten per blokje.
41
Relatieve posities dreven uit elkaar (niet-gehele offsets, gaten
42
én overlaps in dezelfde kolom).
43
44
4. **`packClusterOverlaps` herstelde alleen overlaps, en pas achteraf,
45
door hogere blokjes omhoog te zetten.** Als vijf blokjes al in twee
46
cellen zaten, werden ze in één keer een 5-stapel — de teleport uit
47
de video. Bij gelijke `y` was de sorteervolgorde instabiel, wat als
48
een kleur- of typewisseling oogde (identiteit van twee overlappende
49
sprites).
50
51
5. **Botsingsdetectie was niet fully swept en niet alle paren.**
52
Cluster-cluster keek alleen naar de eindstand van de substep, niet
53
naar het pad. MANUAL–MANUAL ontbrak. MANUAL–cluster duwde zonder
54
te mergen. Vallend–vliegend en MANUAL–vallend waren er (t1108)
55
maar misten gevallen door de volgorde van de integrates.
56
57
6. **`stackTop` negeerde gaten.** Het nam de hoogste grounded
58
oppervlakte in de hele kolom. Een hangend STILL-blokje boven een
59
gat (bijvoorbeeld na het loslaten van een gelande cluster) liet
60
vallende blokjes *onder* dat gat omhoog teleporten en daar landen.
61
Dat is de “gatloze 5-stapel”-teleport bij landing, gevolgd door
62
inzakkende overlaps als die blokjes daarna weer zonder steun
63
vallen (“spreidt zich naar beneden uit”).
64
65
7. **`releaseUnsupported` deed maar twee vaste passes.** Een keten
66
van stills op een net losgelaten gelande groep (A op B op C, C
67
valt) liet de bovenste stills soms een tick te lang staan. Samen
68
met (6) gaf dat hangende stills boven vallende buren, en dan de
69
teleport.
70
71
8. **Landing van een slordige cluster hield gaten en overlaps.**
72
`tryLandCluster` schoof het geheel zodat het diepste contact vlak
73
zat, maar pakte niet eerst. Een gelande groep met rommelige `y`
74
snapte, herschikte en kon onbedoelde matches triggeren (t1110
75
op SETTLING cargo) — “verandering van kleur” die eigenlijk een
76
match naar grijs of een overlap-illusie was. Echte kleurwijziging
77
is alleen: match → grijs, en grijs → recolor.
78
79
9. **`fromManual`-snelheid middelen (t1108) kon de fase van een
80
cluster omdraaien** als vallend cargo aansloot. Dat blijft de
81
bedoelde regel voor worp+vallen, niet voor een schot in een
82
bestaande cluster (die houdt zijn `vy`, het schot neemt die over).
83
84
## Wat er nu geldt
85
86
- Een vliegende cluster is één star lichaam: één `anchorY`, één `vy`,
87
gehele `clusterOffset` per lid. `y = anchorY + offset` altijd.
88
Merges en attaches zijn rooster-uitgelijnd. Volgorde in een kolom
89
blijft (lagere `y` blijft lager; gelijke `y` breekt op `id`).
90
- **Schot in een cluster (t1111):** de geraakte kolom schuift 1 cel
91
omhoog, het schot sluit onderaan aan, grid-aligned, als lid van de
92
cluster. Elke volgende worp hetzelfde. De cluster houdt zijn
93
snelheid. Andere kolommen blijven. Een schot dat van boven komt
94
(dalend) gaat op het dak zitten, zoals vallend cargo.
95
- Twee gegooide blokjes die botsen: de eerste wordt een 1-blokjes-
96
cluster, daarna geldt t1111. Een enkele worp blijft MANUAL (en
97
blijft binnen het veld) tot hij ergens tegenaan botst.
98
- Worp + vallend: blijft t1108 (massagemiddelde `vy`, star lichaam).
99
Vallend op een gewone match-raket: blijft “pak op, zelfde `vy`”.
100
- Swept botsing per substep tussen alle paren: worp–cluster,
101
worp–worp, vallend–vliegend, vallend–worp, cluster–cluster.
102
Daarna een vangnet (`resolveAirborneCollisions`) en herbouw van
103
elk star lichaam.
104
- `stackTop(..., belowY)` telt alleen grounded blokjes onder de
105
valler, nooit een hangend blokje erboven.
106
- `releaseUnsupported` herhaalt tot de keten stil is.
107
- Landing verschuift `anchorY`; offsets (en dus gaten die bewust in
108
de starre vorm zitten, zoals een hangend lid over een vloer-gat)
109
blijven. Overlaps zijn er dan niet meer.
110
- Invariant-checker (`checkInvariants`): geen overlap, geen dubbele
111
cel, vliegende leden grid-aligned. Draait aan het eind van elke
112
`tick` in tests (`strictInvariants`, standaard aan via `makeGame`)
113
en met `?debug` (overlay, zonder te gooien). Kleur mag alleen
114
wijzigen via match→grijs of grijs-recolor; de soak test beweert
115
dat, en dat geen blokje verdwijnt zonder te scoren.
116
117
Zie ook de aannames onder t1111/t1112 in `docs/ASSUMPTIONS.md`.
@@ -0,0 +1,117 @@1
# Physics-audit (t1111 / t1112)2
3
Problemen die we vonden in de vlucht-, bots-, merge-, landings-, settle-4
en recolor-logica op master `1ede900`, nagegaan aan de hand van5
`t1111.webm` en een gerandomiseerde soak. Daarna de herschrijving.6
7
## Wat Tim zag (video, 3e kolom)8
9
- Gegoide roze blokjes liepen een eerder gegooid roze blokje in en10
overlapten in dezelfde cel.11
- Een gegooid geel blokje ging door twee roze blokjes heen en overlapte12
een vallend groen blokje.13
- Bij de landing snapte de stapel, met een gat (geel, gat, roze, groen,14
roze).15
- Een blokje leek van kleur of type te veranderen.16
- Nog een worp ging door het onderste blokje heen.17
- De cluster stortte in tot 2 cellen met overlaps, alsof blokjes18
verdwenen.19
- Een worp liet de cluster in een gatloze 5-stapel teleporten, die20
vervolgens tot 3 rijen met overlaps inzakte.21
- De stapel spreidde zich daarna naar beneden uit, met gaten en22
overlaps over meerdere frames.23
24
## Gevonden oorzaken25
26
1. **Een gegooid blokje duwde een cluster-kolom omhoog maar sloot niet27
aan (t1111).** `checkManualPush` / `pushClusterColumn` schoof de28
geraakte kolom 1 tegel op en zette `pushedClusters` zodat die worp29
de cluster niet nóg eens duwde. Het gegoide blokje zelf bleef30
MANUAL en vloog door de cluster heen. Elke volgende worp deed31
hetzelfde: door elkaar, overlaps, daarna een late pack die alles32
in één stapel duwde (“teleport naar een 5-stapel”).33
34
2. **Twee gegooide (MANUAL) blokjes hadden geen botsing.** Een tweede35
worp in dezelfde kolom liep de eerste in en deelde een cel. Precies36
“roze haalt eerder roze in”.37
38
3. **Een vliegende cluster was geen star lichaam.** Elk lid had een39
eigen `y`. `integrateClusters` telde dezelfde `dy` op, maar duwen,40
attach, merge en `packClusterOverlaps` werkten per blokje.41
Relatieve posities dreven uit elkaar (niet-gehele offsets, gaten42
én overlaps in dezelfde kolom).43
44
4. **`packClusterOverlaps` herstelde alleen overlaps, en pas achteraf,45
door hogere blokjes omhoog te zetten.** Als vijf blokjes al in twee46
cellen zaten, werden ze in één keer een 5-stapel — de teleport uit47
de video. Bij gelijke `y` was de sorteervolgorde instabiel, wat als48
een kleur- of typewisseling oogde (identiteit van twee overlappende49
sprites).50
51
5. **Botsingsdetectie was niet fully swept en niet alle paren.**52
Cluster-cluster keek alleen naar de eindstand van de substep, niet53
naar het pad. MANUAL–MANUAL ontbrak. MANUAL–cluster duwde zonder54
te mergen. Vallend–vliegend en MANUAL–vallend waren er (t1108)55
maar misten gevallen door de volgorde van de integrates.56
57
6. **`stackTop` negeerde gaten.** Het nam de hoogste grounded58
oppervlakte in de hele kolom. Een hangend STILL-blokje boven een59
gat (bijvoorbeeld na het loslaten van een gelande cluster) liet60
vallende blokjes *onder* dat gat omhoog teleporten en daar landen.61
Dat is de “gatloze 5-stapel”-teleport bij landing, gevolgd door62
inzakkende overlaps als die blokjes daarna weer zonder steun63
vallen (“spreidt zich naar beneden uit”).64
65
7. **`releaseUnsupported` deed maar twee vaste passes.** Een keten66
van stills op een net losgelaten gelande groep (A op B op C, C67
valt) liet de bovenste stills soms een tick te lang staan. Samen68
met (6) gaf dat hangende stills boven vallende buren, en dan de69
teleport.70
71
8. **Landing van een slordige cluster hield gaten en overlaps.**72
`tryLandCluster` schoof het geheel zodat het diepste contact vlak73
zat, maar pakte niet eerst. Een gelande groep met rommelige `y`74
snapte, herschikte en kon onbedoelde matches triggeren (t111075
op SETTLING cargo) — “verandering van kleur” die eigenlijk een76
match naar grijs of een overlap-illusie was. Echte kleurwijziging77
is alleen: match → grijs, en grijs → recolor.78
79
9. **`fromManual`-snelheid middelen (t1108) kon de fase van een80
cluster omdraaien** als vallend cargo aansloot. Dat blijft de81
bedoelde regel voor worp+vallen, niet voor een schot in een82
bestaande cluster (die houdt zijn `vy`, het schot neemt die over).83
84
## Wat er nu geldt85
86
- Een vliegende cluster is één star lichaam: één `anchorY`, één `vy`,87
gehele `clusterOffset` per lid. `y = anchorY + offset` altijd.88
Merges en attaches zijn rooster-uitgelijnd. Volgorde in een kolom89
blijft (lagere `y` blijft lager; gelijke `y` breekt op `id`).90
- **Schot in een cluster (t1111):** de geraakte kolom schuift 1 cel91
omhoog, het schot sluit onderaan aan, grid-aligned, als lid van de92
cluster. Elke volgende worp hetzelfde. De cluster houdt zijn93
snelheid. Andere kolommen blijven. Een schot dat van boven komt94
(dalend) gaat op het dak zitten, zoals vallend cargo.95
- Twee gegooide blokjes die botsen: de eerste wordt een 1-blokjes-96
cluster, daarna geldt t1111. Een enkele worp blijft MANUAL (en97
blijft binnen het veld) tot hij ergens tegenaan botst.98
- Worp + vallend: blijft t1108 (massagemiddelde `vy`, star lichaam).99
Vallend op een gewone match-raket: blijft “pak op, zelfde `vy`”.100
- Swept botsing per substep tussen alle paren: worp–cluster,101
worp–worp, vallend–vliegend, vallend–worp, cluster–cluster.102
Daarna een vangnet (`resolveAirborneCollisions`) en herbouw van103
elk star lichaam.104
- `stackTop(..., belowY)` telt alleen grounded blokjes onder de105
valler, nooit een hangend blokje erboven.106
- `releaseUnsupported` herhaalt tot de keten stil is.107
- Landing verschuift `anchorY`; offsets (en dus gaten die bewust in108
de starre vorm zitten, zoals een hangend lid over een vloer-gat)109
blijven. Overlaps zijn er dan niet meer.110
- Invariant-checker (`checkInvariants`): geen overlap, geen dubbele111
cel, vliegende leden grid-aligned. Draait aan het eind van elke112
`tick` in tests (`strictInvariants`, standaard aan via `makeGame`)113
en met `?debug` (overlay, zonder te gooien). Kleur mag alleen114
wijzigen via match→grijs of grijs-recolor; de soak test beweert115
dat, en dat geen blokje verdwijnt zonder te scoren.116
117
Zie ook de aannames onder t1111/t1112 in `docs/ASSUMPTIONS.md`.@@ -80,6 +80,11 @@ function GameCore (planet, rng)
80
80
this.outgoingShots = [];
81
81
// Stage-2 default; stage 3 replaces this with Planet.missChance (Power).
82
82
this.missChance = optsMissChance(arguments);
83
// t1112: invariant checker. strictInvariants throws (tests);
84
// debugInvariants records violations for the ?debug overlay.
85
this.strictInvariants = false;
86
this.debugInvariants = false;
87
this.lastInvariantViolations = [];
83
88
}
84
89
85
90
function optsMissChance (args)
@@ -179,7 +184,12 @@ GameCore.prototype.isGrounded = function (block)
179
184
|| block.state === STATE_LOCKED;
180
185
};
181
186
182
GameCore.prototype.stackTop = function (col, ignore)
187
/**
188
* Highest grounded landing surface in `col`. If `belowY` is given, only
189
* blocks strictly below that y count — a hanging still block above a
190
* gap must never pull a falling or thrown block upward through the gap.
191
*/
192
GameCore.prototype.stackTop = function (col, ignore, belowY)
183
193
{
184
194
var top = 0;
185
195
for (var i = 0; i < this.blocks.length; i++)
@@ -189,6 +199,8 @@ GameCore.prototype.stackTop = function (col, ignore)
189
199
{ continue; }
190
200
if (ignore && ignore(block))
191
201
{ continue; }
202
if (belowY != null && block.y + 1e-9 >= belowY)
203
{ continue; }
192
204
if (this.isGrounded(block))
193
205
{
194
206
var surface = block.y + 1;
@@ -374,18 +386,28 @@ GameCore.prototype.clearFlightState = function (block)
374
386
375
387
GameCore.prototype.releaseUnsupported = function ()
376
388
{
377
for (var i = 0; i < this.blocks.length; i++)
389
// Repeat until stable: a still sitting on a still that itself just
390
// became falling must also drop. Two fixed passes are not enough
391
// for a chain of hanging blocks (t1112).
392
var guard = 0;
393
var changed = true;
394
while (changed && guard++ < this.height + 2)
378
395
{
379
var block = this.blocks[i];
380
if (block.state !== STATE_STILL)
381
{ continue; }
382
if (this.drag && this.drag.blockId === block.id)
383
{ continue; }
384
if (this.hasSupport(block))
385
{ continue; }
386
this.leaveCluster(block);
387
this.clearFlightState(block);
388
block.state = STATE_FALLING;
396
changed = false;
397
for (var i = 0; i < this.blocks.length; i++)
398
{
399
var block = this.blocks[i];
400
if (block.state !== STATE_STILL)
401
{ continue; }
402
if (this.drag && this.drag.blockId === block.id)
403
{ continue; }
404
if (this.hasSupport(block))
405
{ continue; }
406
this.leaveCluster(block);
407
this.clearFlightState(block);
408
block.state = STATE_FALLING;
409
changed = true;
410
}
389
411
}
390
412
};
391
413
@@ -421,24 +443,29 @@ GameCore.prototype.attachToFlyingCluster = function (block, flyer)
421
443
var cluster = this.clusters[flyer.clusterId];
422
444
if (!cluster || cluster.phase === 'landed')
423
445
{ return false; }
424
var roof = flyer.y + 1;
425
for (var i = 0; i < this.blocks.length; i++)
446
this.prepareClusterBody(cluster);
447
var maxOff = null;
448
var members = this.clusterMembers(cluster.id);
449
for (var i = 0; i < members.length; i++)
426
450
{
427
var other = this.blocks[i];
428
if (other === block || other.col !== block.col)
429
{ continue; }
430
if (other.clusterId !== cluster.id)
451
if (members[i].col !== block.col)
431
452
{ continue; }
432
if (other.y + 1 > roof)
433
{ roof = other.y + 1; }
453
if (maxOff == null || members[i].clusterOffset > maxOff)
454
{ maxOff = members[i].clusterOffset; }
434
455
}
435
var oldN = this.clusterMembers(cluster.id).length;
456
var oldN = members.length;
436
457
var fallingVy = block.vy;
437
block.y = roof;
458
if (block.clusterId != null && block.clusterId !== cluster.id)
459
{ this.leaveCluster(block); }
438
460
block.state = STATE_FLYING;
439
461
block.clusterId = cluster.id;
462
block.clusterOffset = (maxOff == null) ? 0 : maxOff + 1;
440
463
block.flame = false;
441
464
block.settleTime = 0;
465
block.manualPhase = null;
466
block.manualTarget = null;
467
block.manualDecel = 0;
468
block.pushedClusters = null;
442
469
// A cluster born from a thrown block averages in falling cargo
443
470
// the same way two flying clusters merge (t1108). Other rockets
444
471
// keep their velocity and just pick the cargo up.
@@ -449,12 +476,8 @@ GameCore.prototype.attachToFlyingCluster = function (block, flyer)
449
476
cluster.decel = ((cluster.decel || 0) * oldN) / newN;
450
477
cluster.jumpHeight = ((cluster.jumpHeight || 0) * oldN) / newN;
451
478
cluster.phase = cluster.vy > 1e-10 ? 'up' : 'down';
452
var members = this.clusterMembers(cluster.id);
453
for (var m = 0; m < members.length; m++)
454
{ members[m].vy = cluster.vy; }
455
479
}
456
else
457
{ block.vy = cluster.vy; }
480
this.syncClusterMembers(cluster);
458
481
return true;
459
482
};
460
483
@@ -512,12 +535,14 @@ GameCore.prototype.tick = function (dt)
512
535
while (left > 1e-12)
513
536
{
514
537
var step = Math.min(SUBSTEP, left);
538
this.snapshotPrevY();
515
539
this.integrateFalling(step);
516
540
this.resolveFlyingMatches();
517
541
this.integrateClusters(step);
518
542
this.mergeFlyingClusters();
519
543
this.integrateManual(step);
520
544
this.mergeAnyManualFallingOverlaps();
545
this.resolveAirborneCollisions();
521
546
this.cullOffTop();
522
547
left -= step;
523
548
}
@@ -534,6 +559,7 @@ GameCore.prototype.tick = function (dt)
534
559
{ this.resolveMatches(); }
535
560
this.checkLocks();
536
561
this.checkGameOver();
562
this.assertInvariants('tick');
537
563
};
538
564
539
565
/** Step a stretch of time in fixed substeps. Useful for tests. */
@@ -611,7 +637,7 @@ GameCore.prototype.integrateFalling = function (dt)
611
637
if (this.attachToFlyingCluster(block, flyer))
612
638
{ continue; }
613
639
}
614
var top = this.stackTop(block.col);
640
var top = this.stackTop(block.col, null, block.y);
615
641
var below = this.highestFallingBelow(block);
616
642
if (below && below.y + 1 > top)
617
643
{ top = below.y + 1; }
@@ -725,14 +751,12 @@ GameCore.prototype.integrateClusters = function (dt)
725
751
if (cluster.phase === 'landed' || cluster.phase === 'hold')
726
752
{ continue; }
727
753
754
this.prepareClusterBody(cluster);
728
755
var dy = this.advanceJump(cluster, dt);
729
for (var i = 0; i < members.length; i++)
730
{
731
members[i].y += dy;
732
members[i].vy = cluster.vy;
733
}
756
cluster.anchorY += dy;
757
this.syncClusterMembers(cluster);
734
758
735
this.catchFallingOntoCluster(cluster, members);
759
this.catchFallingOntoCluster(cluster, this.clusterMembers(cluster.id));
736
760
this.checkChainRelaunch(cluster);
737
761
738
762
if (cluster.phase === 'down' && this.clusters[cluster.id])
@@ -801,13 +825,30 @@ GameCore.prototype.flyingClustersOverlap = function (a, b)
801
825
{
802
826
if (ma[i].col !== mb[j].col)
803
827
{ continue; }
804
if (ma[i].y < mb[j].y + 1 - 1e-9 && mb[j].y < ma[i].y + 1 - 1e-9)
828
if (this.sweptIntervalsOverlap(ma[i], mb[j]))
805
829
{ return true; }
806
830
}
807
831
}
808
832
return false;
809
833
};
810
834
835
/**
836
* Swept [y, y+1) of two blocks this substep, using _prevY when present.
837
* Catches pairs that crossed without sharing a cell at either endpoint.
838
*/
839
GameCore.prototype.sweptIntervalsOverlap = function (a, b)
840
{
841
var a0 = (a._prevY != null) ? a._prevY : a.y;
842
var a1 = a.y;
843
var b0 = (b._prevY != null) ? b._prevY : b.y;
844
var b1 = b.y;
845
var aLo = Math.min(a0, a1);
846
var aHi = Math.max(a0, a1) + 1;
847
var bLo = Math.min(b0, b1);
848
var bHi = Math.max(b0, b1) + 1;
849
return aLo < bHi - 1e-9 && bLo < aHi - 1e-9;
850
};
851
811
852
GameCore.prototype.mergeClusterGroup = function (clusters)
812
853
{
813
854
clusters.sort(function (a, b) { return a.id - b.id; });
@@ -843,7 +884,7 @@ GameCore.prototype.mergeClusterGroup = function (clusters)
843
884
if (clusters[c] !== keep)
844
885
{ delete this.clusters[clusters[c].id]; }
845
886
}
846
this.packClusterOverlaps(keep);
887
this.prepareClusterBody(keep);
847
888
this.checkChainRelaunch(keep);
848
889
if (keep.phase === 'down' && this.clusters[keep.id])
849
890
{ this.tryLandCluster(keep, this.clusterMembers(keep.id)); }
@@ -874,6 +915,297 @@ GameCore.prototype.packClusterOverlaps = function (cluster)
874
915
}
875
916
};
876
917
918
919
/**
920
* Derive integer cell offsets from current member positions and a
921
* single anchorY, packing overlaps in each column while preserving
922
* order (lower y stays lower; ties break on id). Then sync.
923
* Flying clusters are one rigid body: one y, one vy, integer offsets.
924
*/
925
GameCore.prototype.prepareClusterBody = function (cluster)
926
{
927
if (!cluster)
928
{ return; }
929
var members = this.clusterMembers(cluster.id);
930
if (!members.length)
931
{ return; }
932
this.rebuildClusterOffsets(cluster, members);
933
};
934
935
GameCore.prototype.rebuildClusterOffsets = function (cluster, members)
936
{
937
members = members || this.clusterMembers(cluster.id);
938
if (!members.length)
939
{ return; }
940
var byCol = Object.create(null);
941
for (var i = 0; i < members.length; i++)
942
{
943
var col = members[i].col;
944
if (!byCol[col])
945
{ byCol[col] = []; }
946
byCol[col].push(members[i]);
947
}
948
var minY = Infinity;
949
for (var i = 0; i < members.length; i++)
950
{
951
if (members[i].y < minY)
952
{ minY = members[i].y; }
953
}
954
if (cluster.anchorY == null || !isFinite(cluster.anchorY))
955
{ cluster.anchorY = minY; }
956
var cols = Object.keys(byCol);
957
for (var c = 0; c < cols.length; c++)
958
{
959
var list = byCol[cols[c]];
960
list.sort(function (a, b)
961
{
962
if (a.y !== b.y)
963
{ return a.y - b.y; }
964
return a.id - b.id;
965
});
966
var prevOff = -Infinity;
967
for (var i = 0; i < list.length; i++)
968
{
969
var off = Math.round(list[i].y - cluster.anchorY);
970
if (off <= prevOff)
971
{ off = prevOff + 1; }
972
list[i].clusterOffset = off;
973
prevOff = off;
974
}
975
}
976
// Re-base so the lowest offset is 0, keeping relative integers.
977
var minOff = Infinity;
978
for (var i = 0; i < members.length; i++)
979
{
980
if (members[i].clusterOffset < minOff)
981
{ minOff = members[i].clusterOffset; }
982
}
983
if (minOff !== 0 && isFinite(minOff))
984
{
985
cluster.anchorY += minOff;
986
for (var i = 0; i < members.length; i++)
987
{ members[i].clusterOffset -= minOff; }
988
}
989
this.syncClusterMembers(cluster);
990
};
991
992
GameCore.prototype.syncClusterMembers = function (cluster)
993
{
994
if (!cluster)
995
{ return; }
996
var members = this.clusterMembers(cluster.id);
997
if (cluster.anchorY == null)
998
{
999
var minY = Infinity;
1000
for (var i = 0; i < members.length; i++)
1001
{
1002
if (members[i].y < minY)
1003
{ minY = members[i].y; }
1004
}
1005
cluster.anchorY = isFinite(minY) ? minY : 0;
1006
}
1007
for (var i = 0; i < members.length; i++)
1008
{
1009
var block = members[i];
1010
if (block.clusterOffset == null)
1011
{ block.clusterOffset = Math.round(block.y - cluster.anchorY); }
1012
block.y = cluster.anchorY + block.clusterOffset;
1013
if (cluster.phase !== 'landed')
1014
{ block.vy = cluster.vy; }
1015
}
1016
};
1017
1018
GameCore.prototype.snapshotPrevY = function ()
1019
{
1020
for (var i = 0; i < this.blocks.length; i++)
1021
{ this.blocks[i]._prevY = this.blocks[i].y; }
1022
};
1023
1024
/**
1025
* Safety net after the specific integrates: any remaining mid-air
1026
* overlap or swept crossing is resolved with the same rules, then
1027
* every flying cluster is rebuilt as a rigid body. Repeats a few
1028
* times because one attach can create a new contact.
1029
*/
1030
GameCore.prototype.resolveAirborneCollisions = function ()
1031
{
1032
var guard = 0;
1033
while (guard++ < this.height + 4)
1034
{
1035
var changed = false;
1036
1037
// Manual vs falling / cluster / manual.
1038
var manuals = [];
1039
for (var i = 0; i < this.blocks.length; i++)
1040
{
1041
if (this.blocks[i].state === STATE_MANUAL)
1042
{ manuals.push(this.blocks[i]); }
1043
}
1044
manuals.sort(function (a, b) { return b.y - a.y; });
1045
for (var m = 0; m < manuals.length; m++)
1046
{
1047
var manual = manuals[m];
1048
if (manual.state !== STATE_MANUAL)
1049
{ continue; }
1050
var oldY = (manual._prevY != null) ? manual._prevY : manual.y;
1051
if (this.resolveManualCollisions(manual, oldY, manual.y))
1052
{ changed = true; }
1053
}
1054
1055
// Falling vs flying (sit on the roof).
1056
for (var i = 0; i < this.blocks.length; i++)
1057
{
1058
var block = this.blocks[i];
1059
if (block.state !== STATE_FALLING)
1060
{ continue; }
1061
var flyer = this.highestFlyingBelow(block);
1062
if (!flyer)
1063
{
1064
// Also a flyer whose swept path crosses this falling block.
1065
flyer = this.flyingHitOnManualPath(block, (block._prevY != null) ? block._prevY : block.y, block.y);
1066
}
1067
if (flyer && this.sweptIntervalsOverlap(block, flyer))
1068
{
1069
if (this.attachToFlyingCluster(block, flyer))
1070
{ changed = true; }
1071
}
1072
}
1073
1074
// Cluster vs cluster (swept, including after a column push).
1075
var before = Object.keys(this.clusters).length;
1076
this.mergeFlyingClusters();
1077
if (Object.keys(this.clusters).length !== before)
1078
{ changed = true; }
1079
1080
// Rebuild every flying body so offsets stay integer and unique.
1081
var ids = Object.keys(this.clusters);
1082
for (var n = 0; n < ids.length; n++)
1083
{
1084
var cluster = this.clusters[ids[n]];
1085
if (!cluster || cluster.phase === 'landed' || cluster.phase === 'hold')
1086
{ continue; }
1087
this.prepareClusterBody(cluster);
1088
}
1089
1090
if (!changed)
1091
{ break; }
1092
}
1093
};
1094
1095
/**
1096
* Invariant checker (t1112). No two blocks occupy the same cell or
1097
* overlap their [y, y+1) intervals. Flying-cluster members are
1098
* grid-aligned to a single anchor. Returns a list of violation
1099
* strings (empty if clean).
1100
*/
1101
GameCore.prototype.checkInvariants = function ()
1102
{
1103
var issues = [];
1104
var byCol = Object.create(null);
1105
var ids = Object.create(null);
1106
for (var i = 0; i < this.blocks.length; i++)
1107
{
1108
var block = this.blocks[i];
1109
if (ids[block.id])
1110
{ issues.push('duplicate id ' + block.id); }
1111
ids[block.id] = true;
1112
if (!byCol[block.col])
1113
{ byCol[block.col] = []; }
1114
byCol[block.col].push(block);
1115
if (block.color < COLOR_GRAY || (block.color >= 0 && this.planet
1116
&& block.color >= this.planet.colors.length))
1117
{ issues.push('block ' + block.id + ' has invalid color ' + block.color); }
1118
}
1119
var cols = Object.keys(byCol);
1120
for (var c = 0; c < cols.length; c++)
1121
{
1122
var list = byCol[cols[c]];
1123
list.sort(function (a, b)
1124
{
1125
if (a.y !== b.y)
1126
{ return a.y - b.y; }
1127
return a.id - b.id;
1128
});
1129
for (var i = 0; i < list.length; i++)
1130
{
1131
var a = list[i];
1132
if (i > 0)
1133
{
1134
var prev = list[i - 1];
1135
if (a.y < prev.y + 1 - 1e-6)
1136
{
1137
issues.push('overlap col=' + a.col
1138
+ ' ' + this._invBlock(prev) + ' and ' + this._invBlock(a)
1139
+ ' gap=' + (a.y - prev.y));
1140
}
1141
var cellA = Math.floor(a.y + 1e-9);
1142
var cellP = Math.floor(prev.y + 1e-9);
1143
if (cellA === cellP)
1144
{
1145
issues.push('duplicate cell col=' + a.col + ' row=' + cellA
1146
+ ' ' + this._invBlock(prev) + ' and ' + this._invBlock(a));
1147
}
1148
}
1149
}
1150
}
1151
var cids = Object.keys(this.clusters);
1152
for (var n = 0; n < cids.length; n++)
1153
{
1154
var cluster = this.clusters[cids[n]];
1155
if (!cluster || cluster.phase === 'landed' || cluster.phase === 'hold')
1156
{ continue; }
1157
var mem = this.clusterMembers(cluster.id);
1158
var seenOff = Object.create(null);
1159
for (var i = 0; i < mem.length; i++)
1160
{
1161
var b = mem[i];
1162
if (cluster.anchorY != null && b.clusterOffset != null)
1163
{
1164
var expected = cluster.anchorY + b.clusterOffset;
1165
if (Math.abs(b.y - expected) > 1e-6)
1166
{
1167
issues.push('cluster ' + cluster.id + ' member ' + b.id
1168
+ ' y=' + b.y + ' != anchor+off ' + expected);
1169
}
1170
if (Math.abs(b.clusterOffset - Math.round(b.clusterOffset)) > 1e-9)
1171
{
1172
issues.push('cluster ' + cluster.id + ' member ' + b.id
1173
+ ' non-integer offset ' + b.clusterOffset);
1174
}
1175
var key = b.col + ':' + b.clusterOffset;
1176
if (seenOff[key])
1177
{
1178
issues.push('cluster ' + cluster.id + ' duplicate offset ' + key);
1179
}
1180
seenOff[key] = true;
1181
}
1182
}
1183
}
1184
return issues;
1185
};
1186
1187
GameCore.prototype._invBlock = function (b)
1188
{
1189
return '#' + b.id + '(' + b.state + ',c=' + b.color + ',y='
1190
+ (Math.round(b.y * 1000) / 1000) + ',cid=' + b.clusterId + ')';
1191
};
1192
1193
GameCore.prototype.assertInvariants = function (label)
1194
{
1195
if (!this.strictInvariants && !this.debugInvariants)
1196
{ return; }
1197
var issues = this.checkInvariants();
1198
this.lastInvariantViolations = issues;
1199
if (!issues.length)
1200
{ return; }
1201
var msg = 'physics invariants failed'
1202
+ (label ? ' at ' + label : '')
1203
+ ':\n ' + issues.join('\n ')
1204
+ '\n' + (this.snapshot ? this.snapshot().picture : '');
1205
if (this.strictInvariants)
1206
{ throw new Error(msg); }
1207
};
1208
877
1209
GameCore.prototype.tryLandCluster = function (cluster, members)
878
1210
{
879
1211
if (!members.length)
@@ -886,7 +1218,7 @@ GameCore.prototype.tryLandCluster = function (cluster, members)
886
1218
var top = this.stackTop(block.col, function (other)
887
1219
{
888
1220
return other.clusterId === cluster.id;
889
});
1221
}, block.y);
890
1222
if (block.y <= top + 1e-9)
891
1223
{
892
1224
hit = true;
@@ -898,9 +1230,10 @@ GameCore.prototype.tryLandCluster = function (cluster, members)
898
1230
if (!hit)
899
1231
{ return; }
900
1232
// Lift the whole rigid body so the deepest contact sits flush.
901
for (var i = 0; i < members.length; i++)
902
{ members[i].y += shift; }
903
this.landCluster(cluster, members);
1233
this.prepareClusterBody(cluster);
1234
cluster.anchorY += shift;
1235
this.syncClusterMembers(cluster);
1236
this.landCluster(cluster, this.clusterMembers(cluster.id));
904
1237
};
905
1238
906
1239
/**
@@ -1001,12 +1334,11 @@ GameCore.prototype.integrateManual = function (dt)
1001
1334
var proxy = { phase: 'up', vy: block.vy, decel: block.manualDecel };
1002
1335
var dy = this.advanceJump(proxy, dt);
1003
1336
var nextY = oldY + dy;
1004
this.checkManualPush(block, oldY, Math.min(nextY, block.manualTarget));
1005
1337
block.vy = proxy.vy;
1006
1338
block.manualPhase = proxy.phase;
1007
block.y = Math.min(nextY, block.manualTarget);
1008
if (this.tryMergeManualWithFalling(block, oldY, block.y))
1339
if (this.resolveManualCollisions(block, oldY, Math.min(nextY, block.manualTarget)))
1009
1340
{ continue; }
1341
block.y = Math.min(nextY, block.manualTarget);
1010
1342
if (block.y >= block.manualTarget - 1e-12)
1011
1343
{
1012
1344
block.y = block.manualTarget;
@@ -1027,7 +1359,7 @@ GameCore.prototype.integrateManual = function (dt)
1027
1359
var dy = this.advanceJump(proxy, dt);
1028
1360
block.vy = proxy.vy;
1029
1361
var nextY = block.y + dy;
1030
var top = this.stackTop(block.col);
1362
var top = this.stackTop(block.col, null, block.y);
1031
1363
if (nextY <= top)
1032
1364
{
1033
1365
block.y = top;
@@ -1039,9 +1371,10 @@ GameCore.prototype.integrateManual = function (dt)
1039
1371
}
1040
1372
else
1041
1373
{
1042
block.y = Math.min(nextY, this.height - 1);
1043
if (this.tryMergeManualWithFalling(block, block.y - dy, block.y))
1374
var downNext = Math.min(nextY, this.height - 1);
1375
if (this.resolveManualCollisions(block, block.y, downNext))
1044
1376
{ continue; }
1377
block.y = downNext;
1045
1378
}
1046
1379
}
1047
1380
}
@@ -1216,7 +1549,7 @@ GameCore.prototype.mergeManualWithFalling = function (manual, fallingList)
1216
1549
}
1217
1550
if (this.drag && this.drag.blockId === manual.id)
1218
1551
{ this.drag = null; }
1219
this.packClusterOverlaps(cluster);
1552
this.prepareClusterBody(cluster);
1220
1553
this.checkChainRelaunch(cluster);
1221
1554
return cluster;
1222
1555
};
@@ -1241,40 +1574,217 @@ GameCore.prototype.mergeAnyManualFallingOverlaps = function ()
1241
1574
}
1242
1575
};
1243
1576
1244
GameCore.prototype.checkManualPush = function (manual, oldY, nextY)
1577
/**
1578
* Resolve collisions of a thrown (manual) block along [oldY, nextY].
1579
* Falling blocks merge (t1108). A flying cluster is pushed one cell up
1580
* in the hit column and the shot attaches at the bottom (t1111).
1581
* Another thrown block is promoted to a 1-block cluster and then the
1582
* same attach-at-bottom rule applies. Returns true if `manual` is no
1583
* longer in the MANUAL state.
1584
*/
1585
GameCore.prototype.resolveManualCollisions = function (manual, oldY, nextY)
1245
1586
{
1246
if (!manual.pushedClusters)
1247
{ manual.pushedClusters = Object.create(null); }
1587
if (!manual || manual.state !== STATE_MANUAL)
1588
{ return true; }
1248
1589
1249
var manualTopOld = oldY + 1;
1250
var manualTopNew = nextY + 1;
1251
var low = Math.min(oldY, nextY);
1252
var high = Math.max(oldY, nextY) + 1;
1590
var fallingHits = this.fallingHitsOnManualPath(manual, oldY, nextY);
1591
if (fallingHits.length)
1592
{
1593
this.mergeManualWithFalling(manual, fallingHits);
1594
return manual.state !== STATE_MANUAL;
1595
}
1253
1596
1597
var flyer = this.flyingHitOnManualPath(manual, oldY, nextY);
1598
if (flyer)
1599
{
1600
var cluster = this.clusters[flyer.clusterId];
1601
if (cluster && cluster.phase !== 'landed')
1602
{
1603
if (nextY + 1e-12 < oldY)
1604
{ this.attachToFlyingCluster(manual, flyer); }
1605
else
1606
{ this.attachShotUnderCluster(manual, cluster, manual.col); }
1607
return manual.state !== STATE_MANUAL;
1608
}
1609
}
1610
1611
var other = this.manualHitOnManualPath(manual, oldY, nextY);
1612
if (other)
1613
{
1614
var host = this.promoteManualToCluster(other);
1615
if (host)
1616
{
1617
if (nextY + 1e-12 < oldY)
1618
{ this.attachToFlyingCluster(manual, other); }
1619
else
1620
{ this.attachShotUnderCluster(manual, host, manual.col); }
1621
return manual.state !== STATE_MANUAL;
1622
}
1623
}
1624
return false;
1625
};
1626
1627
/** Closest flying cluster member in `manual`'s column on [oldY, nextY]. */
1628
GameCore.prototype.flyingHitOnManualPath = function (manual, oldY, nextY)
1629
{
1630
var lo = Math.min(oldY, nextY);
1631
var hi = Math.max(oldY, nextY) + 1;
1632
var best = null;
1633
var bestY = Infinity;
1254
1634
for (var i = 0; i < this.blocks.length; i++)
1255
1635
{
1256
1636
var other = this.blocks[i];
1257
if (other === manual)
1258
{ continue; }
1259
if (other.col !== manual.col)
1637
if (other === manual || other.col !== manual.col)
1260
1638
{ continue; }
1261
1639
if (other.state !== STATE_FLYING || other.clusterId == null)
1262
1640
{ continue; }
1263
if (manual.pushedClusters[other.clusterId])
1641
var cluster = this.clusters[other.clusterId];
1642
if (!cluster || cluster.phase === 'landed')
1264
1643
{ continue; }
1265
var otherBot = other.y;
1266
var otherTop = other.y + 1;
1267
var overlapping = otherBot < high + 1e-9 && otherTop > low - 1e-9;
1268
var crossing = manualTopOld <= otherBot + 1e-9 && manualTopNew >= otherBot - 1e-9;
1269
if (overlapping || crossing)
1644
var o0 = (other._prevY != null) ? other._prevY : other.y;
1645
var o1 = other.y;
1646
var oLo = Math.min(o0, o1);
1647
var oHi = Math.max(o0, o1) + 1;
1648
if (lo < oHi - 1e-9 && oLo < hi - 1e-9)
1270
1649
{
1271
if (this.pushClusterColumn(other.clusterId, manual.col))
1650
if (other.y < bestY)
1272
1651
{
1273
manual.pushedClusters[other.clusterId] = true;
1274
return;
1652
bestY = other.y;
1653
best = other;
1275
1654
}
1276
1655
}
1277
1656
}
1657
return best;
1658
};
1659
1660
/** Another thrown block in the same column on the path (prefer the lower). */
1661
GameCore.prototype.manualHitOnManualPath = function (manual, oldY, nextY)
1662
{
1663
var lo = Math.min(oldY, nextY);
1664
var hi = Math.max(oldY, nextY) + 1;
1665
var best = null;
1666
for (var i = 0; i < this.blocks.length; i++)
1667
{
1668
var other = this.blocks[i];
1669
if (other === manual || other.col !== manual.col)
1670
{ continue; }
1671
if (other.state !== STATE_MANUAL)
1672
{ continue; }
1673
var o0 = (other._prevY != null) ? other._prevY : other.y;
1674
var o1 = other.y;
1675
var oLo = Math.min(o0, o1);
1676
var oHi = Math.max(o0, o1) + 1;
1677
if (lo < oHi - 1e-9 && oLo < hi - 1e-9)
1678
{
1679
if (!best || other.y < best.y)
1680
{ best = other; }
1681
}
1682
}
1683
return best;
1684
};
1685
1686
/**
1687
* t1111: push every member of `cluster` in `col` up by one cell, then
1688
* attach `manual` at the bottom of that column, grid-aligned, as part
1689
* of the cluster. The cluster keeps its velocity; the shot takes it.
1690
* Other columns are untouched. Same rule for every successive shot.
1691
*/
1692
GameCore.prototype.attachShotUnderCluster = function (manual, cluster, col)
1693
{
1694
if (!manual || !cluster || !this.clusters[cluster.id])
1695
{ return false; }
1696
if (manual.state !== STATE_MANUAL && manual.clusterId !== cluster.id)
1697
{
1698
// Already belonging elsewhere: leave first.
1699
if (manual.clusterId != null)
1700
{ this.leaveCluster(manual); }
1701
}
1702
this.prepareClusterBody(cluster);
1703
var members = this.clusterMembers(cluster.id);
1704
var minOff = null;
1705
for (var i = 0; i < members.length; i++)
1706
{
1707
if (members[i].col !== col)
1708
{ continue; }
1709
if (minOff == null || members[i].clusterOffset < minOff)
1710
{ minOff = members[i].clusterOffset; }
1711
}
1712
if (minOff == null)
1713
{ minOff = 0; }
1714
else
1715
{
1716
for (var i = 0; i < members.length; i++)
1717
{
1718
if (members[i].col === col)
1719
{ members[i].clusterOffset += 1; }
1720
}
1721
}
1722
if (this.drag && this.drag.blockId === manual.id)
1723
{ this.drag = null; }
1724
manual.clusterId = cluster.id;
1725
manual.clusterOffset = minOff;
1726
manual.state = STATE_FLYING;
1727
manual.flame = manual.color === COLOR_GRAY;
1728
manual.settleTime = 0;
1729
manual.manualPhase = null;
1730
manual.manualTarget = null;
1731
manual.manualDecel = 0;
1732
manual.manualJumpHeight = 0;
1733
manual.pushedClusters = null;
1734
this.syncClusterMembers(cluster);
1735
this.cullOffTop();
1736
if (this.clusters[cluster.id])
1737
{ this.checkChainRelaunch(cluster); }
1738
return true;
1739
};
1740
1741
/**
1742
* Turn a lone thrown block into a 1-block flying cluster so a later
1743
* shot can use the t1111 attach-at-bottom rule. A single throw stays
1744
* MANUAL (and is capped at the top of the field) until it collides.
1745
*/
1746
GameCore.prototype.promoteManualToCluster = function (manual)
1747
{
1748
if (!manual)
1749
{ return null; }
1750
if (manual.state === STATE_FLYING && manual.clusterId != null)
1751
{
1752
var existing = this.clusters[manual.clusterId];
1753
if (existing && existing.phase !== 'landed')
1754
{ return existing; }
1755
}
1756
if (manual.state !== STATE_MANUAL)
1757
{ return null; }
1758
var height = manual.manualJumpHeight != null ? manual.manualJumpHeight
1759
: Math.max(0.05, (manual.manualTarget || this.height - 1) - manual.y);
1760
var cluster = {
1761
id: this.nextClusterId++,
1762
jumpHeight: height,
1763
vy: manual.vy,
1764
decel: manual.manualDecel || 0,
1765
phase: (manual.manualPhase === 'down' || manual.vy <= 1e-10) ? 'down' : 'up',
1766
fromManual: true,
1767
anchorY: manual.y
1768
};
1769
this.clusters[cluster.id] = cluster;
1770
manual.state = STATE_FLYING;
1771
manual.clusterId = cluster.id;
1772
manual.clusterOffset = 0;
1773
manual.flame = manual.color === COLOR_GRAY;
1774
manual.settleTime = 0;
1775
manual.manualPhase = null;
1776
manual.manualTarget = null;
1777
manual.manualDecel = 0;
1778
manual.manualJumpHeight = 0;
1779
manual.pushedClusters = null;
1780
this.syncClusterMembers(cluster);
1781
return cluster;
1782
};
1783
1784
/** Kept for older tests / call sites: push a cluster column by one cell. */
1785
GameCore.prototype.checkManualPush = function (manual, oldY, nextY)
1786
{
1787
return this.resolveManualCollisions(manual, oldY, nextY);
1278
1788
};
1279
1789
1280
1790
@@ -1787,6 +2297,7 @@ GameCore.prototype.launchCluster = function (matchedBlocks, height)
1787
2297
block.vy = cluster.vy;
1788
2298
block.settleTime = 0;
1789
2299
}
2300
this.prepareClusterBody(cluster);
1790
2301
return cluster;
1791
2302
};
1792
2303
@@ -80,6 +80,11 @@ function GameCore (planet, rng)80
this.outgoingShots = [];80
this.outgoingShots = [];81
// Stage-2 default; stage 3 replaces this with Planet.missChance (Power).81
// Stage-2 default; stage 3 replaces this with Planet.missChance (Power).82
this.missChance = optsMissChance(arguments);82
this.missChance = optsMissChance(arguments);83
// t1112: invariant checker. strictInvariants throws (tests);84
// debugInvariants records violations for the ?debug overlay.85
this.strictInvariants = false;86
this.debugInvariants = false;87
this.lastInvariantViolations = [];83
}88
}84
89
85
function optsMissChance (args)90
function optsMissChance (args)@@ -179,7 +184,12 @@ GameCore.prototype.isGrounded = function (block)179
|| block.state === STATE_LOCKED;184
|| block.state === STATE_LOCKED;180
};185
};181
186
182
GameCore.prototype.stackTop = function (col, ignore)187
/**188
* Highest grounded landing surface in `col`. If `belowY` is given, only189
* blocks strictly below that y count — a hanging still block above a190
* gap must never pull a falling or thrown block upward through the gap.191
*/192
GameCore.prototype.stackTop = function (col, ignore, belowY)183
{193
{184
var top = 0;194
var top = 0;185
for (var i = 0; i < this.blocks.length; i++)195
for (var i = 0; i < this.blocks.length; i++)@@ -189,6 +199,8 @@ GameCore.prototype.stackTop = function (col, ignore)189
{ continue; }199
{ continue; }190
if (ignore && ignore(block))200
if (ignore && ignore(block))191
{ continue; }201
{ continue; }202
if (belowY != null && block.y + 1e-9 >= belowY)203
{ continue; }192
if (this.isGrounded(block))204
if (this.isGrounded(block))193
{205
{194
var surface = block.y + 1;206
var surface = block.y + 1;@@ -374,18 +386,28 @@ GameCore.prototype.clearFlightState = function (block)374
386
375
GameCore.prototype.releaseUnsupported = function ()387
GameCore.prototype.releaseUnsupported = function ()376
{388
{377
for (var i = 0; i < this.blocks.length; i++)389
// Repeat until stable: a still sitting on a still that itself just390
// became falling must also drop. Two fixed passes are not enough391
// for a chain of hanging blocks (t1112).392
var guard = 0;393
var changed = true;394
while (changed && guard++ < this.height + 2)378
{395
{379
var block = this.blocks[i];396
changed = false;380
if (block.state !== STATE_STILL)397
for (var i = 0; i < this.blocks.length; i++)381
{ continue; }398
{382
if (this.drag && this.drag.blockId === block.id)399
var block = this.blocks[i];383
{ continue; }400
if (block.state !== STATE_STILL)384
if (this.hasSupport(block))401
{ continue; }385
{ continue; }402
if (this.drag && this.drag.blockId === block.id)386
this.leaveCluster(block);403
{ continue; }387
this.clearFlightState(block);404
if (this.hasSupport(block))388
block.state = STATE_FALLING;405
{ continue; }406
this.leaveCluster(block);407
this.clearFlightState(block);408
block.state = STATE_FALLING;409
changed = true;410
}389
}411
}390
};412
};391
413
@@ -421,24 +443,29 @@ GameCore.prototype.attachToFlyingCluster = function (block, flyer)421
var cluster = this.clusters[flyer.clusterId];443
var cluster = this.clusters[flyer.clusterId];422
if (!cluster || cluster.phase === 'landed')444
if (!cluster || cluster.phase === 'landed')423
{ return false; }445
{ return false; }424
var roof = flyer.y + 1;446
this.prepareClusterBody(cluster);425
for (var i = 0; i < this.blocks.length; i++)447
var maxOff = null;448
var members = this.clusterMembers(cluster.id);449
for (var i = 0; i < members.length; i++)426
{450
{427
var other = this.blocks[i];451
if (members[i].col !== block.col)428
if (other === block || other.col !== block.col)429
{ continue; }430
if (other.clusterId !== cluster.id)431
{ continue; }452
{ continue; }432
if (other.y + 1 > roof)453
if (maxOff == null || members[i].clusterOffset > maxOff)433
{ roof = other.y + 1; }454
{ maxOff = members[i].clusterOffset; }434
}455
}435
var oldN = this.clusterMembers(cluster.id).length;456
var oldN = members.length;436
var fallingVy = block.vy;457
var fallingVy = block.vy;437
block.y = roof;458
if (block.clusterId != null && block.clusterId !== cluster.id)459
{ this.leaveCluster(block); }438
block.state = STATE_FLYING;460
block.state = STATE_FLYING;439
block.clusterId = cluster.id;461
block.clusterId = cluster.id;462
block.clusterOffset = (maxOff == null) ? 0 : maxOff + 1;440
block.flame = false;463
block.flame = false;441
block.settleTime = 0;464
block.settleTime = 0;465
block.manualPhase = null;466
block.manualTarget = null;467
block.manualDecel = 0;468
block.pushedClusters = null;442
// A cluster born from a thrown block averages in falling cargo469
// A cluster born from a thrown block averages in falling cargo443
// the same way two flying clusters merge (t1108). Other rockets470
// the same way two flying clusters merge (t1108). Other rockets444
// keep their velocity and just pick the cargo up.471
// keep their velocity and just pick the cargo up.@@ -449,12 +476,8 @@ GameCore.prototype.attachToFlyingCluster = function (block, flyer)449
cluster.decel = ((cluster.decel || 0) * oldN) / newN;476
cluster.decel = ((cluster.decel || 0) * oldN) / newN;450
cluster.jumpHeight = ((cluster.jumpHeight || 0) * oldN) / newN;477
cluster.jumpHeight = ((cluster.jumpHeight || 0) * oldN) / newN;451
cluster.phase = cluster.vy > 1e-10 ? 'up' : 'down';478
cluster.phase = cluster.vy > 1e-10 ? 'up' : 'down';452
var members = this.clusterMembers(cluster.id);453
for (var m = 0; m < members.length; m++)454
{ members[m].vy = cluster.vy; }455
}479
}456
else480
this.syncClusterMembers(cluster);457
{ block.vy = cluster.vy; }458
return true;481
return true;459
};482
};460
483
@@ -512,12 +535,14 @@ GameCore.prototype.tick = function (dt)512
while (left > 1e-12)535
while (left > 1e-12)513
{536
{514
var step = Math.min(SUBSTEP, left);537
var step = Math.min(SUBSTEP, left);538
this.snapshotPrevY();515
this.integrateFalling(step);539
this.integrateFalling(step);516
this.resolveFlyingMatches();540
this.resolveFlyingMatches();517
this.integrateClusters(step);541
this.integrateClusters(step);518
this.mergeFlyingClusters();542
this.mergeFlyingClusters();519
this.integrateManual(step);543
this.integrateManual(step);520
this.mergeAnyManualFallingOverlaps();544
this.mergeAnyManualFallingOverlaps();545
this.resolveAirborneCollisions();521
this.cullOffTop();546
this.cullOffTop();522
left -= step;547
left -= step;523
}548
}@@ -534,6 +559,7 @@ GameCore.prototype.tick = function (dt)534
{ this.resolveMatches(); }559
{ this.resolveMatches(); }535
this.checkLocks();560
this.checkLocks();536
this.checkGameOver();561
this.checkGameOver();562
this.assertInvariants('tick');537
};563
};538
564
539
/** Step a stretch of time in fixed substeps. Useful for tests. */565
/** Step a stretch of time in fixed substeps. Useful for tests. */@@ -611,7 +637,7 @@ GameCore.prototype.integrateFalling = function (dt)611
if (this.attachToFlyingCluster(block, flyer))637
if (this.attachToFlyingCluster(block, flyer))612
{ continue; }638
{ continue; }613
}639
}614
var top = this.stackTop(block.col);640
var top = this.stackTop(block.col, null, block.y);615
var below = this.highestFallingBelow(block);641
var below = this.highestFallingBelow(block);616
if (below && below.y + 1 > top)642
if (below && below.y + 1 > top)617
{ top = below.y + 1; }643
{ top = below.y + 1; }@@ -725,14 +751,12 @@ GameCore.prototype.integrateClusters = function (dt)725
if (cluster.phase === 'landed' || cluster.phase === 'hold')751
if (cluster.phase === 'landed' || cluster.phase === 'hold')726
{ continue; }752
{ continue; }727
753
754
this.prepareClusterBody(cluster);728
var dy = this.advanceJump(cluster, dt);755
var dy = this.advanceJump(cluster, dt);729
for (var i = 0; i < members.length; i++)756
cluster.anchorY += dy;730
{757
this.syncClusterMembers(cluster);731
members[i].y += dy;732
members[i].vy = cluster.vy;733
}734
758
735
this.catchFallingOntoCluster(cluster, members);759
this.catchFallingOntoCluster(cluster, this.clusterMembers(cluster.id));736
this.checkChainRelaunch(cluster);760
this.checkChainRelaunch(cluster);737
761
738
if (cluster.phase === 'down' && this.clusters[cluster.id])762
if (cluster.phase === 'down' && this.clusters[cluster.id])@@ -801,13 +825,30 @@ GameCore.prototype.flyingClustersOverlap = function (a, b)801
{825
{802
if (ma[i].col !== mb[j].col)826
if (ma[i].col !== mb[j].col)803
{ continue; }827
{ continue; }804
if (ma[i].y < mb[j].y + 1 - 1e-9 && mb[j].y < ma[i].y + 1 - 1e-9)828
if (this.sweptIntervalsOverlap(ma[i], mb[j]))805
{ return true; }829
{ return true; }806
}830
}807
}831
}808
return false;832
return false;809
};833
};810
834
835
/**836
* Swept [y, y+1) of two blocks this substep, using _prevY when present.837
* Catches pairs that crossed without sharing a cell at either endpoint.838
*/839
GameCore.prototype.sweptIntervalsOverlap = function (a, b)840
{841
var a0 = (a._prevY != null) ? a._prevY : a.y;842
var a1 = a.y;843
var b0 = (b._prevY != null) ? b._prevY : b.y;844
var b1 = b.y;845
var aLo = Math.min(a0, a1);846
var aHi = Math.max(a0, a1) + 1;847
var bLo = Math.min(b0, b1);848
var bHi = Math.max(b0, b1) + 1;849
return aLo < bHi - 1e-9 && bLo < aHi - 1e-9;850
};851
811
GameCore.prototype.mergeClusterGroup = function (clusters)852
GameCore.prototype.mergeClusterGroup = function (clusters)812
{853
{813
clusters.sort(function (a, b) { return a.id - b.id; });854
clusters.sort(function (a, b) { return a.id - b.id; });@@ -843,7 +884,7 @@ GameCore.prototype.mergeClusterGroup = function (clusters)843
if (clusters[c] !== keep)884
if (clusters[c] !== keep)844
{ delete this.clusters[clusters[c].id]; }885
{ delete this.clusters[clusters[c].id]; }845
}886
}846
this.packClusterOverlaps(keep);887
this.prepareClusterBody(keep);847
this.checkChainRelaunch(keep);888
this.checkChainRelaunch(keep);848
if (keep.phase === 'down' && this.clusters[keep.id])889
if (keep.phase === 'down' && this.clusters[keep.id])849
{ this.tryLandCluster(keep, this.clusterMembers(keep.id)); }890
{ this.tryLandCluster(keep, this.clusterMembers(keep.id)); }@@ -874,6 +915,297 @@ GameCore.prototype.packClusterOverlaps = function (cluster)874
}915
}875
};916
};876
917
918
919
/**920
* Derive integer cell offsets from current member positions and a921
* single anchorY, packing overlaps in each column while preserving922
* order (lower y stays lower; ties break on id). Then sync.923
* Flying clusters are one rigid body: one y, one vy, integer offsets.924
*/925
GameCore.prototype.prepareClusterBody = function (cluster)926
{927
if (!cluster)928
{ return; }929
var members = this.clusterMembers(cluster.id);930
if (!members.length)931
{ return; }932
this.rebuildClusterOffsets(cluster, members);933
};934
935
GameCore.prototype.rebuildClusterOffsets = function (cluster, members)936
{937
members = members || this.clusterMembers(cluster.id);938
if (!members.length)939
{ return; }940
var byCol = Object.create(null);941
for (var i = 0; i < members.length; i++)942
{943
var col = members[i].col;944
if (!byCol[col])945
{ byCol[col] = []; }946
byCol[col].push(members[i]);947
}948
var minY = Infinity;949
for (var i = 0; i < members.length; i++)950
{951
if (members[i].y < minY)952
{ minY = members[i].y; }953
}954
if (cluster.anchorY == null || !isFinite(cluster.anchorY))955
{ cluster.anchorY = minY; }956
var cols = Object.keys(byCol);957
for (var c = 0; c < cols.length; c++)958
{959
var list = byCol[cols[c]];960
list.sort(function (a, b)961
{962
if (a.y !== b.y)963
{ return a.y - b.y; }964
return a.id - b.id;965
});966
var prevOff = -Infinity;967
for (var i = 0; i < list.length; i++)968
{969
var off = Math.round(list[i].y - cluster.anchorY);970
if (off <= prevOff)971
{ off = prevOff + 1; }972
list[i].clusterOffset = off;973
prevOff = off;974
}975
}976
// Re-base so the lowest offset is 0, keeping relative integers.977
var minOff = Infinity;978
for (var i = 0; i < members.length; i++)979
{980
if (members[i].clusterOffset < minOff)981
{ minOff = members[i].clusterOffset; }982
}983
if (minOff !== 0 && isFinite(minOff))984
{985
cluster.anchorY += minOff;986
for (var i = 0; i < members.length; i++)987
{ members[i].clusterOffset -= minOff; }988
}989
this.syncClusterMembers(cluster);990
};991
992
GameCore.prototype.syncClusterMembers = function (cluster)993
{994
if (!cluster)995
{ return; }996
var members = this.clusterMembers(cluster.id);997
if (cluster.anchorY == null)998
{999
var minY = Infinity;1000
for (var i = 0; i < members.length; i++)1001
{1002
if (members[i].y < minY)1003
{ minY = members[i].y; }1004
}1005
cluster.anchorY = isFinite(minY) ? minY : 0;1006
}1007
for (var i = 0; i < members.length; i++)1008
{1009
var block = members[i];1010
if (block.clusterOffset == null)1011
{ block.clusterOffset = Math.round(block.y - cluster.anchorY); }1012
block.y = cluster.anchorY + block.clusterOffset;1013
if (cluster.phase !== 'landed')1014
{ block.vy = cluster.vy; }1015
}1016
};1017
1018
GameCore.prototype.snapshotPrevY = function ()1019
{1020
for (var i = 0; i < this.blocks.length; i++)1021
{ this.blocks[i]._prevY = this.blocks[i].y; }1022
};1023
1024
/**1025
* Safety net after the specific integrates: any remaining mid-air1026
* overlap or swept crossing is resolved with the same rules, then1027
* every flying cluster is rebuilt as a rigid body. Repeats a few1028
* times because one attach can create a new contact.1029
*/1030
GameCore.prototype.resolveAirborneCollisions = function ()1031
{1032
var guard = 0;1033
while (guard++ < this.height + 4)1034
{1035
var changed = false;1036
1037
// Manual vs falling / cluster / manual.1038
var manuals = [];1039
for (var i = 0; i < this.blocks.length; i++)1040
{1041
if (this.blocks[i].state === STATE_MANUAL)1042
{ manuals.push(this.blocks[i]); }1043
}1044
manuals.sort(function (a, b) { return b.y - a.y; });1045
for (var m = 0; m < manuals.length; m++)1046
{1047
var manual = manuals[m];1048
if (manual.state !== STATE_MANUAL)1049
{ continue; }1050
var oldY = (manual._prevY != null) ? manual._prevY : manual.y;1051
if (this.resolveManualCollisions(manual, oldY, manual.y))1052
{ changed = true; }1053
}1054
1055
// Falling vs flying (sit on the roof).1056
for (var i = 0; i < this.blocks.length; i++)1057
{1058
var block = this.blocks[i];1059
if (block.state !== STATE_FALLING)1060
{ continue; }1061
var flyer = this.highestFlyingBelow(block);1062
if (!flyer)1063
{1064
// Also a flyer whose swept path crosses this falling block.1065
flyer = this.flyingHitOnManualPath(block, (block._prevY != null) ? block._prevY : block.y, block.y);1066
}1067
if (flyer && this.sweptIntervalsOverlap(block, flyer))1068
{1069
if (this.attachToFlyingCluster(block, flyer))1070
{ changed = true; }1071
}1072
}1073
1074
// Cluster vs cluster (swept, including after a column push).1075
var before = Object.keys(this.clusters).length;1076
this.mergeFlyingClusters();1077
if (Object.keys(this.clusters).length !== before)1078
{ changed = true; }1079
1080
// Rebuild every flying body so offsets stay integer and unique.1081
var ids = Object.keys(this.clusters);1082
for (var n = 0; n < ids.length; n++)1083
{1084
var cluster = this.clusters[ids[n]];1085
if (!cluster || cluster.phase === 'landed' || cluster.phase === 'hold')1086
{ continue; }1087
this.prepareClusterBody(cluster);1088
}1089
1090
if (!changed)1091
{ break; }1092
}1093
};1094
1095
/**1096
* Invariant checker (t1112). No two blocks occupy the same cell or1097
* overlap their [y, y+1) intervals. Flying-cluster members are1098
* grid-aligned to a single anchor. Returns a list of violation1099
* strings (empty if clean).1100
*/1101
GameCore.prototype.checkInvariants = function ()1102
{1103
var issues = [];1104
var byCol = Object.create(null);1105
var ids = Object.create(null);1106
for (var i = 0; i < this.blocks.length; i++)1107
{1108
var block = this.blocks[i];1109
if (ids[block.id])1110
{ issues.push('duplicate id ' + block.id); }1111
ids[block.id] = true;1112
if (!byCol[block.col])1113
{ byCol[block.col] = []; }1114
byCol[block.col].push(block);1115
if (block.color < COLOR_GRAY || (block.color >= 0 && this.planet1116
&& block.color >= this.planet.colors.length))1117
{ issues.push('block ' + block.id + ' has invalid color ' + block.color); }1118
}1119
var cols = Object.keys(byCol);1120
for (var c = 0; c < cols.length; c++)1121
{1122
var list = byCol[cols[c]];1123
list.sort(function (a, b)1124
{1125
if (a.y !== b.y)1126
{ return a.y - b.y; }1127
return a.id - b.id;1128
});1129
for (var i = 0; i < list.length; i++)1130
{1131
var a = list[i];1132
if (i > 0)1133
{1134
var prev = list[i - 1];1135
if (a.y < prev.y + 1 - 1e-6)1136
{1137
issues.push('overlap col=' + a.col1138
+ ' ' + this._invBlock(prev) + ' and ' + this._invBlock(a)1139
+ ' gap=' + (a.y - prev.y));1140
}1141
var cellA = Math.floor(a.y + 1e-9);1142
var cellP = Math.floor(prev.y + 1e-9);1143
if (cellA === cellP)1144
{1145
issues.push('duplicate cell col=' + a.col + ' row=' + cellA1146
+ ' ' + this._invBlock(prev) + ' and ' + this._invBlock(a));1147
}1148
}1149
}1150
}1151
var cids = Object.keys(this.clusters);1152
for (var n = 0; n < cids.length; n++)1153
{1154
var cluster = this.clusters[cids[n]];1155
if (!cluster || cluster.phase === 'landed' || cluster.phase === 'hold')1156
{ continue; }1157
var mem = this.clusterMembers(cluster.id);1158
var seenOff = Object.create(null);1159
for (var i = 0; i < mem.length; i++)1160
{1161
var b = mem[i];1162
if (cluster.anchorY != null && b.clusterOffset != null)1163
{1164
var expected = cluster.anchorY + b.clusterOffset;1165
if (Math.abs(b.y - expected) > 1e-6)1166
{1167
issues.push('cluster ' + cluster.id + ' member ' + b.id1168
+ ' y=' + b.y + ' != anchor+off ' + expected);1169
}1170
if (Math.abs(b.clusterOffset - Math.round(b.clusterOffset)) > 1e-9)1171
{1172
issues.push('cluster ' + cluster.id + ' member ' + b.id1173
+ ' non-integer offset ' + b.clusterOffset);1174
}1175
var key = b.col + ':' + b.clusterOffset;1176
if (seenOff[key])1177
{1178
issues.push('cluster ' + cluster.id + ' duplicate offset ' + key);1179
}1180
seenOff[key] = true;1181
}1182
}1183
}1184
return issues;1185
};1186
1187
GameCore.prototype._invBlock = function (b)1188
{1189
return '#' + b.id + '(' + b.state + ',c=' + b.color + ',y='1190
+ (Math.round(b.y * 1000) / 1000) + ',cid=' + b.clusterId + ')';1191
};1192
1193
GameCore.prototype.assertInvariants = function (label)1194
{1195
if (!this.strictInvariants && !this.debugInvariants)1196
{ return; }1197
var issues = this.checkInvariants();1198
this.lastInvariantViolations = issues;1199
if (!issues.length)1200
{ return; }1201
var msg = 'physics invariants failed'1202
+ (label ? ' at ' + label : '')1203
+ ':\n ' + issues.join('\n ')1204
+ '\n' + (this.snapshot ? this.snapshot().picture : '');1205
if (this.strictInvariants)1206
{ throw new Error(msg); }1207
};1208
877
GameCore.prototype.tryLandCluster = function (cluster, members)1209
GameCore.prototype.tryLandCluster = function (cluster, members)878
{1210
{879
if (!members.length)1211
if (!members.length)@@ -886,7 +1218,7 @@ GameCore.prototype.tryLandCluster = function (cluster, members)886
var top = this.stackTop(block.col, function (other)1218
var top = this.stackTop(block.col, function (other)887
{1219
{888
return other.clusterId === cluster.id;1220
return other.clusterId === cluster.id;889
});1221
}, block.y);890
if (block.y <= top + 1e-9)1222
if (block.y <= top + 1e-9)891
{1223
{892
hit = true;1224
hit = true;@@ -898,9 +1230,10 @@ GameCore.prototype.tryLandCluster = function (cluster, members)898
if (!hit)1230
if (!hit)899
{ return; }1231
{ return; }900
// Lift the whole rigid body so the deepest contact sits flush.1232
// Lift the whole rigid body so the deepest contact sits flush.901
for (var i = 0; i < members.length; i++)1233
this.prepareClusterBody(cluster);902
{ members[i].y += shift; }1234
cluster.anchorY += shift;903
this.landCluster(cluster, members);1235
this.syncClusterMembers(cluster);1236
this.landCluster(cluster, this.clusterMembers(cluster.id));904
};1237
};905
1238
906
/**1239
/**@@ -1001,12 +1334,11 @@ GameCore.prototype.integrateManual = function (dt)1001
var proxy = { phase: 'up', vy: block.vy, decel: block.manualDecel };1334
var proxy = { phase: 'up', vy: block.vy, decel: block.manualDecel };1002
var dy = this.advanceJump(proxy, dt);1335
var dy = this.advanceJump(proxy, dt);1003
var nextY = oldY + dy;1336
var nextY = oldY + dy;1004
this.checkManualPush(block, oldY, Math.min(nextY, block.manualTarget));1005
block.vy = proxy.vy;1337
block.vy = proxy.vy;1006
block.manualPhase = proxy.phase;1338
block.manualPhase = proxy.phase;1007
block.y = Math.min(nextY, block.manualTarget);1339
if (this.resolveManualCollisions(block, oldY, Math.min(nextY, block.manualTarget)))1008
if (this.tryMergeManualWithFalling(block, oldY, block.y))1009
{ continue; }1340
{ continue; }1341
block.y = Math.min(nextY, block.manualTarget);1010
if (block.y >= block.manualTarget - 1e-12)1342
if (block.y >= block.manualTarget - 1e-12)1011
{1343
{1012
block.y = block.manualTarget;1344
block.y = block.manualTarget;@@ -1027,7 +1359,7 @@ GameCore.prototype.integrateManual = function (dt)1027
var dy = this.advanceJump(proxy, dt);1359
var dy = this.advanceJump(proxy, dt);1028
block.vy = proxy.vy;1360
block.vy = proxy.vy;1029
var nextY = block.y + dy;1361
var nextY = block.y + dy;1030
var top = this.stackTop(block.col);1362
var top = this.stackTop(block.col, null, block.y);1031
if (nextY <= top)1363
if (nextY <= top)1032
{1364
{1033
block.y = top;1365
block.y = top;@@ -1039,9 +1371,10 @@ GameCore.prototype.integrateManual = function (dt)1039
}1371
}1040
else1372
else1041
{1373
{1042
block.y = Math.min(nextY, this.height - 1);1374
var downNext = Math.min(nextY, this.height - 1);1043
if (this.tryMergeManualWithFalling(block, block.y - dy, block.y))1375
if (this.resolveManualCollisions(block, block.y, downNext))1044
{ continue; }1376
{ continue; }1377
block.y = downNext;1045
}1378
}1046
}1379
}1047
}1380
}@@ -1216,7 +1549,7 @@ GameCore.prototype.mergeManualWithFalling = function (manual, fallingList)1216
}1549
}1217
if (this.drag && this.drag.blockId === manual.id)1550
if (this.drag && this.drag.blockId === manual.id)1218
{ this.drag = null; }1551
{ this.drag = null; }1219
this.packClusterOverlaps(cluster);1552
this.prepareClusterBody(cluster);1220
this.checkChainRelaunch(cluster);1553
this.checkChainRelaunch(cluster);1221
return cluster;1554
return cluster;1222
};1555
};@@ -1241,40 +1574,217 @@ GameCore.prototype.mergeAnyManualFallingOverlaps = function ()1241
}1574
}1242
};1575
};1243
1576
1244
GameCore.prototype.checkManualPush = function (manual, oldY, nextY)1577
/**1578
* Resolve collisions of a thrown (manual) block along [oldY, nextY].1579
* Falling blocks merge (t1108). A flying cluster is pushed one cell up1580
* in the hit column and the shot attaches at the bottom (t1111).1581
* Another thrown block is promoted to a 1-block cluster and then the1582
* same attach-at-bottom rule applies. Returns true if `manual` is no1583
* longer in the MANUAL state.1584
*/1585
GameCore.prototype.resolveManualCollisions = function (manual, oldY, nextY)1245
{1586
{1246
if (!manual.pushedClusters)1587
if (!manual || manual.state !== STATE_MANUAL)1247
{ manual.pushedClusters = Object.create(null); }1588
{ return true; }1248
1589
1249
var manualTopOld = oldY + 1;1590
var fallingHits = this.fallingHitsOnManualPath(manual, oldY, nextY);1250
var manualTopNew = nextY + 1;1591
if (fallingHits.length)1251
var low = Math.min(oldY, nextY);1592
{1252
var high = Math.max(oldY, nextY) + 1;1593
this.mergeManualWithFalling(manual, fallingHits);1594
return manual.state !== STATE_MANUAL;1595
}1253
1596
1597
var flyer = this.flyingHitOnManualPath(manual, oldY, nextY);1598
if (flyer)1599
{1600
var cluster = this.clusters[flyer.clusterId];1601
if (cluster && cluster.phase !== 'landed')1602
{1603
if (nextY + 1e-12 < oldY)1604
{ this.attachToFlyingCluster(manual, flyer); }1605
else1606
{ this.attachShotUnderCluster(manual, cluster, manual.col); }1607
return manual.state !== STATE_MANUAL;1608
}1609
}1610
1611
var other = this.manualHitOnManualPath(manual, oldY, nextY);1612
if (other)1613
{1614
var host = this.promoteManualToCluster(other);1615
if (host)1616
{1617
if (nextY + 1e-12 < oldY)1618
{ this.attachToFlyingCluster(manual, other); }1619
else1620
{ this.attachShotUnderCluster(manual, host, manual.col); }1621
return manual.state !== STATE_MANUAL;1622
}1623
}1624
return false;1625
};1626
1627
/** Closest flying cluster member in `manual`'s column on [oldY, nextY]. */1628
GameCore.prototype.flyingHitOnManualPath = function (manual, oldY, nextY)1629
{1630
var lo = Math.min(oldY, nextY);1631
var hi = Math.max(oldY, nextY) + 1;1632
var best = null;1633
var bestY = Infinity;1254
for (var i = 0; i < this.blocks.length; i++)1634
for (var i = 0; i < this.blocks.length; i++)1255
{1635
{1256
var other = this.blocks[i];1636
var other = this.blocks[i];1257
if (other === manual)1637
if (other === manual || other.col !== manual.col)1258
{ continue; }1259
if (other.col !== manual.col)1260
{ continue; }1638
{ continue; }1261
if (other.state !== STATE_FLYING || other.clusterId == null)1639
if (other.state !== STATE_FLYING || other.clusterId == null)1262
{ continue; }1640
{ continue; }1263
if (manual.pushedClusters[other.clusterId])1641
var cluster = this.clusters[other.clusterId];1642
if (!cluster || cluster.phase === 'landed')1264
{ continue; }1643
{ continue; }1265
var otherBot = other.y;1644
var o0 = (other._prevY != null) ? other._prevY : other.y;1266
var otherTop = other.y + 1;1645
var o1 = other.y;1267
var overlapping = otherBot < high + 1e-9 && otherTop > low - 1e-9;1646
var oLo = Math.min(o0, o1);1268
var crossing = manualTopOld <= otherBot + 1e-9 && manualTopNew >= otherBot - 1e-9;1647
var oHi = Math.max(o0, o1) + 1;1269
if (overlapping || crossing)1648
if (lo < oHi - 1e-9 && oLo < hi - 1e-9)1270
{1649
{1271
if (this.pushClusterColumn(other.clusterId, manual.col))1650
if (other.y < bestY)1272
{1651
{1273
manual.pushedClusters[other.clusterId] = true;1652
bestY = other.y;1274
return;1653
best = other;1275
}1654
}1276
}1655
}1277
}1656
}1657
return best;1658
};1659
1660
/** Another thrown block in the same column on the path (prefer the lower). */1661
GameCore.prototype.manualHitOnManualPath = function (manual, oldY, nextY)1662
{1663
var lo = Math.min(oldY, nextY);1664
var hi = Math.max(oldY, nextY) + 1;1665
var best = null;1666
for (var i = 0; i < this.blocks.length; i++)1667
{1668
var other = this.blocks[i];1669
if (other === manual || other.col !== manual.col)1670
{ continue; }1671
if (other.state !== STATE_MANUAL)1672
{ continue; }1673
var o0 = (other._prevY != null) ? other._prevY : other.y;1674
var o1 = other.y;1675
var oLo = Math.min(o0, o1);1676
var oHi = Math.max(o0, o1) + 1;1677
if (lo < oHi - 1e-9 && oLo < hi - 1e-9)1678
{1679
if (!best || other.y < best.y)1680
{ best = other; }1681
}1682
}1683
return best;1684
};1685
1686
/**1687
* t1111: push every member of `cluster` in `col` up by one cell, then1688
* attach `manual` at the bottom of that column, grid-aligned, as part1689
* of the cluster. The cluster keeps its velocity; the shot takes it.1690
* Other columns are untouched. Same rule for every successive shot.1691
*/1692
GameCore.prototype.attachShotUnderCluster = function (manual, cluster, col)1693
{1694
if (!manual || !cluster || !this.clusters[cluster.id])1695
{ return false; }1696
if (manual.state !== STATE_MANUAL && manual.clusterId !== cluster.id)1697
{1698
// Already belonging elsewhere: leave first.1699
if (manual.clusterId != null)1700
{ this.leaveCluster(manual); }1701
}1702
this.prepareClusterBody(cluster);1703
var members = this.clusterMembers(cluster.id);1704
var minOff = null;1705
for (var i = 0; i < members.length; i++)1706
{1707
if (members[i].col !== col)1708
{ continue; }1709
if (minOff == null || members[i].clusterOffset < minOff)1710
{ minOff = members[i].clusterOffset; }1711
}1712
if (minOff == null)1713
{ minOff = 0; }1714
else1715
{1716
for (var i = 0; i < members.length; i++)1717
{1718
if (members[i].col === col)1719
{ members[i].clusterOffset += 1; }1720
}1721
}1722
if (this.drag && this.drag.blockId === manual.id)1723
{ this.drag = null; }1724
manual.clusterId = cluster.id;1725
manual.clusterOffset = minOff;1726
manual.state = STATE_FLYING;1727
manual.flame = manual.color === COLOR_GRAY;1728
manual.settleTime = 0;1729
manual.manualPhase = null;1730
manual.manualTarget = null;1731
manual.manualDecel = 0;1732
manual.manualJumpHeight = 0;1733
manual.pushedClusters = null;1734
this.syncClusterMembers(cluster);1735
this.cullOffTop();1736
if (this.clusters[cluster.id])1737
{ this.checkChainRelaunch(cluster); }1738
return true;1739
};1740
1741
/**1742
* Turn a lone thrown block into a 1-block flying cluster so a later1743
* shot can use the t1111 attach-at-bottom rule. A single throw stays1744
* MANUAL (and is capped at the top of the field) until it collides.1745
*/1746
GameCore.prototype.promoteManualToCluster = function (manual)1747
{1748
if (!manual)1749
{ return null; }1750
if (manual.state === STATE_FLYING && manual.clusterId != null)1751
{1752
var existing = this.clusters[manual.clusterId];1753
if (existing && existing.phase !== 'landed')1754
{ return existing; }1755
}1756
if (manual.state !== STATE_MANUAL)1757
{ return null; }1758
var height = manual.manualJumpHeight != null ? manual.manualJumpHeight1759
: Math.max(0.05, (manual.manualTarget || this.height - 1) - manual.y);1760
var cluster = {1761
id: this.nextClusterId++,1762
jumpHeight: height,1763
vy: manual.vy,1764
decel: manual.manualDecel || 0,1765
phase: (manual.manualPhase === 'down' || manual.vy <= 1e-10) ? 'down' : 'up',1766
fromManual: true,1767
anchorY: manual.y1768
};1769
this.clusters[cluster.id] = cluster;1770
manual.state = STATE_FLYING;1771
manual.clusterId = cluster.id;1772
manual.clusterOffset = 0;1773
manual.flame = manual.color === COLOR_GRAY;1774
manual.settleTime = 0;1775
manual.manualPhase = null;1776
manual.manualTarget = null;1777
manual.manualDecel = 0;1778
manual.manualJumpHeight = 0;1779
manual.pushedClusters = null;1780
this.syncClusterMembers(cluster);1781
return cluster;1782
};1783
1784
/** Kept for older tests / call sites: push a cluster column by one cell. */1785
GameCore.prototype.checkManualPush = function (manual, oldY, nextY)1786
{1787
return this.resolveManualCollisions(manual, oldY, nextY);1278
};1788
};1279
1789
1280
1790
@@ -1787,6 +2297,7 @@ GameCore.prototype.launchCluster = function (matchedBlocks, height)1787
block.vy = cluster.vy;2297
block.vy = cluster.vy;1788
block.settleTime = 0;2298
block.settleTime = 0;1789
}2299
}2300
this.prepareClusterBody(cluster);1790
return cluster;2301
return cluster;1791
};2302
};1792
2303
@@ -61,6 +61,7 @@ var app = {
61
61
pointerType: null,
62
62
activeTouchId: null,
63
63
debugDrag: false,
64
debugPhysics: false,
64
65
gameOverShown: false,
65
66
selectTween: null,
66
67
online: false,
@@ -74,6 +75,7 @@ var app = {
74
75
window.onload = function ()
75
76
{
76
77
app.debugDrag = isDragDebugEnabled();
78
app.debugPhysics = isPhysicsDebugEnabled();
77
79
var play = document.getElementById('btn-play');
78
80
play.addEventListener('click', onPlay);
79
81
play.addEventListener('pointerup', function (e)
@@ -122,6 +124,8 @@ function startPlay (opts)
122
124
if (typeof miss !== 'number' || !isFinite(miss))
123
125
{ miss = planetMod.missChance(app.planet); }
124
126
app.core = new GameCore(app.planet, Math.random, miss);
127
if (app.debugPhysics)
128
{ app.core.debugInvariants = true; }
125
129
app.mode = 'playing';
126
130
app.online = !!opts.online;
127
131
app.gameOverShown = false;
@@ -494,6 +498,8 @@ function tickView (dt)
494
498
syncSprites();
495
499
refreshHud();
496
500
tickOnline(dt);
501
if (app.debugPhysics)
502
{ logPhysicsDebug(); }
497
503
498
504
if (app.core.state === 'gameover' && !app.gameOverShown)
499
505
{
@@ -550,6 +556,22 @@ function isDragDebugEnabled ()
550
556
return false;
551
557
}
552
558
559
/** ?debug, ?debug=physics, ?debug=drag, or localStorage meteors-debug=1. */
560
function isPhysicsDebugEnabled ()
561
{
562
try
563
{
564
var q = window.location && window.location.search;
565
if (q && /(?:\?|&)debug(?:=|&|$)/.test(q))
566
{ return true; }
567
if (window.localStorage && (window.localStorage.getItem('meteors-debug') === '1'
568
|| window.localStorage.getItem('meteors-debug-drag') === '1'))
569
{ return true; }
570
}
571
catch (err) { /* ignore */ }
572
return false;
573
}
574
553
575
function eventClient (e)
554
576
{
555
577
var t = null;
@@ -859,6 +881,42 @@ function onTouchCancel (e)
859
881
finishDrag({ noLaunch: true });
860
882
}
861
883
884
function logPhysicsDebug ()
885
{
886
if (!app.debugPhysics || !app.core)
887
{ return; }
888
ensureDragDebugOverlay();
889
var el = document.getElementById('drag-debug');
890
if (!el)
891
{ return; }
892
var issues = app.core.lastInvariantViolations || [];
893
var flying = 0;
894
var manuals = 0;
895
var clusters = app.core.clusters ? Object.keys(app.core.clusters).length : 0;
896
for (var i = 0; i < app.core.blocks.length; i++)
897
{
898
if (app.core.blocks[i].state === 'flying')
899
{ flying++; }
900
if (app.core.blocks[i].state === 'manual')
901
{ manuals++; }
902
}
903
var status = issues.length
904
? ('PHYSICS FAIL x' + issues.length + '\n' + issues.slice(0, 6).join('\n'))
905
: ('physics ok blocks=' + app.core.blocks.length
906
+ ' fly=' + flying + ' man=' + manuals + ' cl=' + clusters);
907
// Keep any live drag line above the physics status.
908
var dragLine = '';
909
if (app.debugDrag && lastDragDebug)
910
{
911
dragLine = el.textContent && el.textContent.indexOf('drag ') === 0
912
? el.textContent.split('\n')[0] + '\n'
913
: '';
914
}
915
el.textContent = dragLine + status;
916
el.hidden = false;
917
el.style.color = issues.length ? '#ffb4b4' : '#c6f6c8';
918
}
919
862
920
function ensureDragDebugOverlay ()
863
921
{
864
922
if (document.getElementById('drag-debug'))
@@ -61,6 +61,7 @@ var app = {61
pointerType: null,61
pointerType: null,62
activeTouchId: null,62
activeTouchId: null,63
debugDrag: false,63
debugDrag: false,64
debugPhysics: false,64
gameOverShown: false,65
gameOverShown: false,65
selectTween: null,66
selectTween: null,66
online: false,67
online: false,@@ -74,6 +75,7 @@ var app = {74
window.onload = function ()75
window.onload = function ()75
{76
{76
app.debugDrag = isDragDebugEnabled();77
app.debugDrag = isDragDebugEnabled();78
app.debugPhysics = isPhysicsDebugEnabled();77
var play = document.getElementById('btn-play');79
var play = document.getElementById('btn-play');78
play.addEventListener('click', onPlay);80
play.addEventListener('click', onPlay);79
play.addEventListener('pointerup', function (e)81
play.addEventListener('pointerup', function (e)@@ -122,6 +124,8 @@ function startPlay (opts)122
if (typeof miss !== 'number' || !isFinite(miss))124
if (typeof miss !== 'number' || !isFinite(miss))123
{ miss = planetMod.missChance(app.planet); }125
{ miss = planetMod.missChance(app.planet); }124
app.core = new GameCore(app.planet, Math.random, miss);126
app.core = new GameCore(app.planet, Math.random, miss);127
if (app.debugPhysics)128
{ app.core.debugInvariants = true; }125
app.mode = 'playing';129
app.mode = 'playing';126
app.online = !!opts.online;130
app.online = !!opts.online;127
app.gameOverShown = false;131
app.gameOverShown = false;@@ -494,6 +498,8 @@ function tickView (dt)494
syncSprites();498
syncSprites();495
refreshHud();499
refreshHud();496
tickOnline(dt);500
tickOnline(dt);501
if (app.debugPhysics)502
{ logPhysicsDebug(); }497
503
498
if (app.core.state === 'gameover' && !app.gameOverShown)504
if (app.core.state === 'gameover' && !app.gameOverShown)499
{505
{@@ -550,6 +556,22 @@ function isDragDebugEnabled ()550
return false;556
return false;551
}557
}552
558
559
/** ?debug, ?debug=physics, ?debug=drag, or localStorage meteors-debug=1. */560
function isPhysicsDebugEnabled ()561
{562
try563
{564
var q = window.location && window.location.search;565
if (q && /(?:\?|&)debug(?:=|&|$)/.test(q))566
{ return true; }567
if (window.localStorage && (window.localStorage.getItem('meteors-debug') === '1'568
|| window.localStorage.getItem('meteors-debug-drag') === '1'))569
{ return true; }570
}571
catch (err) { /* ignore */ }572
return false;573
}574
553
function eventClient (e)575
function eventClient (e)554
{576
{555
var t = null;577
var t = null;@@ -859,6 +881,42 @@ function onTouchCancel (e)859
finishDrag({ noLaunch: true });881
finishDrag({ noLaunch: true });860
}882
}861
883
884
function logPhysicsDebug ()885
{886
if (!app.debugPhysics || !app.core)887
{ return; }888
ensureDragDebugOverlay();889
var el = document.getElementById('drag-debug');890
if (!el)891
{ return; }892
var issues = app.core.lastInvariantViolations || [];893
var flying = 0;894
var manuals = 0;895
var clusters = app.core.clusters ? Object.keys(app.core.clusters).length : 0;896
for (var i = 0; i < app.core.blocks.length; i++)897
{898
if (app.core.blocks[i].state === 'flying')899
{ flying++; }900
if (app.core.blocks[i].state === 'manual')901
{ manuals++; }902
}903
var status = issues.length904
? ('PHYSICS FAIL x' + issues.length + '\n' + issues.slice(0, 6).join('\n'))905
: ('physics ok blocks=' + app.core.blocks.length906
+ ' fly=' + flying + ' man=' + manuals + ' cl=' + clusters);907
// Keep any live drag line above the physics status.908
var dragLine = '';909
if (app.debugDrag && lastDragDebug)910
{911
dragLine = el.textContent && el.textContent.indexOf('drag ') === 0912
? el.textContent.split('\n')[0] + '\n'913
: '';914
}915
el.textContent = dragLine + status;916
el.hidden = false;917
el.style.color = issues.length ? '#ffb4b4' : '#c6f6c8';918
}919
862
function ensureDragDebugOverlay ()920
function ensureDragDebugOverlay ()863
{921
{864
if (document.getElementById('drag-debug'))922
if (document.getElementById('drag-debug'))@@ -16,6 +16,8 @@ function makeGame (opts)
16
16
const game = new GameCore(planet, rng);
17
17
if (opts.noSpawn)
18
18
{ game.spawnInterval = 1e9; }
19
if (opts.strictInvariants !== false)
20
{ game.strictInvariants = true; }
19
21
return game;
20
22
}
21
23
@@ -16,6 +16,8 @@ function makeGame (opts)16
const game = new GameCore(planet, rng);16
const game = new GameCore(planet, rng);17
if (opts.noSpawn)17
if (opts.noSpawn)18
{ game.spawnInterval = 1e9; }18
{ game.spawnInterval = 1e9; }19
if (opts.strictInvariants !== false)20
{ game.strictInvariants = true; }19
return game;21
return game;20
}22
}21
23
@@ -0,0 +1,406 @@
1
'use strict';
2
3
const { describe, it } = require('node:test');
4
const assert = require('node:assert/strict');
5
const { makeGame, almost, GameCore, Planet, Rng } = require('./helpers.js');
6
7
function flyingHeld (game, y, colorsByCol)
8
{
9
const cols = Object.keys(colorsByCol).map(Number).sort((a, b) => a - b);
10
const cluster = {
11
id: game.nextClusterId++,
12
jumpHeight: 3,
13
vy: 0,
14
decel: 0,
15
phase: 'hold',
16
anchorY: y
17
};
18
game.clusters[cluster.id] = cluster;
19
const members = [];
20
for (const col of cols)
21
{
22
const b = game.createBlock(col, y, colorsByCol[col], 'flying');
23
b.clusterId = cluster.id;
24
b.clusterOffset = 0;
25
b.vy = 0;
26
if (colorsByCol[col] === GameCore.COLOR_GRAY)
27
{ b.flame = true; }
28
members.push(b);
29
}
30
game.prepareClusterBody(cluster);
31
return { cluster, members };
32
}
33
34
function waitUntil (g, pred, maxTicks)
35
{
36
for (let i = 0; i < (maxTicks || 800); i++)
37
{
38
g.tick(1 / 120);
39
if (pred())
40
{ return i; }
41
}
42
return -1;
43
}
44
45
function columnStack (g, col)
46
{
47
return g.blocks
48
.filter((b) => b.col === col)
49
.sort((a, b) => a.y - b.y)
50
.map((b) => ({
51
id: b.id,
52
color: b.color,
53
y: b.y,
54
state: b.state,
55
clusterId: b.clusterId,
56
offset: b.clusterOffset
57
}));
58
}
59
60
function assertPacked (blocks, label)
61
{
62
const sorted = blocks.slice().sort((a, b) => a.y - b.y);
63
for (let i = 1; i < sorted.length; i++)
64
{
65
assert.ok(sorted[i].y >= sorted[i - 1].y + 1 - 1e-6,
66
(label || 'pack') + ': overlap ' + sorted[i - 1].y + ' and ' + sorted[i].y);
67
}
68
}
69
70
describe('Shot into a flying cluster (t1111)', () =>
71
{
72
it('pushes the hit column up by 1 and attaches the shot at the bottom, grid-aligned', () =>
73
{
74
const g = makeGame({ noSpawn: true });
75
const { cluster, members } = flyingHeld(g, 6, {
76
1: GameCore.COLOR_GRAY,
77
2: GameCore.COLOR_GRAY,
78
3: GameCore.COLOR_GRAY
79
});
80
const hit = members.find((b) => b.col === 2);
81
const left = members.find((b) => b.col === 1);
82
const right = members.find((b) => b.col === 3);
83
const shot = g.place(2, 1, 4);
84
g.startManualLaunch(shot);
85
const n = waitUntil(g, () => shot.state === 'flying' && shot.clusterId === cluster.id);
86
assert.ok(n >= 0, 'shot must attach, state=' + shot.state + ' cid=' + shot.clusterId
87
+ ' y=' + shot.y + ' hit=' + hit.y);
88
assert.equal(shot.clusterId, cluster.id);
89
assert.equal(hit.clusterId, cluster.id);
90
assert.ok(almost(hit.y - shot.y, 1, 1e-6),
91
'shot sits exactly 1 under the pushed member, shot=' + shot.y + ' hit=' + hit.y);
92
assert.ok(almost(left.y, right.y, 1e-6), 'other columns stay level');
93
assert.ok(almost(left.y, shot.y, 0.05), 'shot is at the old bottom (other cols), left=' + left.y + ' shot=' + shot.y);
94
assert.ok(almost(hit.y - left.y, 1, 0.05), 'hit column rose by 1 relative to neighbours');
95
assert.equal(g.checkInvariants().length, 0, g.checkInvariants().join('; '));
96
});
97
98
it('successive shots each push the column 1 and insert at the bottom, never overlapping', () =>
99
{
100
const g = makeGame({ noSpawn: true });
101
const { cluster, members } = flyingHeld(g, 7, { 4: GameCore.COLOR_GRAY });
102
const original = members[0];
103
const shots = [];
104
for (let s = 0; s < 4; s++)
105
{
106
const shot = g.createBlock(4, 0.2, s % 5, 'still');
107
g.startManualLaunch(shot);
108
shots.push(shot);
109
const n = waitUntil(g, () => shot.state === 'flying' && shot.clusterId === cluster.id, 600);
110
assert.ok(n >= 0, 'shot ' + s + ' must attach, state=' + shot.state + ' y=' + shot.y
111
+ ' stack=' + JSON.stringify(columnStack(g, 4)));
112
assert.equal(shot.clusterId, cluster.id);
113
assert.equal(g.checkInvariants().length, 0, g.checkInvariants().join('; '));
114
}
115
const stack = g.clusterMembers(cluster.id)
116
.filter((b) => b.col === 4)
117
.sort((a, b) => a.y - b.y);
118
assert.equal(stack.length, 5, 'original + 4 shots, got ' + stack.length);
119
// Bottom-to-top: last shot, then earlier shots, then the original at the top.
120
assert.equal(stack[0].id, shots[3].id, 'last shot is at the bottom');
121
assert.equal(stack[4].id, original.id, 'original member is at the top');
122
for (let i = 1; i < stack.length; i++)
123
{
124
assert.ok(almost(stack[i].y - stack[i - 1].y, 1, 1e-6),
125
'integer packing, ' + stack[i - 1].y + ' then ' + stack[i].y);
126
}
127
});
128
129
it('two launched blocks in the same column never overlap; the later one attaches under the earlier', () =>
130
{
131
const g = makeGame({ noSpawn: true, planetOpts: { jumpsToClear: 2, fallTime: 3, riseTime: 1.5 } });
132
const first = g.place(3, 0, 1);
133
g.startManualLaunch(first);
134
// Let the first rise a few tiles.
135
g.step(0.25, 1 / 120);
136
assert.equal(first.state, 'manual');
137
assert.ok(first.y > 1, 'first is in the air, y=' + first.y);
138
const second = g.createBlock(3, 0.2, 2, 'still');
139
g.startManualLaunch(second);
140
const n = waitUntil(g, () => second.state === 'flying' && first.state === 'flying'
141
&& first.clusterId != null && first.clusterId === second.clusterId, 800);
142
assert.ok(n >= 0, 'they must form a cluster, first=' + first.state + '@' + first.y
143
+ ' second=' + second.state + '@' + second.y);
144
assert.ok(almost(Math.abs(first.y - second.y), 1, 1e-6),
145
'packed 1 apart, first=' + first.y + ' second=' + second.y);
146
assert.ok(second.y < first.y - 0.5, 'later shot is under the earlier');
147
assert.equal(g.checkInvariants().length, 0);
148
});
149
});
150
151
describe('Video scenario: repeated launches under a cluster with falling blocks (t1111/t1112)', () =>
152
{
153
it('never overlaps, vanishes, duplicates or reorders illegally', () =>
154
{
155
const g = makeGame({ noSpawn: true, planetOpts: { jumpsToClear: 2, fallTime: 3, riseTime: 1.5 } });
156
// 3rd column from the left is col 2. A flying grey+pink cluster,
157
// falling greens, and several launched pinks and a yellow — the
158
// shape of the t1111.webm clip.
159
const { cluster } = flyingHeld(g, 8, {
160
2: GameCore.COLOR_GRAY
161
});
162
cluster.phase = 'down';
163
cluster.vy = -1;
164
cluster.decel = 0;
165
g.syncClusterMembers(cluster);
166
167
const cargo = g.createBlock(2, 9, 1, 'falling'); // pink-ish color 1
168
cargo.vy = -g.planet.fallSpeed;
169
const fallingGreen = g.createBlock(2, 12, 3, 'falling');
170
fallingGreen.vy = -g.planet.fallSpeed * 0.5;
171
172
const launched = [];
173
// First pink already on the way.
174
const p1 = g.place(2, 1, 1);
175
g.startManualLaunch(p1);
176
launched.push(p1);
177
178
const seen = new Map();
179
const recordColors = () =>
180
{
181
for (const b of g.blocks)
182
{
183
if (!seen.has(b.id))
184
{ seen.set(b.id, b.color); }
185
else
186
{
187
const prev = seen.get(b.id);
188
if (prev !== b.color)
189
{
190
const ok = prev === GameCore.COLOR_GRAY || b.color === GameCore.COLOR_GRAY;
191
assert.ok(ok, 'illegal colour change id=' + b.id + ' ' + prev + ' → ' + b.color
192
+ ' at y=' + b.y);
193
seen.set(b.id, b.color);
194
}
195
}
196
}
197
};
198
recordColors();
199
200
let launchesLeft = 4;
201
const colorsToShoot = [1, 2, 1, 2]; // pink, yellow, pink, yellow
202
for (let i = 0; i < 900; i++)
203
{
204
if (launchesLeft > 0 && i > 0 && i % 40 === 0)
205
{
206
// Only launch if the floor cell is free.
207
const occupant = g.blocks.find((b) => b.col === 2 && b.y < 1);
208
if (!occupant)
209
{
210
const shot = g.createBlock(2, 0, colorsToShoot[4 - launchesLeft], 'still');
211
g.startManualLaunch(shot);
212
launched.push(shot);
213
launchesLeft--;
214
seen.set(shot.id, shot.color);
215
}
216
}
217
g.tick(1 / 120);
218
recordColors();
219
const issues = g.checkInvariants();
220
assert.equal(issues.length, 0, 'tick ' + i + ': ' + issues.join('; ')
221
+ '\n' + g.snapshot().picture
222
+ '\n' + JSON.stringify(columnStack(g, 2)));
223
}
224
225
// Everything still in col 2 is packed, no overlaps, and every
226
// launched block still exists or was scored off the top.
227
const remaining = g.blocks.filter((b) => b.col === 2);
228
assertPacked(remaining, 'final col 2');
229
for (const shot of launched)
230
{
231
const still = g.blockById(shot.id);
232
const scored = g.score > 0 || !still;
233
assert.ok(still || scored, 'shot ' + shot.id + ' vanished without scoring');
234
}
235
assert.equal(g.checkInvariants().length, 0);
236
});
237
});
238
239
describe('Falling must not teleport up through a gap (t1112)', () =>
240
{
241
it('a falling block below a hanging still lands on the stack under it, not on the hanging block', () =>
242
{
243
const g = makeGame({ noSpawn: true });
244
g.place(2, 0, 0);
245
const hanging = g.place(2, 5, 1);
246
const falling = g.createBlock(2, 2, 3, 'falling');
247
falling.vy = 0;
248
g.tick(1 / 120);
249
assert.ok(falling.y < hanging.y - 0.5,
250
'must not teleport up onto the hanging block, falling.y=' + falling.y
251
+ ' hanging.y=' + hanging.y + ' state=' + falling.state);
252
assert.ok(falling.y <= 2 + 1e-6, 'must not rise, y=' + falling.y);
253
assert.equal(g.checkInvariants().length, 0);
254
});
255
256
it('a chain of stills sitting on a released landed cluster all fall, from rest', () =>
257
{
258
const g = makeGame({ noSpawn: true });
259
const { cluster } = flyingHeld(g, 0, { 3: GameCore.COLOR_GRAY });
260
// Build a 3-high landed group and two stills on top.
261
const grey = g.clusterMembers(cluster.id)[0];
262
grey.y = 0;
263
grey.state = 'settling';
264
grey.settleTime = 0;
265
cluster.phase = 'landed';
266
const mid = g.createBlock(3, 1, GameCore.COLOR_GRAY, 'settling');
267
mid.clusterId = cluster.id;
268
mid.settleTime = 0;
269
const topGrey = g.createBlock(3, 2, GameCore.COLOR_GRAY, 'settling');
270
topGrey.clusterId = cluster.id;
271
topGrey.settleTime = 0;
272
g.prepareClusterBody(cluster);
273
const a = g.place(3, 3, 1);
274
const b = g.place(3, 4, 2);
275
// Recolor and release.
276
g.randomColor = () => 4;
277
g.step(g.settleTime + 0.05, 1 / 120);
278
// After release the original greys (now colour 4) that have no
279
// outside support fall; the stills that sat on them must fall too,
280
// not hang or teleport.
281
for (const block of [a, b, mid, topGrey])
282
{
283
if (!g.blockById(block.id))
284
{ continue; }
285
assert.notEqual(block.state, 'still',
286
'block ' + block.id + ' at y=' + block.y + ' should have fallen or launched, state=' + block.state);
287
}
288
assert.equal(g.checkInvariants().length, 0, g.checkInvariants().join('; '));
289
});
290
});
291
292
describe('Randomized physics soak (t1112)', () =>
293
{
294
it('thousands of ticks of random launches, drags, matches and landings keep the invariants', () =>
295
{
296
const seeds = [1, 2, 7, 13, 42, 99, 128, 255];
297
const ticksPerSeed = 2500;
298
for (const seed of seeds)
299
{
300
const rng = Rng.create(seed);
301
const g = makeGame({
302
noSpawn: true,
303
seed,
304
planetOpts: { jumpsToClear: 2, fallTime: 3, riseTime: 1.2 }
305
});
306
g.strictInvariants = true;
307
// A grounded mess of colours, not a ready-made match.
308
for (let c = 0; c < 10; c++)
309
{
310
const h = 1 + Math.floor(rng() * 4);
311
for (let r = 0; r < h; r++)
312
{ g.place(c, r, Math.floor(rng() * 5)); }
313
}
314
const colors = new Map();
315
for (const b of g.blocks)
316
{ colors.set(b.id, b.color); }
317
let scored = 0;
318
for (let t = 0; t < ticksPerSeed; t++)
319
{
320
const roll = rng();
321
if (roll < 0.04)
322
{
323
// Random drag in a still column.
324
const still = g.blocks.filter((b) => g.isDraggableBlock && g.isDraggableBlock(b));
325
if (still.length)
326
{
327
const b = still[Math.floor(rng() * still.length)];
328
if (g.beginDrag(b.col + 0.5, b.y + 0.5))
329
{
330
const dest = b.y + (rng() < 0.5 ? 1 : -1) * (1 + Math.floor(rng() * 3));
331
g.moveDrag(dest);
332
g.endDrag();
333
}
334
}
335
}
336
else if (roll < 0.08)
337
{
338
// Launch a top still block.
339
const tops = [];
340
for (let c = 0; c < g.width; c++)
341
{
342
const list = g.blocks.filter((b) => b.col === c && (b.state === 'still' || b.state === 'settling'));
343
if (!list.length)
344
{ continue; }
345
list.sort((a, b) => b.y - a.y);
346
tops.push(list[0]);
347
}
348
if (tops.length)
349
{
350
const b = tops[Math.floor(rng() * tops.length)];
351
if (g.beginDrag(b.col + 0.5, b.y + 0.5))
352
{
353
g.moveDrag(b.y + 1 + 0.5);
354
g.endDrag();
355
}
356
}
357
}
358
else if (roll < 0.1)
359
{
360
// Drop a falling block into a random column if there is room.
361
const col = Math.floor(rng() * g.width);
362
const top = Math.max(-1, ...g.blocks.filter((b) => b.col === col).map((b) => b.y));
363
if (top < g.height - 3)
364
{
365
const fb = g.createBlock(col, g.height - 1.2, Math.floor(rng() * 5), 'falling');
366
fb.vy = -g.planet.fallSpeed;
367
colors.set(fb.id, fb.color);
368
}
369
}
370
371
const beforeIds = new Set(g.blocks.map((b) => b.id));
372
const scoreBefore = g.score;
373
g.tick(1 / 120);
374
scored += g.score - scoreBefore;
375
376
for (const b of g.blocks)
377
{
378
if (!colors.has(b.id))
379
{ colors.set(b.id, b.color); }
380
else if (colors.get(b.id) !== b.color)
381
{
382
const prev = colors.get(b.id);
383
const ok = prev === GameCore.COLOR_GRAY || b.color === GameCore.COLOR_GRAY;
384
assert.ok(ok, 'seed=' + seed + ' tick=' + t
385
+ ' illegal colour change id=' + b.id + ' ' + prev + ' → ' + b.color
386
+ '\n' + g.snapshot().picture);
387
colors.set(b.id, b.color);
388
}
389
}
390
for (const id of beforeIds)
391
{
392
if (!g.blockById(id) && g.score === scoreBefore)
393
{
394
// cullOffTop increments score. A disappearance
395
// without a point is a vanish.
396
assert.ok(g.score > scoreBefore,
397
'seed=' + seed + ' tick=' + t + ' block ' + id + ' vanished without scoring'
398
+ '\n' + g.snapshot().picture);
399
}
400
}
401
}
402
assert.equal(g.checkInvariants().length, 0, 'seed=' + seed + ' final: '
403
+ g.checkInvariants().join('; '));
404
}
405
});
406
});
@@ -0,0 +1,406 @@1
'use strict';2
3
const { describe, it } = require('node:test');4
const assert = require('node:assert/strict');5
const { makeGame, almost, GameCore, Planet, Rng } = require('./helpers.js');6
7
function flyingHeld (game, y, colorsByCol)8
{9
const cols = Object.keys(colorsByCol).map(Number).sort((a, b) => a - b);10
const cluster = {11
id: game.nextClusterId++,12
jumpHeight: 3,13
vy: 0,14
decel: 0,15
phase: 'hold',16
anchorY: y17
};18
game.clusters[cluster.id] = cluster;19
const members = [];20
for (const col of cols)21
{22
const b = game.createBlock(col, y, colorsByCol[col], 'flying');23
b.clusterId = cluster.id;24
b.clusterOffset = 0;25
b.vy = 0;26
if (colorsByCol[col] === GameCore.COLOR_GRAY)27
{ b.flame = true; }28
members.push(b);29
}30
game.prepareClusterBody(cluster);31
return { cluster, members };32
}33
34
function waitUntil (g, pred, maxTicks)35
{36
for (let i = 0; i < (maxTicks || 800); i++)37
{38
g.tick(1 / 120);39
if (pred())40
{ return i; }41
}42
return -1;43
}44
45
function columnStack (g, col)46
{47
return g.blocks48
.filter((b) => b.col === col)49
.sort((a, b) => a.y - b.y)50
.map((b) => ({51
id: b.id,52
color: b.color,53
y: b.y,54
state: b.state,55
clusterId: b.clusterId,56
offset: b.clusterOffset57
}));58
}59
60
function assertPacked (blocks, label)61
{62
const sorted = blocks.slice().sort((a, b) => a.y - b.y);63
for (let i = 1; i < sorted.length; i++)64
{65
assert.ok(sorted[i].y >= sorted[i - 1].y + 1 - 1e-6,66
(label || 'pack') + ': overlap ' + sorted[i - 1].y + ' and ' + sorted[i].y);67
}68
}69
70
describe('Shot into a flying cluster (t1111)', () =>71
{72
it('pushes the hit column up by 1 and attaches the shot at the bottom, grid-aligned', () =>73
{74
const g = makeGame({ noSpawn: true });75
const { cluster, members } = flyingHeld(g, 6, {76
1: GameCore.COLOR_GRAY,77
2: GameCore.COLOR_GRAY,78
3: GameCore.COLOR_GRAY79
});80
const hit = members.find((b) => b.col === 2);81
const left = members.find((b) => b.col === 1);82
const right = members.find((b) => b.col === 3);83
const shot = g.place(2, 1, 4);84
g.startManualLaunch(shot);85
const n = waitUntil(g, () => shot.state === 'flying' && shot.clusterId === cluster.id);86
assert.ok(n >= 0, 'shot must attach, state=' + shot.state + ' cid=' + shot.clusterId87
+ ' y=' + shot.y + ' hit=' + hit.y);88
assert.equal(shot.clusterId, cluster.id);89
assert.equal(hit.clusterId, cluster.id);90
assert.ok(almost(hit.y - shot.y, 1, 1e-6),91
'shot sits exactly 1 under the pushed member, shot=' + shot.y + ' hit=' + hit.y);92
assert.ok(almost(left.y, right.y, 1e-6), 'other columns stay level');93
assert.ok(almost(left.y, shot.y, 0.05), 'shot is at the old bottom (other cols), left=' + left.y + ' shot=' + shot.y);94
assert.ok(almost(hit.y - left.y, 1, 0.05), 'hit column rose by 1 relative to neighbours');95
assert.equal(g.checkInvariants().length, 0, g.checkInvariants().join('; '));96
});97
98
it('successive shots each push the column 1 and insert at the bottom, never overlapping', () =>99
{100
const g = makeGame({ noSpawn: true });101
const { cluster, members } = flyingHeld(g, 7, { 4: GameCore.COLOR_GRAY });102
const original = members[0];103
const shots = [];104
for (let s = 0; s < 4; s++)105
{106
const shot = g.createBlock(4, 0.2, s % 5, 'still');107
g.startManualLaunch(shot);108
shots.push(shot);109
const n = waitUntil(g, () => shot.state === 'flying' && shot.clusterId === cluster.id, 600);110
assert.ok(n >= 0, 'shot ' + s + ' must attach, state=' + shot.state + ' y=' + shot.y111
+ ' stack=' + JSON.stringify(columnStack(g, 4)));112
assert.equal(shot.clusterId, cluster.id);113
assert.equal(g.checkInvariants().length, 0, g.checkInvariants().join('; '));114
}115
const stack = g.clusterMembers(cluster.id)116
.filter((b) => b.col === 4)117
.sort((a, b) => a.y - b.y);118
assert.equal(stack.length, 5, 'original + 4 shots, got ' + stack.length);119
// Bottom-to-top: last shot, then earlier shots, then the original at the top.120
assert.equal(stack[0].id, shots[3].id, 'last shot is at the bottom');121
assert.equal(stack[4].id, original.id, 'original member is at the top');122
for (let i = 1; i < stack.length; i++)123
{124
assert.ok(almost(stack[i].y - stack[i - 1].y, 1, 1e-6),125
'integer packing, ' + stack[i - 1].y + ' then ' + stack[i].y);126
}127
});128
129
it('two launched blocks in the same column never overlap; the later one attaches under the earlier', () =>130
{131
const g = makeGame({ noSpawn: true, planetOpts: { jumpsToClear: 2, fallTime: 3, riseTime: 1.5 } });132
const first = g.place(3, 0, 1);133
g.startManualLaunch(first);134
// Let the first rise a few tiles.135
g.step(0.25, 1 / 120);136
assert.equal(first.state, 'manual');137
assert.ok(first.y > 1, 'first is in the air, y=' + first.y);138
const second = g.createBlock(3, 0.2, 2, 'still');139
g.startManualLaunch(second);140
const n = waitUntil(g, () => second.state === 'flying' && first.state === 'flying'141
&& first.clusterId != null && first.clusterId === second.clusterId, 800);142
assert.ok(n >= 0, 'they must form a cluster, first=' + first.state + '@' + first.y143
+ ' second=' + second.state + '@' + second.y);144
assert.ok(almost(Math.abs(first.y - second.y), 1, 1e-6),145
'packed 1 apart, first=' + first.y + ' second=' + second.y);146
assert.ok(second.y < first.y - 0.5, 'later shot is under the earlier');147
assert.equal(g.checkInvariants().length, 0);148
});149
});150
151
describe('Video scenario: repeated launches under a cluster with falling blocks (t1111/t1112)', () =>152
{153
it('never overlaps, vanishes, duplicates or reorders illegally', () =>154
{155
const g = makeGame({ noSpawn: true, planetOpts: { jumpsToClear: 2, fallTime: 3, riseTime: 1.5 } });156
// 3rd column from the left is col 2. A flying grey+pink cluster,157
// falling greens, and several launched pinks and a yellow — the158
// shape of the t1111.webm clip.159
const { cluster } = flyingHeld(g, 8, {160
2: GameCore.COLOR_GRAY161
});162
cluster.phase = 'down';163
cluster.vy = -1;164
cluster.decel = 0;165
g.syncClusterMembers(cluster);166
167
const cargo = g.createBlock(2, 9, 1, 'falling'); // pink-ish color 1168
cargo.vy = -g.planet.fallSpeed;169
const fallingGreen = g.createBlock(2, 12, 3, 'falling');170
fallingGreen.vy = -g.planet.fallSpeed * 0.5;171
172
const launched = [];173
// First pink already on the way.174
const p1 = g.place(2, 1, 1);175
g.startManualLaunch(p1);176
launched.push(p1);177
178
const seen = new Map();179
const recordColors = () =>180
{181
for (const b of g.blocks)182
{183
if (!seen.has(b.id))184
{ seen.set(b.id, b.color); }185
else186
{187
const prev = seen.get(b.id);188
if (prev !== b.color)189
{190
const ok = prev === GameCore.COLOR_GRAY || b.color === GameCore.COLOR_GRAY;191
assert.ok(ok, 'illegal colour change id=' + b.id + ' ' + prev + ' → ' + b.color192
+ ' at y=' + b.y);193
seen.set(b.id, b.color);194
}195
}196
}197
};198
recordColors();199
200
let launchesLeft = 4;201
const colorsToShoot = [1, 2, 1, 2]; // pink, yellow, pink, yellow202
for (let i = 0; i < 900; i++)203
{204
if (launchesLeft > 0 && i > 0 && i % 40 === 0)205
{206
// Only launch if the floor cell is free.207
const occupant = g.blocks.find((b) => b.col === 2 && b.y < 1);208
if (!occupant)209
{210
const shot = g.createBlock(2, 0, colorsToShoot[4 - launchesLeft], 'still');211
g.startManualLaunch(shot);212
launched.push(shot);213
launchesLeft--;214
seen.set(shot.id, shot.color);215
}216
}217
g.tick(1 / 120);218
recordColors();219
const issues = g.checkInvariants();220
assert.equal(issues.length, 0, 'tick ' + i + ': ' + issues.join('; ')221
+ '\n' + g.snapshot().picture222
+ '\n' + JSON.stringify(columnStack(g, 2)));223
}224
225
// Everything still in col 2 is packed, no overlaps, and every226
// launched block still exists or was scored off the top.227
const remaining = g.blocks.filter((b) => b.col === 2);228
assertPacked(remaining, 'final col 2');229
for (const shot of launched)230
{231
const still = g.blockById(shot.id);232
const scored = g.score > 0 || !still;233
assert.ok(still || scored, 'shot ' + shot.id + ' vanished without scoring');234
}235
assert.equal(g.checkInvariants().length, 0);236
});237
});238
239
describe('Falling must not teleport up through a gap (t1112)', () =>240
{241
it('a falling block below a hanging still lands on the stack under it, not on the hanging block', () =>242
{243
const g = makeGame({ noSpawn: true });244
g.place(2, 0, 0);245
const hanging = g.place(2, 5, 1);246
const falling = g.createBlock(2, 2, 3, 'falling');247
falling.vy = 0;248
g.tick(1 / 120);249
assert.ok(falling.y < hanging.y - 0.5,250
'must not teleport up onto the hanging block, falling.y=' + falling.y251
+ ' hanging.y=' + hanging.y + ' state=' + falling.state);252
assert.ok(falling.y <= 2 + 1e-6, 'must not rise, y=' + falling.y);253
assert.equal(g.checkInvariants().length, 0);254
});255
256
it('a chain of stills sitting on a released landed cluster all fall, from rest', () =>257
{258
const g = makeGame({ noSpawn: true });259
const { cluster } = flyingHeld(g, 0, { 3: GameCore.COLOR_GRAY });260
// Build a 3-high landed group and two stills on top.261
const grey = g.clusterMembers(cluster.id)[0];262
grey.y = 0;263
grey.state = 'settling';264
grey.settleTime = 0;265
cluster.phase = 'landed';266
const mid = g.createBlock(3, 1, GameCore.COLOR_GRAY, 'settling');267
mid.clusterId = cluster.id;268
mid.settleTime = 0;269
const topGrey = g.createBlock(3, 2, GameCore.COLOR_GRAY, 'settling');270
topGrey.clusterId = cluster.id;271
topGrey.settleTime = 0;272
g.prepareClusterBody(cluster);273
const a = g.place(3, 3, 1);274
const b = g.place(3, 4, 2);275
// Recolor and release.276
g.randomColor = () => 4;277
g.step(g.settleTime + 0.05, 1 / 120);278
// After release the original greys (now colour 4) that have no279
// outside support fall; the stills that sat on them must fall too,280
// not hang or teleport.281
for (const block of [a, b, mid, topGrey])282
{283
if (!g.blockById(block.id))284
{ continue; }285
assert.notEqual(block.state, 'still',286
'block ' + block.id + ' at y=' + block.y + ' should have fallen or launched, state=' + block.state);287
}288
assert.equal(g.checkInvariants().length, 0, g.checkInvariants().join('; '));289
});290
});291
292
describe('Randomized physics soak (t1112)', () =>293
{294
it('thousands of ticks of random launches, drags, matches and landings keep the invariants', () =>295
{296
const seeds = [1, 2, 7, 13, 42, 99, 128, 255];297
const ticksPerSeed = 2500;298
for (const seed of seeds)299
{300
const rng = Rng.create(seed);301
const g = makeGame({302
noSpawn: true,303
seed,304
planetOpts: { jumpsToClear: 2, fallTime: 3, riseTime: 1.2 }305
});306
g.strictInvariants = true;307
// A grounded mess of colours, not a ready-made match.308
for (let c = 0; c < 10; c++)309
{310
const h = 1 + Math.floor(rng() * 4);311
for (let r = 0; r < h; r++)312
{ g.place(c, r, Math.floor(rng() * 5)); }313
}314
const colors = new Map();315
for (const b of g.blocks)316
{ colors.set(b.id, b.color); }317
let scored = 0;318
for (let t = 0; t < ticksPerSeed; t++)319
{320
const roll = rng();321
if (roll < 0.04)322
{323
// Random drag in a still column.324
const still = g.blocks.filter((b) => g.isDraggableBlock && g.isDraggableBlock(b));325
if (still.length)326
{327
const b = still[Math.floor(rng() * still.length)];328
if (g.beginDrag(b.col + 0.5, b.y + 0.5))329
{330
const dest = b.y + (rng() < 0.5 ? 1 : -1) * (1 + Math.floor(rng() * 3));331
g.moveDrag(dest);332
g.endDrag();333
}334
}335
}336
else if (roll < 0.08)337
{338
// Launch a top still block.339
const tops = [];340
for (let c = 0; c < g.width; c++)341
{342
const list = g.blocks.filter((b) => b.col === c && (b.state === 'still' || b.state === 'settling'));343
if (!list.length)344
{ continue; }345
list.sort((a, b) => b.y - a.y);346
tops.push(list[0]);347
}348
if (tops.length)349
{350
const b = tops[Math.floor(rng() * tops.length)];351
if (g.beginDrag(b.col + 0.5, b.y + 0.5))352
{353
g.moveDrag(b.y + 1 + 0.5);354
g.endDrag();355
}356
}357
}358
else if (roll < 0.1)359
{360
// Drop a falling block into a random column if there is room.361
const col = Math.floor(rng() * g.width);362
const top = Math.max(-1, ...g.blocks.filter((b) => b.col === col).map((b) => b.y));363
if (top < g.height - 3)364
{365
const fb = g.createBlock(col, g.height - 1.2, Math.floor(rng() * 5), 'falling');366
fb.vy = -g.planet.fallSpeed;367
colors.set(fb.id, fb.color);368
}369
}370
371
const beforeIds = new Set(g.blocks.map((b) => b.id));372
const scoreBefore = g.score;373
g.tick(1 / 120);374
scored += g.score - scoreBefore;375
376
for (const b of g.blocks)377
{378
if (!colors.has(b.id))379
{ colors.set(b.id, b.color); }380
else if (colors.get(b.id) !== b.color)381
{382
const prev = colors.get(b.id);383
const ok = prev === GameCore.COLOR_GRAY || b.color === GameCore.COLOR_GRAY;384
assert.ok(ok, 'seed=' + seed + ' tick=' + t385
+ ' illegal colour change id=' + b.id + ' ' + prev + ' → ' + b.color386
+ '\n' + g.snapshot().picture);387
colors.set(b.id, b.color);388
}389
}390
for (const id of beforeIds)391
{392
if (!g.blockById(id) && g.score === scoreBefore)393
{394
// cullOffTop increments score. A disappearance395
// without a point is a vanish.396
assert.ok(g.score > scoreBefore,397
'seed=' + seed + ' tick=' + t + ' block ' + id + ' vanished without scoring'398
+ '\n' + g.snapshot().picture);399
}400
}401
}402
assert.equal(g.checkInvariants().length, 0, 'seed=' + seed + ' final: '403
+ g.checkInvariants().join('; '));404
}405
});406
});