Compare commits
No commits in common. "2268c749183784cbfa2933753531e299569c96d5" and "78c61c1cd51f851fcf5582d0f373282fac42de39" have entirely different histories.
2268c74918
...
78c61c1cd5
|
|
@ -0,0 +1,31 @@
|
|||
{
|
||||
"version": 1,
|
||||
"level": 1,
|
||||
"name": "Ground Level",
|
||||
"episode": 1,
|
||||
"world": {
|
||||
"w": 2400,
|
||||
"h": 1080,
|
||||
"groundY": 900,
|
||||
"slingX": 300,
|
||||
"slingY": 750
|
||||
},
|
||||
"birds": [
|
||||
"red",
|
||||
"red",
|
||||
"red"
|
||||
],
|
||||
"blocks": [],
|
||||
"pigs": [
|
||||
{
|
||||
"x": 1400,
|
||||
"y": 878,
|
||||
"r": 22
|
||||
}
|
||||
],
|
||||
"stars": [
|
||||
12000,
|
||||
20000,
|
||||
28000
|
||||
]
|
||||
}
|
||||
|
|
@ -0,0 +1,53 @@
|
|||
{
|
||||
"version": 1,
|
||||
"level": 2,
|
||||
"name": "First House",
|
||||
"episode": 1,
|
||||
"world": {
|
||||
"w": 2400,
|
||||
"h": 1080,
|
||||
"groundY": 900,
|
||||
"slingX": 300,
|
||||
"slingY": 750
|
||||
},
|
||||
"birds": [
|
||||
"red",
|
||||
"red",
|
||||
"red"
|
||||
],
|
||||
"blocks": [
|
||||
{
|
||||
"x": 1300,
|
||||
"y": 845,
|
||||
"w": 24,
|
||||
"h": 110,
|
||||
"material": "wood"
|
||||
},
|
||||
{
|
||||
"x": 1460,
|
||||
"y": 845,
|
||||
"w": 24,
|
||||
"h": 110,
|
||||
"material": "wood"
|
||||
},
|
||||
{
|
||||
"x": 1380,
|
||||
"y": 778,
|
||||
"w": 220,
|
||||
"h": 24,
|
||||
"material": "wood"
|
||||
}
|
||||
],
|
||||
"pigs": [
|
||||
{
|
||||
"x": 1380,
|
||||
"y": 878,
|
||||
"r": 22
|
||||
}
|
||||
],
|
||||
"stars": [
|
||||
18000,
|
||||
27000,
|
||||
35000
|
||||
]
|
||||
}
|
||||
|
|
@ -0,0 +1,79 @@
|
|||
{
|
||||
"version": 1,
|
||||
"level": 3,
|
||||
"name": "Two Up",
|
||||
"episode": 1,
|
||||
"world": {
|
||||
"w": 2400,
|
||||
"h": 1080,
|
||||
"groundY": 900,
|
||||
"slingX": 300,
|
||||
"slingY": 750
|
||||
},
|
||||
"birds": [
|
||||
"red",
|
||||
"red",
|
||||
"red"
|
||||
],
|
||||
"blocks": [
|
||||
{
|
||||
"x": 1280,
|
||||
"y": 845,
|
||||
"w": 24,
|
||||
"h": 110,
|
||||
"material": "wood"
|
||||
},
|
||||
{
|
||||
"x": 1460,
|
||||
"y": 845,
|
||||
"w": 24,
|
||||
"h": 110,
|
||||
"material": "wood"
|
||||
},
|
||||
{
|
||||
"x": 1370,
|
||||
"y": 778,
|
||||
"w": 240,
|
||||
"h": 24,
|
||||
"material": "wood"
|
||||
},
|
||||
{
|
||||
"x": 1310,
|
||||
"y": 721,
|
||||
"w": 24,
|
||||
"h": 90,
|
||||
"material": "wood"
|
||||
},
|
||||
{
|
||||
"x": 1430,
|
||||
"y": 721,
|
||||
"w": 24,
|
||||
"h": 90,
|
||||
"material": "wood"
|
||||
},
|
||||
{
|
||||
"x": 1370,
|
||||
"y": 664,
|
||||
"w": 180,
|
||||
"h": 24,
|
||||
"material": "wood"
|
||||
}
|
||||
],
|
||||
"pigs": [
|
||||
{
|
||||
"x": 1370,
|
||||
"y": 878,
|
||||
"r": 22
|
||||
},
|
||||
{
|
||||
"x": 1370,
|
||||
"y": 744,
|
||||
"r": 22
|
||||
}
|
||||
],
|
||||
"stars": [
|
||||
26000,
|
||||
38000,
|
||||
48000
|
||||
]
|
||||
}
|
||||
|
|
@ -0,0 +1,72 @@
|
|||
{
|
||||
"version": 1,
|
||||
"level": 4,
|
||||
"name": "Thin Ice",
|
||||
"episode": 1,
|
||||
"world": {
|
||||
"w": 2400,
|
||||
"h": 1080,
|
||||
"groundY": 900,
|
||||
"slingX": 300,
|
||||
"slingY": 750
|
||||
},
|
||||
"birds": [
|
||||
"red",
|
||||
"red",
|
||||
"red"
|
||||
],
|
||||
"blocks": [
|
||||
{
|
||||
"x": 1250,
|
||||
"y": 840,
|
||||
"w": 28,
|
||||
"h": 120,
|
||||
"material": "ice"
|
||||
},
|
||||
{
|
||||
"x": 1400,
|
||||
"y": 840,
|
||||
"w": 28,
|
||||
"h": 120,
|
||||
"material": "ice"
|
||||
},
|
||||
{
|
||||
"x": 1325,
|
||||
"y": 768,
|
||||
"w": 200,
|
||||
"h": 24,
|
||||
"material": "ice"
|
||||
},
|
||||
{
|
||||
"x": 1550,
|
||||
"y": 840,
|
||||
"w": 28,
|
||||
"h": 120,
|
||||
"material": "ice"
|
||||
},
|
||||
{
|
||||
"x": 1480,
|
||||
"y": 768,
|
||||
"w": 180,
|
||||
"h": 24,
|
||||
"material": "ice"
|
||||
}
|
||||
],
|
||||
"pigs": [
|
||||
{
|
||||
"x": 1325,
|
||||
"y": 878,
|
||||
"r": 22
|
||||
},
|
||||
{
|
||||
"x": 1480,
|
||||
"y": 878,
|
||||
"r": 22
|
||||
}
|
||||
],
|
||||
"stars": [
|
||||
30000,
|
||||
42000,
|
||||
54000
|
||||
]
|
||||
}
|
||||
|
|
@ -0,0 +1,65 @@
|
|||
{
|
||||
"version": 1,
|
||||
"level": 5,
|
||||
"name": "Hard Going",
|
||||
"episode": 1,
|
||||
"world": {
|
||||
"w": 2400,
|
||||
"h": 1080,
|
||||
"groundY": 900,
|
||||
"slingX": 300,
|
||||
"slingY": 750
|
||||
},
|
||||
"birds": [
|
||||
"red",
|
||||
"chuck",
|
||||
"chuck"
|
||||
],
|
||||
"blocks": [
|
||||
{
|
||||
"x": 1300,
|
||||
"y": 840,
|
||||
"w": 34,
|
||||
"h": 120,
|
||||
"material": "stone"
|
||||
},
|
||||
{
|
||||
"x": 1480,
|
||||
"y": 840,
|
||||
"w": 34,
|
||||
"h": 120,
|
||||
"material": "stone"
|
||||
},
|
||||
{
|
||||
"x": 1390,
|
||||
"y": 765,
|
||||
"w": 240,
|
||||
"h": 30,
|
||||
"material": "stone"
|
||||
},
|
||||
{
|
||||
"x": 1390,
|
||||
"y": 705,
|
||||
"w": 24,
|
||||
"h": 90,
|
||||
"material": "wood"
|
||||
}
|
||||
],
|
||||
"pigs": [
|
||||
{
|
||||
"x": 1390,
|
||||
"y": 878,
|
||||
"r": 22
|
||||
},
|
||||
{
|
||||
"x": 1390,
|
||||
"y": 730,
|
||||
"r": 20
|
||||
}
|
||||
],
|
||||
"stars": [
|
||||
32000,
|
||||
45000,
|
||||
58000
|
||||
]
|
||||
}
|
||||
|
|
@ -0,0 +1,70 @@
|
|||
{
|
||||
"version": 1,
|
||||
"level": 6,
|
||||
"name": "Powder Keg",
|
||||
"episode": 1,
|
||||
"world": {
|
||||
"w": 2400,
|
||||
"h": 1080,
|
||||
"groundY": 900,
|
||||
"slingX": 300,
|
||||
"slingY": 750
|
||||
},
|
||||
"birds": [
|
||||
"red",
|
||||
"chuck",
|
||||
"blue"
|
||||
],
|
||||
"blocks": [
|
||||
{
|
||||
"x": 1280,
|
||||
"y": 845,
|
||||
"w": 24,
|
||||
"h": 110,
|
||||
"material": "wood"
|
||||
},
|
||||
{
|
||||
"x": 1520,
|
||||
"y": 845,
|
||||
"w": 24,
|
||||
"h": 110,
|
||||
"material": "wood"
|
||||
},
|
||||
{
|
||||
"x": 1400,
|
||||
"y": 775,
|
||||
"w": 280,
|
||||
"h": 30,
|
||||
"material": "stone"
|
||||
},
|
||||
{
|
||||
"x": 1400,
|
||||
"y": 860,
|
||||
"w": 70,
|
||||
"h": 80,
|
||||
"material": "tnt"
|
||||
}
|
||||
],
|
||||
"pigs": [
|
||||
{
|
||||
"x": 1300,
|
||||
"y": 880,
|
||||
"r": 20
|
||||
},
|
||||
{
|
||||
"x": 1500,
|
||||
"y": 880,
|
||||
"r": 20
|
||||
},
|
||||
{
|
||||
"x": 1400,
|
||||
"y": 706,
|
||||
"r": 22
|
||||
}
|
||||
],
|
||||
"stars": [
|
||||
40000,
|
||||
55000,
|
||||
70000
|
||||
]
|
||||
}
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
{
|
||||
"version": 1,
|
||||
"episodes": [
|
||||
{
|
||||
"id": 1,
|
||||
"name": "Poached Eggs",
|
||||
"blurb": "They took the eggs. Get them back.",
|
||||
"from": 1,
|
||||
"to": 6
|
||||
}
|
||||
],
|
||||
"levels": [
|
||||
{
|
||||
"level": 1,
|
||||
"name": "Ground Level",
|
||||
"episode": 1,
|
||||
"file": "level-001.json"
|
||||
},
|
||||
{
|
||||
"level": 2,
|
||||
"name": "First House",
|
||||
"episode": 1,
|
||||
"file": "level-002.json"
|
||||
},
|
||||
{
|
||||
"level": 3,
|
||||
"name": "Two Up",
|
||||
"episode": 1,
|
||||
"file": "level-003.json"
|
||||
},
|
||||
{
|
||||
"level": 4,
|
||||
"name": "Thin Ice",
|
||||
"episode": 1,
|
||||
"file": "level-004.json"
|
||||
},
|
||||
{
|
||||
"level": 5,
|
||||
"name": "Hard Going",
|
||||
"episode": 1,
|
||||
"file": "level-005.json"
|
||||
},
|
||||
{
|
||||
"level": 6,
|
||||
"name": "Powder Keg",
|
||||
"episode": 1,
|
||||
"file": "level-006.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -205,27 +205,6 @@
|
|||
997
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "solid",
|
||||
"poly": [
|
||||
[
|
||||
754,
|
||||
652
|
||||
],
|
||||
[
|
||||
754,
|
||||
682
|
||||
],
|
||||
[
|
||||
875,
|
||||
682
|
||||
],
|
||||
[
|
||||
873,
|
||||
647
|
||||
]
|
||||
]
|
||||
}
|
||||
],
|
||||
"gears": [
|
||||
|
|
|
|||
|
|
@ -70,275 +70,30 @@
|
|||
1000
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "solid",
|
||||
"poly": [
|
||||
[
|
||||
322,
|
||||
356
|
||||
],
|
||||
[
|
||||
719,
|
||||
356
|
||||
],
|
||||
[
|
||||
740,
|
||||
364
|
||||
],
|
||||
[
|
||||
754,
|
||||
376
|
||||
],
|
||||
[
|
||||
763,
|
||||
395
|
||||
],
|
||||
[
|
||||
762,
|
||||
412
|
||||
],
|
||||
[
|
||||
393,
|
||||
417
|
||||
],
|
||||
[
|
||||
376,
|
||||
425
|
||||
],
|
||||
[
|
||||
354,
|
||||
452
|
||||
],
|
||||
[
|
||||
350,
|
||||
483
|
||||
],
|
||||
[
|
||||
341,
|
||||
819
|
||||
],
|
||||
[
|
||||
366,
|
||||
854
|
||||
],
|
||||
[
|
||||
243,
|
||||
855
|
||||
],
|
||||
[
|
||||
264,
|
||||
386
|
||||
],
|
||||
[
|
||||
273,
|
||||
365
|
||||
],
|
||||
[
|
||||
292,
|
||||
356
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "spike",
|
||||
"poly": [
|
||||
[
|
||||
632,
|
||||
9
|
||||
],
|
||||
[
|
||||
656,
|
||||
60
|
||||
],
|
||||
[
|
||||
691,
|
||||
120
|
||||
],
|
||||
[
|
||||
725,
|
||||
173
|
||||
],
|
||||
[
|
||||
768,
|
||||
211
|
||||
],
|
||||
[
|
||||
818,
|
||||
257
|
||||
],
|
||||
[
|
||||
872,
|
||||
277
|
||||
],
|
||||
[
|
||||
916,
|
||||
296
|
||||
],
|
||||
[
|
||||
982,
|
||||
301
|
||||
],
|
||||
[
|
||||
1062,
|
||||
298
|
||||
],
|
||||
[
|
||||
1111,
|
||||
280
|
||||
],
|
||||
[
|
||||
1155,
|
||||
227
|
||||
],
|
||||
[
|
||||
1217,
|
||||
157
|
||||
],
|
||||
[
|
||||
1256,
|
||||
97
|
||||
],
|
||||
[
|
||||
1266,
|
||||
60
|
||||
],
|
||||
[
|
||||
1272,
|
||||
17
|
||||
],
|
||||
[
|
||||
1270,
|
||||
5
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "solid",
|
||||
"poly": [
|
||||
[
|
||||
900,
|
||||
428
|
||||
],
|
||||
[
|
||||
891,
|
||||
441
|
||||
],
|
||||
[
|
||||
886,
|
||||
461
|
||||
],
|
||||
[
|
||||
900,
|
||||
474
|
||||
],
|
||||
[
|
||||
1362,
|
||||
479
|
||||
],
|
||||
[
|
||||
1387,
|
||||
494
|
||||
],
|
||||
[
|
||||
1396,
|
||||
516
|
||||
],
|
||||
[
|
||||
1395,
|
||||
816
|
||||
],
|
||||
[
|
||||
1368,
|
||||
849
|
||||
],
|
||||
[
|
||||
1466,
|
||||
849
|
||||
],
|
||||
[
|
||||
1527,
|
||||
268
|
||||
],
|
||||
[
|
||||
1546,
|
||||
257
|
||||
],
|
||||
[
|
||||
1568,
|
||||
250
|
||||
],
|
||||
[
|
||||
1593,
|
||||
249
|
||||
],
|
||||
[
|
||||
1592,
|
||||
194
|
||||
],
|
||||
[
|
||||
1363,
|
||||
197
|
||||
],
|
||||
[
|
||||
1344,
|
||||
216
|
||||
],
|
||||
[
|
||||
1337,
|
||||
255
|
||||
],
|
||||
[
|
||||
1395,
|
||||
272
|
||||
],
|
||||
[
|
||||
1414,
|
||||
313
|
||||
],
|
||||
[
|
||||
1404,
|
||||
392
|
||||
],
|
||||
[
|
||||
1376,
|
||||
431
|
||||
]
|
||||
]
|
||||
}
|
||||
],
|
||||
"gears": [
|
||||
{
|
||||
"x": 689,
|
||||
"y": 460,
|
||||
"r": 100,
|
||||
"teeth": 9,
|
||||
"omega": 1.4
|
||||
}
|
||||
],
|
||||
"balls": [
|
||||
{
|
||||
"x": 1376,
|
||||
"y": 175,
|
||||
"type": "ivy",
|
||||
"pinned": false
|
||||
"x": 566,
|
||||
"y": 836,
|
||||
"type": "common",
|
||||
"pinned": true
|
||||
},
|
||||
{
|
||||
"x": 1442,
|
||||
"y": 173,
|
||||
"type": "ivy",
|
||||
"pinned": false
|
||||
"x": 628,
|
||||
"y": 836,
|
||||
"type": "common",
|
||||
"pinned": true
|
||||
},
|
||||
{
|
||||
"x": 1409,
|
||||
"y": 108,
|
||||
"type": "ivy",
|
||||
"pinned": false
|
||||
"x": 597,
|
||||
"y": 782,
|
||||
"type": "common"
|
||||
}
|
||||
],
|
||||
"strands": [
|
||||
[
|
||||
1,
|
||||
2,
|
||||
0
|
||||
],
|
||||
[
|
||||
|
|
@ -346,90 +101,135 @@
|
|||
1
|
||||
],
|
||||
[
|
||||
2,
|
||||
0
|
||||
0,
|
||||
1
|
||||
]
|
||||
],
|
||||
"pile": [
|
||||
{
|
||||
"x": 1492,
|
||||
"y": 173,
|
||||
"type": "ivy"
|
||||
"x": 857,
|
||||
"y": 834,
|
||||
"type": "common"
|
||||
},
|
||||
{
|
||||
"x": 1527,
|
||||
"y": 171,
|
||||
"type": "ivy"
|
||||
"x": 887,
|
||||
"y": 834,
|
||||
"type": "common"
|
||||
},
|
||||
{
|
||||
"x": 1559,
|
||||
"y": 170,
|
||||
"type": "ivy"
|
||||
"x": 917,
|
||||
"y": 834,
|
||||
"type": "common"
|
||||
},
|
||||
{
|
||||
"x": 1563,
|
||||
"y": 135,
|
||||
"type": "ivy"
|
||||
"x": 947,
|
||||
"y": 834,
|
||||
"type": "common"
|
||||
},
|
||||
{
|
||||
"x": 1527,
|
||||
"y": 138,
|
||||
"type": "ivy"
|
||||
"x": 977,
|
||||
"y": 834,
|
||||
"type": "common"
|
||||
},
|
||||
{
|
||||
"x": 1488,
|
||||
"y": 137,
|
||||
"type": "ivy"
|
||||
"x": 1007,
|
||||
"y": 834,
|
||||
"type": "common"
|
||||
},
|
||||
{
|
||||
"x": 1486,
|
||||
"y": 96,
|
||||
"type": "ivy"
|
||||
"x": 1037,
|
||||
"y": 834,
|
||||
"type": "common"
|
||||
},
|
||||
{
|
||||
"x": 1527,
|
||||
"y": 97,
|
||||
"type": "ivy"
|
||||
"x": 1067,
|
||||
"y": 834,
|
||||
"type": "common"
|
||||
},
|
||||
{
|
||||
"x": 1567,
|
||||
"y": 97,
|
||||
"type": "ivy"
|
||||
"x": 857,
|
||||
"y": 804,
|
||||
"type": "common"
|
||||
},
|
||||
{
|
||||
"x": 1563,
|
||||
"y": 63,
|
||||
"type": "ivy"
|
||||
"x": 887,
|
||||
"y": 804,
|
||||
"type": "common"
|
||||
},
|
||||
{
|
||||
"x": 1521,
|
||||
"y": 60,
|
||||
"type": "ivy"
|
||||
"x": 917,
|
||||
"y": 804,
|
||||
"type": "common"
|
||||
},
|
||||
{
|
||||
"x": 1486,
|
||||
"y": 64,
|
||||
"type": "ivy"
|
||||
"x": 947,
|
||||
"y": 804,
|
||||
"type": "common"
|
||||
},
|
||||
{
|
||||
"x": 1480,
|
||||
"y": 23,
|
||||
"type": "ivy"
|
||||
"x": 977,
|
||||
"y": 804,
|
||||
"type": "common"
|
||||
},
|
||||
{
|
||||
"x": 1521,
|
||||
"y": 28,
|
||||
"type": "ivy"
|
||||
"x": 1007,
|
||||
"y": 804,
|
||||
"type": "common"
|
||||
},
|
||||
{
|
||||
"x": 1562,
|
||||
"y": 22,
|
||||
"type": "ivy"
|
||||
"x": 1037,
|
||||
"y": 804,
|
||||
"type": "common"
|
||||
},
|
||||
{
|
||||
"x": 1067,
|
||||
"y": 804,
|
||||
"type": "common"
|
||||
},
|
||||
{
|
||||
"x": 857,
|
||||
"y": 774,
|
||||
"type": "common"
|
||||
},
|
||||
{
|
||||
"x": 887,
|
||||
"y": 774,
|
||||
"type": "common"
|
||||
},
|
||||
{
|
||||
"x": 917,
|
||||
"y": 774,
|
||||
"type": "common"
|
||||
},
|
||||
{
|
||||
"x": 947,
|
||||
"y": 774,
|
||||
"type": "common"
|
||||
},
|
||||
{
|
||||
"x": 977,
|
||||
"y": 774,
|
||||
"type": "common"
|
||||
},
|
||||
{
|
||||
"x": 1007,
|
||||
"y": 774,
|
||||
"type": "common"
|
||||
},
|
||||
{
|
||||
"x": 1037,
|
||||
"y": 774,
|
||||
"type": "common"
|
||||
},
|
||||
{
|
||||
"x": 1067,
|
||||
"y": 774,
|
||||
"type": "common"
|
||||
}
|
||||
],
|
||||
"pipe": {
|
||||
"x": 495,
|
||||
"y": 75,
|
||||
"x": 597,
|
||||
"y": 553,
|
||||
"r": 46
|
||||
},
|
||||
"required": 4,
|
||||
|
|
|
|||
|
|
@ -70,161 +70,6 @@
|
|||
1000
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "solid",
|
||||
"poly": [
|
||||
[
|
||||
1593,
|
||||
617
|
||||
],
|
||||
[
|
||||
884,
|
||||
562
|
||||
],
|
||||
[
|
||||
884,
|
||||
542
|
||||
],
|
||||
[
|
||||
1314,
|
||||
546
|
||||
],
|
||||
[
|
||||
1332,
|
||||
534
|
||||
],
|
||||
[
|
||||
1332,
|
||||
387
|
||||
],
|
||||
[
|
||||
1318,
|
||||
368
|
||||
],
|
||||
[
|
||||
1102,
|
||||
370
|
||||
],
|
||||
[
|
||||
1099,
|
||||
356
|
||||
],
|
||||
[
|
||||
1592,
|
||||
359
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "spike",
|
||||
"poly": [
|
||||
[
|
||||
899,
|
||||
362
|
||||
],
|
||||
[
|
||||
902,
|
||||
378
|
||||
],
|
||||
[
|
||||
708,
|
||||
381
|
||||
],
|
||||
[
|
||||
667,
|
||||
408
|
||||
],
|
||||
[
|
||||
628,
|
||||
471
|
||||
],
|
||||
[
|
||||
604,
|
||||
540
|
||||
],
|
||||
[
|
||||
602,
|
||||
824
|
||||
],
|
||||
[
|
||||
596,
|
||||
833
|
||||
],
|
||||
[
|
||||
473,
|
||||
833
|
||||
],
|
||||
[
|
||||
456,
|
||||
800
|
||||
],
|
||||
[
|
||||
458,
|
||||
726
|
||||
],
|
||||
[
|
||||
465,
|
||||
581
|
||||
],
|
||||
[
|
||||
454,
|
||||
435
|
||||
],
|
||||
[
|
||||
464,
|
||||
340
|
||||
],
|
||||
[
|
||||
445,
|
||||
280
|
||||
],
|
||||
[
|
||||
465,
|
||||
231
|
||||
],
|
||||
[
|
||||
521,
|
||||
227
|
||||
],
|
||||
[
|
||||
579,
|
||||
241
|
||||
],
|
||||
[
|
||||
637,
|
||||
304
|
||||
],
|
||||
[
|
||||
708,
|
||||
361
|
||||
],
|
||||
[
|
||||
900,
|
||||
362
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "spike",
|
||||
"poly": [
|
||||
[
|
||||
787,
|
||||
238
|
||||
],
|
||||
[
|
||||
1185,
|
||||
241
|
||||
],
|
||||
[
|
||||
1185,
|
||||
179
|
||||
],
|
||||
[
|
||||
784,
|
||||
187
|
||||
]
|
||||
]
|
||||
}
|
||||
],
|
||||
"balls": [
|
||||
|
|
@ -243,8 +88,7 @@
|
|||
{
|
||||
"x": 839,
|
||||
"y": 782,
|
||||
"type": "common",
|
||||
"pinned": false
|
||||
"type": "common"
|
||||
}
|
||||
],
|
||||
"strands": [
|
||||
|
|
@ -381,81 +225,11 @@
|
|||
"x": 1309,
|
||||
"y": 774,
|
||||
"type": "common"
|
||||
},
|
||||
{
|
||||
"x": 1099,
|
||||
"y": 735,
|
||||
"type": "common"
|
||||
},
|
||||
{
|
||||
"x": 1135,
|
||||
"y": 732,
|
||||
"type": "common"
|
||||
},
|
||||
{
|
||||
"x": 1171,
|
||||
"y": 732,
|
||||
"type": "common"
|
||||
},
|
||||
{
|
||||
"x": 1203,
|
||||
"y": 729,
|
||||
"type": "common"
|
||||
},
|
||||
{
|
||||
"x": 1242,
|
||||
"y": 734,
|
||||
"type": "common"
|
||||
},
|
||||
{
|
||||
"x": 1289,
|
||||
"y": 734,
|
||||
"type": "common"
|
||||
},
|
||||
{
|
||||
"x": 1330,
|
||||
"y": 734,
|
||||
"type": "common"
|
||||
},
|
||||
{
|
||||
"x": 1322,
|
||||
"y": 694,
|
||||
"type": "common"
|
||||
},
|
||||
{
|
||||
"x": 1281,
|
||||
"y": 696,
|
||||
"type": "common"
|
||||
},
|
||||
{
|
||||
"x": 1234,
|
||||
"y": 696,
|
||||
"type": "common"
|
||||
},
|
||||
{
|
||||
"x": 1199,
|
||||
"y": 691,
|
||||
"type": "common"
|
||||
},
|
||||
{
|
||||
"x": 1160,
|
||||
"y": 694,
|
||||
"type": "common"
|
||||
},
|
||||
{
|
||||
"x": 1125,
|
||||
"y": 688,
|
||||
"type": "common"
|
||||
},
|
||||
{
|
||||
"x": 1097,
|
||||
"y": 688,
|
||||
"type": "common"
|
||||
}
|
||||
],
|
||||
"pipe": {
|
||||
"x": 1469,
|
||||
"y": 71,
|
||||
"x": 839,
|
||||
"y": 505,
|
||||
"r": 46
|
||||
},
|
||||
"required": 5,
|
||||
|
|
|
|||
|
|
@ -1,237 +1,232 @@
|
|||
{
|
||||
"level": 6,
|
||||
"name": "Crossroads",
|
||||
"frog": [
|
||||
960,
|
||||
990
|
||||
],
|
||||
"colors": 4,
|
||||
"seed": 48514,
|
||||
"starScores": [
|
||||
1120,
|
||||
1670,
|
||||
2230
|
||||
],
|
||||
"paths": [
|
||||
{
|
||||
"shape": "figureEight",
|
||||
"points": [
|
||||
[
|
||||
-80,
|
||||
830
|
||||
],
|
||||
[
|
||||
60,
|
||||
690
|
||||
],
|
||||
[
|
||||
130,
|
||||
505
|
||||
],
|
||||
[
|
||||
136,
|
||||
416
|
||||
],
|
||||
[
|
||||
154,
|
||||
333
|
||||
],
|
||||
[
|
||||
183,
|
||||
259
|
||||
],
|
||||
[
|
||||
223,
|
||||
199
|
||||
],
|
||||
[
|
||||
274,
|
||||
156
|
||||
],
|
||||
[
|
||||
334,
|
||||
134
|
||||
],
|
||||
[
|
||||
404,
|
||||
132
|
||||
],
|
||||
[
|
||||
481,
|
||||
152
|
||||
],
|
||||
[
|
||||
565,
|
||||
191
|
||||
],
|
||||
[
|
||||
655,
|
||||
249
|
||||
],
|
||||
[
|
||||
749,
|
||||
321
|
||||
],
|
||||
[
|
||||
846,
|
||||
403
|
||||
],
|
||||
[
|
||||
945,
|
||||
491
|
||||
],
|
||||
[
|
||||
1044,
|
||||
581
|
||||
],
|
||||
[
|
||||
1142,
|
||||
665
|
||||
],
|
||||
[
|
||||
1237,
|
||||
741
|
||||
],
|
||||
[
|
||||
1328,
|
||||
803
|
||||
],
|
||||
[
|
||||
1414,
|
||||
849
|
||||
],
|
||||
[
|
||||
1494,
|
||||
874
|
||||
],
|
||||
[
|
||||
1566,
|
||||
879
|
||||
],
|
||||
[
|
||||
1629,
|
||||
863
|
||||
],
|
||||
[
|
||||
1683,
|
||||
826
|
||||
],
|
||||
[
|
||||
1726,
|
||||
771
|
||||
],
|
||||
[
|
||||
1759,
|
||||
701
|
||||
],
|
||||
[
|
||||
1780,
|
||||
620
|
||||
],
|
||||
[
|
||||
1789,
|
||||
532
|
||||
],
|
||||
[
|
||||
1787,
|
||||
443
|
||||
],
|
||||
[
|
||||
1773,
|
||||
357
|
||||
],
|
||||
[
|
||||
1747,
|
||||
280
|
||||
],
|
||||
[
|
||||
1710,
|
||||
215
|
||||
],
|
||||
[
|
||||
1663,
|
||||
167
|
||||
],
|
||||
[
|
||||
1605,
|
||||
138
|
||||
],
|
||||
[
|
||||
1538,
|
||||
130
|
||||
],
|
||||
[
|
||||
1463,
|
||||
143
|
||||
],
|
||||
[
|
||||
1381,
|
||||
177
|
||||
],
|
||||
[
|
||||
1293,
|
||||
230
|
||||
],
|
||||
[
|
||||
1200,
|
||||
298
|
||||
],
|
||||
[
|
||||
1103,
|
||||
377
|
||||
],
|
||||
[
|
||||
1005,
|
||||
464
|
||||
],
|
||||
[
|
||||
906,
|
||||
554
|
||||
],
|
||||
[
|
||||
808,
|
||||
640
|
||||
],
|
||||
[
|
||||
711,
|
||||
719
|
||||
],
|
||||
[
|
||||
619,
|
||||
786
|
||||
],
|
||||
[
|
||||
531,
|
||||
837
|
||||
],
|
||||
[
|
||||
449,
|
||||
869
|
||||
],
|
||||
[
|
||||
375,
|
||||
880
|
||||
],
|
||||
[
|
||||
309,
|
||||
870
|
||||
],
|
||||
[
|
||||
252,
|
||||
839
|
||||
]
|
||||
],
|
||||
"tunnels": [
|
||||
[
|
||||
1320,
|
||||
1846
|
||||
]
|
||||
],
|
||||
"quota": 34,
|
||||
"introBalls": 10,
|
||||
"pushSpeed": 60,
|
||||
"powerUpRate": 0.06
|
||||
}
|
||||
],
|
||||
"background": "zuma-background-1"
|
||||
"level": 6,
|
||||
"name": "Crossroads",
|
||||
"frog": [
|
||||
960,
|
||||
990
|
||||
],
|
||||
"colors": 4,
|
||||
"background": "zuma-background-1",
|
||||
"seed": 48514,
|
||||
"starScores": [
|
||||
1120,
|
||||
1670,
|
||||
2230
|
||||
],
|
||||
"paths": [
|
||||
{
|
||||
"shape": "figureEight",
|
||||
"points": [
|
||||
[
|
||||
-80,
|
||||
830
|
||||
],
|
||||
[
|
||||
60,
|
||||
690
|
||||
],
|
||||
[
|
||||
130,
|
||||
505
|
||||
],
|
||||
[
|
||||
136,
|
||||
416
|
||||
],
|
||||
[
|
||||
154,
|
||||
333
|
||||
],
|
||||
[
|
||||
183,
|
||||
259
|
||||
],
|
||||
[
|
||||
223,
|
||||
199
|
||||
],
|
||||
[
|
||||
274,
|
||||
156
|
||||
],
|
||||
[
|
||||
334,
|
||||
134
|
||||
],
|
||||
[
|
||||
404,
|
||||
132
|
||||
],
|
||||
[
|
||||
481,
|
||||
152
|
||||
],
|
||||
[
|
||||
565,
|
||||
191
|
||||
],
|
||||
[
|
||||
655,
|
||||
249
|
||||
],
|
||||
[
|
||||
749,
|
||||
321
|
||||
],
|
||||
[
|
||||
846,
|
||||
403
|
||||
],
|
||||
[
|
||||
945,
|
||||
491
|
||||
],
|
||||
[
|
||||
1044,
|
||||
581
|
||||
],
|
||||
[
|
||||
1142,
|
||||
665
|
||||
],
|
||||
[
|
||||
1237,
|
||||
741
|
||||
],
|
||||
[
|
||||
1328,
|
||||
803
|
||||
],
|
||||
[
|
||||
1414,
|
||||
849
|
||||
],
|
||||
[
|
||||
1494,
|
||||
874
|
||||
],
|
||||
[
|
||||
1566,
|
||||
879
|
||||
],
|
||||
[
|
||||
1629,
|
||||
863
|
||||
],
|
||||
[
|
||||
1683,
|
||||
826
|
||||
],
|
||||
[
|
||||
1726,
|
||||
771
|
||||
],
|
||||
[
|
||||
1759,
|
||||
701
|
||||
],
|
||||
[
|
||||
1780,
|
||||
620
|
||||
],
|
||||
[
|
||||
1789,
|
||||
532
|
||||
],
|
||||
[
|
||||
1787,
|
||||
443
|
||||
],
|
||||
[
|
||||
1773,
|
||||
357
|
||||
],
|
||||
[
|
||||
1747,
|
||||
280
|
||||
],
|
||||
[
|
||||
1710,
|
||||
215
|
||||
],
|
||||
[
|
||||
1663,
|
||||
167
|
||||
],
|
||||
[
|
||||
1605,
|
||||
138
|
||||
],
|
||||
[
|
||||
1538,
|
||||
130
|
||||
],
|
||||
[
|
||||
1463,
|
||||
143
|
||||
],
|
||||
[
|
||||
1381,
|
||||
177
|
||||
],
|
||||
[
|
||||
1293,
|
||||
230
|
||||
],
|
||||
[
|
||||
1200,
|
||||
298
|
||||
],
|
||||
[
|
||||
1103,
|
||||
377
|
||||
],
|
||||
[
|
||||
1005,
|
||||
464
|
||||
],
|
||||
[
|
||||
906,
|
||||
554
|
||||
],
|
||||
[
|
||||
808,
|
||||
640
|
||||
],
|
||||
[
|
||||
711,
|
||||
719
|
||||
],
|
||||
[
|
||||
619,
|
||||
786
|
||||
],
|
||||
[
|
||||
531,
|
||||
837
|
||||
],
|
||||
[
|
||||
449,
|
||||
869
|
||||
],
|
||||
[
|
||||
375,
|
||||
880
|
||||
],
|
||||
[
|
||||
309,
|
||||
870
|
||||
],
|
||||
[
|
||||
252,
|
||||
839
|
||||
]
|
||||
],
|
||||
"tunnels": [],
|
||||
"quota": 34,
|
||||
"introBalls": 10,
|
||||
"pushSpeed": 88,
|
||||
"powerUpRate": 0.06
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,59 +0,0 @@
|
|||
{
|
||||
"_readme": [
|
||||
"Drop-in art for Worms. Every slot starts null, which means 'not painted' —",
|
||||
"the game renders that slot procedurally from the theme palette in",
|
||||
"src/games/worms/WormsThemes.js and looks complete either way. Fill in a",
|
||||
"'path' (relative to the repo root, e.g. assets/images/worms/bg-forest.png)",
|
||||
"and that slot upgrades on the next load. No code change is needed.",
|
||||
"",
|
||||
"Per theme:",
|
||||
" backdrop a single image, 1920x1080 or wider, parallaxed behind the world",
|
||||
" fill a SEAMLESS 256x256 tile for the inside of the terrain",
|
||||
" surface a SEAMLESS 256x48 strip for the top crust of the terrain",
|
||||
" objects a spritesheet of background scenery, 160x160 cells, 8 per sheet",
|
||||
"",
|
||||
"Shared:",
|
||||
" worms a spritesheet of worm frames, 64x64 cells (see sprites.md)",
|
||||
" icons weapon icons for the weapon panel, 64x64 cells, in PANEL_ORDER"
|
||||
],
|
||||
|
||||
"themes": {
|
||||
"forest": { "backdrop": { "key": "worms-bg-forest", "path": null },
|
||||
"fill": { "key": "worms-fill-forest", "path": null },
|
||||
"surface": { "key": "worms-surface-forest", "path": null },
|
||||
"objects": { "key": "worms-objects-forest", "path": null, "frameWidth": 160, "frameHeight": 160 } },
|
||||
"desert": { "backdrop": { "key": "worms-bg-desert", "path": null },
|
||||
"fill": { "key": "worms-fill-desert", "path": null },
|
||||
"surface": { "key": "worms-surface-desert", "path": null },
|
||||
"objects": { "key": "worms-objects-desert", "path": null, "frameWidth": 160, "frameHeight": 160 } },
|
||||
"farm": { "backdrop": { "key": "worms-bg-farm", "path": null },
|
||||
"fill": { "key": "worms-fill-farm", "path": null },
|
||||
"surface": { "key": "worms-surface-farm", "path": null },
|
||||
"objects": { "key": "worms-objects-farm", "path": null, "frameWidth": 160, "frameHeight": 160 } },
|
||||
"hell": { "backdrop": { "key": "worms-bg-hell", "path": null },
|
||||
"fill": { "key": "worms-fill-hell", "path": null },
|
||||
"surface": { "key": "worms-surface-hell", "path": null },
|
||||
"objects": { "key": "worms-objects-hell", "path": null, "frameWidth": 160, "frameHeight": 160 } },
|
||||
"arctic": { "backdrop": { "key": "worms-bg-arctic", "path": null },
|
||||
"fill": { "key": "worms-fill-arctic", "path": null },
|
||||
"surface": { "key": "worms-surface-arctic", "path": null },
|
||||
"objects": { "key": "worms-objects-arctic", "path": null, "frameWidth": 160, "frameHeight": 160 } },
|
||||
"jungle": { "backdrop": { "key": "worms-bg-jungle", "path": null },
|
||||
"fill": { "key": "worms-fill-jungle", "path": null },
|
||||
"surface": { "key": "worms-surface-jungle", "path": null },
|
||||
"objects": { "key": "worms-objects-jungle", "path": null, "frameWidth": 160, "frameHeight": 160 } },
|
||||
"construction": { "backdrop": { "key": "worms-bg-construction", "path": null },
|
||||
"fill": { "key": "worms-fill-construction", "path": null },
|
||||
"surface": { "key": "worms-surface-construction", "path": null },
|
||||
"objects": { "key": "worms-objects-construction", "path": null, "frameWidth": 160, "frameHeight": 160 } },
|
||||
"space": { "backdrop": { "key": "worms-bg-space", "path": null },
|
||||
"fill": { "key": "worms-fill-space", "path": null },
|
||||
"surface": { "key": "worms-surface-space", "path": null },
|
||||
"objects": { "key": "worms-objects-space", "path": null, "frameWidth": 160, "frameHeight": 160 } }
|
||||
},
|
||||
|
||||
"shared": {
|
||||
"worms": { "key": "worms-sprites", "path": null, "frameWidth": 64, "frameHeight": 64 },
|
||||
"icons": { "key": "worms-icons", "path": null, "frameWidth": 64, "frameHeight": 64 }
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,159 @@
|
|||
# Angry Birds — build plan
|
||||
|
||||
Living plan doc. Survives context clears: **read this file first**, pick the next unchecked item, update the checkboxes and the Status line as work lands.
|
||||
|
||||
## Status
|
||||
|
||||
**Waves 0 and 1 complete 2026-07-30. Playable end to end, never browser-tested.** `node tools/verifyAngryBirds.js` → **114 checks green**.
|
||||
|
||||
The solver holds: a 10-box tower settles in 0.68s, sleeps, drifts <1px sideways and tilts 0.35°; a 15-box pyramid settles too; a 6-second 41-body shot runs in 254ms headless. The rules layer is in: 3 materials + TNT, health-model damage with crack stages, all 8 birds, scoring/stars/win/lose, and a 6-level starter bank that a greedy aim sweep clears.
|
||||
|
||||
Registered and wired (slug `angrybirds`, iconFrame **92**) — it appears under **Video Games** and is reachable from the menu.
|
||||
|
||||
Next: Wave 2 is largely done inside Wave 1 (all 8 birds and TNT landed early). The real remaining work is **Wave 3** (editor + generator + `AngryBirdsAuto`), **Wave 4** (grow 6 levels → 63), and **Wave 5** (artwork JSON, tutorial, icon art).
|
||||
|
||||
## Decisions taken up front
|
||||
|
||||
| Question | Answer |
|
||||
|---|---|
|
||||
| Slug / category / iconFrame | `angrybirds` / `arcade-console-pc` ("Video Games") / **92** (next free after Excitebike's 91) |
|
||||
| Physics | **Bespoke deterministic rigid-body solver.** Matter.js ships inside the CDN Phaser build and would work in-browser, but it is not importable in bare Node and not reproducible — that forfeits the verifier, the generator's measured star thresholds, and the editor's winnability gate. |
|
||||
| Visual treatment | **No CRT overlay, no scanlines, no pixel font.** It's a 2009 touch game, not an arcade cabinet. Clean cartoon look, app's normal fonts. |
|
||||
| Campaign scale | **63 levels, 3 episodes of 21** — Poached Eggs / Mighty Hoax / Danger Above. |
|
||||
| Art | Procedural, with a `data/angrybirds-artwork.json` drop-in hook so real sprites can replace the fallbacks later with no code change. Procedural fallbacks must always work standalone. |
|
||||
| Bird roster | All 8 — Red, Chuck, Blue, Bomb, Matilda, Terence, Hal, Bubbles. |
|
||||
| Modes | Single-player campaign only. `maxOpponents: 0`, so it skips `OpponentSelect` entirely. |
|
||||
|
||||
## Files
|
||||
|
||||
| File | Role | State |
|
||||
|---|---|---|
|
||||
| `src/games/angrybirds/AngryBirdsPhysics.js` | Rigid-body solver. Zero imports. | ✅ Wave 0 |
|
||||
| `src/games/angrybirds/AngryBirdsLogic.js` | Materials, damage, birds, scoring, `stepSim`. Only imports Physics. | ✅ Wave 1 |
|
||||
| `src/games/angrybirds/AngryBirdsGame.js` | Phaser scene, key `AngryBirdsGame`. | ✅ Wave 1 |
|
||||
| `src/games/angrybirds/AngryBirdsArt.js` | Procedural textures + artwork-JSON resolution. | ⬜ Wave 5 |
|
||||
| `src/games/angrybirds/AngryBirdsEditor.js` | Level editor, key `AngryBirdsEditor`. | ⬜ Wave 3 |
|
||||
| `src/games/angrybirds/AngryBirdsAuto.js` | Reference bot / winnability gate. In `src/` so the editor button and the verifier run the same gate. | ⬜ Wave 3 |
|
||||
| `src/games/angrybirds/tutorial.md` | Tutorial copy. | ⬜ Wave 5 |
|
||||
| `tools/genAngryBirds.js` | Level-bank generator; **measures** star thresholds. | ⬜ Wave 3 |
|
||||
| `tools/verifyAngryBirds.js` | Node harness. | ✅ 114 checks |
|
||||
| `assets/gamedata/angrybirds/` | `levels.json` manifest + level files. | 🔨 6 of 63 |
|
||||
| `data/angrybirds-artwork.json` | Drop-in sprite map. | ⬜ Wave 5 |
|
||||
|
||||
Wiring touchpoints: `src/data/gamesRegistry.js`, `src/main.js` (import + scene array, both scenes), `src/scenes/GameRoomScene.js:26` (`slugDispatch`), `src/data/assetManifest.js`, `src/scenes/PreloadScene.js` (manifest JSON + `?angrybirds-editor=1` entrance).
|
||||
|
||||
---
|
||||
|
||||
## Wave 0 — the rigid-body solver — ✅ DONE 2026-07-30
|
||||
|
||||
- [x] Convex polygon + circle bodies, mass/inertia derived from geometry
|
||||
- [x] Uniform-grid AABB broadphase
|
||||
- [x] SAT narrowphase with reference-face clipping → 2-point manifolds
|
||||
- [x] Sequential-impulse solver with warm starting
|
||||
- [x] Coulomb friction clamped against the accumulated normal impulse
|
||||
- [x] **Split-impulse** position correction with penetration slop (not plain Baumgarte — see finding 1)
|
||||
- [x] Island-based sleeping
|
||||
- [x] `cloneWorld` / `hashWorld` for determinism tests
|
||||
- [x] Verifier green — all four gate conditions pass
|
||||
|
||||
### The gate — all four passed
|
||||
|
||||
1. ✅ 10-box tower settles in 0.68s, every body asleep, drift 0.00px, tilt 6.1e-3 rad. A 15-box pyramid also settles.
|
||||
2. ✅ Box on a 15° slope with µ=0.9 does not creep; a µ=0.2 box on 40° does slide.
|
||||
3. ✅ Bit-identical replay; 1/60 frame == 4 substeps exactly; ragged frame pacing matches even pacing.
|
||||
4. ✅ 12 monkey seeds × 900 substeps: no NaN, no overspeed, nothing sinks.
|
||||
|
||||
### Wave 0 findings
|
||||
|
||||
1. **Plain Baumgarte is not good enough for a 10-high stack, and the failure looks like a bug when it isn't.** Feeding position error back as bias velocity makes a contact behave like a stiff spring, so penetration is proportional to load — the bottom contact of a 10-box tower carries 9 boxes and sinks ~9× deeper than the top one. Measured sag was 12.85px. Switching to **split impulse** (a separate pseudo-velocity accumulator, added into the position integration then discarded) removes a fixed fraction of the excess per substep *regardless of load*, and never leaks the correction back as bounce energy. Sag dropped to 0.46px per contact, which is exactly `SLOP` — i.e. the remaining sag is the slop band we deliberately allow, not solver error. **Do not "simplify" this back to a single bias term.**
|
||||
2. **Total stack sag is bounded by `SLOP × contactCount`, by design.** The verifier asserts against that budget rather than a flat pixel value. Shrinking `SLOP` tightens stacks but reintroduces resting-contact jitter — 0.5px on a 40px block is the sweet spot.
|
||||
3. **Warm starting must key on a stable feature id, not array position.** Contact points are matched across substeps by `(refFace << 8) | incidentVert`, with a flip bit. Matching by index scrambles impulses the moment the clip order changes and the stack sags visibly.
|
||||
4. **The reference-face choice needs hysteresis.** Preferring A unless B is deeper by a relative margin (`0.1 × |sepA| + 0.01`) keeps the choice stable frame to frame, which is what keeps feature ids — and therefore warm starting — stable for a resting contact.
|
||||
5. **Sequential impulses are Gauss-Seidel, so solve order genuinely changes the answer.** Bit-identical results across different body *creation* orders are not achievable and were never the goal; the verifier asserts the dependence stays sub-pixel (measured 0.4px). What must be exact — and is — is that a *given* scene replays identically.
|
||||
6. **Island sleeping, not per-body sleeping.** Union-find over contacts; an island sleeps only when its slowest member has been slow for `SLEEP_TIME`. Per-body sleeping freezes half a tower while the rest still moves. Sleeping is also how the rules layer knows a shot is over, so it is not just an optimization.
|
||||
7. **Anti-tunnelling is a design constraint, not a runtime check.** `MAX_SPEED × SUBSTEP_DT < MIN_HALF_EXTENT` (10px < 12px) is asserted by the verifier, which is what forced `SUBSTEP_DT` to 1/240 and `MAX_SPEED` to 2400. No block may be thinner than 24px.
|
||||
8. **String keys dominated the profile.** Numeric composite keys for the grid and contact maps, plus building the contact list in already-sorted pair order instead of re-sorting it four times per substep, took a 6-second shot from 368ms to 254ms with bit-identical output.
|
||||
9. **Contacts cache direct body references, so `cloneWorld` must rewire them.** A shallow spread leaves the clone's contacts pointing at the original's bodies — the clone then drives the world it was supposed to leave alone. The winnability bot and shot preview both depend on this; the verifier now asserts it explicitly.
|
||||
|
||||
### Baselines
|
||||
|
||||
```
|
||||
node tools/verifyAngryBirds.js -> 114 checks green
|
||||
node tools/verifyAngryBirds.js --seeds=40 -> slower monkey soak, still green
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Wave 1 — playable core — ✅ DONE 2026-07-30
|
||||
|
||||
- [x] Materials: wood / stone / ice with distinct density, friction, restitution, hp, damage threshold
|
||||
- [x] Damage as a **health model** — impact above threshold subtracts hp; 2/3 and 1/3 crossings emit crack stages
|
||||
- [x] Pigs take damage from debris, not just direct hits
|
||||
- [x] Slingshot: drag, clamp to max draw, release
|
||||
- [x] Win/lose evaluated only once the world is settled or `MAX_SHOT_TIME` expires
|
||||
- [x] `stepSim(state, dt) → events[]` contract
|
||||
- [x] Phaser scene with sim-space→screen-space mapping
|
||||
- [x] Trajectory memory (dotted trail of previous shots)
|
||||
- [x] Level select, progress persistence, win/lose panel
|
||||
- [x] 6-level starter bank, all stable and sweep-clearable
|
||||
- [ ] Camera pan/zoom — deliberately deferred, see finding 4
|
||||
|
||||
### Wave 1 findings
|
||||
|
||||
1. **The damage signal must be approach velocity, not the solver's accumulated normal impulse — and this one is a trap.** The accumulated impulse includes the static load a contact carries, which grows with stack height. Measured: the base contact of a 10-block stone tower sits at **3.4e5**, which is *above* the threshold that should shatter wood (1.5e5) and level with stone's (3.2e5). Wiring damage to it makes tall towers quietly crush themselves while nothing is happening — and it looks like a level-design bug, not a physics one. `Physics.prestep` now also publishes `contact.impactImpulse` = the momentum needed to stop the approach, which is zero at rest by construction. Resting dropped to **2.4e4**, real hits run 1.9e5 (feeble) to 2.7e6 (full draw). `verifyAngryBirds.js` pins both ends.
|
||||
2. **Calibrate thresholds by measuring, never by guessing.** The whole material table was set from a one-off script that fired birds at 400/800/1200/1600/2000 px/s and printed peak impact impulses. Re-run it after any change to density, gravity or `SUBSTEP_DT` — all three move the impulse scale.
|
||||
3. **Levels must be authored already at rest.** `createState` drops blocks exactly where the file says; if the author's structure was mid-collapse when exported, the player sees a different level. The verifier asserts every level stands unaided for 4s with zero self-damage. Wave 3's editor gets a **Settle** button for this.
|
||||
4. **No camera pan/zoom yet, on purpose.** The scene maps the 2400×1080 logical level to the canvas through fixed `sx()`/`sy()` helpers at scale 0.78 (the PeggleGame idiom) rather than zooming the camera, which keeps HUD text in plain screen coordinates. The whole level is visible at once. A follow-camera is the more faithful feel but is pure presentation and cannot be validated headlessly — it belongs in Wave 5 alongside a real browser pass.
|
||||
5. **Bubbles has to be rebuilt, not resized.** The solver derives mass and inertia at creation and assumes they never change, so inflating means swapping in a new, larger, lower-density body and transferring velocity. Mutating `radius` in place would leave mass properties describing the old bird.
|
||||
6. **Spent birds are removed when a shot resolves.** Left in, a dead bird props structures up forever and the next shot plays against a level the author never built.
|
||||
|
||||
---
|
||||
|
||||
## Wave 2 — the full roster, TNT, scoring — ✅ DONE 2026-07-30 (landed inside Wave 1)
|
||||
|
||||
- [x] 8 birds, abilities fire on tap mid-flight, one use per shot
|
||||
- [x] TNT blocks detonate when damaged (removed before detonating, so they can't recurse into themselves)
|
||||
- [x] Scoring: 5,000/pig + material destruction points + 10,000 per unused bird
|
||||
|
||||
---
|
||||
|
||||
## Wave 3 — editor and generator — ⬜
|
||||
|
||||
- [ ] `?angrybirds-editor=1` entrance, authoring in play coordinates
|
||||
- [ ] **Settle** button so levels export already at rest
|
||||
- [ ] **Test Winnable** button running the same gate as the verifier
|
||||
- [ ] `AngryBirdsAuto` beam search over (angle, power, ability timing)
|
||||
- [ ] Blob export of `level-NNN.json` + regenerated `levels.json`
|
||||
|
||||
Gate is **one-directional**: if the bot wins, a human can. A bot failure is *not* proof a level is impossible.
|
||||
|
||||
---
|
||||
|
||||
## Wave 4 — the 63-level campaign — ⬜
|
||||
|
||||
- [ ] Poached Eggs (1-21) — wood then stone; Red, Chuck, Blue
|
||||
- [ ] Mighty Hoax (22-42) — ice, TNT, taller structures; adds Bomb, Matilda
|
||||
- [ ] Danger Above (43-63) — mixed materials, elevated structures; adds Terence, Hal, Bubbles
|
||||
|
||||
Every level needs a **load-bearing** support whose removal collapses the structure. That, not bird variety, is what makes a shot feel clever.
|
||||
|
||||
---
|
||||
|
||||
## Wave 5 — art, audio, progress, polish — ⬜
|
||||
|
||||
- [ ] Procedural art + artwork-JSON drop-in
|
||||
- [ ] Progress via `/puzzles/angrybirds/{progress,complete}`, per-level best/stars in `ab-best-N` / `ab-stars-N`
|
||||
- [ ] Match history — use `{ slug, score, opponentScores, result }`. ⚠️ Goo Tower gets this **wrong** (`GooTowerGame.js:879-881`); copy `RushHourGame.js:513-516` instead.
|
||||
- [ ] `tutorial.md` + `hasTutorial: true`
|
||||
- [ ] Paint `game-icons.png` frame 92 (row 6, col 2 → 44×44 at x=88, y=264)
|
||||
|
||||
---
|
||||
|
||||
## How difficulty is decided
|
||||
|
||||
`TUNING` in `AngryBirdsLogic.js` owns damage thresholds and material hp — tune there, not in level files. Star thresholds are **measured** by `tools/genAngryBirds.js` from the bot's achieved score, never hand-authored (same discipline as Excitebike's `qualifyMs`).
|
||||
|
||||
## Sources for original-game behaviour
|
||||
|
||||
- Rovio *Angry Birds* (2009) — material behaviour, bird abilities, 5,000/pig and 10,000/unused-bird scoring.
|
||||
- Episode structure: Poached Eggs, Mighty Hoax, Danger Above — 21 levels each.
|
||||
|
|
@ -1,212 +0,0 @@
|
|||
# Worms (Worms Armageddon) — build plan
|
||||
|
||||
Living plan doc. Survives context clears: **read this file first**, pick the next unchecked
|
||||
item, update the checkboxes and the Status line as work lands.
|
||||
|
||||
**Status:** Waves 0–1 done (2026-07-31). `node tools/verifyWorms.js` → **207 checks green**
|
||||
(~4 min; `--quick` ≈ 30 s). The game is wired into the menu and a full match is playable
|
||||
with 9 of the 16 weapons. **Never opened in a browser** — Brian playtests, and nothing here
|
||||
is signed off until he has.
|
||||
|
||||
---
|
||||
|
||||
## Decisions taken up front
|
||||
|
||||
| Question | Answer |
|
||||
|---|---|
|
||||
| Slug / name / category | `worms` / "Worms" / `arcade-console-pc` ("Video Games") |
|
||||
| iconFrame | **92** — freed by the Angry Birds removal; 0–91 were contiguous with no gaps |
|
||||
| Physics | Bespoke deterministic solver. Matter.js ships inside the CDN Phaser build but is not importable in bare Node, which would forfeit the verifier and the AI's shot replay |
|
||||
| Weapons | 16 core: Bazooka, Grenade, Cluster, Shotgun, Uzi, Fire Punch, Dynamite, Mine, Air Strike, Homing Missile, Holy Hand Grenade, Blowtorch, Girder, Teleport, Ninja Rope, Skip Go (+ Surrender) |
|
||||
| Single-player | 20-match campaign ladder fronted by the shared opponent roster, plus free Quick Match |
|
||||
| 2 player | Hotseat round-robin, one shared control set (turns never overlap) |
|
||||
| Themes | 8 — Forest, Desert, Farm, Hell, Arctic, Jungle, Construction, Space |
|
||||
| Art | Terrain shape procedural; worms procedural with a drop-in hook. Brian supplies theme backdrops, terrain fill/surface textures and background-object sheets |
|
||||
| Map shapes | Island (open sky) and Cavern (indestructible frame) |
|
||||
| Look | Clean late-90s PC. **No CRT overlay, no m6x11 pixel font** |
|
||||
| Rules | 45 s turns, 5 s retreat, fall damage, wind, sudden death + rising water, crates, mines, oil drums |
|
||||
|
||||
---
|
||||
|
||||
## Files
|
||||
|
||||
| File | Role | State |
|
||||
|---|---|---|
|
||||
| `src/games/worms/WormsTerrain.js` | Mask terrain: generation, destruction, queries, spawn lint | ✅ Wave 0 |
|
||||
| `src/games/worms/WormsPhysics.js` | Worm locomotion, projectiles, rope, blast geometry | ✅ Wave 0 |
|
||||
| `tools/verifyWorms.js` | Headless verifier, sections 1–9 | ✅ Wave 0 (152 checks) |
|
||||
| `src/games/worms/WormsWeapons.js` | The 16-weapon table | ✅ Wave 1 |
|
||||
| `src/games/worms/WormsLogic.js` | Match rules, turn order, event list | ✅ Wave 1 |
|
||||
| `src/games/worms/WormsThemes.js` | 8 theme palettes + art slot names | ✅ Wave 1 |
|
||||
| `src/games/worms/WormsRender.js` | Procedural worms, terrain painting, FX | ✅ Wave 1 |
|
||||
| `src/games/worms/WormsGame.js` | Phaser scene | ✅ Wave 1 |
|
||||
| `src/games/worms/tutorial.md` | Player-facing rules and controls | ✅ Wave 1 |
|
||||
| `data/worms-artwork.json` | Drop-in art slots, all `path: null` | ✅ Wave 1 |
|
||||
| `src/games/worms/WormsAI.js` | Skill 1–5 opponent | ⬜ Wave 3 |
|
||||
| `data/worms-campaign.json` | 20 ladder rungs | ⬜ Wave 3 |
|
||||
| `src/games/worms/sprites.md` | Art spec for Brian | ⬜ Wave 4 |
|
||||
|
||||
**Wiring touchpoints** — all done in Wave 1: `src/data/gamesRegistry.js` (iconFrame 92),
|
||||
`src/main.js` (import + scene array), `src/scenes/GameRoomScene.js:26` (`slugDispatch`),
|
||||
`src/data/assetManifest.js` (`wormsArt` resolver), `src/scenes/PreloadScene.js`
|
||||
(`worms-artwork` JSON). The `?worms-maplab=1` entrance is still Wave 4.
|
||||
|
||||
**Deviation from the original plan:** the weapon table lives in `WormsWeapons.js`, not
|
||||
`data/worms-rules.json`. The verifier, the AI and the scene must agree on those numbers
|
||||
exactly, and a plain ESM import gives that in both the browser and bare Node with no fetch
|
||||
and no async boot ordering. Theme palettes are in `WormsThemes.js` for the same reason;
|
||||
only the *art paths* are data (`data/worms-artwork.json`).
|
||||
|
||||
---
|
||||
|
||||
## Wave 0 — terrain + physics core, headless — ✅ DONE 2026-07-31
|
||||
|
||||
Landed: `WormsTerrain.js`, `WormsPhysics.js`, `tools/verifyWorms.js` sections 1–9.
|
||||
|
||||
- [x] Seeded RNG + integer-hash value noise, no `Math.random` anywhere in the sim
|
||||
- [x] Island generation — heightfield crust, coastline envelope, noise caves, arches, speck prune
|
||||
- [x] Cavern generation — ceiling/floor band, interior pillars and ledges, largest-void filter, ROCK frame
|
||||
- [x] `carveCircle` / `addCircle` / `addGirder`, ROCK immunity, order independence
|
||||
- [x] `raycast`, `normalAt`, `surfaceY`, `firstSolidBelow`, `hashMask`
|
||||
- [x] Worm locomotion — step-up walking, jump, backflip, ballistic flight, fall damage
|
||||
- [x] Projectiles — swept collision, bounce, fuse, `maxAge`, wind, homing
|
||||
- [x] Ninja rope — raycast anchor, pendulum, corner push/pop wrapping
|
||||
- [x] Blast geometry — linear falloff, impulse direction
|
||||
- [x] Fairness lint + `generateValidMap` retry loop
|
||||
|
||||
### Wave 0 findings
|
||||
|
||||
1. **A plain noise threshold cannot generate a cavern.** The base octave decides huge regions
|
||||
at once, so thresholding fBm gives *one* usable chamber and welds two thirds of the map
|
||||
shut — measured 70 % solid with the right-hand 60 % of the map unreachable. The fix is to
|
||||
carve the void as a band between a wavy ceiling and a wavy floor, which is connected across
|
||||
the full width **by construction**, and get the interest from what is put *back*: pillars,
|
||||
stalactites and floating ledges from a second noise field. Verifier pins this: "cavern void
|
||||
spans the full width" requires >98 % of columns to contain air.
|
||||
|
||||
2. **Only the ROOT rope anchor is attached to terrain.** Every later anchor is a corner the
|
||||
rope merely bends around, and by construction it sits in AIR (it is the last *free* point
|
||||
before the raycast contact). Validating those the same way as the root made the rope
|
||||
release itself the instant it wrapped anything — 14 of 35 swings dropped mid-flight. Bends
|
||||
are geometry, not attachments.
|
||||
|
||||
3. **Sub-pixel residue from a landing rides along forever.** The mask is only sampled at
|
||||
integers, so a worm that settles at y=290.625 stands a visible pixel higher than one at
|
||||
y=291 and reports a different standing height for the rest of the match — it made a
|
||||
correct 6px step-climb look 1.4px wrong. `snapToGround` now rounds to integers on landing.
|
||||
|
||||
4. **`resolveOverlap` has to be a per-frame safety net, not just a landing fixup.** Backing
|
||||
off 1.5px along the surface normal after a bounce is not enough in a concave corner, and
|
||||
terrain can be built or destroyed around an airborne worm. Without the net, a randomised
|
||||
walk had a worm inside terrain on 14 of 14 400 frames. The invariant worth having is
|
||||
absolute: **a worm is never inside terrain at the end of a step.**
|
||||
|
||||
5. **A 6px drop is a step, not a fall — and that is load-bearing.** `MAX_STEP` (10px) governs
|
||||
both climbing up and walking down. Terrain features below it are invisible to movement;
|
||||
features above it are walls. This is what makes terrain shape tactical rather than
|
||||
incidental, and it means "walked off a ledge" tests need a drop taller than `MAX_STEP`.
|
||||
|
||||
6. **Explosion falloff divides by the radius.** A zero-radius blast (which a weapon table
|
||||
typo will produce sooner or later) put NaN into worm velocities and from there into the
|
||||
whole sim. Guarded at the source.
|
||||
|
||||
### Wave 0 baselines
|
||||
|
||||
| Measurement | Result |
|
||||
|---|---|
|
||||
| Map generation, medium island / cavern | 93 ms / 199 ms |
|
||||
| Map generation, large island / cavern | 148 ms / 266 ms |
|
||||
| `generateValidMap` retries | 1.0–1.2 mean, ≤8 worst |
|
||||
| `carveCircle` r=30 / r=75 / r=120 | 0.011 / 0.033 / 0.080 ms |
|
||||
| 8 worms × 120 substeps (1 s of sim) | 6.0 ms |
|
||||
| 500 AI shot replays | 40 ms |
|
||||
| Bazooka range, full power, flat ground | ~1030 px (matches `2v²sin θ cos θ / g` to 2 %) |
|
||||
|
||||
The AI budget risk in the original plan is **resolved**: at 0.08 ms per shot replay the AI can
|
||||
evaluate a few thousand candidates inside a 200 ms turn, so no coarse-to-fine sweep is needed.
|
||||
Terrain repaint is a non-issue on the logic side; the CanvasTexture upload still wants
|
||||
measuring in the browser during Wave 1.
|
||||
|
||||
---
|
||||
|
||||
## Wave 1 — rules engine + one playable match — ✅ DONE 2026-07-31
|
||||
|
||||
Landed: the 16-weapon table, the match rules engine, the 8 theme palettes, the renderer,
|
||||
the scene, the tutorial, and all five wiring touchpoints. Verifier sections 10–12 added.
|
||||
|
||||
- [x] `WormsWeapons.js` — 16 weapons + surrender, crate table, charge curve
|
||||
- [x] `WormsLogic.js` — teams, turn rotation, timer, retreat, wind, crates, mines, barrels,
|
||||
sudden death + rising water, drowning, corpse blasts, chain reactions, win check
|
||||
- [x] `WormsThemes.js` — 8 palettes with named art slots
|
||||
- [x] `WormsRender.js` — terrain RenderTexture, procedural worms, water, explosions
|
||||
- [x] `WormsGame.js` — mode select, quick-match setup, camera, HUD, weapon panel,
|
||||
keyboard + slingshot mouse aim, 2-player hotseat
|
||||
- [x] Wiring: registry (iconFrame 92), `main.js`, `slugDispatch`, manifest resolver, preload
|
||||
- [x] Verifier §10 weapon table, §11 match rules, §12 scripted match soak
|
||||
|
||||
**9 of 16 weapons are live** (bazooka, grenade, cluster, shotgun, uzi, fire punch, dynamite,
|
||||
mine, holy hand grenade, plus skip/surrender). The `target` and `utility` kinds — air strike,
|
||||
homing missile, blowtorch, girder, teleport, ninja rope — deliberately **refuse to fire**
|
||||
rather than silently eating the ammo and the turn; the verifier pins that. The rope already
|
||||
works in physics and is reachable from the scene, it just has no ammo accounting yet.
|
||||
|
||||
### Wave 1 findings
|
||||
|
||||
1. **`pendingDeath` must not block the settle phase.** "Is the world quiet?" and "is anything
|
||||
waiting to be resolved?" are different questions. Treating a worm at 0 HP as *still
|
||||
moving* stranded every kill until the 14-second settle timeout fired, turning a two-second
|
||||
turn into a sixteen-second one. Deaths are resolved by the phase that comes *after* settle.
|
||||
|
||||
2. **A body has to be seated by its own radius.** Barrels were being placed 8 px above the
|
||||
surface with a 13 px radius, so they started half-buried — and a half-buried body is never
|
||||
"grounded" by the contact test, so it fell through its own first frame.
|
||||
|
||||
3. **A two-shot weapon costs one ammo for the pair.** Spending per trigger pull halves the
|
||||
shotgun. The fix is to spend only on the pull that *starts* the pair, which needs the
|
||||
decision made before the switch, not inside the multi-shot bookkeeping.
|
||||
|
||||
4. **Phaser Containers swallow `scrollFactor` the same way they swallow depth.** Parenting
|
||||
the parallax layers to one backdrop container made every layer move at the container's
|
||||
rate — the backdrop looked painted onto the terrain. `makeBackdrop` returns loose root
|
||||
objects with explicit depths instead. (Same family as the container-depth gotcha already
|
||||
burned into the repo.)
|
||||
|
||||
5. **"Leave match" leaves `this.state` set.** Tearing down the graphics while the state
|
||||
object survives means the next `update()` draws into destroyed objects. A single
|
||||
`matchLive` flag set by `teardownMatch`/`buildWorld` guards every path — rematch, menu,
|
||||
scene shutdown — instead of null-checking six fields.
|
||||
|
||||
6. **Craters must be smaller than the damage radius.** Otherwise every hit that hurts also
|
||||
opens a hole big enough to fall through, and matches devolve into everyone drowning.
|
||||
Pinned by the verifier across the whole weapon table.
|
||||
|
||||
### Wave 1 baselines
|
||||
|
||||
| Measurement | Result |
|
||||
|---|---|
|
||||
| Scripted match, 4v4 | terminates 30/30, 0 NaN, 0 draws, mean 50 turns |
|
||||
| Wall time per scripted match | ~5.7 s (~2.5 s with `retreatSeconds: 0`) |
|
||||
| Whole-match determinism | same seed → same `hashState` |
|
||||
|
||||
The soak cost matters for Wave 3: 400 AI matches at ~5.7 s is 38 minutes. The soak config
|
||||
sets `retreatSeconds: 0` (the retreat wait is dead time headlessly), which is why §12 runs
|
||||
24 matches by default and `--games=400` is the long run.
|
||||
|
||||
## Wave 2 — full arsenal and rule extras — ⬜ NEXT
|
||||
|
||||
- [ ] `target` kind: air strike, homing missile, girder, teleport (click-to-place flow)
|
||||
- [ ] `utility` kind: blowtorch, ninja rope ammo + turn integration
|
||||
- [ ] Verifier §13: a fixture per weapon pinning damage, blast and behaviour
|
||||
## Wave 3 — AI and campaign ladder — ⬜
|
||||
## Wave 4 — presentation, themes, 2-player — ⬜
|
||||
## Wave 5 — retune after Brian's playtest — ⬜
|
||||
|
||||
---
|
||||
|
||||
## Sources for original-game behaviour
|
||||
|
||||
Worms Armageddon (Team17, 1999): 45 s default turn with 5 s retreat, 100 HP worms, wind
|
||||
re-rolled each turn and affecting only unpowered arcing weapons, fall damage from the peak of
|
||||
the fall, sudden death dropping every worm to 1 HP with the water rising per turn, crates
|
||||
parachuting in between turns, and the ninja rope wrapping terrain corners rather than passing
|
||||
through them.
|
||||
|
|
@ -47,31 +47,6 @@ function imagesFrom(scene, jsonKey) {
|
|||
.map((a) => ({ type: 'image', key: a.key, path: a.path }));
|
||||
}
|
||||
|
||||
// Worms art is two levels deep (theme → slot) and mixes plain images with a
|
||||
// spritesheet, so it gets its own resolver rather than bending sheetsFrom.
|
||||
// Slots whose `path` is still null render procedurally from the theme palette
|
||||
// in src/games/worms/WormsThemes.js, so an empty result here is the normal,
|
||||
// fully playable state — not a missing asset.
|
||||
function wormsArt(scene) {
|
||||
const art = scene.cache.json.get('worms-artwork');
|
||||
if (!art) return [];
|
||||
const out = [];
|
||||
const add = (slot, asSheet) => {
|
||||
if (!slot || !slot.key || !slot.path) return;
|
||||
out.push(asSheet
|
||||
? { type: 'spritesheet', key: slot.key, path: slot.path, frameWidth: slot.frameWidth, frameHeight: slot.frameHeight }
|
||||
: { type: 'image', key: slot.key, path: slot.path });
|
||||
};
|
||||
for (const theme of Object.values(art.themes ?? {})) {
|
||||
add(theme.backdrop, false);
|
||||
add(theme.fill, false);
|
||||
add(theme.surface, false);
|
||||
add(theme.objects, true);
|
||||
}
|
||||
for (const slot of Object.values(art.shared ?? {})) add(slot, true);
|
||||
return out;
|
||||
}
|
||||
|
||||
// Drop-in per-game soundtrack tracks declared in a cached `<name>-music.json`
|
||||
// (see services/soundtrack.js). Audio bytes lazy-load only when the owning
|
||||
// game is entered — never part of the shared default-soundtrack preload.
|
||||
|
|
@ -86,11 +61,6 @@ const sheet = (key, path, frameWidth, frameHeight) => ({ type: 'spritesheet', ke
|
|||
const image = (key, path) => ({ type: 'image', key, path });
|
||||
|
||||
export const MANIFEST = {
|
||||
// All of Worms' art is optional drop-in theme art; the game is fully
|
||||
// playable with none of it (see data/worms-artwork.json).
|
||||
worms: [
|
||||
(scene) => wormsArt(scene),
|
||||
],
|
||||
gootower: [
|
||||
image('gootower-bg', 'assets/images/gootower/background-1.png'),
|
||||
image('gootower-pipe', 'assets/images/gootower/pipe.png'),
|
||||
|
|
@ -101,6 +71,11 @@ export const MANIFEST = {
|
|||
excitebike: [
|
||||
(scene) => musicFrom(scene, 'nintendo-music'),
|
||||
],
|
||||
|
||||
// Angry Birds draws every block, pig and bird procedurally (see the MAT_COLORS
|
||||
// and BIRD_COLORS tables in AngryBirdsGame.js), so there is nothing to fetch
|
||||
// yet. Wave 5 adds data/angrybirds-artwork.json here as a drop-in sprite map.
|
||||
angrybirds: [],
|
||||
forbiddenisland: [
|
||||
// Tiles: 2 cols (dry, flooded) × 24 rows. Row i → dry frame 2i, flooded
|
||||
// frame 2i+1 (see IslandData.TILE_FRAME_ROW).
|
||||
|
|
|
|||
|
|
@ -118,5 +118,5 @@ registerGame({ slug: 'tetrisattack', name: 'Tetris Attack', category: 'arcade-co
|
|||
registerGame({ slug: 'totalannihilation', name: 'Total Annihilation', category: 'arcade-console-pc', minPlayers: 1, maxPlayers: 1, minOpponents: 0, maxOpponents: 0, iconFrame: 88 });
|
||||
registerGame({ slug: 'bloxorz', name: 'Bloxorz', category: 'logic', minPlayers: 1, maxPlayers: 1, minOpponents: 0, maxOpponents: 0, hasTutorial: true, iconFrame: 89 });
|
||||
registerGame({ slug: 'gootower', name: 'Goo Tower', category: 'logic', minPlayers: 1, maxPlayers: 1, minOpponents: 0, maxOpponents: 0, hasTutorial: true, iconFrame: 90 });
|
||||
registerGame({ slug: 'worms', name: 'Worms', category: 'arcade-console-pc', minPlayers: 1, maxPlayers: 2, minOpponents: 0, maxOpponents: 0, hasTutorial: true, iconFrame: 92 });
|
||||
registerGame({ slug: 'excitebike', name: 'Excitebike', category: 'arcade-console-pc', minPlayers: 1, maxPlayers: 1, minOpponents: 0, maxOpponents: 0, iconFrame: 91 });
|
||||
registerGame({ slug: 'angrybirds', name: 'Angry Birds', category: 'arcade-console-pc', minPlayers: 1, maxPlayers: 1, minOpponents: 0, maxOpponents: 0, iconFrame: 92 });
|
||||
|
|
|
|||
|
|
@ -0,0 +1,599 @@
|
|||
import * as Phaser from 'phaser';
|
||||
import { GAME_HEIGHT, GAME_WIDTH } from '../../config.js';
|
||||
import { Button } from '../../ui/Button.js';
|
||||
import { Tooltip } from '../../ui/Tooltip.js';
|
||||
import { SFX, playSound } from '../../ui/Sounds.js';
|
||||
import { api } from '../../services/api.js';
|
||||
import {
|
||||
TUNING, MATERIALS, BIRDS,
|
||||
createState, stepSim, launch, useAbility, clampDraw, slingAnchor,
|
||||
currentBird, birdsRemaining, starsFor,
|
||||
} from './AngryBirdsLogic.js';
|
||||
|
||||
// Logical level space is 2400x1080; the canvas is 1920x1080. Everything is
|
||||
// drawn through sx()/sy() at a fixed scale rather than by zooming the camera,
|
||||
// exactly as PeggleGame maps its 1200x900 board — that keeps HUD text in plain
|
||||
// screen coordinates instead of fighting camera zoom. Sim space is never
|
||||
// screen space.
|
||||
const SCALE = 0.78;
|
||||
const OFF_X = 24;
|
||||
const OFF_Y = 158;
|
||||
|
||||
const GAMEDATA = 'assets/gamedata/angrybirds';
|
||||
const SIM_STEP = 1 / 60;
|
||||
|
||||
const MAT_COLORS = {
|
||||
wood: { fill: 0xc8873c, line: 0x8b5a22 },
|
||||
stone: { fill: 0x9ba3a8, line: 0x656d72 },
|
||||
ice: { fill: 0x9bd8f0, line: 0x59a6cc },
|
||||
tnt: { fill: 0xd03a2a, line: 0x8c1d12 },
|
||||
};
|
||||
|
||||
const BIRD_COLORS = {
|
||||
red: 0xd6332b, chuck: 0xf5c518, blue: 0x35a7dd, bomb: 0x3b3b42,
|
||||
matilda: 0xf2f0e6, terence: 0x8f2b23, hal: 0x4aa64a, bubbles: 0xf07f22,
|
||||
};
|
||||
|
||||
export default class AngryBirdsGame extends Phaser.Scene {
|
||||
constructor() { super('AngryBirdsGame'); }
|
||||
|
||||
init(data) {
|
||||
this.gameDef = data?.game ?? { slug: 'angrybirds', name: 'Angry Birds' };
|
||||
this.testLevel = data?.testLevel ?? null;
|
||||
this.returnToEditor = !!data?.returnToEditor;
|
||||
this.state = null;
|
||||
this.manifest = null;
|
||||
this.levelCache = new Map();
|
||||
this.levelsCompleted = 0;
|
||||
this.canPersist = true;
|
||||
this.accum = 0;
|
||||
}
|
||||
|
||||
sx(x) { return x * SCALE + OFF_X; }
|
||||
sy(y) { return y * SCALE + OFF_Y; }
|
||||
wx(x) { return (x - OFF_X) / SCALE; }
|
||||
wy(y) { return (y - OFF_Y) / SCALE; }
|
||||
|
||||
async create() {
|
||||
this.cameras.main.setBackgroundColor('#7ec8e8');
|
||||
|
||||
if (this.testLevel) {
|
||||
this.startLevel(this.testLevel);
|
||||
return;
|
||||
}
|
||||
|
||||
const cached = this.cache.json.get('angrybirds-levels');
|
||||
this.manifest = cached ?? await fetch(`${GAMEDATA}/levels.json`).then((r) => r.json()).catch(() => null);
|
||||
|
||||
try {
|
||||
const res = await api.get('/puzzles/angrybirds/progress');
|
||||
this.levelsCompleted = res?.levelsCompleted ?? 0;
|
||||
} catch (_) {
|
||||
// Offline or unavailable — play in-session without persisting.
|
||||
this.canPersist = false;
|
||||
this.levelsCompleted = 0;
|
||||
}
|
||||
|
||||
this.showSelect();
|
||||
}
|
||||
|
||||
// ── Level select ──────────────────────────────────────────────────────────
|
||||
|
||||
clearScreen() {
|
||||
if (this.tooltip) { this.tooltip.destroy?.(); this.tooltip = null; }
|
||||
this.children.removeAll();
|
||||
this.input.removeAllListeners();
|
||||
}
|
||||
|
||||
showSelect() {
|
||||
this.clearScreen();
|
||||
this.state = null;
|
||||
this.screen = 'select';
|
||||
|
||||
this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x7ec8e8);
|
||||
this.drawHills(this.add.graphics());
|
||||
|
||||
this.add.text(GAME_WIDTH / 2, 70, 'ANGRY BIRDS', {
|
||||
fontFamily: '"Righteous", sans-serif', fontSize: '58px', color: '#ffffff',
|
||||
stroke: '#1d2a33', strokeThickness: 8,
|
||||
}).setOrigin(0.5);
|
||||
|
||||
if (!this.manifest) {
|
||||
this.add.text(GAME_WIDTH / 2, GAME_HEIGHT / 2, 'Could not load levels.', {
|
||||
fontFamily: 'sans-serif', fontSize: '28px', color: '#ffffff',
|
||||
}).setOrigin(0.5);
|
||||
new Button(this, 120, GAME_HEIGHT - 60, 'Back', () => this.scene.start('GameMenu'), { width: 160 });
|
||||
return;
|
||||
}
|
||||
|
||||
this.tooltip = new Tooltip(this);
|
||||
|
||||
for (const ep of this.manifest.episodes ?? []) {
|
||||
this.add.text(GAME_WIDTH / 2, 150, ep.name, {
|
||||
fontFamily: '"Righteous", sans-serif', fontSize: '34px', color: '#ffe9a8',
|
||||
stroke: '#1d2a33', strokeThickness: 5,
|
||||
}).setOrigin(0.5);
|
||||
this.add.text(GAME_WIDTH / 2, 190, ep.blurb ?? '', {
|
||||
fontFamily: 'sans-serif', fontSize: '20px', color: '#ffffff',
|
||||
}).setOrigin(0.5);
|
||||
}
|
||||
|
||||
const levels = this.manifest.levels ?? [];
|
||||
const COLS = 6;
|
||||
const TW = 190;
|
||||
const TH = 150;
|
||||
const startX = GAME_WIDTH / 2 - ((Math.min(COLS, levels.length) - 1) * (TW + 20)) / 2;
|
||||
levels.forEach((m, i) => {
|
||||
const col = i % COLS;
|
||||
const row = Math.floor(i / COLS);
|
||||
const x = startX + col * (TW + 20);
|
||||
const y = 320 + row * (TH + 24);
|
||||
const unlocked = m.level <= this.levelsCompleted + 1;
|
||||
this.makeLevelTile(x, y, m, unlocked, TW, TH);
|
||||
});
|
||||
|
||||
new Button(this, 120, GAME_HEIGHT - 60, 'Back', () => this.scene.start('GameMenu'), { width: 160 });
|
||||
if (this.levelsCompleted > 0) {
|
||||
new Button(this, GAME_WIDTH - 140, GAME_HEIGHT - 60, 'Reset', () => this.resetProgress(),
|
||||
{ width: 160, variant: 'ghost' });
|
||||
}
|
||||
}
|
||||
|
||||
makeLevelTile(x, y, m, unlocked, w, h) {
|
||||
const best = this.bestFor(m.level);
|
||||
const bg = this.add.rectangle(x, y, w, h, unlocked ? 0xffffff : 0x9aa6ad, unlocked ? 0.95 : 0.6)
|
||||
.setStrokeStyle(4, unlocked ? 0x1d2a33 : 0x5c666d);
|
||||
this.add.text(x, y - 40, `${m.level}`, {
|
||||
fontFamily: '"Righteous", sans-serif', fontSize: '40px',
|
||||
color: unlocked ? '#1d2a33' : '#e8eef1',
|
||||
}).setOrigin(0.5);
|
||||
this.add.text(x, y + 2, m.name, {
|
||||
fontFamily: 'sans-serif', fontSize: '17px',
|
||||
color: unlocked ? '#3a4a55' : '#e8eef1',
|
||||
wordWrap: { width: w - 20 }, align: 'center',
|
||||
}).setOrigin(0.5);
|
||||
|
||||
// Stars earned so far.
|
||||
for (let s = 0; s < 3; s += 1) {
|
||||
this.add.text(x - 30 + s * 30, y + 46, '★', {
|
||||
fontFamily: 'sans-serif', fontSize: '26px',
|
||||
color: s < best.stars ? '#ffc93c' : (unlocked ? '#c9d3d9' : '#8b969c'),
|
||||
}).setOrigin(0.5);
|
||||
}
|
||||
|
||||
if (!unlocked) {
|
||||
this.add.text(x, y + 46, '🔒', { fontSize: '22px' }).setOrigin(0.5);
|
||||
return;
|
||||
}
|
||||
|
||||
bg.setInteractive({ useHandCursor: true });
|
||||
bg.on('pointerdown', () => this.openLevel(m));
|
||||
this.tooltip?.attachTo(bg, () => ({
|
||||
title: `${m.level}. ${m.name}`,
|
||||
lines: [
|
||||
best.score ? `Best: ${best.score.toLocaleString()}` : 'Not yet cleared',
|
||||
best.stars ? `${best.stars} of 3 stars` : 'No stars yet',
|
||||
],
|
||||
}));
|
||||
}
|
||||
|
||||
async openLevel(m) {
|
||||
const def = await this.fetchLevel(m);
|
||||
if (def) this.startLevel(def);
|
||||
}
|
||||
|
||||
async fetchLevel(m) {
|
||||
if (this.levelCache.has(m.level)) return this.levelCache.get(m.level);
|
||||
try {
|
||||
const json = await fetch(`${GAMEDATA}/${m.file}`).then((r) => r.json());
|
||||
this.levelCache.set(m.level, json);
|
||||
return json;
|
||||
} catch (_) { return null; }
|
||||
}
|
||||
|
||||
// ── Progress ──────────────────────────────────────────────────────────────
|
||||
|
||||
bestFor(level) {
|
||||
try {
|
||||
return {
|
||||
score: Number(localStorage.getItem(`ab-best-${level}`) || 0),
|
||||
stars: Number(localStorage.getItem(`ab-stars-${level}`) || 0),
|
||||
};
|
||||
} catch (_) { return { score: 0, stars: 0 }; }
|
||||
}
|
||||
|
||||
recordBest(level, score, stars) {
|
||||
try {
|
||||
const prev = this.bestFor(level);
|
||||
if (score > prev.score) localStorage.setItem(`ab-best-${level}`, String(score));
|
||||
if (stars > prev.stars) localStorage.setItem(`ab-stars-${level}`, String(stars));
|
||||
} catch (_) { /* storage full or blocked */ }
|
||||
}
|
||||
|
||||
async resetProgress() {
|
||||
try { await api.post('/puzzles/angrybirds/reset', {}); } catch (_) { /* offline */ }
|
||||
try {
|
||||
for (const m of this.manifest?.levels ?? []) {
|
||||
localStorage.removeItem(`ab-best-${m.level}`);
|
||||
localStorage.removeItem(`ab-stars-${m.level}`);
|
||||
}
|
||||
} catch (_) { /* ignore */ }
|
||||
this.levelsCompleted = 0;
|
||||
this.showSelect();
|
||||
}
|
||||
|
||||
// ── Play ──────────────────────────────────────────────────────────────────
|
||||
|
||||
startLevel(def) {
|
||||
this.clearScreen();
|
||||
this.screen = 'play';
|
||||
this.state = createState(def);
|
||||
this.accum = 0;
|
||||
this.dragging = false;
|
||||
this.dragPt = null;
|
||||
|
||||
this.bgGfx = this.add.graphics().setDepth(0);
|
||||
this.worldGfx = this.add.graphics().setDepth(10);
|
||||
this.aimGfx = this.add.graphics().setDepth(20);
|
||||
this.drawBackground();
|
||||
|
||||
this.hud = this.add.container(0, 0).setDepth(40);
|
||||
this.scoreText = this.add.text(GAME_WIDTH - 40, 32, '0', {
|
||||
fontFamily: '"Righteous", sans-serif', fontSize: '40px', color: '#ffffff',
|
||||
stroke: '#1d2a33', strokeThickness: 6,
|
||||
}).setOrigin(1, 0);
|
||||
this.levelText = this.add.text(GAME_WIDTH / 2, 32, `${def.level}. ${def.name}`, {
|
||||
fontFamily: 'sans-serif', fontSize: '24px', color: '#ffffff',
|
||||
stroke: '#1d2a33', strokeThickness: 4,
|
||||
}).setOrigin(0.5, 0);
|
||||
this.hintText = this.add.text(GAME_WIDTH / 2, GAME_HEIGHT - 34, '', {
|
||||
fontFamily: 'sans-serif', fontSize: '20px', color: '#ffffff',
|
||||
stroke: '#1d2a33', strokeThickness: 4,
|
||||
}).setOrigin(0.5).setDepth(40);
|
||||
this.hud.add([this.scoreText, this.levelText]);
|
||||
|
||||
new Button(this, 110, 44, 'Back', () => this.exitLevel(), { width: 150, height: 46 });
|
||||
new Button(this, 280, 44, 'Retry', () => this.startLevel(this.state.level), { width: 150, height: 46, variant: 'ghost' });
|
||||
|
||||
this.input.on('pointerdown', (p) => this.onDown(p));
|
||||
this.input.on('pointermove', (p) => this.onMove(p));
|
||||
this.input.on('pointerup', () => this.onUp());
|
||||
}
|
||||
|
||||
exitLevel() {
|
||||
if (this.returnToEditor) this.scene.start('AngryBirdsEditor', { resume: true });
|
||||
else this.showSelect();
|
||||
}
|
||||
|
||||
onDown(p) {
|
||||
if (!this.state) return;
|
||||
if (this.state.phase === 'flight') { useAbility(this.state); return; }
|
||||
if (this.state.phase !== 'aim') return;
|
||||
const a = slingAnchor(this.state);
|
||||
const d = Math.hypot(this.wx(p.x) - a.x, this.wy(p.y) - a.y);
|
||||
// Generous grab radius: the band, not the bird, is the target.
|
||||
if (d > 260) return;
|
||||
this.dragging = true;
|
||||
this.dragPt = clampDraw(this.state, this.wx(p.x), this.wy(p.y));
|
||||
}
|
||||
|
||||
onMove(p) {
|
||||
if (!this.dragging || !this.state) return;
|
||||
this.dragPt = clampDraw(this.state, this.wx(p.x), this.wy(p.y));
|
||||
}
|
||||
|
||||
onUp() {
|
||||
if (!this.dragging || !this.state) return;
|
||||
this.dragging = false;
|
||||
const pt = this.dragPt;
|
||||
this.dragPt = null;
|
||||
if (!pt) return;
|
||||
if (launch(this.state, pt.x, pt.y)) playSound(this, SFX.EIGHTBIT_JUMP);
|
||||
}
|
||||
|
||||
update(time, delta) {
|
||||
if (this.screen !== 'play' || !this.state) return;
|
||||
this.accum = Math.min(this.accum + delta / 1000, 0.25);
|
||||
while (this.accum >= SIM_STEP) {
|
||||
this.accum -= SIM_STEP;
|
||||
const events = stepSim(this.state, SIM_STEP);
|
||||
if (events.length) this.processEvents(events);
|
||||
}
|
||||
this.render();
|
||||
}
|
||||
|
||||
processEvents(events) {
|
||||
for (const e of events) {
|
||||
switch (e.t) {
|
||||
case 'blockDestroyed':
|
||||
playSound(this, SFX.EIGHTBIT_EXPLODE);
|
||||
this.puff(e.x, e.y, MAT_COLORS[e.material]?.fill ?? 0xffffff);
|
||||
break;
|
||||
case 'pigKilled':
|
||||
playSound(this, SFX.EIGHTBIT_EXPLODE_2);
|
||||
this.puff(e.x, e.y, 0x86c232);
|
||||
break;
|
||||
case 'explosion':
|
||||
playSound(this, SFX.SCIFI_EXPLODE);
|
||||
this.blast(e.x, e.y, e.radius);
|
||||
break;
|
||||
case 'won':
|
||||
playSound(this, SFX.VICTORY_SHORT);
|
||||
this.onFinished(true, e.stars);
|
||||
break;
|
||||
case 'lost':
|
||||
this.onFinished(false, 0);
|
||||
break;
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
puff(x, y, color) {
|
||||
const c = this.add.circle(this.sx(x), this.sy(y), 6, color, 0.9).setDepth(30);
|
||||
this.tweens.add({
|
||||
targets: c, scale: 4, alpha: 0, duration: 340, ease: 'Cubic.Out',
|
||||
onComplete: () => c.destroy(),
|
||||
});
|
||||
}
|
||||
|
||||
blast(x, y, radius) {
|
||||
const c = this.add.circle(this.sx(x), this.sy(y), radius * SCALE * 0.3, 0xffd27f, 0.7).setDepth(30);
|
||||
this.tweens.add({
|
||||
targets: c, scale: 3.4, alpha: 0, duration: 420, ease: 'Cubic.Out',
|
||||
onComplete: () => c.destroy(),
|
||||
});
|
||||
this.cameras.main.shake(220, 0.006);
|
||||
}
|
||||
|
||||
async onFinished(won, stars) {
|
||||
const st = this.state;
|
||||
const level = st.level.level;
|
||||
if (won) this.recordBest(level, st.score, stars);
|
||||
|
||||
// An editor test-play is not a real run: it must not advance saved
|
||||
// progress or write a match record.
|
||||
if (won && this.canPersist && !this.returnToEditor) {
|
||||
try {
|
||||
const res = await api.post('/puzzles/angrybirds/complete', { level });
|
||||
if (res?.levelsCompleted != null) {
|
||||
this.levelsCompleted = Math.max(this.levelsCompleted, res.levelsCompleted);
|
||||
}
|
||||
} catch (_) { /* best effort */ }
|
||||
api.post('/history/single-player', {
|
||||
slug: 'angrybirds',
|
||||
score: Math.min(st.score, 100000),
|
||||
opponentScores: [],
|
||||
result: 'win',
|
||||
}).catch(() => { /* best effort */ });
|
||||
}
|
||||
if (won && level > this.levelsCompleted) this.levelsCompleted = level;
|
||||
|
||||
this.showResult(won, stars);
|
||||
}
|
||||
|
||||
showResult(won, stars) {
|
||||
const panel = this.add.container(GAME_WIDTH / 2, GAME_HEIGHT / 2).setDepth(60);
|
||||
panel.add(this.add.rectangle(0, 0, 620, 380, 0x11212b, 0.94).setStrokeStyle(5, 0xffc93c));
|
||||
panel.add(this.add.text(0, -128, won ? 'LEVEL CLEARED' : 'OUT OF BIRDS', {
|
||||
fontFamily: '"Righteous", sans-serif', fontSize: '42px',
|
||||
color: won ? '#ffc93c' : '#ff8a7a',
|
||||
}).setOrigin(0.5));
|
||||
|
||||
if (won) {
|
||||
for (let s = 0; s < 3; s += 1) {
|
||||
panel.add(this.add.text(-90 + s * 90, -50, '★', {
|
||||
fontFamily: 'sans-serif', fontSize: '64px',
|
||||
color: s < stars ? '#ffc93c' : '#3c4b56',
|
||||
}).setOrigin(0.5));
|
||||
}
|
||||
}
|
||||
panel.add(this.add.text(0, 30, `Score ${this.state.score.toLocaleString()}`, {
|
||||
fontFamily: 'sans-serif', fontSize: '30px', color: '#ffffff',
|
||||
}).setOrigin(0.5));
|
||||
|
||||
const nextEntry = (this.manifest?.levels ?? []).find((m) => m.level === this.state.level.level + 1);
|
||||
const retry = new Button(this, -150, 120, 'Retry', () => {
|
||||
panel.destroy();
|
||||
this.startLevel(this.state.level);
|
||||
}, { width: 230, height: 56 });
|
||||
panel.add(retry);
|
||||
|
||||
if (won && nextEntry) {
|
||||
const next = new Button(this, 150, 120, 'Next', async () => {
|
||||
panel.destroy();
|
||||
const def = await this.fetchLevel(nextEntry);
|
||||
if (def) this.startLevel(def); else this.showSelect();
|
||||
}, { width: 230, height: 56 });
|
||||
panel.add(next);
|
||||
} else {
|
||||
const back = new Button(this, 150, 120, 'Levels', () => { panel.destroy(); this.showSelect(); },
|
||||
{ width: 230, height: 56, variant: 'ghost' });
|
||||
panel.add(back);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Rendering ─────────────────────────────────────────────────────────────
|
||||
|
||||
drawHills(g) {
|
||||
g.fillStyle(0x4f9d3a, 1);
|
||||
g.fillEllipse(GAME_WIDTH * 0.2, GAME_HEIGHT + 60, 900, 340);
|
||||
g.fillEllipse(GAME_WIDTH * 0.75, GAME_HEIGHT + 90, 1100, 420);
|
||||
g.fillStyle(0x3f8c2e, 1);
|
||||
g.fillRect(0, GAME_HEIGHT - 40, GAME_WIDTH, 40);
|
||||
}
|
||||
|
||||
drawBackground() {
|
||||
const g = this.bgGfx;
|
||||
g.clear();
|
||||
g.fillStyle(0x7ec8e8, 1);
|
||||
g.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT);
|
||||
// Distant hills behind the play line.
|
||||
g.fillStyle(0x9fd6a0, 1);
|
||||
g.fillEllipse(GAME_WIDTH * 0.25, this.sy(this.state.groundY) + 40, 1200, 420);
|
||||
g.fillEllipse(GAME_WIDTH * 0.8, this.sy(this.state.groundY) + 60, 1500, 500);
|
||||
// Ground.
|
||||
const gy = this.sy(this.state.groundY);
|
||||
g.fillStyle(0x6fbf46, 1);
|
||||
g.fillRect(0, gy, GAME_WIDTH, GAME_HEIGHT - gy);
|
||||
g.fillStyle(0x8b5a2b, 1);
|
||||
g.fillRect(0, gy + 26, GAME_WIDTH, GAME_HEIGHT - gy - 26);
|
||||
g.lineStyle(4, 0x4d8c2f, 1);
|
||||
g.lineBetween(0, gy, GAME_WIDTH, gy);
|
||||
}
|
||||
|
||||
render() {
|
||||
const st = this.state;
|
||||
const g = this.worldGfx;
|
||||
g.clear();
|
||||
|
||||
// Blocks.
|
||||
for (const [id, rec] of st.blocks) {
|
||||
const b = st.world.byId.get(id);
|
||||
if (!b) continue;
|
||||
const col = MAT_COLORS[rec.material] ?? MAT_COLORS.wood;
|
||||
const pts = b.wverts.map(([x, y]) => new Phaser.Math.Vector2(this.sx(x), this.sy(y)));
|
||||
g.fillStyle(col.fill, rec.material === 'ice' ? 0.72 : 1);
|
||||
g.lineStyle(3, col.line, 1);
|
||||
g.beginPath();
|
||||
g.moveTo(pts[0].x, pts[0].y);
|
||||
for (let i = 1; i < pts.length; i += 1) g.lineTo(pts[i].x, pts[i].y);
|
||||
g.closePath();
|
||||
g.fillPath();
|
||||
g.strokePath();
|
||||
|
||||
// Damage reads as cracks across the face, darkening as hp falls.
|
||||
const f = rec.hp / rec.maxHp;
|
||||
if (f <= 2 / 3) {
|
||||
const stage = f > 1 / 3 ? 1 : 2;
|
||||
g.lineStyle(2, 0x2b1c10, 0.55);
|
||||
const cx = this.sx(b.x);
|
||||
const cy = this.sy(b.y);
|
||||
const r = Math.min(rec.w, rec.h) * SCALE * 0.42;
|
||||
for (let i = 0; i < stage * 2; i += 1) {
|
||||
const a = (i / (stage * 2)) * Math.PI * 2 + b.angle;
|
||||
g.lineBetween(cx, cy, cx + Math.cos(a) * r, cy + Math.sin(a) * r);
|
||||
}
|
||||
}
|
||||
if (rec.material === 'tnt') {
|
||||
g.fillStyle(0xffe9a8, 1);
|
||||
g.fillRect(this.sx(b.x) - 14, this.sy(b.y) - 5, 28, 10);
|
||||
}
|
||||
}
|
||||
|
||||
// Pigs.
|
||||
for (const [id, rec] of st.pigs) {
|
||||
const b = st.world.byId.get(id);
|
||||
if (!b) continue;
|
||||
const x = this.sx(b.x);
|
||||
const y = this.sy(b.y);
|
||||
const r = rec.r * SCALE;
|
||||
const hurt = rec.hp / rec.maxHp;
|
||||
g.fillStyle(hurt > 2 / 3 ? 0x86c232 : hurt > 1 / 3 ? 0x9ec24a : 0xb6b84a, 1);
|
||||
g.fillCircle(x, y, r);
|
||||
g.lineStyle(3, 0x4c7a1c, 1);
|
||||
g.strokeCircle(x, y, r);
|
||||
g.fillStyle(0xffffff, 1);
|
||||
g.fillCircle(x - r * 0.3, y - r * 0.25, r * 0.22);
|
||||
g.fillCircle(x + r * 0.3, y - r * 0.25, r * 0.22);
|
||||
g.fillStyle(0x1d2a33, 1);
|
||||
g.fillCircle(x - r * 0.26, y - r * 0.25, r * 0.1);
|
||||
g.fillCircle(x + r * 0.34, y - r * 0.25, r * 0.1);
|
||||
g.fillStyle(0x6ba428, 1);
|
||||
g.fillCircle(x, y + r * 0.18, r * 0.32);
|
||||
g.fillStyle(0x3f6b16, 1);
|
||||
g.fillCircle(x - r * 0.12, y + r * 0.18, r * 0.08);
|
||||
g.fillCircle(x + r * 0.12, y + r * 0.18, r * 0.08);
|
||||
}
|
||||
|
||||
// Slingshot.
|
||||
const a = slingAnchor(st);
|
||||
const ax = this.sx(a.x);
|
||||
const ay = this.sy(a.y);
|
||||
const groundY = this.sy(st.groundY);
|
||||
g.lineStyle(14, 0x6b4423, 1);
|
||||
g.lineBetween(ax, ay + 10, ax, groundY);
|
||||
g.lineBetween(ax, ay + 12, ax - 18, ay - 14);
|
||||
g.lineBetween(ax, ay + 12, ax + 18, ay - 14);
|
||||
|
||||
// Birds in flight.
|
||||
for (const id of st.activeBirds) {
|
||||
const b = st.world.byId.get(id);
|
||||
if (!b) continue;
|
||||
this.drawBird(g, b, this.sx(b.x), this.sy(b.y), b.radius * SCALE);
|
||||
}
|
||||
|
||||
this.renderAim();
|
||||
this.scoreText?.setText(st.score.toLocaleString());
|
||||
this.updateHint();
|
||||
}
|
||||
|
||||
drawBird(g, body, x, y, r) {
|
||||
const def = BIRDS[body.userData?.bird] ?? BIRDS.red;
|
||||
g.fillStyle(BIRD_COLORS[def.id] ?? 0xd6332b, 1);
|
||||
g.fillCircle(x, y, r);
|
||||
g.lineStyle(3, 0x6b1a15, 1);
|
||||
g.strokeCircle(x, y, r);
|
||||
g.fillStyle(0xffffff, 1);
|
||||
g.fillCircle(x + r * 0.18, y - r * 0.28, r * 0.3);
|
||||
g.fillStyle(0x1d2a33, 1);
|
||||
g.fillCircle(x + r * 0.26, y - r * 0.28, r * 0.14);
|
||||
g.fillStyle(0xf5a623, 1);
|
||||
g.fillTriangle(x + r * 0.55, y, x + r * 1.15, y - r * 0.16, x + r * 0.55, y + r * 0.3);
|
||||
}
|
||||
|
||||
renderAim() {
|
||||
const g = this.aimGfx;
|
||||
g.clear();
|
||||
const st = this.state;
|
||||
const a = slingAnchor(st);
|
||||
|
||||
// Ghost trails of previous shots. Without this, aiming is guesswork
|
||||
// instead of iteration — it is how the original teaches.
|
||||
g.fillStyle(0xffffff, 0.4);
|
||||
for (const trail of st.trails) {
|
||||
for (let i = 0; i < trail.length; i += 6) {
|
||||
g.fillCircle(this.sx(trail[i].x), this.sy(trail[i].y), 3);
|
||||
}
|
||||
}
|
||||
|
||||
if (st.phase === 'aim') {
|
||||
const def = currentBird(st);
|
||||
const pt = this.dragPt;
|
||||
const bx = pt ? this.sx(pt.x) : this.sx(a.x);
|
||||
const by = pt ? this.sy(pt.y) : this.sy(a.y) - 8;
|
||||
if (def) {
|
||||
// Band, drawn behind the waiting bird.
|
||||
g.lineStyle(8, 0x3a2416, 1);
|
||||
g.lineBetween(this.sx(a.x) - 18, this.sy(a.y) - 14, bx, by);
|
||||
g.lineBetween(this.sx(a.x) + 18, this.sy(a.y) - 14, bx, by);
|
||||
this.drawBird(g, { userData: { bird: def.id } }, bx, by, def.r * SCALE);
|
||||
}
|
||||
// Queue of waiting birds beside the sling.
|
||||
for (let i = st.birdIndex + 1; i < st.birdQueue.length; i += 1) {
|
||||
const d = BIRDS[st.birdQueue[i]] ?? BIRDS.red;
|
||||
const qx = this.sx(a.x) - 70 - (i - st.birdIndex - 1) * 46;
|
||||
this.drawBird(g, { userData: { bird: d.id } }, qx, this.sy(st.groundY) - d.r * SCALE, d.r * SCALE * 0.85);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
updateHint() {
|
||||
const st = this.state;
|
||||
if (!this.hintText) return;
|
||||
if (st.phase === 'aim') {
|
||||
const def = currentBird(st);
|
||||
const left = birdsRemaining(st);
|
||||
this.hintText.setText(def
|
||||
? `${def.name} — ${def.blurb} (${left} left)`
|
||||
: '');
|
||||
} else if (st.phase === 'flight' && !st.abilityUsed) {
|
||||
const id = st.activeBirds[0];
|
||||
const body = st.world.byId.get(id);
|
||||
const def = body ? BIRDS[body.userData?.bird] : null;
|
||||
this.hintText.setText(def && def.ability !== 'none' ? 'Click to use ability' : '');
|
||||
} else {
|
||||
this.hintText.setText('');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,585 @@
|
|||
// Angry Birds — game rules over the rigid-body solver. Zero imports besides
|
||||
// the physics module, no Phaser, no DOM, no timers. Shared by the client
|
||||
// scene, the level editor, the offline generator and the verifier.
|
||||
//
|
||||
// ── WHAT MAKES IT READ AS ANGRY BIRDS ───────────────────────────────────────
|
||||
// Not the birds. The two things that actually matter are:
|
||||
//
|
||||
// * MATERIALS WITH DISTINCT DENSITY. Wood, stone and ice differ in mass,
|
||||
// friction and fragility, so a structure has a load path and a support
|
||||
// beam worth aiming at. Uniform blocks turn every level into "hit it
|
||||
// harder".
|
||||
// * DAMAGE AS A HEALTH MODEL, NOT INSTANT SHATTERING. A block accumulates
|
||||
// damage from impacts above its threshold and cracks through visible
|
||||
// stages before breaking. Pigs take damage the same way, which is why
|
||||
// they die to DEBRIS LANDING ON THEM rather than only to direct hits —
|
||||
// the collapse doing the killing is the whole feel of the game. Clones
|
||||
// that destroy a block on any contact feel wrong immediately.
|
||||
//
|
||||
// ── UNITS ───────────────────────────────────────────────────────────────────
|
||||
// Pixels and seconds in the level's own logical space (level.world). The scene
|
||||
// maps that to the 1920x1080 canvas with a camera; nothing in here knows about
|
||||
// the screen.
|
||||
//
|
||||
// Impulse units: contact impulses are mass x velocity in the solver's units,
|
||||
// where a 24x80 wood plank masses ~1050. A resting contact in a tall stack
|
||||
// runs a few 1e4; a solid bird hit runs 1e6+. Damage thresholds live in that
|
||||
// space — see calibrateDamage() in tools/verifyAngryBirds.js, which pins the
|
||||
// separation between "resting" and "hit" so a tower can never crush itself.
|
||||
|
||||
import {
|
||||
PHYS, createWorld, addBox, addCircle, removeBody,
|
||||
substep, isSettled, applyExplosion, cloneWorld, hashWorld, wakeBody,
|
||||
} from './AngryBirdsPhysics.js';
|
||||
|
||||
export const TUNING = {
|
||||
GROUND_Y: 900,
|
||||
SLING_X: 260,
|
||||
SLING_Y: 700,
|
||||
SLING_HEIGHT: 150, // fork height above the ground contact
|
||||
MAX_DRAW: 150, // px the band can be pulled back
|
||||
SPEED_PER_DRAW: 13.5, // draw px -> launch px/s (150 * 13.5 = 2025)
|
||||
MIN_DRAW: 12, // below this a release is treated as a cancel
|
||||
MAX_SHOT_TIME: 12, // s before a shot is force-resolved
|
||||
SETTLE_GRACE: 0.35, // s of stillness required after the world sleeps
|
||||
DESPAWN_X: -400, // bodies past these bounds are removed
|
||||
DESPAWN_X_MAX: 4200,
|
||||
DESPAWN_Y: 1600,
|
||||
DAMAGE_SCALE: 1 / 9000, // impulse above threshold -> hp
|
||||
DEBRIS_MIN_IMPULSE: 60000,
|
||||
};
|
||||
|
||||
// hp/threshold are in solver impulse units (see the header note).
|
||||
export const MATERIALS = {
|
||||
wood: {
|
||||
id: 'wood', density: 0.55, friction: 0.55, restitution: 0.10,
|
||||
hp: 42, threshold: 150000, points: 500,
|
||||
},
|
||||
stone: {
|
||||
id: 'stone', density: 1.35, friction: 0.62, restitution: 0.05,
|
||||
hp: 105, threshold: 320000, points: 1000,
|
||||
},
|
||||
ice: {
|
||||
id: 'ice', density: 0.32, friction: 0.18, restitution: 0.14,
|
||||
hp: 18, threshold: 90000, points: 300,
|
||||
},
|
||||
// TNT is deliberately fragile: it is a trigger, not a wall.
|
||||
tnt: {
|
||||
id: 'tnt', density: 0.6, friction: 0.5, restitution: 0.08,
|
||||
hp: 10, threshold: 70000, points: 800,
|
||||
blast: { radius: 260, power: 1500, damage: 60 },
|
||||
},
|
||||
};
|
||||
|
||||
export const PIG = {
|
||||
density: 0.5, friction: 0.5, restitution: 0.25,
|
||||
hp: 26, threshold: 80000, points: 5000,
|
||||
};
|
||||
|
||||
export const BIRDS = {
|
||||
red: {
|
||||
id: 'red', name: 'Red', r: 17, density: 2.2, restitution: 0.35,
|
||||
ability: 'none', blurb: 'No trick. Just a bird.',
|
||||
},
|
||||
chuck: {
|
||||
id: 'chuck', name: 'Chuck', r: 15, density: 1.9, restitution: 0.3,
|
||||
ability: 'dart', params: { mult: 2.15 },
|
||||
blurb: 'Tap to dart forward at speed. Best against wood.',
|
||||
},
|
||||
blue: {
|
||||
id: 'blue', name: 'Blue', r: 13, density: 1.5, restitution: 0.35,
|
||||
ability: 'split', params: { count: 3, spreadDeg: 14 },
|
||||
blurb: 'Tap to split into three. Shreds ice.',
|
||||
},
|
||||
bomb: {
|
||||
id: 'bomb', name: 'Bomb', r: 21, density: 3.1, restitution: 0.2,
|
||||
ability: 'blast', params: { radius: 240, power: 1400, damage: 45 },
|
||||
blurb: 'Tap to detonate. Levels stone.',
|
||||
},
|
||||
matilda: {
|
||||
id: 'matilda', name: 'Matilda', r: 19, density: 2.2, restitution: 0.25,
|
||||
ability: 'egg', params: { radius: 170, power: 900, damage: 30, kick: 620 },
|
||||
blurb: 'Tap to drop an egg bomb and climb.',
|
||||
},
|
||||
terence: {
|
||||
id: 'terence', name: 'Terence', r: 27, density: 4.4, restitution: 0.15,
|
||||
ability: 'none', blurb: 'Enormous. Goes through things.',
|
||||
},
|
||||
hal: {
|
||||
id: 'hal', name: 'Hal', r: 16, density: 2.0, restitution: 0.3,
|
||||
ability: 'boomerang', params: { spin: 26 },
|
||||
blurb: 'Tap to boomerang back. Hits from behind.',
|
||||
},
|
||||
bubbles: {
|
||||
id: 'bubbles', name: 'Bubbles', r: 12, density: 1.6, restitution: 0.4,
|
||||
ability: 'inflate', params: { scale: 3.0, push: 520 },
|
||||
blurb: 'Tap to inflate and shove everything apart.',
|
||||
},
|
||||
};
|
||||
|
||||
export const SCORING = {
|
||||
PIG: PIG.points,
|
||||
BIRD_LEFT: 10000,
|
||||
};
|
||||
|
||||
// ── Level construction ──────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Build a live state from a level definition.
|
||||
*
|
||||
* Level schema:
|
||||
* { version, level, name, episode, world: {w, h, groundY},
|
||||
* birds: ['red', 'chuck', ...],
|
||||
* blocks: [{ x, y, w, h, angle?, material }],
|
||||
* pigs: [{ x, y, r }],
|
||||
* terrain?: [{ x, y, w, h, angle? }], // static scenery
|
||||
* stars: [oneStar, twoStar, threeStar] }
|
||||
*/
|
||||
export function createState(level) {
|
||||
const groundY = level.world?.groundY ?? TUNING.GROUND_Y;
|
||||
const world = createWorld();
|
||||
const state = {
|
||||
level,
|
||||
world,
|
||||
groundY,
|
||||
blocks: new Map(), // bodyId -> { material, hp, maxHp, w, h }
|
||||
pigs: new Map(), // bodyId -> { hp, maxHp, r }
|
||||
birdQueue: (level.birds ?? ['red']).slice(),
|
||||
birdIndex: 0,
|
||||
activeBirds: [], // bodyIds currently in flight
|
||||
abilityUsed: false,
|
||||
phase: 'aim', // aim | flight | resolving | won | lost
|
||||
score: 0,
|
||||
shotTime: 0,
|
||||
settleTimer: 0,
|
||||
trails: [], // completed shot trails, for the aiming ghost
|
||||
liveTrail: [],
|
||||
events: [],
|
||||
};
|
||||
|
||||
// Ground: wide enough that nothing rolls off the end of the world.
|
||||
addBox(world, {
|
||||
x: (level.world?.w ?? 1920) / 2, y: groundY + 400, w: 12000, h: 800,
|
||||
isStatic: true, friction: 0.75, restitution: 0.05,
|
||||
});
|
||||
|
||||
for (const t of level.terrain ?? []) {
|
||||
addBox(world, {
|
||||
x: t.x, y: t.y, w: t.w, h: t.h, angle: t.angle ?? 0,
|
||||
isStatic: true, friction: t.friction ?? 0.7, restitution: 0.05,
|
||||
});
|
||||
}
|
||||
|
||||
for (const b of level.blocks ?? []) {
|
||||
const mat = MATERIALS[b.material] ?? MATERIALS.wood;
|
||||
const body = addBox(world, {
|
||||
x: b.x, y: b.y, w: b.w, h: b.h, angle: b.angle ?? 0,
|
||||
density: mat.density, friction: mat.friction, restitution: mat.restitution,
|
||||
});
|
||||
body.userData = { kind: 'block', material: mat.id };
|
||||
state.blocks.set(body.id, { material: mat.id, hp: mat.hp, maxHp: mat.hp, w: b.w, h: b.h });
|
||||
}
|
||||
|
||||
for (const p of level.pigs ?? []) {
|
||||
const r = p.r ?? 22;
|
||||
// Bigger pigs are tougher, so a boss pig reads as one at a glance.
|
||||
const scale = r / 22;
|
||||
const body = addCircle(world, {
|
||||
x: p.x, y: p.y, r,
|
||||
density: PIG.density, friction: PIG.friction, restitution: PIG.restitution,
|
||||
});
|
||||
body.userData = { kind: 'pig' };
|
||||
const hp = PIG.hp * scale;
|
||||
state.pigs.set(body.id, { hp, maxHp: hp, r });
|
||||
}
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
// ── Aiming and launching ────────────────────────────────────────────────────
|
||||
|
||||
export function slingAnchor(state) {
|
||||
return {
|
||||
x: state.level.world?.slingX ?? TUNING.SLING_X,
|
||||
y: (state.level.world?.slingY ?? (state.groundY - TUNING.SLING_HEIGHT)),
|
||||
};
|
||||
}
|
||||
|
||||
/** Clamp a raw drag point to the band's reach. Returns the clamped point. */
|
||||
export function clampDraw(state, px, py) {
|
||||
const a = slingAnchor(state);
|
||||
let dx = px - a.x;
|
||||
let dy = py - a.y;
|
||||
const d = Math.hypot(dx, dy);
|
||||
if (d > TUNING.MAX_DRAW) {
|
||||
dx = (dx / d) * TUNING.MAX_DRAW;
|
||||
dy = (dy / d) * TUNING.MAX_DRAW;
|
||||
}
|
||||
return { x: a.x + dx, y: a.y + dy, draw: Math.min(d, TUNING.MAX_DRAW) };
|
||||
}
|
||||
|
||||
/** Launch velocity for a drag point — the bird flies OPPOSITE the pull. */
|
||||
export function drawToVelocity(state, px, py) {
|
||||
const a = slingAnchor(state);
|
||||
const c = clampDraw(state, px, py);
|
||||
return {
|
||||
vx: (a.x - c.x) * TUNING.SPEED_PER_DRAW,
|
||||
vy: (a.y - c.y) * TUNING.SPEED_PER_DRAW,
|
||||
draw: c.draw,
|
||||
};
|
||||
}
|
||||
|
||||
export function currentBird(state) {
|
||||
if (state.birdIndex >= state.birdQueue.length) return null;
|
||||
return BIRDS[state.birdQueue[state.birdIndex]] ?? BIRDS.red;
|
||||
}
|
||||
|
||||
export function birdsRemaining(state) {
|
||||
return Math.max(0, state.birdQueue.length - state.birdIndex);
|
||||
}
|
||||
|
||||
function spawnBird(state, def, x, y, vx, vy) {
|
||||
const body = addCircle(state.world, {
|
||||
x, y, r: def.r,
|
||||
density: def.density, friction: 0.4, restitution: def.restitution,
|
||||
});
|
||||
body.userData = { kind: 'bird', bird: def.id };
|
||||
body.vx = vx;
|
||||
body.vy = vy;
|
||||
state.activeBirds.push(body.id);
|
||||
return body;
|
||||
}
|
||||
|
||||
/** Fire the queued bird. Returns false if the draw was too short to count. */
|
||||
export function launch(state, px, py) {
|
||||
if (state.phase !== 'aim') return false;
|
||||
const def = currentBird(state);
|
||||
if (!def) return false;
|
||||
const { vx, vy, draw } = drawToVelocity(state, px, py);
|
||||
if (draw < TUNING.MIN_DRAW) return false;
|
||||
|
||||
const a = slingAnchor(state);
|
||||
spawnBird(state, def, a.x, a.y, vx, vy);
|
||||
state.birdIndex += 1;
|
||||
state.abilityUsed = false;
|
||||
state.phase = 'flight';
|
||||
state.shotTime = 0;
|
||||
state.settleTimer = 0;
|
||||
state.liveTrail = [{ x: a.x, y: a.y }];
|
||||
state.events.push({ t: 'birdLaunched', bird: def.id, vx, vy });
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fire the in-flight bird's ability. One per shot, as in the original — the
|
||||
* limit is what makes timing the tap a decision rather than a reflex.
|
||||
*/
|
||||
export function useAbility(state) {
|
||||
if (state.phase !== 'flight' || state.abilityUsed) return false;
|
||||
const id = state.activeBirds[0];
|
||||
const body = state.world.byId.get(id);
|
||||
if (!body) return false;
|
||||
const def = BIRDS[body.userData?.bird] ?? BIRDS.red;
|
||||
if (def.ability === 'none') return false;
|
||||
|
||||
state.abilityUsed = true;
|
||||
const p = def.params ?? {};
|
||||
|
||||
switch (def.ability) {
|
||||
case 'dart': {
|
||||
const sp = Math.hypot(body.vx, body.vy) || 1;
|
||||
body.vx = (body.vx / sp) * sp * p.mult;
|
||||
body.vy = (body.vy / sp) * sp * p.mult;
|
||||
break;
|
||||
}
|
||||
case 'split': {
|
||||
const ang = Math.atan2(body.vy, body.vx);
|
||||
const sp = Math.hypot(body.vx, body.vy);
|
||||
const spread = (p.spreadDeg * Math.PI) / 180;
|
||||
for (let i = 1; i < p.count; i += 1) {
|
||||
const off = (i % 2 === 1 ? 1 : -1) * spread * Math.ceil(i / 2);
|
||||
spawnBird(state, def, body.x, body.y,
|
||||
Math.cos(ang + off) * sp, Math.sin(ang + off) * sp);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'blast': {
|
||||
detonate(state, body.x, body.y, p.radius, p.power, p.damage);
|
||||
killBody(state, body);
|
||||
break;
|
||||
}
|
||||
case 'egg': {
|
||||
detonate(state, body.x, body.y + def.r + 8, p.radius, p.power, p.damage);
|
||||
body.vy = -p.kick; // Matilda climbs as the egg drops
|
||||
break;
|
||||
}
|
||||
case 'boomerang': {
|
||||
body.vx = -body.vx * 1.15;
|
||||
body.omega = p.spin;
|
||||
break;
|
||||
}
|
||||
case 'inflate': {
|
||||
// Grow in place and shove neighbours apart. Rebuilding the body is
|
||||
// simpler than mutating radius + mass in the solver, and keeps the
|
||||
// invariant that a body's mass properties never change mid-life.
|
||||
const grown = spawnBird(state, def, body.x, body.y, body.vx, body.vy);
|
||||
grown.userData = { kind: 'bird', bird: def.id, inflated: true };
|
||||
state.activeBirds = state.activeBirds.filter((b) => b !== body.id);
|
||||
removeBody(state.world, body);
|
||||
const bigger = addCircle(state.world, {
|
||||
x: grown.x, y: grown.y, r: def.r * p.scale,
|
||||
density: def.density * 0.35, friction: 0.5, restitution: def.restitution,
|
||||
});
|
||||
bigger.userData = { kind: 'bird', bird: def.id, inflated: true };
|
||||
bigger.vx = grown.vx; bigger.vy = grown.vy;
|
||||
state.activeBirds = state.activeBirds.filter((b) => b !== grown.id);
|
||||
removeBody(state.world, grown);
|
||||
state.activeBirds.unshift(bigger.id);
|
||||
applyExplosion(state.world, bigger.x, bigger.y, def.r * p.scale * 2.2, p.push);
|
||||
break;
|
||||
}
|
||||
default: break;
|
||||
}
|
||||
|
||||
state.events.push({ t: 'abilityUsed', bird: def.id, x: body.x, y: body.y });
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── Damage ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function crackStage(hp, maxHp) {
|
||||
const f = hp / maxHp;
|
||||
if (f > 2 / 3) return 0;
|
||||
if (f > 1 / 3) return 1;
|
||||
return 2;
|
||||
}
|
||||
|
||||
function killBody(state, body) {
|
||||
state.activeBirds = state.activeBirds.filter((b) => b !== body.id);
|
||||
state.blocks.delete(body.id);
|
||||
state.pigs.delete(body.id);
|
||||
removeBody(state.world, body);
|
||||
}
|
||||
|
||||
function detonate(state, x, y, radius, power, damage) {
|
||||
state.events.push({ t: 'explosion', x, y, radius });
|
||||
const hit = applyExplosion(state.world, x, y, radius, power);
|
||||
for (const { body, falloff } of hit) {
|
||||
const dmg = damage * falloff;
|
||||
if (state.blocks.has(body.id)) damageBlock(state, body, dmg);
|
||||
else if (state.pigs.has(body.id)) damagePig(state, body, dmg);
|
||||
}
|
||||
}
|
||||
|
||||
function damageBlock(state, body, amount) {
|
||||
const rec = state.blocks.get(body.id);
|
||||
if (!rec) return;
|
||||
const before = crackStage(rec.hp, rec.maxHp);
|
||||
rec.hp -= amount;
|
||||
const after = crackStage(Math.max(rec.hp, 0), rec.maxHp);
|
||||
if (rec.hp <= 0) {
|
||||
const mat = MATERIALS[rec.material];
|
||||
state.score += mat.points;
|
||||
state.events.push({ t: 'blockDestroyed', id: body.id, material: rec.material, x: body.x, y: body.y });
|
||||
// TNT takes the neighbourhood with it. Remove it BEFORE detonating so it
|
||||
// cannot damage itself and recurse.
|
||||
const blast = mat.blast;
|
||||
killBody(state, body);
|
||||
if (blast) detonate(state, body.x, body.y, blast.radius, blast.power, blast.damage);
|
||||
return;
|
||||
}
|
||||
if (after !== before) {
|
||||
state.events.push({ t: 'blockCracked', id: body.id, stage: after, x: body.x, y: body.y });
|
||||
}
|
||||
}
|
||||
|
||||
function damagePig(state, body, amount) {
|
||||
const rec = state.pigs.get(body.id);
|
||||
if (!rec) return;
|
||||
const before = crackStage(rec.hp, rec.maxHp);
|
||||
rec.hp -= amount;
|
||||
if (rec.hp <= 0) {
|
||||
state.score += SCORING.PIG;
|
||||
state.events.push({ t: 'pigKilled', id: body.id, x: body.x, y: body.y });
|
||||
killBody(state, body);
|
||||
return;
|
||||
}
|
||||
const after = crackStage(rec.hp, rec.maxHp);
|
||||
if (after !== before) {
|
||||
state.events.push({ t: 'pigHurt', id: body.id, stage: after, x: body.x, y: body.y });
|
||||
}
|
||||
}
|
||||
|
||||
// Convert this substep's contact impulses into damage. Reading the solver's
|
||||
// per-contact peak (rather than a body's total) is what lets debris landing on
|
||||
// a pig hurt it exactly as much as the geometry says it should.
|
||||
function applyContactDamage(state) {
|
||||
for (const c of state.world.contactList) {
|
||||
// impactImpulse, never maxImpulse — see the note in Physics.prestep. The
|
||||
// accumulated impulse carries the weight of everything stacked above, so
|
||||
// using it would make tall towers damage themselves at rest.
|
||||
const imp = c.impactImpulse;
|
||||
if (imp <= 0) continue;
|
||||
for (const body of [c.a, c.b]) {
|
||||
const block = state.blocks.get(body.id);
|
||||
if (block) {
|
||||
const mat = MATERIALS[block.material];
|
||||
if (imp > mat.threshold) damageBlock(state, body, (imp - mat.threshold) * TUNING.DAMAGE_SCALE);
|
||||
continue;
|
||||
}
|
||||
const pig = state.pigs.get(body.id);
|
||||
if (pig && imp > PIG.threshold) {
|
||||
damagePig(state, body, (imp - PIG.threshold) * TUNING.DAMAGE_SCALE);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function despawnStrays(state) {
|
||||
for (const b of [...state.world.bodies]) {
|
||||
if (b.isStatic) continue;
|
||||
if (b.x > TUNING.DESPAWN_X && b.x < TUNING.DESPAWN_X_MAX && b.y < TUNING.DESPAWN_Y) continue;
|
||||
if (state.pigs.has(b.id)) {
|
||||
// A pig that falls off the world still counts as dealt with.
|
||||
state.score += SCORING.PIG;
|
||||
state.events.push({ t: 'pigKilled', id: b.id, x: b.x, y: b.y, offscreen: true });
|
||||
}
|
||||
killBody(state, b);
|
||||
}
|
||||
}
|
||||
|
||||
// ── The frame ───────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Advance the sim. Returns an ordered event list the renderer replays as FX and
|
||||
* sound — the same contract GooTower and Peggle use.
|
||||
*/
|
||||
export function stepSim(state, dt) {
|
||||
state.events = [];
|
||||
if (state.phase === 'won' || state.phase === 'lost') return state.events;
|
||||
|
||||
const clamped = Math.min(dt, 0.05);
|
||||
const steps = Math.max(1, Math.round(clamped / PHYS.SUBSTEP_DT));
|
||||
for (let i = 0; i < steps; i += 1) {
|
||||
substep(state.world, PHYS.SUBSTEP_DT);
|
||||
applyContactDamage(state);
|
||||
}
|
||||
despawnStrays(state);
|
||||
|
||||
if (state.phase === 'flight' || state.phase === 'resolving') {
|
||||
state.shotTime += clamped;
|
||||
const lead = state.world.byId.get(state.activeBirds[0]);
|
||||
if (lead) state.liveTrail.push({ x: lead.x, y: lead.y });
|
||||
|
||||
if (state.pigs.size === 0) {
|
||||
finish(state, true);
|
||||
return state.events;
|
||||
}
|
||||
|
||||
const still = isSettled(state.world);
|
||||
state.settleTimer = still ? state.settleTimer + clamped : 0;
|
||||
const resolved = state.settleTimer >= TUNING.SETTLE_GRACE
|
||||
|| state.shotTime >= TUNING.MAX_SHOT_TIME;
|
||||
|
||||
if (resolved) {
|
||||
if (state.liveTrail.length > 2) state.trails.push(state.liveTrail);
|
||||
state.liveTrail = [];
|
||||
// Spent birds are cleared so they can't prop a structure up forever.
|
||||
for (const id of [...state.activeBirds]) {
|
||||
const b = state.world.byId.get(id);
|
||||
if (b) killBody(state, b);
|
||||
}
|
||||
state.activeBirds = [];
|
||||
state.events.push({ t: 'shotEnded', score: state.score });
|
||||
|
||||
if (state.pigs.size === 0) finish(state, true);
|
||||
else if (birdsRemaining(state) === 0) finish(state, false);
|
||||
else state.phase = 'aim';
|
||||
}
|
||||
}
|
||||
|
||||
return state.events;
|
||||
}
|
||||
|
||||
function finish(state, won) {
|
||||
if (won) {
|
||||
const bonus = birdsRemaining(state) * SCORING.BIRD_LEFT;
|
||||
state.score += bonus;
|
||||
state.phase = 'won';
|
||||
state.events.push({ t: 'won', score: state.score, birdBonus: bonus, stars: starsFor(state) });
|
||||
} else {
|
||||
state.phase = 'lost';
|
||||
state.events.push({ t: 'lost', score: state.score });
|
||||
}
|
||||
}
|
||||
|
||||
export function starsFor(state, score = state.score) {
|
||||
const cuts = state.level.stars ?? [];
|
||||
let stars = 0;
|
||||
for (const c of cuts) if (score >= c) stars += 1;
|
||||
return Math.min(3, Math.max(state.phase === 'won' ? 1 : 0, stars));
|
||||
}
|
||||
|
||||
export const isWon = (state) => state.phase === 'won';
|
||||
export const isLost = (state) => state.phase === 'lost';
|
||||
|
||||
// ── Determinism helpers ─────────────────────────────────────────────────────
|
||||
|
||||
export function cloneState(state) {
|
||||
return {
|
||||
...state,
|
||||
world: cloneWorld(state.world),
|
||||
blocks: new Map([...state.blocks].map(([k, v]) => [k, { ...v }])),
|
||||
pigs: new Map([...state.pigs].map(([k, v]) => [k, { ...v }])),
|
||||
birdQueue: state.birdQueue.slice(),
|
||||
activeBirds: state.activeBirds.slice(),
|
||||
trails: state.trails.map((t) => t.slice()),
|
||||
liveTrail: state.liveTrail.slice(),
|
||||
events: [],
|
||||
};
|
||||
}
|
||||
|
||||
export function hashState(state) {
|
||||
let h = hashWorld(state.world);
|
||||
const mixInt = (v) => { h = (Math.imul(h ^ (v | 0), 0x01000193) >>> 0); };
|
||||
mixInt(state.score);
|
||||
mixInt(state.birdIndex);
|
||||
mixInt(state.pigs.size);
|
||||
mixInt(state.blocks.size);
|
||||
for (const [id, b] of [...state.blocks].sort((p, q) => p[0] - q[0])) {
|
||||
mixInt(id); mixInt(Math.round(b.hp * 1000));
|
||||
}
|
||||
for (const [id, p] of [...state.pigs].sort((a, b) => a[0] - b[0])) {
|
||||
mixInt(id); mixInt(Math.round(p.hp * 1000));
|
||||
}
|
||||
return h >>> 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dry-run a shot on a clone and report what it would achieve. This is what the
|
||||
* winnability bot samples over and what the generator measures star thresholds
|
||||
* from; it never touches the live state.
|
||||
*/
|
||||
export function simulateShot(state, px, py, opts = {}) {
|
||||
const sim = cloneState(state);
|
||||
if (!launch(sim, px, py)) return null;
|
||||
const abilityAt = opts.abilityAt ?? -1;
|
||||
let t = 0;
|
||||
let guard = 0;
|
||||
while (sim.phase === 'flight' && guard < 4000) {
|
||||
if (abilityAt >= 0 && t >= abilityAt && !sim.abilityUsed) useAbility(sim);
|
||||
stepSim(sim, 1 / 60);
|
||||
t += 1 / 60;
|
||||
guard += 1;
|
||||
}
|
||||
return {
|
||||
score: sim.score - state.score,
|
||||
pigsKilled: state.pigs.size - sim.pigs.size,
|
||||
blocksDestroyed: state.blocks.size - sim.blocks.size,
|
||||
won: sim.phase === 'won',
|
||||
finalScore: sim.score,
|
||||
state: sim,
|
||||
};
|
||||
}
|
||||
|
||||
export { PHYS, wakeBody };
|
||||
|
|
@ -0,0 +1,943 @@
|
|||
// Angry Birds — rigid-body physics. Zero imports, deterministic, Node-testable.
|
||||
//
|
||||
// Generic 2D rigid-body solver: it knows about convex polygons and circles and
|
||||
// nothing at all about birds, pigs or scoring. AngryBirdsLogic.js layers the
|
||||
// game on top.
|
||||
//
|
||||
// ── WHY A BESPOKE SOLVER ────────────────────────────────────────────────────
|
||||
// Matter.js ships inside the CDN Phaser build and would have worked in the
|
||||
// browser, but it cannot be imported in bare Node and is not reproducible.
|
||||
// This repo's whole quality apparatus — tools/verifyAngryBirds.js, the level
|
||||
// generator's MEASURED star thresholds, and the editor's winnability gate —
|
||||
// depends on replaying a shot headlessly and getting the same answer twice.
|
||||
//
|
||||
// Neither existing engine could be extended into this. PeggleLogic collides a
|
||||
// moving circle against STATIC pegs with no rotation and no persistent
|
||||
// contacts; GooTowerLogic has no angular state anywhere, because its rigidity
|
||||
// is emergent from triangulation. A toppling tower of boxes needs both
|
||||
// rotation and lasting contacts, so this is new code.
|
||||
//
|
||||
// ── THE THREE THINGS THAT MAKE STACKS STAND UP ──────────────────────────────
|
||||
// 1. TWO-POINT MANIFOLDS. A single contact point cannot resist rotation, so a
|
||||
// box resting on a box rocks forever. Reference-face clipping yields up to
|
||||
// 2 points per pair, which is what makes a face-to-face rest contact rigid.
|
||||
// 2. WARM STARTING. Each contact point remembers last substep's accumulated
|
||||
// impulse — keyed by a FEATURE ID that survives across frames, not by array
|
||||
// position — and reapplies it before iterating. Without it a 6-box tower
|
||||
// visibly sags every frame because the solver spends all its iterations
|
||||
// rediscovering gravity from zero.
|
||||
// 3. ISLAND SLEEPING. Bodies are grouped by contact into islands; an island
|
||||
// sleeps only when EVERY member has been slow for SLEEP_TIME. Per-body
|
||||
// sleeping would let half a tower freeze while the other half moves.
|
||||
// Sleeping is load-bearing three times over: stack stability, perf, and the
|
||||
// "shot is finished" test the rules layer waits on.
|
||||
//
|
||||
// ── UNITS AND CONVENTIONS ───────────────────────────────────────────────────
|
||||
// Pixels, seconds, radians. Y IS DOWN (screen convention). Polygon winding is
|
||||
// normalized on insert so the shoelace area is positive; the outward normal of
|
||||
// edge v[i]->v[i+1] is then (e.y, -e.x). Contact normals point from A to B.
|
||||
//
|
||||
// Determinism rules, all load-bearing:
|
||||
// * bodies and contacts are always iterated in ascending id order;
|
||||
// * no Math.random() anywhere — callers pass a seeded rng if they need one;
|
||||
// * no Date/performance reads;
|
||||
// * nothing that affects the result may depend on Map/Set iteration order —
|
||||
// broadphase pairs are sorted by (aId, bId) and the solver walks that list.
|
||||
|
||||
export const PHYS = {
|
||||
SUBSTEP_DT: 1 / 240,
|
||||
VEL_ITERS: 8, // sequential-impulse passes per substep
|
||||
GRAVITY: 1400, // px/s²
|
||||
BAUMGARTE: 0.25, // fraction of excess penetration removed per substep
|
||||
SLOP: 0.5, // allowed penetration, px — stops resting contacts buzzing
|
||||
REST_THRESHOLD: 120, // approach speed below which restitution is ignored
|
||||
MAX_SPEED: 2400, // px/s
|
||||
MAX_OMEGA: 40, // rad/s
|
||||
LINEAR_DAMPING: 0.002,
|
||||
ANGULAR_DAMPING: 0.004,
|
||||
SLEEP_LIN: 14, // px/s
|
||||
SLEEP_ANG: 0.14, // rad/s
|
||||
SLEEP_TIME: 0.5, // s below both thresholds before an island sleeps
|
||||
GRID_CELL: 96, // broadphase cell size, px
|
||||
MIN_HALF_EXTENT: 12, // smallest half-extent any body may have (anti-tunnel)
|
||||
};
|
||||
|
||||
// ── Small math helpers ──────────────────────────────────────────────────────
|
||||
|
||||
const cross = (ax, ay, bx, by) => ax * by - ay * bx;
|
||||
const clamp = (v, lo, hi) => (v < lo ? lo : v > hi ? hi : v);
|
||||
|
||||
// Numeric composite keys. Body ids are dense and small, so this is exact well
|
||||
// past any level we'd author, and it keeps Map lookups off the string path.
|
||||
const PAIR_STRIDE = 1 << 20;
|
||||
const pairKey = (aId, bId) => aId * PAIR_STRIDE + bId;
|
||||
// Grid cells can be negative, so bias into non-negative space before packing.
|
||||
const GRID_BIAS = 1 << 14;
|
||||
const cellKey = (gx, gy) => (gx + GRID_BIAS) * (1 << 15) + (gy + GRID_BIAS);
|
||||
|
||||
// ── Mass properties ─────────────────────────────────────────────────────────
|
||||
|
||||
// Signed shoelace area. Positive means the winding matches our normal formula.
|
||||
function signedArea(verts) {
|
||||
let a = 0;
|
||||
for (let i = 0; i < verts.length; i += 1) {
|
||||
const [x0, y0] = verts[i];
|
||||
const [x1, y1] = verts[(i + 1) % verts.length];
|
||||
a += x0 * y1 - x1 * y0;
|
||||
}
|
||||
return a * 0.5;
|
||||
}
|
||||
|
||||
// Area, centroid and second moment of a convex polygon, integrated over the
|
||||
// triangle fan from the origin. Inertia comes out about the ORIGIN, so it is
|
||||
// shifted to the centroid with the parallel-axis theorem before returning.
|
||||
function polyMassData(verts, density) {
|
||||
let area = 0;
|
||||
let cx = 0;
|
||||
let cy = 0;
|
||||
let inertia = 0;
|
||||
for (let i = 0; i < verts.length; i += 1) {
|
||||
const [x0, y0] = verts[i];
|
||||
const [x1, y1] = verts[(i + 1) % verts.length];
|
||||
const c = x0 * y1 - x1 * y0;
|
||||
area += c;
|
||||
cx += (x0 + x1) * c;
|
||||
cy += (y0 + y1) * c;
|
||||
inertia += c * (x0 * x0 + x0 * x1 + x1 * x1 + y0 * y0 + y0 * y1 + y1 * y1);
|
||||
}
|
||||
area *= 0.5;
|
||||
const inv6A = 1 / (6 * area);
|
||||
cx *= inv6A;
|
||||
cy *= inv6A;
|
||||
const mass = density * Math.abs(area);
|
||||
let I = density * Math.abs(inertia) / 12;
|
||||
I -= mass * (cx * cx + cy * cy); // parallel axis: origin -> centroid
|
||||
return { mass, cx, cy, I: Math.max(I, 1e-6) };
|
||||
}
|
||||
|
||||
// ── World ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function createWorld(opts = {}) {
|
||||
return {
|
||||
bodies: [],
|
||||
byId: new Map(),
|
||||
// Keyed by pairKey(a,b) — a NUMBER, not a string. Contact lookup runs a few
|
||||
// thousand times a substep and string keys dominated the profile.
|
||||
contacts: new Map(),
|
||||
// Rebuilt in pair order each substep; the solver iterates this, never the
|
||||
// Map, so nothing depends on Map insertion history.
|
||||
contactList: [],
|
||||
nextId: 1,
|
||||
gravity: opts.gravity ?? PHYS.GRAVITY,
|
||||
accum: 0,
|
||||
time: 0,
|
||||
};
|
||||
}
|
||||
|
||||
function addBody(world, body) {
|
||||
body.id = world.nextId;
|
||||
world.nextId += 1;
|
||||
world.bodies.push(body);
|
||||
world.byId.set(body.id, body);
|
||||
return body;
|
||||
}
|
||||
|
||||
function baseBody(o) {
|
||||
return {
|
||||
id: 0,
|
||||
x: o.x, y: o.y, angle: o.angle ?? 0,
|
||||
vx: 0, vy: 0, omega: 0,
|
||||
// Pseudo-velocity for the split-impulse position solve. Accumulated during
|
||||
// the bias pass, added into the position integration, then zeroed. It never
|
||||
// survives a substep, so it can't inject energy into the real velocity.
|
||||
psx: 0, psy: 0, psw: 0,
|
||||
friction: o.friction ?? 0.5,
|
||||
restitution: o.restitution ?? 0.1,
|
||||
isStatic: !!o.isStatic,
|
||||
sleeping: false,
|
||||
sleepTimer: 0,
|
||||
// Free-form pointer the rules layer hangs blocks/pigs/birds off. The solver
|
||||
// never reads it, which is what keeps this file game-agnostic.
|
||||
userData: o.userData ?? null,
|
||||
aabb: { minx: 0, miny: 0, maxx: 0, maxy: 0 },
|
||||
};
|
||||
}
|
||||
|
||||
/** Convex polygon from local-space verts (any winding, recentred on centroid). */
|
||||
export function addPoly(world, o) {
|
||||
let verts = o.verts.map(([x, y]) => [x, y]);
|
||||
if (signedArea(verts) < 0) verts.reverse();
|
||||
const md = polyMassData(verts, o.density ?? 1);
|
||||
// Recentre so the body origin IS the centre of mass; the solver assumes it.
|
||||
verts = verts.map(([x, y]) => [x - md.cx, y - md.cy]);
|
||||
|
||||
const b = baseBody(o);
|
||||
b.kind = 'poly';
|
||||
b.verts = verts;
|
||||
b.normals = verts.map(([x0, y0], i) => {
|
||||
const [x1, y1] = verts[(i + 1) % verts.length];
|
||||
const ex = x1 - x0;
|
||||
const ey = y1 - y0;
|
||||
const len = Math.hypot(ex, ey) || 1;
|
||||
return [ey / len, -ex / len];
|
||||
});
|
||||
b.wverts = verts.map(() => [0, 0]);
|
||||
b.wnormals = verts.map(() => [0, 0]);
|
||||
b.radius = Math.max(...verts.map(([x, y]) => Math.hypot(x, y)));
|
||||
b.invMass = o.isStatic ? 0 : 1 / md.mass;
|
||||
b.invI = o.isStatic ? 0 : 1 / md.I;
|
||||
b.mass = o.isStatic ? Infinity : md.mass;
|
||||
addBody(world, b);
|
||||
syncTransform(b);
|
||||
return b;
|
||||
}
|
||||
|
||||
/** Axis-aligned-at-rest box helper; `angle` still rotates it. */
|
||||
export function addBox(world, o) {
|
||||
const hw = o.w / 2;
|
||||
const hh = o.h / 2;
|
||||
return addPoly(world, {
|
||||
...o,
|
||||
verts: [[-hw, -hh], [hw, -hh], [hw, hh], [-hw, hh]],
|
||||
});
|
||||
}
|
||||
|
||||
export function addCircle(world, o) {
|
||||
const b = baseBody(o);
|
||||
b.kind = 'circle';
|
||||
b.radius = o.r;
|
||||
const mass = (o.density ?? 1) * Math.PI * o.r * o.r;
|
||||
b.invMass = o.isStatic ? 0 : 1 / mass;
|
||||
b.invI = o.isStatic ? 0 : 1 / (0.5 * mass * o.r * o.r);
|
||||
b.mass = o.isStatic ? Infinity : mass;
|
||||
addBody(world, b);
|
||||
syncTransform(b);
|
||||
return b;
|
||||
}
|
||||
|
||||
export function removeBody(world, body) {
|
||||
const i = world.bodies.indexOf(body);
|
||||
if (i >= 0) world.bodies.splice(i, 1);
|
||||
world.byId.delete(body.id);
|
||||
for (const [key, c] of [...world.contacts]) {
|
||||
if (c.aId === body.id || c.bId === body.id) world.contacts.delete(key);
|
||||
}
|
||||
world.contactList = world.contactList.filter((c) => c.aId !== body.id && c.bId !== body.id);
|
||||
}
|
||||
|
||||
// Recompute world-space verts/normals and the AABB after a transform change.
|
||||
function syncTransform(b) {
|
||||
const c = Math.cos(b.angle);
|
||||
const s = Math.sin(b.angle);
|
||||
if (b.kind === 'poly') {
|
||||
let minx = Infinity; let miny = Infinity; let maxx = -Infinity; let maxy = -Infinity;
|
||||
for (let i = 0; i < b.verts.length; i += 1) {
|
||||
const [lx, ly] = b.verts[i];
|
||||
const wx = b.x + lx * c - ly * s;
|
||||
const wy = b.y + lx * s + ly * c;
|
||||
b.wverts[i][0] = wx;
|
||||
b.wverts[i][1] = wy;
|
||||
const [nx, ny] = b.normals[i];
|
||||
b.wnormals[i][0] = nx * c - ny * s;
|
||||
b.wnormals[i][1] = nx * s + ny * c;
|
||||
if (wx < minx) minx = wx;
|
||||
if (wy < miny) miny = wy;
|
||||
if (wx > maxx) maxx = wx;
|
||||
if (wy > maxy) maxy = wy;
|
||||
}
|
||||
b.aabb.minx = minx; b.aabb.miny = miny; b.aabb.maxx = maxx; b.aabb.maxy = maxy;
|
||||
} else {
|
||||
b.aabb.minx = b.x - b.radius; b.aabb.miny = b.y - b.radius;
|
||||
b.aabb.maxx = b.x + b.radius; b.aabb.maxy = b.y + b.radius;
|
||||
}
|
||||
}
|
||||
|
||||
export function wakeBody(b) {
|
||||
if (b.isStatic) return;
|
||||
b.sleeping = false;
|
||||
b.sleepTimer = 0;
|
||||
}
|
||||
|
||||
export function applyImpulse(b, ix, iy, px, py) {
|
||||
if (b.isStatic) return;
|
||||
wakeBody(b);
|
||||
b.vx += ix * b.invMass;
|
||||
b.vy += iy * b.invMass;
|
||||
if (px !== undefined) b.omega += cross(px - b.x, py - b.y, ix, iy) * b.invI;
|
||||
}
|
||||
|
||||
// ── Broadphase ──────────────────────────────────────────────────────────────
|
||||
|
||||
// Uniform grid over AABBs, rebuilt each substep. Bodies here are large relative
|
||||
// to their per-substep travel, so a rebuild is cheaper than incremental upkeep.
|
||||
function broadphase(world) {
|
||||
const cell = PHYS.GRID_CELL;
|
||||
const grid = new Map();
|
||||
const bodies = world.bodies;
|
||||
for (let i = 0; i < bodies.length; i += 1) {
|
||||
const b = bodies[i];
|
||||
const x0 = Math.floor(b.aabb.minx / cell);
|
||||
const x1 = Math.floor(b.aabb.maxx / cell);
|
||||
const y0 = Math.floor(b.aabb.miny / cell);
|
||||
const y1 = Math.floor(b.aabb.maxy / cell);
|
||||
for (let gx = x0; gx <= x1; gx += 1) {
|
||||
for (let gy = y0; gy <= y1; gy += 1) {
|
||||
const key = cellKey(gx, gy);
|
||||
let bucket = grid.get(key);
|
||||
if (!bucket) { bucket = []; grid.set(key, bucket); }
|
||||
bucket.push(b);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const pairs = [];
|
||||
const seen = new Set();
|
||||
for (const bucket of grid.values()) {
|
||||
for (let i = 0; i < bucket.length; i += 1) {
|
||||
for (let j = i + 1; j < bucket.length; j += 1) {
|
||||
let a = bucket[i];
|
||||
let b = bucket[j];
|
||||
if (a.id > b.id) { const t = a; a = b; b = t; }
|
||||
// A pair where neither side can move produces no useful contact. A
|
||||
// sleeping body against a static one is already at rest by definition.
|
||||
if (a.isStatic && b.isStatic) continue;
|
||||
if (a.sleeping && b.sleeping) continue;
|
||||
if (a.sleeping && b.isStatic) continue;
|
||||
if (b.sleeping && a.isStatic) continue;
|
||||
const key = pairKey(a.id, b.id);
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
if (a.aabb.maxx < b.aabb.minx || b.aabb.maxx < a.aabb.minx) continue;
|
||||
if (a.aabb.maxy < b.aabb.miny || b.aabb.maxy < a.aabb.miny) continue;
|
||||
pairs.push(a, b); // flat, to avoid a per-pair array allocation
|
||||
}
|
||||
}
|
||||
}
|
||||
// Sorted so the solve order never depends on Map/Set iteration order.
|
||||
const order = [];
|
||||
for (let i = 0; i < pairs.length; i += 2) order.push(i);
|
||||
order.sort((p, q) => (pairs[p].id - pairs[q].id) || (pairs[p + 1].id - pairs[q + 1].id));
|
||||
const sorted = [];
|
||||
for (const i of order) sorted.push(pairs[i], pairs[i + 1]);
|
||||
return sorted;
|
||||
}
|
||||
|
||||
// ── Narrowphase ─────────────────────────────────────────────────────────────
|
||||
|
||||
// Largest separation of B's verts from any of A's faces. Negative => overlap.
|
||||
function maxSeparation(a, b) {
|
||||
let best = -Infinity;
|
||||
let bestFace = 0;
|
||||
for (let i = 0; i < a.wverts.length; i += 1) {
|
||||
const [nx, ny] = a.wnormals[i];
|
||||
const [vx, vy] = a.wverts[i];
|
||||
// Support point of B in direction -n: the deepest vert against this face.
|
||||
let lowest = Infinity;
|
||||
for (let j = 0; j < b.wverts.length; j += 1) {
|
||||
const d = (b.wverts[j][0] - vx) * nx + (b.wverts[j][1] - vy) * ny;
|
||||
if (d < lowest) lowest = d;
|
||||
}
|
||||
if (lowest > best) { best = lowest; bestFace = i; }
|
||||
}
|
||||
return { sep: best, face: bestFace };
|
||||
}
|
||||
|
||||
// The face of `inc` most anti-parallel to the reference normal.
|
||||
function incidentFace(inc, refNx, refNy) {
|
||||
let best = Infinity;
|
||||
let bestFace = 0;
|
||||
for (let i = 0; i < inc.wnormals.length; i += 1) {
|
||||
const d = inc.wnormals[i][0] * refNx + inc.wnormals[i][1] * refNy;
|
||||
if (d < best) { best = d; bestFace = i; }
|
||||
}
|
||||
return bestFace;
|
||||
}
|
||||
|
||||
// Clip a segment against a half-plane, keeping the portion where
|
||||
// dot(n, p) - offset <= 0. Feature ids ride along so warm starting can match
|
||||
// points across frames even when clipping order changes.
|
||||
function clipSegment(pts, nx, ny, offset) {
|
||||
const out = [];
|
||||
const d0 = pts[0].x * nx + pts[0].y * ny - offset;
|
||||
const d1 = pts[1].x * nx + pts[1].y * ny - offset;
|
||||
if (d0 <= 0) out.push(pts[0]);
|
||||
if (d1 <= 0) out.push(pts[1]);
|
||||
if (d0 * d1 < 0) {
|
||||
const t = d0 / (d0 - d1);
|
||||
out.push({
|
||||
x: pts[0].x + t * (pts[1].x - pts[0].x),
|
||||
y: pts[0].y + t * (pts[1].y - pts[0].y),
|
||||
fid: d0 > 0 ? pts[1].fid : pts[0].fid,
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function collidePolyPoly(a, b) {
|
||||
const sa = maxSeparation(a, b);
|
||||
if (sa.sep > 0) return null;
|
||||
const sb = maxSeparation(b, a);
|
||||
if (sb.sep > 0) return null;
|
||||
|
||||
// Prefer A as reference unless B is clearly deeper — the small bias keeps the
|
||||
// choice stable frame to frame, which keeps feature ids (and warm starting)
|
||||
// stable for a resting contact.
|
||||
let ref = a; let inc = b; let refFace = sa.face; let flip = false;
|
||||
if (sb.sep > sa.sep + 0.1 * Math.abs(sa.sep) + 0.01) {
|
||||
ref = b; inc = a; refFace = sb.face; flip = true;
|
||||
}
|
||||
|
||||
const [rnx, rny] = ref.wnormals[refFace];
|
||||
const rv0 = ref.wverts[refFace];
|
||||
const rv1 = ref.wverts[(refFace + 1) % ref.wverts.length];
|
||||
|
||||
const incFace = incidentFace(inc, rnx, rny);
|
||||
const iv0 = inc.wverts[incFace];
|
||||
const iv1 = inc.wverts[(incFace + 1) % inc.wverts.length];
|
||||
|
||||
// Tangent of the reference face; clip the incident edge to its side planes.
|
||||
const tx = rv1[0] - rv0[0];
|
||||
const ty = rv1[1] - rv0[1];
|
||||
const tlen = Math.hypot(tx, ty) || 1;
|
||||
const utx = tx / tlen;
|
||||
const uty = ty / tlen;
|
||||
|
||||
let pts = [
|
||||
{ x: iv0[0], y: iv0[1], fid: (refFace << 8) | incFace },
|
||||
{ x: iv1[0], y: iv1[1], fid: (refFace << 8) | ((incFace + 1) % inc.wverts.length) },
|
||||
];
|
||||
pts = clipSegment(pts, -utx, -uty, -(rv0[0] * utx + rv0[1] * uty));
|
||||
if (pts.length < 2) return null;
|
||||
pts = clipSegment(pts, utx, uty, rv1[0] * utx + rv1[1] * uty);
|
||||
if (pts.length < 2) return null;
|
||||
|
||||
const offset = rv0[0] * rnx + rv0[1] * rny;
|
||||
const points = [];
|
||||
for (const p of pts) {
|
||||
const sep = p.x * rnx + p.y * rny - offset;
|
||||
if (sep <= 0) points.push({ x: p.x, y: p.y, sep, fid: p.fid | (flip ? 0x10000 : 0) });
|
||||
}
|
||||
if (!points.length) return null;
|
||||
|
||||
// Normal must always point A -> B.
|
||||
return { nx: flip ? -rnx : rnx, ny: flip ? -rny : rny, points };
|
||||
}
|
||||
|
||||
function collideCirclePoly(c, p, circleIsA) {
|
||||
// Work in the polygon's local frame so the face tests are cheap.
|
||||
const cs = Math.cos(-p.angle);
|
||||
const sn = Math.sin(-p.angle);
|
||||
const dx = c.x - p.x;
|
||||
const dy = c.y - p.y;
|
||||
const lx = dx * cs - dy * sn;
|
||||
const ly = dx * sn + dy * cs;
|
||||
|
||||
let best = -Infinity;
|
||||
let bestFace = 0;
|
||||
for (let i = 0; i < p.verts.length; i += 1) {
|
||||
const [nx, ny] = p.normals[i];
|
||||
const [vx, vy] = p.verts[i];
|
||||
const d = (lx - vx) * nx + (ly - vy) * ny;
|
||||
if (d > c.radius) return null;
|
||||
if (d > best) { best = d; bestFace = i; }
|
||||
}
|
||||
|
||||
const [v0x, v0y] = p.verts[bestFace];
|
||||
const [v1x, v1y] = p.verts[(bestFace + 1) % p.verts.length];
|
||||
let nlx; let nly; let sep;
|
||||
|
||||
if (best < 1e-6) {
|
||||
// Centre is inside the polygon — push straight out along the closest face.
|
||||
[nlx, nly] = p.normals[bestFace];
|
||||
sep = best - c.radius;
|
||||
} else {
|
||||
// Voronoi regions: nearest to v0, to v1, or to the face interior.
|
||||
const ex = v1x - v0x;
|
||||
const ey = v1y - v0y;
|
||||
const t = clamp(((lx - v0x) * ex + (ly - v0y) * ey) / (ex * ex + ey * ey), 0, 1);
|
||||
const px = v0x + ex * t;
|
||||
const py = v0y + ey * t;
|
||||
const ddx = lx - px;
|
||||
const ddy = ly - py;
|
||||
const dist = Math.hypot(ddx, ddy);
|
||||
if (dist > c.radius) return null;
|
||||
if (dist < 1e-9) { [nlx, nly] = p.normals[bestFace]; } else { nlx = ddx / dist; nly = ddy / dist; }
|
||||
sep = dist - c.radius;
|
||||
}
|
||||
|
||||
// Back to world space. Local normal points polygon -> circle.
|
||||
const wc = Math.cos(p.angle);
|
||||
const ws = Math.sin(p.angle);
|
||||
const nwx = nlx * wc - nly * ws;
|
||||
const nwy = nlx * ws + nly * wc;
|
||||
const contactX = c.x - nwx * (c.radius + sep * 0.5);
|
||||
const contactY = c.y - nwy * (c.radius + sep * 0.5);
|
||||
|
||||
// Caller's A is `circleIsA ? c : p`; normal must run A -> B.
|
||||
const sign = circleIsA ? -1 : 1;
|
||||
return {
|
||||
nx: nwx * sign, ny: nwy * sign,
|
||||
points: [{ x: contactX, y: contactY, sep, fid: 1 }],
|
||||
};
|
||||
}
|
||||
|
||||
function collideCircleCircle(a, b) {
|
||||
const dx = b.x - a.x;
|
||||
const dy = b.y - a.y;
|
||||
const r = a.radius + b.radius;
|
||||
const d2 = dx * dx + dy * dy;
|
||||
if (d2 >= r * r) return null;
|
||||
const d = Math.sqrt(d2);
|
||||
let nx; let ny;
|
||||
if (d < 1e-9) { nx = 0; ny = -1; } else { nx = dx / d; ny = dy / d; }
|
||||
return {
|
||||
nx, ny,
|
||||
points: [{ x: a.x + nx * a.radius, y: a.y + ny * a.radius, sep: d - r, fid: 1 }],
|
||||
};
|
||||
}
|
||||
|
||||
function collide(a, b) {
|
||||
if (a.kind === 'circle' && b.kind === 'circle') return collideCircleCircle(a, b);
|
||||
if (a.kind === 'circle') return collideCirclePoly(a, b, true);
|
||||
if (b.kind === 'circle') return collideCirclePoly(b, a, false);
|
||||
return collidePolyPoly(a, b);
|
||||
}
|
||||
|
||||
// ── Contact bookkeeping ─────────────────────────────────────────────────────
|
||||
|
||||
// Rebuild manifolds, carrying accumulated impulses across from last substep by
|
||||
// feature id. This is the warm-starting half of stack stability; matching by
|
||||
// array index instead would scramble impulses the moment a clip order flips.
|
||||
function updateContacts(world, pairs) {
|
||||
const live = new Set();
|
||||
const list = [];
|
||||
for (let pi = 0; pi < pairs.length; pi += 2) {
|
||||
const a = pairs[pi];
|
||||
const b = pairs[pi + 1];
|
||||
const m = collide(a, b);
|
||||
const key = pairKey(a.id, b.id);
|
||||
if (!m) { world.contacts.delete(key); continue; }
|
||||
live.add(key);
|
||||
|
||||
const prev = world.contacts.get(key);
|
||||
const points = m.points.map((p) => {
|
||||
const old = prev?.points.find((q) => q.fid === p.fid);
|
||||
return {
|
||||
x: p.x, y: p.y, sep: p.sep, fid: p.fid,
|
||||
pn: old?.pn ?? 0, pt: old?.pt ?? 0,
|
||||
pnBias: 0, // never warm-started: position error is transient
|
||||
massNormal: 0, massTangent: 0, bias: 0, restTarget: 0,
|
||||
rax: 0, ray: 0, rbx: 0, rby: 0,
|
||||
};
|
||||
});
|
||||
const contact = {
|
||||
aId: a.id, bId: b.id, a, b,
|
||||
nx: m.nx, ny: m.ny,
|
||||
friction: Math.sqrt(a.friction * b.friction),
|
||||
restitution: Math.max(a.restitution, b.restitution),
|
||||
points,
|
||||
maxImpulse: 0, // peak accumulated |pn| — includes static load
|
||||
impactImpulse: 0, // peak approach momentum — THIS is the damage signal
|
||||
};
|
||||
world.contacts.set(key, contact);
|
||||
list.push(contact);
|
||||
}
|
||||
for (const [key] of [...world.contacts]) {
|
||||
if (!live.has(key)) world.contacts.delete(key);
|
||||
}
|
||||
// Pairs arrive pre-sorted by (aId, bId), so this list is already in the
|
||||
// canonical solve order and needs no further sorting.
|
||||
world.contactList = list;
|
||||
}
|
||||
|
||||
// The solver's contact iteration order. Never iterate world.contacts directly:
|
||||
// Map order depends on insertion history, which would make the sim depend on
|
||||
// the order bodies happened to be created in.
|
||||
function orderedContacts(world) {
|
||||
return world.contactList;
|
||||
}
|
||||
|
||||
function prestep(world, h) {
|
||||
const invH = 1 / h;
|
||||
for (const c of orderedContacts(world)) {
|
||||
const a = c.a;
|
||||
const b = c.b;
|
||||
const { nx, ny } = c;
|
||||
const tx = -ny;
|
||||
const ty = nx;
|
||||
let peakImpact = 0;
|
||||
|
||||
for (const p of c.points) {
|
||||
p.rax = p.x - a.x; p.ray = p.y - a.y;
|
||||
p.rbx = p.x - b.x; p.rby = p.y - b.y;
|
||||
|
||||
const rnA = cross(p.rax, p.ray, nx, ny);
|
||||
const rnB = cross(p.rbx, p.rby, nx, ny);
|
||||
p.massNormal = 1 / (a.invMass + b.invMass + a.invI * rnA * rnA + b.invI * rnB * rnB);
|
||||
|
||||
const rtA = cross(p.rax, p.ray, tx, ty);
|
||||
const rtB = cross(p.rbx, p.rby, tx, ty);
|
||||
p.massTangent = 1 / (a.invMass + b.invMass + a.invI * rtA * rtA + b.invI * rtB * rtB);
|
||||
|
||||
// Position error is corrected by a SEPARATE pseudo-velocity pass (split
|
||||
// impulse), not by biasing the real velocity. With plain Baumgarte the
|
||||
// steady-state penetration is proportional to the load, so the bottom
|
||||
// contact of a 10-box tower sinks ~10x deeper than the top one and the
|
||||
// stack visibly sags. Driving position through pseudo-velocities removes
|
||||
// a fixed fraction of the excess per substep regardless of load, and the
|
||||
// correction never leaks into the real velocity as bounce energy.
|
||||
p.bias = -PHYS.BAUMGARTE * invH * Math.min(0, p.sep + PHYS.SLOP);
|
||||
p.pnBias = 0;
|
||||
|
||||
// Restitution, sampled once from the APPROACH velocity. Sampling it every
|
||||
// iteration would let a resting box slowly bounce itself apart.
|
||||
const rvx = (b.vx - p.rby * b.omega) - (a.vx - p.ray * a.omega);
|
||||
const rvy = (b.vy + p.rbx * b.omega) - (a.vy + p.rax * a.omega);
|
||||
const vn = rvx * nx + rvy * ny;
|
||||
p.restTarget = vn < -PHYS.REST_THRESHOLD ? -c.restitution * vn : 0;
|
||||
|
||||
// IMPACT momentum: the impulse it would take to just stop the approach.
|
||||
//
|
||||
// This is the damage signal, and it must NOT be the solver's accumulated
|
||||
// normal impulse. That value includes the static load a contact carries,
|
||||
// which grows with stack height — measured 3.4e5 at the base of a
|
||||
// 10-block stone tower, above the threshold that should shatter wood. A
|
||||
// tower would quietly crush itself while nothing was happening. Approach
|
||||
// velocity is zero at rest by definition, so this separates "being leaned
|
||||
// on" from "being hit" for free.
|
||||
const impact = vn < 0 ? p.massNormal * -vn : 0;
|
||||
if (impact > peakImpact) peakImpact = impact;
|
||||
}
|
||||
c.impactImpulse = peakImpact;
|
||||
}
|
||||
for (const b of world.bodies) { b.psx = 0; b.psy = 0; b.psw = 0; }
|
||||
}
|
||||
|
||||
function warmStart(world) {
|
||||
for (const c of orderedContacts(world)) {
|
||||
const a = c.a;
|
||||
const b = c.b;
|
||||
const { nx, ny } = c;
|
||||
const tx = -ny;
|
||||
const ty = nx;
|
||||
for (const p of c.points) {
|
||||
const ix = p.pn * nx + p.pt * tx;
|
||||
const iy = p.pn * ny + p.pt * ty;
|
||||
if (!a.isStatic) {
|
||||
a.vx -= ix * a.invMass; a.vy -= iy * a.invMass;
|
||||
a.omega -= cross(p.rax, p.ray, ix, iy) * a.invI;
|
||||
}
|
||||
if (!b.isStatic) {
|
||||
b.vx += ix * b.invMass; b.vy += iy * b.invMass;
|
||||
b.omega += cross(p.rbx, p.rby, ix, iy) * b.invI;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function solveVelocities(world) {
|
||||
const contacts = orderedContacts(world);
|
||||
for (let iter = 0; iter < PHYS.VEL_ITERS; iter += 1) {
|
||||
for (const c of contacts) {
|
||||
const a = c.a;
|
||||
const b = c.b;
|
||||
const { nx, ny } = c;
|
||||
const tx = -ny;
|
||||
const ty = nx;
|
||||
|
||||
for (const p of c.points) {
|
||||
// Normal impulse. Accumulate then clamp to >= 0, applying only the
|
||||
// delta — clamping the per-iteration impulse instead would let a
|
||||
// contact pull bodies together.
|
||||
let rvx = (b.vx - p.rby * b.omega) - (a.vx - p.ray * a.omega);
|
||||
let rvy = (b.vy + p.rbx * b.omega) - (a.vy + p.rax * a.omega);
|
||||
const vn = rvx * nx + rvy * ny;
|
||||
let dPn = p.massNormal * (-vn + p.restTarget);
|
||||
const pn0 = p.pn;
|
||||
p.pn = Math.max(pn0 + dPn, 0);
|
||||
dPn = p.pn - pn0;
|
||||
|
||||
let ix = dPn * nx;
|
||||
let iy = dPn * ny;
|
||||
if (!a.isStatic) {
|
||||
a.vx -= ix * a.invMass; a.vy -= iy * a.invMass;
|
||||
a.omega -= cross(p.rax, p.ray, ix, iy) * a.invI;
|
||||
}
|
||||
if (!b.isStatic) {
|
||||
b.vx += ix * b.invMass; b.vy += iy * b.invMass;
|
||||
b.omega += cross(p.rbx, p.rby, ix, iy) * b.invI;
|
||||
}
|
||||
|
||||
// Split-impulse position pass, run on pseudo-velocities only.
|
||||
const pvx = (b.psx - p.rby * b.psw) - (a.psx - p.ray * a.psw);
|
||||
const pvy = (b.psy + p.rbx * b.psw) - (a.psy + p.rax * a.psw);
|
||||
const pvn = pvx * nx + pvy * ny;
|
||||
let dPb = p.massNormal * (-pvn + p.bias);
|
||||
const pb0 = p.pnBias;
|
||||
p.pnBias = Math.max(pb0 + dPb, 0);
|
||||
dPb = p.pnBias - pb0;
|
||||
|
||||
const bx = dPb * nx;
|
||||
const by = dPb * ny;
|
||||
if (!a.isStatic) {
|
||||
a.psx -= bx * a.invMass; a.psy -= by * a.invMass;
|
||||
a.psw -= cross(p.rax, p.ray, bx, by) * a.invI;
|
||||
}
|
||||
if (!b.isStatic) {
|
||||
b.psx += bx * b.invMass; b.psy += by * b.invMass;
|
||||
b.psw += cross(p.rbx, p.rby, bx, by) * b.invI;
|
||||
}
|
||||
|
||||
// Coulomb friction, clamped against the ACCUMULATED normal impulse.
|
||||
rvx = (b.vx - p.rby * b.omega) - (a.vx - p.ray * a.omega);
|
||||
rvy = (b.vy + p.rbx * b.omega) - (a.vy + p.rax * a.omega);
|
||||
const vt = rvx * tx + rvy * ty;
|
||||
let dPt = p.massTangent * -vt;
|
||||
const maxPt = c.friction * p.pn;
|
||||
const pt0 = p.pt;
|
||||
p.pt = clamp(pt0 + dPt, -maxPt, maxPt);
|
||||
dPt = p.pt - pt0;
|
||||
|
||||
ix = dPt * tx;
|
||||
iy = dPt * ty;
|
||||
if (!a.isStatic) {
|
||||
a.vx -= ix * a.invMass; a.vy -= iy * a.invMass;
|
||||
a.omega -= cross(p.rax, p.ray, ix, iy) * a.invI;
|
||||
}
|
||||
if (!b.isStatic) {
|
||||
b.vx += ix * b.invMass; b.vy += iy * b.invMass;
|
||||
b.omega += cross(p.rbx, p.rby, ix, iy) * b.invI;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const c of contacts) {
|
||||
let peak = 0;
|
||||
for (const p of c.points) if (p.pn > peak) peak = p.pn;
|
||||
c.maxImpulse = peak;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Islands and sleeping ────────────────────────────────────────────────────
|
||||
|
||||
// Union-find over contacts between dynamic bodies. An island sleeps only when
|
||||
// every member has been slow for SLEEP_TIME — per-body sleeping would freeze
|
||||
// half a tower while the rest still moves.
|
||||
function updateSleeping(world, h) {
|
||||
const parent = new Map();
|
||||
const find = (x) => {
|
||||
let r = x;
|
||||
while (parent.get(r) !== r) r = parent.get(r);
|
||||
while (parent.get(x) !== r) { const nx = parent.get(x); parent.set(x, r); x = nx; }
|
||||
return r;
|
||||
};
|
||||
const union = (x, y) => {
|
||||
const rx = find(x);
|
||||
const ry = find(y);
|
||||
if (rx !== ry) parent.set(rx > ry ? rx : ry, rx > ry ? ry : rx);
|
||||
};
|
||||
|
||||
for (const b of world.bodies) if (!b.isStatic) parent.set(b.id, b.id);
|
||||
for (const c of orderedContacts(world)) {
|
||||
const a = c.a;
|
||||
const b = c.b;
|
||||
if (!a.isStatic && !b.isStatic) union(a.id, b.id);
|
||||
}
|
||||
|
||||
// Per-body slow timer.
|
||||
for (const b of world.bodies) {
|
||||
if (b.isStatic || b.sleeping) continue;
|
||||
const slow = Math.hypot(b.vx, b.vy) < PHYS.SLEEP_LIN && Math.abs(b.omega) < PHYS.SLEEP_ANG;
|
||||
b.sleepTimer = slow ? b.sleepTimer + h : 0;
|
||||
}
|
||||
|
||||
// An island's timer is its slowest member's.
|
||||
const islandTimer = new Map();
|
||||
for (const b of world.bodies) {
|
||||
if (b.isStatic) continue;
|
||||
const root = find(b.id);
|
||||
const t = b.sleeping ? Infinity : b.sleepTimer;
|
||||
const cur = islandTimer.get(root);
|
||||
if (cur === undefined || t < cur) islandTimer.set(root, t);
|
||||
}
|
||||
|
||||
for (const b of world.bodies) {
|
||||
if (b.isStatic) continue;
|
||||
const t = islandTimer.get(find(b.id)) ?? 0;
|
||||
if (t >= PHYS.SLEEP_TIME) {
|
||||
b.sleeping = true;
|
||||
b.vx = 0; b.vy = 0; b.omega = 0;
|
||||
} else if (t < PHYS.SLEEP_TIME && b.sleeping) {
|
||||
// A neighbour woke up; the whole island comes with it.
|
||||
b.sleeping = false;
|
||||
b.sleepTimer = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Integration ─────────────────────────────────────────────────────────────
|
||||
|
||||
function integrateVelocities(world, h) {
|
||||
for (const b of world.bodies) {
|
||||
if (b.isStatic || b.sleeping) continue;
|
||||
b.vy += world.gravity * h;
|
||||
b.vx *= 1 - PHYS.LINEAR_DAMPING;
|
||||
b.vy *= 1 - PHYS.LINEAR_DAMPING;
|
||||
b.omega *= 1 - PHYS.ANGULAR_DAMPING;
|
||||
}
|
||||
}
|
||||
|
||||
function integratePositions(world, h) {
|
||||
for (const b of world.bodies) {
|
||||
if (b.isStatic || b.sleeping) continue;
|
||||
const sp = Math.hypot(b.vx, b.vy);
|
||||
if (sp > PHYS.MAX_SPEED) { const k = PHYS.MAX_SPEED / sp; b.vx *= k; b.vy *= k; }
|
||||
b.omega = clamp(b.omega, -PHYS.MAX_OMEGA, PHYS.MAX_OMEGA);
|
||||
// Pseudo-velocity moves the body but is then discarded, so position error
|
||||
// is repaired without the correction showing up as momentum next substep.
|
||||
b.x += (b.vx + b.psx) * h;
|
||||
b.y += (b.vy + b.psy) * h;
|
||||
b.angle += (b.omega + b.psw) * h;
|
||||
b.psx = 0; b.psy = 0; b.psw = 0;
|
||||
syncTransform(b);
|
||||
}
|
||||
}
|
||||
|
||||
// ── The frame ───────────────────────────────────────────────────────────────
|
||||
|
||||
export function substep(world, h) {
|
||||
integrateVelocities(world, h);
|
||||
const pairs = broadphase(world);
|
||||
updateContacts(world, pairs);
|
||||
prestep(world, h);
|
||||
warmStart(world);
|
||||
solveVelocities(world);
|
||||
integratePositions(world, h);
|
||||
updateSleeping(world, h);
|
||||
world.time += h;
|
||||
}
|
||||
|
||||
/**
|
||||
* Advance by `dt` seconds in whole fixed substeps. Any leftover is carried in
|
||||
* world.accum, which is what makes 1/60 and 1/120 frames produce identical
|
||||
* trajectories — the property tools/verifyAngryBirds.js asserts.
|
||||
*/
|
||||
export function step(world, dt) {
|
||||
world.accum += Math.min(dt, 0.05); // a backgrounded tab must not teleport
|
||||
let steps = 0;
|
||||
while (world.accum >= PHYS.SUBSTEP_DT && steps < 16) {
|
||||
substep(world, PHYS.SUBSTEP_DT);
|
||||
world.accum -= PHYS.SUBSTEP_DT;
|
||||
steps += 1;
|
||||
}
|
||||
return steps;
|
||||
}
|
||||
|
||||
/** True when nothing is moving — the rules layer's "shot is over" test. */
|
||||
export function isSettled(world) {
|
||||
for (const b of world.bodies) {
|
||||
if (b.isStatic) continue;
|
||||
if (!b.sleeping) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Peak normal impulse seen on each body this substep, keyed by body id. */
|
||||
export function contactImpulses(world) {
|
||||
const out = new Map();
|
||||
for (const c of world.contacts.values()) {
|
||||
if (c.maxImpulse <= 0) continue;
|
||||
for (const id of [c.aId, c.bId]) {
|
||||
const cur = out.get(id) ?? 0;
|
||||
if (c.maxImpulse > cur) out.set(id, c.maxImpulse);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Radial impulse + falloff, used by Bomb and TNT. Returns bodies affected. */
|
||||
export function applyExplosion(world, x, y, radius, power) {
|
||||
const hit = [];
|
||||
for (const b of world.bodies) {
|
||||
if (b.isStatic) continue;
|
||||
const dx = b.x - x;
|
||||
const dy = b.y - y;
|
||||
const d = Math.hypot(dx, dy);
|
||||
if (d > radius) continue;
|
||||
const falloff = 1 - d / radius;
|
||||
const nx = d < 1e-6 ? 0 : dx / d;
|
||||
const ny = d < 1e-6 ? -1 : dy / d;
|
||||
const j = power * falloff * b.mass;
|
||||
applyImpulse(b, nx * j, ny * j, b.x, b.y);
|
||||
hit.push({ body: b, falloff, dist: d });
|
||||
}
|
||||
return hit;
|
||||
}
|
||||
|
||||
// ── Determinism helpers ─────────────────────────────────────────────────────
|
||||
|
||||
export function cloneWorld(world) {
|
||||
const copy = createWorld({ gravity: world.gravity });
|
||||
copy.nextId = world.nextId;
|
||||
copy.accum = world.accum;
|
||||
copy.time = world.time;
|
||||
for (const b of world.bodies) {
|
||||
const nb = { ...b, aabb: { ...b.aabb } };
|
||||
if (b.kind === 'poly') {
|
||||
nb.verts = b.verts.map((v) => [v[0], v[1]]);
|
||||
nb.normals = b.normals.map((v) => [v[0], v[1]]);
|
||||
nb.wverts = b.wverts.map((v) => [v[0], v[1]]);
|
||||
nb.wnormals = b.wnormals.map((v) => [v[0], v[1]]);
|
||||
}
|
||||
copy.bodies.push(nb);
|
||||
copy.byId.set(nb.id, nb);
|
||||
}
|
||||
// Contacts cache direct body references for speed, so a shallow spread would
|
||||
// leave the clone's contacts pointing at the ORIGINAL world's bodies — the
|
||||
// clone would silently drive the thing it was supposed to leave untouched.
|
||||
// Rewire every reference through the copy's id map.
|
||||
for (const [key, c] of world.contacts) {
|
||||
copy.contacts.set(key, {
|
||||
...c,
|
||||
a: copy.byId.get(c.aId),
|
||||
b: copy.byId.get(c.bId),
|
||||
points: c.points.map((p) => ({ ...p })),
|
||||
});
|
||||
}
|
||||
copy.contactList = world.contactList.map((c) => copy.contacts.get(pairKey(c.aId, c.bId))).filter(Boolean);
|
||||
return copy;
|
||||
}
|
||||
|
||||
// FNV-1a over the Float64 bit patterns of every body's transform and velocity.
|
||||
// Hashing the bits rather than rounded values means a 1-ULP divergence still
|
||||
// shows up, which is the point.
|
||||
export function hashWorld(world) {
|
||||
const buf = new ArrayBuffer(8);
|
||||
const f64 = new Float64Array(buf);
|
||||
const u32 = new Uint32Array(buf);
|
||||
let h = 0x811c9dc5;
|
||||
const mix = (v) => {
|
||||
f64[0] = v;
|
||||
for (let i = 0; i < 2; i += 1) {
|
||||
h ^= u32[i];
|
||||
h = Math.imul(h, 0x01000193) >>> 0;
|
||||
}
|
||||
};
|
||||
const sorted = [...world.bodies].sort((a, b) => a.id - b.id);
|
||||
for (const b of sorted) {
|
||||
mix(b.x); mix(b.y); mix(b.angle);
|
||||
mix(b.vx); mix(b.vy); mix(b.omega);
|
||||
mix(b.sleeping ? 1 : 0);
|
||||
}
|
||||
return h >>> 0;
|
||||
}
|
||||
|
||||
/** Run until everything sleeps (or `maxSeconds` elapses). Used by the editor. */
|
||||
export function settle(world, maxSeconds = 10) {
|
||||
const limit = Math.ceil(maxSeconds / PHYS.SUBSTEP_DT);
|
||||
for (let i = 0; i < limit; i += 1) {
|
||||
substep(world, PHYS.SUBSTEP_DT);
|
||||
if (isSettled(world)) return true;
|
||||
}
|
||||
return isSettled(world);
|
||||
}
|
||||
|
|
@ -25,33 +25,9 @@ const GRASS_DARK = 0x3f7d28;
|
|||
const GRASS_INSET = DIRT_STROKE_W; // keeps the whole accent stroke visible; grass starts past it
|
||||
const GRASS_DEPTH = 15; // how far the patchy band reaches down into the dirt, beyond the inset
|
||||
const GRASS_SEG = 20; // approx width of one grass patch, in px
|
||||
// Spikes -- gunmetal plate with faceted steel teeth stamped on every outward
|
||||
// edge. SPIKE_LIGHT_DIR is a fixed "sun" used to pick which facet of each
|
||||
// tooth reads as lit vs shadowed, regardless of which way the edge faces.
|
||||
const SPIKE_BASE = 0x3a4250;
|
||||
const SPIKE_BASE_DARK = 0x1f232b;
|
||||
const SPIKE_BASE_EDGE_HI = 0x788597;
|
||||
const SPIKE_BASE_EDGE_LO = 0x13151a;
|
||||
const SPIKE_TOOTH_LIGHT = 0xcdd9e6;
|
||||
const SPIKE_TOOTH_DARK = 0x4a5262;
|
||||
const SPIKE_RIVET = 0x14161b;
|
||||
const SPIKE_RIVET_HI = 0x9aa5b4;
|
||||
const SPIKE_RUST = 0x8a5a3a;
|
||||
const SPIKE_GLINT = 0xf3fbff;
|
||||
const SPIKE_LIGHT_DIR = { x: -0.55, y: -0.83 };
|
||||
const SPIKE_TOOTH_LEN = 20;
|
||||
const SPIKE_TOOTH_STEP = 24;
|
||||
|
||||
// Fire/lava -- layered heat gradient (crust rim -> white-hot core) with an
|
||||
// animated surface: drifting flow streaks and rising/popping bubbles.
|
||||
const LAVA_CRUST = 0x2a1410;
|
||||
const LAVA_CRUST_EDGE = 0x140a08;
|
||||
const LAVA_OUTER = 0x8a2410;
|
||||
const LAVA_MID = 0xd4642a;
|
||||
const LAVA_HOT = 0xf59a3c;
|
||||
const LAVA_CORE = 0xffe9a8;
|
||||
const LAVA_FLOW_LINE = 0xffb459;
|
||||
const LAVA_BUBBLE = 0xffd98a;
|
||||
const SPIKE = 0x7d3550;
|
||||
const SPIKE_RIM = 0xd46a8c;
|
||||
const FIRE = 0xd4642a;
|
||||
const STRAND = 0x1c1626;
|
||||
const STRAND_HOT = 0xff5a4a;
|
||||
const PIPE_BODY = 0x3d5a6c;
|
||||
|
|
@ -127,10 +103,7 @@ const hash01 = (n) => {
|
|||
// Splits a terrain polygon into edges tagged with their true outward normal
|
||||
// (found via the centroid, so it works regardless of winding order) and
|
||||
// whether that edge faces up -- i.e. is exposed ground a grass patch belongs
|
||||
// on, as opposed to a side or the underside. Despite the historical name,
|
||||
// every edge is returned (not just top-facing ones): callers that only want
|
||||
// the top filter on `.top` themselves; spike teeth and lava crust want all of
|
||||
// them.
|
||||
// on, as opposed to a side or the underside.
|
||||
function topFacingEdges(poly) {
|
||||
const n = poly.length;
|
||||
let cx = 0, cy = 0;
|
||||
|
|
@ -150,32 +123,6 @@ function topFacingEdges(poly) {
|
|||
return edges;
|
||||
}
|
||||
|
||||
function polyCentroid(poly) {
|
||||
let cx = 0, cy = 0;
|
||||
for (const [x, y] of poly) { cx += x; cy += y; }
|
||||
return { x: cx / poly.length, y: cy / poly.length };
|
||||
}
|
||||
|
||||
// Shrinks a polygon toward a center point by factor f (1 = unchanged, 0 =
|
||||
// collapsed to the point). Used to fake a soft radial "hot core" gradient on
|
||||
// lava by layering a few of these, each hotter and more shrunk than the last,
|
||||
// instead of one flat fill.
|
||||
function scalePoly(poly, cx, cy, f) {
|
||||
return poly.map(([x, y]) => [cx + (x - cx) * f, cy + (y - cy) * f]);
|
||||
}
|
||||
|
||||
// The outward-facing unit normal of edge p0->p1, chosen to point away from
|
||||
// `insidePt` -- used to shade a tooth's two facets against a fixed light
|
||||
// direction regardless of which way the tooth itself is pointing.
|
||||
function edgeNormalAway(p0, p1, insidePt) {
|
||||
const ex = p1.x - p0.x, ey = p1.y - p0.y;
|
||||
const len = Math.hypot(ex, ey) || 1;
|
||||
let nx = -ey / len, ny = ex / len;
|
||||
const mx = (p0.x + p1.x) / 2, my = (p0.y + p1.y) / 2;
|
||||
if ((insidePt.x - mx) * nx + (insidePt.y - my) * ny > 0) { nx = -nx; ny = -ny; }
|
||||
return { x: nx, y: ny };
|
||||
}
|
||||
|
||||
// Standard ray-cast point-in-polygon test, used to clip the dirt-fleck
|
||||
// texture to a terrain piece's actual shape rather than its bounding box --
|
||||
// most pieces are simple rectangles/trapezoids, but this keeps flecks from
|
||||
|
|
@ -583,11 +530,12 @@ export default class GooTowerGame extends Phaser.Scene {
|
|||
if (e.top) this.drawGrassEdge(g, e);
|
||||
}
|
||||
} else if (t.kind === 'spike') {
|
||||
this.drawSpikeBase(g, t);
|
||||
g.fillStyle(SPIKE, 1);
|
||||
g.fillPoints(pts, true);
|
||||
this.drawTeeth(g, t);
|
||||
this.drawMetalGrit(g, t);
|
||||
} else if (t.kind === 'fire') {
|
||||
this.drawLavaBase(g, t);
|
||||
g.fillStyle(FIRE, 0.75);
|
||||
g.fillPoints(pts, true);
|
||||
}
|
||||
if (t.destructible) {
|
||||
// Cross-hatch marks rock a blast can open.
|
||||
|
|
@ -698,225 +646,29 @@ export default class GooTowerGame extends Phaser.Scene {
|
|||
}
|
||||
}
|
||||
|
||||
// Gunmetal plate under the teeth: a dark base, a soft highlight blob
|
||||
// pulled toward the fixed light direction so it doesn't read as flat, and
|
||||
// a bright/dark rim stroke on whichever edges face toward/away from that
|
||||
// light -- the same trick drawTeeth uses per-tooth, applied to the plate.
|
||||
drawSpikeBase(g, t) {
|
||||
const pts = t.poly.map(([x, y]) => ({ x, y }));
|
||||
const c = polyCentroid(t.poly);
|
||||
g.fillStyle(SPIKE_BASE_DARK, 1);
|
||||
g.fillPoints(pts, true);
|
||||
const hiPts = scalePoly(
|
||||
t.poly, c.x + SPIKE_LIGHT_DIR.x * 14, c.y + SPIKE_LIGHT_DIR.y * 14, 0.62,
|
||||
).map(([x, y]) => ({ x, y }));
|
||||
g.fillStyle(SPIKE_BASE, 0.55);
|
||||
g.fillPoints(hiPts, true);
|
||||
for (const e of topFacingEdges(t.poly)) {
|
||||
const lit = e.nx * SPIKE_LIGHT_DIR.x + e.ny * SPIKE_LIGHT_DIR.y;
|
||||
if (lit > 0.3) { g.lineStyle(2, SPIKE_BASE_EDGE_HI, 0.8); g.lineBetween(e.ax, e.ay, e.bx, e.by); }
|
||||
else if (lit < -0.3) { g.lineStyle(2, SPIKE_BASE_EDGE_LO, 0.8); g.lineBetween(e.ax, e.ay, e.bx, e.by); }
|
||||
}
|
||||
}
|
||||
|
||||
// Spikes read as spikes because of the teeth, not the fill colour. Unlike
|
||||
// the old version, teeth are stamped along EVERY outward edge (via
|
||||
// topFacingEdges' true per-edge normal), not just horizontal ones, so a
|
||||
// block bristles on every side that faces open air. Each tooth is split
|
||||
// into two facets -- (p0, mid, tip) and (mid, p1, tip) -- shaded against a
|
||||
// fixed light direction via edgeNormalAway, so it reads as a faceted steel
|
||||
// point instead of a flat silhouette regardless of which way it points.
|
||||
// Tip world positions are cached on the piece for drawSpikeTwinkle.
|
||||
// Spikes read as spikes because of the teeth, not the fill colour. Teeth are
|
||||
// stamped along whichever edge faces away from the polygon's interior.
|
||||
drawTeeth(g, t) {
|
||||
const tips = [];
|
||||
for (const e of topFacingEdges(t.poly)) {
|
||||
const dx = e.bx - e.ax, dy = e.by - e.ay;
|
||||
const len = Math.hypot(dx, dy);
|
||||
if (len < 1) continue;
|
||||
const n = Math.max(1, Math.round(len / SPIKE_TOOTH_STEP));
|
||||
const poly = t.poly;
|
||||
const cy = poly.reduce((s, p) => s + p[1], 0) / poly.length;
|
||||
g.fillStyle(SPIKE_RIM, 1);
|
||||
for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
|
||||
const [ax, ay] = poly[j];
|
||||
const [bx, by] = poly[i];
|
||||
const mid = (ay + by) / 2;
|
||||
if (Math.abs(ay - by) > 4) continue; // only horizontal edges
|
||||
const up = mid < cy ? -1 : 1; // point away from the middle
|
||||
const len = Math.abs(bx - ax);
|
||||
const n = Math.max(2, Math.round(len / 26));
|
||||
const step = (bx - ax) / n;
|
||||
for (let k = 0; k < n; k += 1) {
|
||||
const p0 = { x: e.ax + dx * (k / n), y: e.ay + dy * (k / n) };
|
||||
const p1 = { x: e.ax + dx * ((k + 1) / n), y: e.ay + dy * ((k + 1) / n) };
|
||||
const mid = { x: (p0.x + p1.x) / 2, y: (p0.y + p1.y) / 2 };
|
||||
const tip = { x: mid.x + e.nx * SPIKE_TOOTH_LEN, y: mid.y + e.ny * SPIKE_TOOTH_LEN };
|
||||
tips.push({ x: tip.x, y: tip.y, seed: hash01(tip.x * 0.13 + tip.y * 0.29) });
|
||||
|
||||
const n1 = edgeNormalAway(p0, tip, mid);
|
||||
const n2 = edgeNormalAway(tip, p1, mid);
|
||||
const lit1 = n1.x * SPIKE_LIGHT_DIR.x + n1.y * SPIKE_LIGHT_DIR.y;
|
||||
const lit2 = n2.x * SPIKE_LIGHT_DIR.x + n2.y * SPIKE_LIGHT_DIR.y;
|
||||
g.fillStyle(lit1 >= lit2 ? SPIKE_TOOTH_LIGHT : SPIKE_TOOTH_DARK, 1);
|
||||
g.fillTriangle(p0.x, p0.y, mid.x, mid.y, tip.x, tip.y);
|
||||
g.fillStyle(lit1 >= lit2 ? SPIKE_TOOTH_DARK : SPIKE_TOOTH_LIGHT, 1);
|
||||
g.fillTriangle(mid.x, mid.y, p1.x, p1.y, tip.x, tip.y);
|
||||
g.lineStyle(1, SPIKE_BASE_EDGE_LO, 0.5);
|
||||
g.lineBetween(p0.x, p0.y, p1.x, p1.y);
|
||||
|
||||
// A rivet stamped into the plate at most tooth bases, inset along
|
||||
// the inward normal so it sits on the metal, not floating past it.
|
||||
if (hash01(mid.x * 0.07 + mid.y * 0.11) > 0.4) {
|
||||
const rx = mid.x - e.nx * 7, ry = mid.y - e.ny * 7;
|
||||
g.fillStyle(SPIKE_RIVET, 1);
|
||||
g.fillCircle(rx, ry, 2.4);
|
||||
g.fillStyle(SPIKE_RIVET_HI, 0.8);
|
||||
g.fillCircle(rx - 0.6, ry - 0.6, 0.9);
|
||||
}
|
||||
}
|
||||
}
|
||||
t._teethTips = tips;
|
||||
}
|
||||
|
||||
// Rust speckling + fine scratches, reusing the dirt-fleck clipping trick
|
||||
// (drawDirtTexture) so grit stays inside the plate's actual silhouette.
|
||||
drawMetalGrit(g, t) {
|
||||
const bb = t.bounds;
|
||||
const STEP = 26;
|
||||
for (let gx = bb.minX; gx < bb.maxX; gx += STEP) {
|
||||
for (let gy = bb.minY; gy < bb.maxY; gy += STEP) {
|
||||
const seed = gx * 0.053 + gy * 0.091;
|
||||
if (hash01(seed) < 0.72) continue;
|
||||
const jx = gx + (hash01(seed + 1.3) - 0.5) * STEP * 0.8;
|
||||
const jy = gy + (hash01(seed + 2.7) - 0.5) * STEP * 0.8;
|
||||
if (!pointInPoly(jx, jy, t.poly)) continue;
|
||||
if (hash01(seed + 3.1) < 0.5) {
|
||||
g.fillStyle(SPIKE_RUST, 0.3);
|
||||
g.fillCircle(jx, jy, 1.5 + hash01(seed + 4.2) * 1.8);
|
||||
} else {
|
||||
const ang = hash01(seed + 5.5) * Math.PI;
|
||||
const len = 4 + hash01(seed + 6.6) * 5;
|
||||
g.lineStyle(1, SPIKE_TOOTH_LIGHT, 0.12);
|
||||
g.lineBetween(
|
||||
jx - Math.cos(ang) * len / 2, jy - Math.sin(ang) * len / 2,
|
||||
jx + Math.cos(ang) * len / 2, jy + Math.sin(ang) * len / 2,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Molten pool: a layered heat gradient (crust rim -> white-hot core) faked
|
||||
// with a few polygons shrunk toward the centroid via scalePoly instead of a
|
||||
// real radial gradient, topped with jagged "broken crust" chunks along
|
||||
// every edge with glowing seams between them. Also seeds the flow-lane and
|
||||
// bubble-slot data drawLavaFlow animates every frame.
|
||||
drawLavaBase(g, t) {
|
||||
const pts = t.poly.map(([x, y]) => ({ x, y }));
|
||||
const c = polyCentroid(t.poly);
|
||||
g.fillStyle(LAVA_CRUST, 1);
|
||||
g.fillPoints(pts, true);
|
||||
const layers = [
|
||||
{ f: 0.86, color: LAVA_OUTER },
|
||||
{ f: 0.62, color: LAVA_MID },
|
||||
{ f: 0.36, color: LAVA_HOT },
|
||||
{ f: 0.16, color: LAVA_CORE },
|
||||
];
|
||||
for (const layer of layers) {
|
||||
const lp = scalePoly(t.poly, c.x, c.y, layer.f).map(([x, y]) => ({ x, y }));
|
||||
g.fillStyle(layer.color, 1);
|
||||
g.fillPoints(lp, true);
|
||||
}
|
||||
|
||||
for (const e of topFacingEdges(t.poly)) {
|
||||
const dx = e.bx - e.ax, dy = e.by - e.ay;
|
||||
const len = Math.hypot(dx, dy);
|
||||
if (len < 1) continue;
|
||||
const seed = e.ax * 0.11 + e.ay * 0.19 + e.bx * 0.07 + e.by * 0.23;
|
||||
const n = Math.max(1, Math.round(len / 30));
|
||||
for (let k = 0; k < n; k += 1) {
|
||||
const s = seed + k * 5.31;
|
||||
if (hash01(s + 2.2) < 0.2) continue; // occasional gap: a wider crack of bare lava
|
||||
const depth = 8 + hash01(s) * 10;
|
||||
const p0 = { x: e.ax + dx * (k / n), y: e.ay + dy * (k / n) };
|
||||
const p1 = { x: e.ax + dx * ((k + 1) / n), y: e.ay + dy * ((k + 1) / n) };
|
||||
const q0 = { x: p0.x - e.nx * depth, y: p0.y - e.ny * depth };
|
||||
const q1 = { x: p1.x - e.nx * depth, y: p1.y - e.ny * depth };
|
||||
g.fillStyle(LAVA_CRUST, 0.9);
|
||||
g.fillPoints([p0, p1, q1, q0], true);
|
||||
g.lineStyle(1.5, LAVA_FLOW_LINE, 0.55);
|
||||
g.lineBetween(p0.x, p0.y, q0.x, q0.y);
|
||||
}
|
||||
}
|
||||
|
||||
const bb = t.bounds;
|
||||
const laneCount = Math.max(2, Math.round((bb.maxX - bb.minX) / 40));
|
||||
const lanes = [];
|
||||
for (let i = 0; i < laneCount; i += 1) {
|
||||
const s = i * 3.7 + bb.minX * 0.01;
|
||||
lanes.push({
|
||||
y: bb.minY + (bb.maxY - bb.minY) * (0.25 + 0.5 * hash01(s)),
|
||||
speed: 14 + hash01(s + 1) * 10,
|
||||
amp: 3 + hash01(s + 2) * 4,
|
||||
freq: 0.02 + hash01(s + 3) * 0.02,
|
||||
phase: hash01(s + 4) * Math.PI * 2,
|
||||
dir: hash01(s + 5) < 0.5 ? 1 : -1,
|
||||
});
|
||||
}
|
||||
t._lavaLanes = lanes;
|
||||
|
||||
const area = (bb.maxX - bb.minX) * (bb.maxY - bb.minY);
|
||||
const bubbleCount = Math.max(2, Math.round(area / 4500));
|
||||
const bubbles = [];
|
||||
for (let i = 0; i < bubbleCount; i += 1) {
|
||||
const s = i * 5.3 + bb.minY * 0.017;
|
||||
bubbles.push({
|
||||
x: bb.minX + (bb.maxX - bb.minX) * hash01(s),
|
||||
y: bb.minY + (bb.maxY - bb.minY) * (0.3 + 0.5 * hash01(s + 1)),
|
||||
period: 1.4 + hash01(s + 2) * 1.8,
|
||||
offset: hash01(s + 3) * 10,
|
||||
maxR: 3 + hash01(s + 4) * 4,
|
||||
});
|
||||
}
|
||||
t._lavaBubbles = bubbles;
|
||||
}
|
||||
|
||||
// A handful of tooth tips catch a bright glint at a time, cycling on
|
||||
// desynced per-tip timers via `time` (the sim clock) -- reads as light
|
||||
// twinkling off steel points rather than a static texture.
|
||||
drawSpikeTwinkle(g, t, time) {
|
||||
const tips = t._teethTips;
|
||||
if (!tips) return;
|
||||
for (const tip of tips) {
|
||||
const phase = (time * 0.35 + tip.seed * 6.28) % (Math.PI * 2);
|
||||
const bright = Math.pow(Math.max(0, Math.sin(phase)), 10); // sharp, brief peak
|
||||
if (bright < 0.05) continue;
|
||||
g.fillStyle(SPIKE_GLINT, bright * 0.9);
|
||||
g.fillCircle(tip.x, tip.y, 2 + bright * 1.5);
|
||||
}
|
||||
}
|
||||
|
||||
// Drifting wavy flow-streaks (per-lane sine offset scrolling over time) and
|
||||
// rising/popping bubbles, animated each frame from the slots drawLavaBase
|
||||
// seeded once per piece.
|
||||
drawLavaFlow(g, t, time) {
|
||||
const lanes = t._lavaLanes;
|
||||
const bb = t.bounds;
|
||||
if (lanes) {
|
||||
for (const lane of lanes) {
|
||||
const linePts = [];
|
||||
const steps = 10;
|
||||
for (let i = 0; i <= steps; i += 1) {
|
||||
const x = bb.minX + (bb.maxX - bb.minX) * (i / steps);
|
||||
const y = lane.y + Math.sin(x * lane.freq + time * lane.speed * lane.dir + lane.phase) * lane.amp;
|
||||
if (pointInPoly(x, y, t.poly)) linePts.push({ x, y });
|
||||
}
|
||||
if (linePts.length > 1) {
|
||||
g.lineStyle(2, LAVA_FLOW_LINE, 0.4);
|
||||
g.strokePoints(linePts, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
const bubbles = t._lavaBubbles;
|
||||
if (bubbles) {
|
||||
for (const b of bubbles) {
|
||||
const phase = ((time + b.offset) % b.period) / b.period;
|
||||
let r, a;
|
||||
if (phase < 0.7) { r = b.maxR * (phase / 0.7); a = 0.8; }
|
||||
else { r = b.maxR * (1 - (phase - 0.7) / 0.3); a = 0.8 * (1 - (phase - 0.7) / 0.3); }
|
||||
if (r <= 0.3) continue;
|
||||
g.fillStyle(LAVA_BUBBLE, a);
|
||||
g.fillCircle(b.x, b.y - r * 0.3, r);
|
||||
g.lineStyle(1, LAVA_CORE, a * 0.7);
|
||||
g.strokeCircle(b.x, b.y - r * 0.3, r);
|
||||
const x0 = ax + step * k;
|
||||
const x1 = x0 + step;
|
||||
g.fillTriangle(
|
||||
x0, mid,
|
||||
x1, mid,
|
||||
(x0 + x1) / 2, mid + up * 20,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1169,13 +921,6 @@ export default class GooTowerGame extends Phaser.Scene {
|
|||
this.drawGears(g);
|
||||
}
|
||||
|
||||
// Spike glints and lava flow/bubbles animate every frame off the sim
|
||||
// clock, layered on top of the static plate/pool fill drawn in terrainG.
|
||||
for (const tr of st.terrain) {
|
||||
if (tr.kind === 'spike') this.drawSpikeTwinkle(g, tr, st.clock);
|
||||
else if (tr.kind === 'fire') this.drawLavaFlow(g, tr, st.clock);
|
||||
}
|
||||
|
||||
// Strands first, under the balls — drawn as pinched goo shapes (thick
|
||||
// at the ends, thin in the middle with curved edges).
|
||||
for (const s of st.strands) {
|
||||
|
|
|
|||
|
|
@ -1,802 +0,0 @@
|
|||
// Worms — the Phaser scene.
|
||||
//
|
||||
// Holds no rules. It drives WormsLogic with input, replays the event list the
|
||||
// simulation returns as camera moves, sound and particles, and draws the world.
|
||||
// Anything that decides an outcome belongs in WormsLogic, so the verifier can
|
||||
// reach it.
|
||||
|
||||
import * as Phaser from 'phaser';
|
||||
import { GAME_WIDTH, GAME_HEIGHT, COLORS } from '../../config.js';
|
||||
import { Button } from '../../ui/Button.js';
|
||||
import { addFullscreenButton } from '../../ui/FullscreenButton.js';
|
||||
import { MusicPlayer } from '../../ui/MusicPlayer.js';
|
||||
import { getGameSoundtrack } from '../../services/soundtrack.js';
|
||||
import { SFX, playSound, playSoundEx } from '../../ui/Sounds.js';
|
||||
|
||||
import { MAP_SIZES } from './WormsTerrain.js';
|
||||
import { fireRope, releaseRope } from './WormsPhysics.js';
|
||||
import { THEMES, getTheme } from './WormsThemes.js';
|
||||
import { getWeapon } from './WormsWeapons.js';
|
||||
import {
|
||||
createMatch, stepMatch, activeWorm, canAct, availableWeapons, livingWorms,
|
||||
teamHealth, setMove, setRopeInput, setAim, jump, selectWeapon, setFuse,
|
||||
beginCharge, fire,
|
||||
} from './WormsLogic.js';
|
||||
import {
|
||||
makeTerrainSurface, makeBackdrop, drawWorms, drawWormLabels, drawObjects,
|
||||
drawRope, drawWater, spawnExplosion, spawnDamageNumber, spawnTracer,
|
||||
} from './WormsRender.js';
|
||||
|
||||
const MODES = [
|
||||
{ id: 'ai', label: '1 PLAYER vs COMPUTER' },
|
||||
{ id: 'hotseat', label: '2 PLAYER HOTSEAT' },
|
||||
];
|
||||
|
||||
const TEAM_COLORS = [0xe05a4a, 0x4a8fe0, 0x5ac86a, 0xe0c04a];
|
||||
const TEAM_NAMES = ['Red', 'Blue', 'Green', 'Gold'];
|
||||
|
||||
const FONT = '"Julius Sans One"';
|
||||
|
||||
export default class WormsGame extends Phaser.Scene {
|
||||
constructor() { super('WormsGame'); }
|
||||
|
||||
init(data) {
|
||||
this.gameDef = data?.game ?? { slug: 'worms', name: 'Worms' };
|
||||
this.mode = 'ai';
|
||||
this.state = null;
|
||||
this.surface = null;
|
||||
this.music = null;
|
||||
this.screenObjs = [];
|
||||
this.worldObjs = [];
|
||||
this.hudObjs = [];
|
||||
this.setup = {
|
||||
theme: 'forest',
|
||||
shape: 'island',
|
||||
size: 'medium',
|
||||
wormsPerTeam: 4,
|
||||
difficulty: 3,
|
||||
teams: 2,
|
||||
};
|
||||
this.charging = false;
|
||||
this.aimHold = 0;
|
||||
this.dragAim = null;
|
||||
this.followTarget = null;
|
||||
this.cameraFree = false;
|
||||
this.matchLive = false;
|
||||
this.aiTurn = -1;
|
||||
this.aiActAt = Infinity;
|
||||
this.quitArmedAt = 0;
|
||||
}
|
||||
|
||||
create() {
|
||||
this.cameras.main.setBackgroundColor(COLORS.bg);
|
||||
const { tracks, volume } = getGameSoundtrack(this);
|
||||
if (tracks.length) this.music = new MusicPlayer(this, tracks, volume);
|
||||
this.events.once('shutdown', () => this.teardownMatch());
|
||||
this.showModeSelect();
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Screens
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
clearScreen() {
|
||||
for (const o of this.screenObjs) o.destroy();
|
||||
this.screenObjs = [];
|
||||
}
|
||||
|
||||
track(o) { this.screenObjs.push(o); return o; }
|
||||
|
||||
title(text, y = 120, size = 72) {
|
||||
return this.track(this.add.text(GAME_WIDTH / 2, y, text, {
|
||||
fontFamily: 'Righteous', fontSize: `${size}px`, color: COLORS.textHex,
|
||||
}).setOrigin(0.5).setScrollFactor(0).setDepth(100));
|
||||
}
|
||||
|
||||
showModeSelect() {
|
||||
this.clearScreen();
|
||||
this.cameras.main.setScroll(0, 0).setZoom(1).setBounds(0, 0, GAME_WIDTH, GAME_HEIGHT);
|
||||
this.title('WORMS', 150, 96);
|
||||
this.track(this.add.text(GAME_WIDTH / 2, 232, 'Total annihilation, one turn at a time.', {
|
||||
fontFamily: FONT, fontSize: '30px', color: COLORS.mutedHex,
|
||||
}).setOrigin(0.5).setScrollFactor(0).setDepth(100));
|
||||
|
||||
MODES.forEach((m, i) => {
|
||||
this.track(new Button(this, GAME_WIDTH / 2, 400 + i * 96, m.label, () => {
|
||||
this.mode = m.id;
|
||||
this.showSetup();
|
||||
}, { width: 560, height: 72 }));
|
||||
});
|
||||
|
||||
this.track(new Button(this, GAME_WIDTH / 2, 720, 'Leave', () => {
|
||||
this.scene.start('GameMenu');
|
||||
}, { width: 260, height: 60 }));
|
||||
|
||||
this.track(addFullscreenButton(this));
|
||||
}
|
||||
|
||||
showSetup() {
|
||||
this.clearScreen();
|
||||
this.title(this.mode === 'hotseat' ? '2 PLAYER SETUP' : 'QUICK MATCH', 90, 60);
|
||||
|
||||
const rows = [
|
||||
{ key: 'theme', label: 'Theme', values: THEMES.map((t) => t.id), display: (v) => getTheme(v).name },
|
||||
{ key: 'shape', label: 'Landscape', values: ['island', 'cavern'], display: (v) => v === 'island' ? 'Island' : 'Cavern' },
|
||||
{ key: 'size', label: 'Map size', values: ['small', 'medium', 'large'], display: (v) => MAP_SIZES[v].name },
|
||||
{ key: 'wormsPerTeam', label: 'Worms per team', values: [2, 3, 4, 5, 6], display: (v) => `${v}` },
|
||||
{ key: 'teams', label: 'Teams', values: this.mode === 'hotseat' ? [2] : [2, 3, 4], display: (v) => `${v}` },
|
||||
];
|
||||
if (this.mode === 'ai') {
|
||||
rows.push({ key: 'difficulty', label: 'Difficulty', values: [1, 2, 3, 4, 5], display: (v) => '★'.repeat(v) });
|
||||
}
|
||||
|
||||
const startY = 210, rowH = 76;
|
||||
rows.forEach((row, i) => {
|
||||
const y = startY + i * rowH;
|
||||
this.track(this.add.text(GAME_WIDTH / 2 - 340, y, row.label, {
|
||||
fontFamily: FONT, fontSize: '30px', color: COLORS.textHex,
|
||||
}).setOrigin(0, 0.5).setDepth(100));
|
||||
|
||||
const valueText = this.track(this.add.text(GAME_WIDTH / 2 + 150, y, row.display(this.setup[row.key]), {
|
||||
fontFamily: FONT, fontSize: '30px', color: COLORS.accentHex,
|
||||
}).setOrigin(0.5, 0.5).setDepth(100));
|
||||
|
||||
// A value carried over from the other mode may not be offered here
|
||||
// (hotseat is always 2 teams), so snap it back before it can be shown.
|
||||
if (!row.values.includes(this.setup[row.key])) {
|
||||
this.setup[row.key] = row.values[0];
|
||||
valueText.setText(row.display(this.setup[row.key]));
|
||||
}
|
||||
|
||||
const cycle = (dir) => {
|
||||
const idx = row.values.indexOf(this.setup[row.key]);
|
||||
const next = (idx + dir + row.values.length) % row.values.length;
|
||||
this.setup[row.key] = row.values[next];
|
||||
valueText.setText(row.display(this.setup[row.key]));
|
||||
};
|
||||
this.track(new Button(this, GAME_WIDTH / 2 + 40, y, '‹', () => cycle(-1), { width: 56, height: 52 }));
|
||||
this.track(new Button(this, GAME_WIDTH / 2 + 260, y, '›', () => cycle(1), { width: 56, height: 52 }));
|
||||
});
|
||||
|
||||
this.track(new Button(this, GAME_WIDTH / 2 - 170, 780, 'Back', () => this.showModeSelect(), { width: 240, height: 64 }));
|
||||
this.track(new Button(this, GAME_WIDTH / 2 + 170, 780, 'Start match', () => this.startMatch(), { width: 300, height: 64 }));
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Match setup
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
startMatch() {
|
||||
this.clearScreen();
|
||||
const note = this.add.text(GAME_WIDTH / 2, GAME_HEIGHT / 2, 'Sculpting the landscape…', {
|
||||
fontFamily: FONT, fontSize: '36px', color: COLORS.textHex,
|
||||
}).setOrigin(0.5).setScrollFactor(0).setDepth(200);
|
||||
|
||||
// Generation is ~100-270ms of straight-line work, so let the browser paint
|
||||
// the notice before we block on it.
|
||||
this.time.delayedCall(30, () => {
|
||||
const teamCount = this.setup.teams;
|
||||
const teams = [];
|
||||
for (let i = 0; i < teamCount; i++) {
|
||||
const human = this.mode === 'hotseat' ? true : i === 0;
|
||||
teams.push({
|
||||
id: `t${i}`,
|
||||
name: this.mode === 'hotseat' ? `Player ${i + 1}` : (i === 0 ? 'You' : TEAM_NAMES[i]),
|
||||
color: TEAM_COLORS[i],
|
||||
controller: human ? 'human' : 'ai',
|
||||
skill: this.setup.difficulty,
|
||||
});
|
||||
}
|
||||
|
||||
const seed = (Math.floor(Math.random() * 0x7fffffff)) >>> 0;
|
||||
this.state = createMatch({
|
||||
seed,
|
||||
mapSeed: seed,
|
||||
shape: this.setup.shape,
|
||||
size: this.setup.size,
|
||||
theme: this.setup.theme,
|
||||
wormsPerTeam: this.setup.wormsPerTeam,
|
||||
teams,
|
||||
});
|
||||
|
||||
note.destroy();
|
||||
this.buildWorld();
|
||||
this.bindInput();
|
||||
this.snapCameraToActive(true);
|
||||
});
|
||||
}
|
||||
|
||||
teardownMatch() {
|
||||
// Guards update(): the graphics below are about to be destroyed, and
|
||||
// "Menu" leaves this.state set so a stray frame would draw into them.
|
||||
this.matchLive = false;
|
||||
if (this.weaponPanel) { this.weaponPanel.destroy(); this.weaponPanel = null; }
|
||||
if (this.surface) { this.surface.destroy(); this.surface = null; }
|
||||
for (const o of this.worldObjs) o.destroy();
|
||||
for (const o of this.hudObjs) o.destroy();
|
||||
this.worldObjs = [];
|
||||
this.hudObjs = [];
|
||||
}
|
||||
|
||||
buildWorld() {
|
||||
this.teardownMatch();
|
||||
const t = this.state.terrain;
|
||||
const theme = this.setup.theme;
|
||||
|
||||
this.cameras.main.setBounds(-200, -400, t.w + 400, t.h + 700);
|
||||
this.cameras.main.setBackgroundColor(getTheme(theme).sky[0]);
|
||||
|
||||
const push = (o, depth) => { o.setDepth(depth); this.worldObjs.push(o); return o; };
|
||||
|
||||
// makeBackdrop returns loose root objects, not a container, so each
|
||||
// parallax layer keeps its own scrollFactor.
|
||||
for (const o of makeBackdrop(this, t, theme, 0)) this.worldObjs.push(o);
|
||||
|
||||
this.surface = makeTerrainSurface(this, t, theme, 10);
|
||||
|
||||
this.gObjects = push(this.add.graphics(), 12);
|
||||
this.gRope = push(this.add.graphics(), 13);
|
||||
this.gWorms = push(this.add.graphics(), 14);
|
||||
this.gAim = push(this.add.graphics(), 15);
|
||||
this.gLabels = push(this.add.graphics(), 16);
|
||||
this.fxLayer = push(this.add.container(0, 0), 20);
|
||||
this.gWater = push(this.add.graphics(), 25);
|
||||
|
||||
this.buildHud();
|
||||
this.matchLive = true;
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// HUD
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
buildHud() {
|
||||
const hud = (o) => { o.setScrollFactor(0).setDepth(60); this.hudObjs.push(o); return o; };
|
||||
|
||||
this.hudPanel = hud(this.add.graphics());
|
||||
this.hudTimer = hud(this.add.text(GAME_WIDTH / 2, 40, '45', {
|
||||
fontFamily: 'Righteous', fontSize: '64px', color: COLORS.textHex,
|
||||
stroke: '#000000', strokeThickness: 6,
|
||||
}).setOrigin(0.5, 0));
|
||||
|
||||
this.hudTurn = hud(this.add.text(GAME_WIDTH / 2, 116, '', {
|
||||
fontFamily: FONT, fontSize: '28px', color: COLORS.accentHex,
|
||||
stroke: '#000000', strokeThickness: 4,
|
||||
}).setOrigin(0.5, 0));
|
||||
|
||||
this.hudWeapon = hud(this.add.text(40, GAME_HEIGHT - 96, '', {
|
||||
fontFamily: FONT, fontSize: '32px', color: COLORS.textHex,
|
||||
stroke: '#000000', strokeThickness: 4,
|
||||
}).setOrigin(0, 0));
|
||||
|
||||
this.hudTip = hud(this.add.text(40, GAME_HEIGHT - 54, '', {
|
||||
fontFamily: FONT, fontSize: '22px', color: COLORS.mutedHex,
|
||||
stroke: '#000000', strokeThickness: 3,
|
||||
}).setOrigin(0, 0));
|
||||
|
||||
this.hudTeams = this.state.teams.map((team, i) => hud(this.add.text(40, 34 + i * 34, '', {
|
||||
fontFamily: FONT, fontSize: '26px',
|
||||
color: `#${team.color.toString(16).padStart(6, '0')}`,
|
||||
stroke: '#000000', strokeThickness: 4,
|
||||
}).setOrigin(0, 0)));
|
||||
|
||||
this.hudWind = hud(this.add.graphics());
|
||||
this.hudWindText = hud(this.add.text(GAME_WIDTH - 40, 34, 'WIND', {
|
||||
fontFamily: FONT, fontSize: '22px', color: COLORS.mutedHex,
|
||||
stroke: '#000000', strokeThickness: 3,
|
||||
}).setOrigin(1, 0));
|
||||
|
||||
this.hudPower = hud(this.add.graphics());
|
||||
this.hudBanner = hud(this.add.text(GAME_WIDTH / 2, GAME_HEIGHT / 2 - 40, '', {
|
||||
fontFamily: 'Righteous', fontSize: '78px', color: COLORS.textHex,
|
||||
stroke: '#000000', strokeThickness: 8, align: 'center',
|
||||
}).setOrigin(0.5).setAlpha(0));
|
||||
|
||||
this.weaponPanel = null;
|
||||
}
|
||||
|
||||
refreshHud() {
|
||||
const st = this.state;
|
||||
if (!st) return;
|
||||
|
||||
const t = Math.max(0, st.phase === 'retreat' ? st.retreatTime : st.turnTime);
|
||||
this.hudTimer.setText(st.phase === 'settle' || st.phase === 'resolve' ? '…' : `${Math.ceil(t)}`);
|
||||
this.hudTimer.setColor(st.phase === 'retreat' ? '#ffd24a' : (t <= 5 ? '#ff6a5a' : COLORS.textHex));
|
||||
|
||||
const team = st.teams[st.activeTeam];
|
||||
const worm = activeWorm(st);
|
||||
this.hudTurn.setText(worm && team
|
||||
? `${team.name} — ${worm.name}${st.suddenDeath ? ' · SUDDEN DEATH' : ''}`
|
||||
: '');
|
||||
|
||||
for (let i = 0; i < this.hudTeams.length; i++) {
|
||||
const tm = st.teams[i];
|
||||
const hp = teamHealth(st, i);
|
||||
const alive = livingWorms(st, i).length;
|
||||
this.hudTeams[i].setText(`${tm.name} ${hp} (${alive})`);
|
||||
this.hudTeams[i].setAlpha(st.activeTeam === i ? 1 : 0.65);
|
||||
}
|
||||
|
||||
const w = getWeapon(st.selectedWeapon);
|
||||
const ammo = team ? team.ammo[st.selectedWeapon] : 0;
|
||||
this.hudWeapon.setText(w ? `${w.name}${ammo === Infinity ? '' : ` ×${ammo}`}${w.fuseOptions ? ` fuse ${st.fuse}s` : ''}` : '');
|
||||
this.hudTip.setText(w?.tip ?? '');
|
||||
|
||||
// Wind arrow.
|
||||
const g = this.hudWind;
|
||||
g.clear();
|
||||
const wx = GAME_WIDTH - 220, wy = 78;
|
||||
g.fillStyle(0x000000, 0.35);
|
||||
g.fillRoundedRect(wx - 10, wy - 14, 190, 28, 6);
|
||||
const mag = Math.abs(st.wind);
|
||||
const dir = Math.sign(st.wind) || 1;
|
||||
g.fillStyle(mag > 0.6 ? 0xff6a5a : mag > 0.3 ? 0xffd24a : 0x8fd8ff, 1);
|
||||
const barW = 84 * mag;
|
||||
if (dir > 0) g.fillRect(wx + 86, wy - 7, barW, 14);
|
||||
else g.fillRect(wx + 86 - barW, wy - 7, barW, 14);
|
||||
g.lineStyle(2, 0xffffff, 0.7);
|
||||
g.lineBetween(wx + 86, wy - 12, wx + 86, wy + 12);
|
||||
|
||||
// Power bar while charging.
|
||||
const p = this.hudPower;
|
||||
p.clear();
|
||||
if (st.charging || st.power > 0) {
|
||||
const pw = 420, ph = 20, px = GAME_WIDTH / 2 - pw / 2, py = GAME_HEIGHT - 130;
|
||||
p.fillStyle(0x000000, 0.55);
|
||||
p.fillRoundedRect(px - 3, py - 3, pw + 6, ph + 6, 4);
|
||||
p.fillStyle(0xffd24a, 1);
|
||||
p.fillRect(px, py, pw * st.power, ph);
|
||||
p.lineStyle(2, 0xffffff, 0.8);
|
||||
p.strokeRoundedRect(px - 3, py - 3, pw + 6, ph + 6, 4);
|
||||
}
|
||||
}
|
||||
|
||||
banner(text, ms = 1600) {
|
||||
this.hudBanner.setText(text).setAlpha(1).setScale(0.8);
|
||||
this.tweens.add({ targets: this.hudBanner, scale: 1, duration: 220, ease: 'Back.easeOut' });
|
||||
this.tweens.add({ targets: this.hudBanner, alpha: 0, delay: ms, duration: 380 });
|
||||
}
|
||||
|
||||
toggleWeaponPanel(force = null) {
|
||||
if (this.weaponPanel) {
|
||||
this.weaponPanel.destroy();
|
||||
this.weaponPanel = null;
|
||||
if (force !== true) return;
|
||||
}
|
||||
if (force === false) return;
|
||||
|
||||
const st = this.state;
|
||||
const list = availableWeapons(st);
|
||||
const cols = 4;
|
||||
const cw = 250, ch = 74;
|
||||
const rows = Math.ceil(list.length / cols);
|
||||
const pw = cols * cw + 40, ph = rows * ch + 80;
|
||||
const px = GAME_WIDTH / 2 - pw / 2, py = GAME_HEIGHT / 2 - ph / 2;
|
||||
|
||||
const panel = this.add.container(0, 0).setScrollFactor(0).setDepth(80);
|
||||
const bg = this.add.graphics();
|
||||
bg.fillStyle(0x11100c, 0.94);
|
||||
bg.fillRoundedRect(px, py, pw, ph, 10);
|
||||
bg.lineStyle(3, COLORS.accent, 1);
|
||||
bg.strokeRoundedRect(px, py, pw, ph, 10);
|
||||
panel.add(bg);
|
||||
panel.add(this.add.text(GAME_WIDTH / 2, py + 22, 'WEAPONS', {
|
||||
fontFamily: 'Righteous', fontSize: '30px', color: COLORS.accentHex,
|
||||
}).setOrigin(0.5, 0));
|
||||
|
||||
list.forEach((entry, i) => {
|
||||
const cx = px + 20 + (i % cols) * cw;
|
||||
const cy = py + 62 + Math.floor(i / cols) * ch;
|
||||
const selected = entry.id === st.selectedWeapon;
|
||||
const box = this.add.graphics();
|
||||
box.fillStyle(selected ? 0x3a3320 : 0x1e1a12, 1);
|
||||
box.fillRoundedRect(cx, cy, cw - 10, ch - 10, 6);
|
||||
box.lineStyle(2, selected ? COLORS.accent : 0x4a4438, 1);
|
||||
box.strokeRoundedRect(cx, cy, cw - 10, ch - 10, 6);
|
||||
panel.add(box);
|
||||
const label = this.add.text(cx + 12, cy + 12,
|
||||
`${entry.weapon.name}\n${entry.ammo === Infinity ? '∞' : `×${entry.ammo}`}`, {
|
||||
fontFamily: FONT, fontSize: '21px', color: COLORS.textHex, lineSpacing: 2,
|
||||
});
|
||||
panel.add(label);
|
||||
const hit = this.add.rectangle(cx + (cw - 10) / 2, cy + (ch - 10) / 2, cw - 10, ch - 10, 0xffffff, 0.001)
|
||||
.setInteractive({ useHandCursor: true });
|
||||
hit.on('pointerdown', () => {
|
||||
selectWeapon(st, entry.id);
|
||||
this.toggleWeaponPanel(false);
|
||||
});
|
||||
panel.add(hit);
|
||||
});
|
||||
|
||||
this.weaponPanel = panel;
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Input
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
bindInput() {
|
||||
if (this.inputBound) return;
|
||||
this.inputBound = true;
|
||||
|
||||
this.keys = this.input.keyboard.addKeys({
|
||||
left: 'LEFT', right: 'RIGHT', up: 'UP', down: 'DOWN',
|
||||
fire: 'SPACE', jump: 'ENTER', flip: 'BACKSPACE',
|
||||
panel: 'TAB', skip: 'K', zoomIn: 'PLUS', zoomOut: 'MINUS',
|
||||
one: 'ONE', two: 'TWO', three: 'THREE', four: 'FOUR', five: 'FIVE',
|
||||
six: 'SIX', seven: 'SEVEN', eight: 'EIGHT', nine: 'NINE',
|
||||
});
|
||||
|
||||
this.input.keyboard.on('keydown-TAB', (e) => { e.preventDefault(); this.toggleWeaponPanel(); });
|
||||
this.input.keyboard.on('keydown-ENTER', () => jump(this.state, 'forward'));
|
||||
this.input.keyboard.on('keydown-BACKSPACE', (e) => { e.preventDefault(); jump(this.state, 'backflip'); });
|
||||
this.input.keyboard.on('keydown-K', () => this.doSkip());
|
||||
this.input.keyboard.on('keydown-F', () => this.cycleFuse());
|
||||
this.input.keyboard.on('keydown-ESC', () => this.confirmQuit());
|
||||
|
||||
// Number keys cycle the weapons in that panel slot, like the original.
|
||||
for (let n = 1; n <= 9; n++) {
|
||||
this.input.keyboard.on(`keydown-${['ONE','TWO','THREE','FOUR','FIVE','SIX','SEVEN','EIGHT','NINE'][n - 1]}`,
|
||||
() => this.cycleSlot(n));
|
||||
}
|
||||
|
||||
this.input.on('wheel', (p, o, dx, dy) => {
|
||||
const cam = this.cameras.main;
|
||||
const before = cam.getWorldPoint(p.x, p.y);
|
||||
const z = Phaser.Math.Clamp(cam.zoom * (dy > 0 ? 0.9 : 1.1), 0.45, 2.4);
|
||||
cam.setZoom(z);
|
||||
const after = cam.getWorldPoint(p.x, p.y);
|
||||
cam.scrollX += before.x - after.x;
|
||||
cam.scrollY += before.y - after.y;
|
||||
this.cameraFree = true;
|
||||
});
|
||||
|
||||
this.input.on('pointerdown', (p) => {
|
||||
if (p.rightButtonDown()) { this.panFrom = { x: p.x, y: p.y, sx: this.cameras.main.scrollX, sy: this.cameras.main.scrollY }; return; }
|
||||
if (this.weaponPanel) return;
|
||||
if (!canAct(this.state)) return;
|
||||
const worm = activeWorm(this.state);
|
||||
if (!worm) return;
|
||||
// Slingshot aim: drag away from the worm to set angle and power.
|
||||
const wp = this.cameras.main.getWorldPoint(p.x, p.y);
|
||||
this.dragAim = { x: wp.x, y: wp.y, worm };
|
||||
});
|
||||
|
||||
this.input.on('pointermove', (p) => {
|
||||
if (this.panFrom && p.rightButtonDown()) {
|
||||
const cam = this.cameras.main;
|
||||
cam.setScroll(this.panFrom.sx - (p.x - this.panFrom.x) / cam.zoom,
|
||||
this.panFrom.sy - (p.y - this.panFrom.y) / cam.zoom);
|
||||
this.cameraFree = true;
|
||||
return;
|
||||
}
|
||||
if (this.dragAim) {
|
||||
const wp = this.cameras.main.getWorldPoint(p.x, p.y);
|
||||
this.dragAim.x = wp.x;
|
||||
this.dragAim.y = wp.y;
|
||||
}
|
||||
});
|
||||
|
||||
this.input.on('pointerup', (p) => {
|
||||
if (this.panFrom) { this.panFrom = null; return; }
|
||||
if (!this.dragAim) return;
|
||||
const { worm } = this.dragAim;
|
||||
const dx = this.dragAim.x - worm.x, dy = this.dragAim.y - worm.y;
|
||||
const dist = Math.hypot(dx, dy);
|
||||
const drag = this.dragAim;
|
||||
this.dragAim = null;
|
||||
if (dist < 24) return; // a click, not a drag
|
||||
const angle = Math.atan2(dy, dx);
|
||||
const power = Phaser.Math.Clamp(dist / 260, 0.1, 1);
|
||||
setAim(this.state, angle);
|
||||
this.fireSelected({ angle, power });
|
||||
drag;
|
||||
});
|
||||
}
|
||||
|
||||
cycleSlot(slot) {
|
||||
const st = this.state;
|
||||
if (!canAct(st)) return;
|
||||
const inSlot = availableWeapons(st).filter((e) => e.weapon.slot === slot);
|
||||
if (!inSlot.length) return;
|
||||
const idx = inSlot.findIndex((e) => e.id === st.selectedWeapon);
|
||||
const next = inSlot[(idx + 1) % inSlot.length];
|
||||
selectWeapon(st, next.id);
|
||||
playSound(this, SFX.PIECE_CLICK);
|
||||
}
|
||||
|
||||
// Grenade-family fuse. The number keys already cycle weapon slots, so the
|
||||
// original's "press 1-5 to set the fuse" would collide.
|
||||
cycleFuse() {
|
||||
const st = this.state;
|
||||
const w = getWeapon(st.selectedWeapon);
|
||||
if (!w || !w.fuseOptions || !canAct(st)) return;
|
||||
const i = w.fuseOptions.indexOf(st.fuse);
|
||||
setFuse(st, w.fuseOptions[(i + 1) % w.fuseOptions.length]);
|
||||
playSound(this, SFX.PIECE_CLICK);
|
||||
}
|
||||
|
||||
doSkip() {
|
||||
const st = this.state;
|
||||
if (!canAct(st) || st.hasFired) return;
|
||||
selectWeapon(st, 'skip');
|
||||
fire(st, {});
|
||||
}
|
||||
|
||||
fireSelected(opts) {
|
||||
const st = this.state;
|
||||
const weapon = getWeapon(st.selectedWeapon);
|
||||
if (!weapon) return;
|
||||
|
||||
// The rope is not a weapon in the firing sense — it changes the worm's
|
||||
// state and hands control straight back.
|
||||
if (weapon.id === 'ninjarope') {
|
||||
const worm = activeWorm(st);
|
||||
if (!worm) return;
|
||||
if (worm.rope) { releaseRope(worm); return; }
|
||||
if (fireRope(st.terrain, worm, opts.angle ?? st.aim)) {
|
||||
playSound(this, SFX.WOOSH);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (fire(st, opts)) {
|
||||
if (weapon.kind === 'charge') playSound(this, SFX.SCIFI_LAUNCH);
|
||||
this.followProjectile();
|
||||
}
|
||||
}
|
||||
|
||||
confirmQuit() {
|
||||
if (!this.matchLive) return;
|
||||
const now = this.time.now;
|
||||
if (this.quitArmedAt && now - this.quitArmedAt < 1400) {
|
||||
this.quitArmedAt = 0;
|
||||
this.teardownMatch();
|
||||
this.showModeSelect();
|
||||
return;
|
||||
}
|
||||
this.quitArmedAt = now;
|
||||
this.banner('Press ESC again to leave', 1200);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Camera
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
snapCameraToActive(instant = false) {
|
||||
const w = activeWorm(this.state);
|
||||
if (!w) return;
|
||||
this.followTarget = w;
|
||||
this.cameraFree = false;
|
||||
if (instant) this.cameras.main.centerOn(w.x, w.y - 60);
|
||||
}
|
||||
|
||||
followProjectile() {
|
||||
this.cameraFree = false;
|
||||
this.followTarget = null; // update() picks the newest projectile
|
||||
}
|
||||
|
||||
updateCamera(delta) {
|
||||
if (this.cameraFree) return;
|
||||
const st = this.state;
|
||||
let target = null;
|
||||
if (st.projectiles.length) target = st.projectiles[st.projectiles.length - 1];
|
||||
else if (this.followTarget && !this.followTarget.dead) target = this.followTarget;
|
||||
else target = activeWorm(st);
|
||||
if (!target) return;
|
||||
|
||||
const cam = this.cameras.main;
|
||||
const k = 1 - Math.pow(0.001, delta / 1000); // frame-rate independent lerp
|
||||
const cx = cam.scrollX + cam.width / 2 / cam.zoom;
|
||||
const cy = cam.scrollY + cam.height / 2 / cam.zoom;
|
||||
cam.centerOn(cx + (target.x - cx) * k, cy + (target.y - 50 - cy) * k);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Frame
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
update(time, delta) {
|
||||
const st = this.state;
|
||||
if (!st || !this.matchLive) return;
|
||||
|
||||
this.readHeldKeys(delta);
|
||||
this.driveAI(time);
|
||||
|
||||
const events = stepMatch(st, Math.min(delta, 50) / 1000);
|
||||
this.handleEvents(events);
|
||||
|
||||
this.updateCamera(delta);
|
||||
this.drawFrame(time);
|
||||
this.refreshHud();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// PLACEHOLDER opponent — replaced wholesale by WormsAI.js in Wave 3.
|
||||
//
|
||||
// It aims straight at a random enemy with a fixed lead and fires. It does
|
||||
// not read the wind, does not check line of fire, and does not reposition,
|
||||
// so it is beatable by anyone paying attention. It exists so 1-player mode
|
||||
// is not a 45-second wait per enemy turn while the real AI is being built.
|
||||
// ---------------------------------------------------------------------
|
||||
driveAI(time) {
|
||||
const st = this.state;
|
||||
const team = st.teams[st.activeTeam];
|
||||
if (!team || team.controller !== 'ai') { this.aiTurn = -1; return; }
|
||||
if (st.phase !== 'play' || !canAct(st) || st.hasFired) return;
|
||||
|
||||
if (this.aiTurn !== st.turnCount) {
|
||||
this.aiTurn = st.turnCount;
|
||||
this.aiActAt = time + 900 + Math.random() * 700;
|
||||
return;
|
||||
}
|
||||
if (time < this.aiActAt) return;
|
||||
this.aiActAt = Infinity;
|
||||
|
||||
const me = activeWorm(st);
|
||||
const foes = st.worms.filter((w) => !w.dead && w.team !== me.team);
|
||||
if (!foes.length) { this.doSkip(); return; }
|
||||
|
||||
const target = foes[Math.floor(Math.random() * foes.length)];
|
||||
const dx = target.x - me.x, dy = target.y - me.y;
|
||||
const dist = Math.hypot(dx, dy);
|
||||
const angle = Math.atan2(dy - Math.min(200, dist * 0.45), dx);
|
||||
const power = Phaser.Math.Clamp(dist / 900, 0.35, 1);
|
||||
|
||||
selectWeapon(st, 'bazooka');
|
||||
setAim(st, angle);
|
||||
if (!fire(st, { angle, power })) this.doSkip();
|
||||
this.followProjectile();
|
||||
}
|
||||
|
||||
readHeldKeys(delta) {
|
||||
const st = this.state;
|
||||
if (!canAct(st) || this.weaponPanel) { setMove(st, 0); setRopeInput(st, 0); return; }
|
||||
const k = this.keys;
|
||||
const worm = activeWorm(st);
|
||||
|
||||
setMove(st, (k.left.isDown ? -1 : 0) + (k.right.isDown ? 1 : 0));
|
||||
setRopeInput(st, worm && worm.rope ? ((k.up.isDown ? -1 : 0) + (k.down.isDown ? 1 : 0)) : 0);
|
||||
|
||||
// Aiming only when not roped — up/down reels the rope instead.
|
||||
if (worm && !worm.rope) {
|
||||
const rate = 1.5 * (delta / 1000);
|
||||
if (k.up.isDown) setAim(st, st.aim - rate * (Math.cos(st.aim) >= 0 ? 1 : -1));
|
||||
if (k.down.isDown) setAim(st, st.aim + rate * (Math.cos(st.aim) >= 0 ? 1 : -1));
|
||||
}
|
||||
|
||||
// Hold to charge, release to fire.
|
||||
const firing = k.fire.isDown;
|
||||
if (firing && !this.charging && !st.hasFired) {
|
||||
const weapon = getWeapon(st.selectedWeapon);
|
||||
if (weapon && weapon.kind === 'charge') { beginCharge(st); this.charging = true; }
|
||||
else { this.fireSelected({ angle: st.aim, power: 1 }); this.charging = true; }
|
||||
} else if (!firing && this.charging) {
|
||||
this.charging = false;
|
||||
const weapon = getWeapon(st.selectedWeapon);
|
||||
if (weapon && weapon.kind === 'charge' && st.charging) {
|
||||
this.fireSelected({ angle: st.aim, power: st.power });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
drawFrame(time) {
|
||||
const st = this.state;
|
||||
drawObjects(this.gObjects, st, this.setup.theme);
|
||||
drawRope(this.gRope, activeWorm(st));
|
||||
drawWorms(this.gWorms, st, {
|
||||
activeId: st.activeWorm, time, aim: st.aim, teams: st.teams,
|
||||
});
|
||||
drawWormLabels(this.gLabels, st, st.teams);
|
||||
drawWater(this.gWater, st.terrain, st.waterY, this.setup.theme, time);
|
||||
this.drawAimHelper();
|
||||
}
|
||||
|
||||
drawAimHelper() {
|
||||
const st = this.state;
|
||||
const g = this.gAim;
|
||||
g.clear();
|
||||
if (!canAct(st)) return;
|
||||
const worm = activeWorm(st);
|
||||
if (!worm || worm.rope) return;
|
||||
const weapon = getWeapon(st.selectedWeapon);
|
||||
if (!weapon || weapon.kind === 'meta' || weapon.kind === 'place') return;
|
||||
|
||||
const angle = this.dragAim
|
||||
? Math.atan2(this.dragAim.y - worm.y, this.dragAim.x - worm.x)
|
||||
: st.aim;
|
||||
const power = this.dragAim
|
||||
? Phaser.Math.Clamp(Math.hypot(this.dragAim.x - worm.x, this.dragAim.y - worm.y) / 260, 0.1, 1)
|
||||
: Math.max(0.25, st.power);
|
||||
|
||||
// A short dotted crosshair line — not a full trajectory preview, which
|
||||
// would remove the whole skill of the game.
|
||||
const len = 42 + power * 46;
|
||||
for (let d = 20; d < len; d += 8) {
|
||||
const x = worm.x + Math.cos(angle) * d;
|
||||
const y = worm.y + Math.sin(angle) * d;
|
||||
g.fillStyle(0xffffff, 0.55);
|
||||
g.fillCircle(x, y, 1.8);
|
||||
}
|
||||
g.fillStyle(0xffd24a, 0.9);
|
||||
g.fillCircle(worm.x + Math.cos(angle) * len, worm.y + Math.sin(angle) * len, 3.5);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Event replay
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
handleEvents(events) {
|
||||
if (!events || !events.length) return;
|
||||
const st = this.state;
|
||||
|
||||
for (const e of events) {
|
||||
switch (e.type) {
|
||||
case 'explosion': {
|
||||
if (e.crater > 0) this.surface.crater(e.x, e.y, e.crater);
|
||||
spawnExplosion(this, this.fxLayer, e.x, e.y, e.radius || 40, this.setup.theme);
|
||||
const shake = Math.min(0.02, (e.radius || 40) / 5000);
|
||||
this.cameras.main.shake(220, shake);
|
||||
playSoundEx(this, SFX.EIGHTBIT_EXPLODE, { volume: 0.5, rate: 1.4 - Math.min(0.6, (e.radius || 40) / 200) });
|
||||
break;
|
||||
}
|
||||
case 'hitscan':
|
||||
spawnTracer(this, this.fxLayer, e.x0, e.y0, e.x1, e.y1);
|
||||
break;
|
||||
case 'damage': {
|
||||
const w = st.worms[e.wormId];
|
||||
if (w) spawnDamageNumber(this, this.fxLayer, w.x, w.y, e.amount, '#ff8a7a');
|
||||
break;
|
||||
}
|
||||
case 'wormDied': {
|
||||
this.banner(e.cause === 'drowned' ? 'Glug glug!' : 'Ooof!', 900);
|
||||
playSound(this, e.cause === 'drowned' ? SFX.WATER_SPLASH : SFX.EIGHTBIT_EXPLODE_2);
|
||||
break;
|
||||
}
|
||||
case 'turnStart':
|
||||
this.snapCameraToActive();
|
||||
this.toggleWeaponPanel(false);
|
||||
this.charging = false;
|
||||
if (this.mode === 'hotseat') this.banner(`${st.teams[e.team].name}'s turn`, 900);
|
||||
break;
|
||||
case 'suddenDeath':
|
||||
this.banner('SUDDEN DEATH', 2200);
|
||||
playSound(this, SFX.SCIFI_RISER);
|
||||
break;
|
||||
case 'crateDropped':
|
||||
playSound(this, SFX.UI_CHIME);
|
||||
break;
|
||||
case 'crateCollected':
|
||||
this.banner(e.kind === 'health' ? `+${e.amount} health`
|
||||
: e.kind === 'trap' ? 'It was a trap!'
|
||||
: `${getWeapon(e.weapon)?.name ?? 'Weapon'} ×${e.amount}`, 1100);
|
||||
break;
|
||||
case 'waterRose':
|
||||
playSoundEx(this, SFX.WATER_RAISE, { volume: 0.4 });
|
||||
break;
|
||||
case 'matchOver':
|
||||
this.showResult(e.winner);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
showResult(winner) {
|
||||
const st = this.state;
|
||||
const name = winner == null ? null : st.teams[winner].name;
|
||||
this.banner(winner == null ? 'DRAW' : `${name} WINS`, 4000);
|
||||
playSound(this, winner === 0 || this.mode === 'hotseat' ? SFX.VICTORY_SHORT : SFX.EIGHTBIT_EXPLODE_2);
|
||||
|
||||
this.time.delayedCall(2200, () => {
|
||||
if (!this.matchLive) return;
|
||||
this.track(new Button(this, GAME_WIDTH / 2 - 170, GAME_HEIGHT - 110, 'Rematch', () => {
|
||||
this.clearScreen(); this.startMatch();
|
||||
}, { width: 260, height: 64 }));
|
||||
this.track(new Button(this, GAME_WIDTH / 2 + 170, GAME_HEIGHT - 110, 'Menu', () => {
|
||||
this.teardownMatch(); this.showModeSelect();
|
||||
}, { width: 260, height: 64 }));
|
||||
});
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -1,623 +0,0 @@
|
|||
// Worms — particle-vs-bitmask physics.
|
||||
//
|
||||
// Imports WormsTerrain only; no Phaser, so the verifier and the AI run it in
|
||||
// bare Node. Everything here is deterministic: fixed substeps, no Math.random,
|
||||
// no wall-clock reads.
|
||||
//
|
||||
// Three kinds of moving thing, in rising order of fiddliness:
|
||||
// 1. Projectiles — points, swept against the mask, bounce or detonate.
|
||||
// 2. Worms — non-rotating circles that WALK (a step-up search, not a
|
||||
// velocity integration) while grounded and fly ballistically otherwise.
|
||||
// 3. The ninja rope — a polyline of anchors that wraps terrain corners.
|
||||
//
|
||||
// The walk/fly split matters: Worms locomotion is not physical. A worm climbs
|
||||
// a 10px step instantly and is stopped dead by an 11px one, which is what makes
|
||||
// terrain shape tactical rather than incidental.
|
||||
|
||||
import { isSolid, isRock, raycast, normalAt, cellAt, AIR } from './WormsTerrain.js';
|
||||
|
||||
export const PHYS = {
|
||||
SUBSTEP: 1 / 120,
|
||||
MAX_SUBSTEPS: 8, // dt clamp, so a stalled tab can't fast-forward a turn
|
||||
|
||||
GRAVITY: 700, // px/s^2 — tuned so a full-power bazooka carries ~1000px
|
||||
TERMINAL_V: 1400,
|
||||
WIND_ACCEL: 110, // px/s^2 at |wind| == 1, on windAffected projectiles only
|
||||
|
||||
// --- worms ---
|
||||
WORM_R: 8, // collision radius
|
||||
WALK_SPEED: 46, // px/s
|
||||
MAX_STEP: 10, // climbable step height; 11px stops a worm dead
|
||||
JUMP_VX: 135,
|
||||
JUMP_VY: -300,
|
||||
BACKFLIP_VX: -95,
|
||||
BACKFLIP_VY: -430,
|
||||
WORM_RESTITUTION: 0.32, // bounce when blasted into terrain
|
||||
WORM_FRICTION: 0.55,
|
||||
WORM_REST_SPEED: 26, // below this on contact, a flying worm settles
|
||||
FALL_SAFE: 55, // px of drop that costs nothing
|
||||
FALL_DAMAGE_PER_PX: 0.20,
|
||||
FALL_DAMAGE_MAX: 50,
|
||||
|
||||
// --- projectiles ---
|
||||
PROJ_STEP_MAX: 6, // max px advanced per collision probe
|
||||
BOUNCE_MIN_SPEED: 45, // below this a bouncing projectile comes to rest
|
||||
SURFACE_PROBE_R: 6, // radius of the normal-estimate disc
|
||||
|
||||
// --- ninja rope ---
|
||||
ROPE_MAX_LEN: 520,
|
||||
ROPE_REEL_SPEED: 150, // px/s of length change on up/down
|
||||
ROPE_MIN_LEN: 26,
|
||||
ROPE_SWING_ACCEL: 260, // px/s^2 of left/right input while roped
|
||||
ROPE_DAMPING: 0.06, // per second, so a swing decays instead of ringing
|
||||
ROPE_CORNER_EPS: 1.5,
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Circle-vs-mask
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Disc offsets are precomputed per radius; a worm test is then a flat loop over
|
||||
// ~200 offsets with no arithmetic. Checking the FULL disc, not just its
|
||||
// perimeter, is deliberate — a girder is 8px thick and would otherwise slip
|
||||
// between the perimeter samples.
|
||||
const discCache = new Map();
|
||||
function discOffsets(r) {
|
||||
let d = discCache.get(r);
|
||||
if (d) return d;
|
||||
const xs = [], ys = [];
|
||||
for (let dy = -r; dy <= r; dy++) {
|
||||
for (let dx = -r; dx <= r; dx++) {
|
||||
if (dx * dx + dy * dy <= r * r) { xs.push(dx); ys.push(dy); }
|
||||
}
|
||||
}
|
||||
d = { xs: Int16Array.from(xs), ys: Int16Array.from(ys), n: xs.length };
|
||||
discCache.set(r, d);
|
||||
return d;
|
||||
}
|
||||
|
||||
export function circleHits(t, cx, cy, r = PHYS.WORM_R) {
|
||||
const d = discOffsets(r | 0);
|
||||
const x = Math.round(cx), y = Math.round(cy);
|
||||
for (let i = 0; i < d.n; i++) {
|
||||
if (cellAt(t, x + d.xs[i], y + d.ys[i]) !== AIR) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Nudge a circle out of terrain it has ended up inside (an explosion can hurl a
|
||||
// worm into a wall, and a Girder can be built around one). Spirals outward and
|
||||
// takes the first free spot, so the displacement is always minimal.
|
||||
export function resolveOverlap(t, body, r = PHYS.WORM_R, maxPush = 40) {
|
||||
if (!circleHits(t, body.x, body.y, r)) return false;
|
||||
for (let d = 1; d <= maxPush; d++) {
|
||||
for (let a = 0; a < 16; a++) {
|
||||
const ang = (a / 16) * Math.PI * 2;
|
||||
const nx = body.x + Math.cos(ang) * d;
|
||||
const ny = body.y + Math.sin(ang) * d;
|
||||
if (!circleHits(t, nx, ny, r)) { body.x = nx; body.y = ny; return true; }
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Worms
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function makeWorm(x, y, extra = {}) {
|
||||
return {
|
||||
x, y,
|
||||
vx: 0, vy: 0,
|
||||
facing: 1,
|
||||
grounded: false,
|
||||
airborne: true,
|
||||
peakY: y, // highest point reached this flight, for fall damage
|
||||
walkAcc: 0,
|
||||
rope: null,
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
|
||||
export function groundedAt(t, x, y, r = PHYS.WORM_R) {
|
||||
// Solid immediately under the disc but not intersecting it.
|
||||
return !circleHits(t, x, y, r) && circleHits(t, x, y + 2, r);
|
||||
}
|
||||
|
||||
// One 1px walk attempt. Returns 'moved' | 'blocked' | 'fell'.
|
||||
function walkPixel(t, worm, dir) {
|
||||
const r = PHYS.WORM_R;
|
||||
// Step up: take the lowest free position at or above the current height.
|
||||
let nx = worm.x + dir, ny = -1;
|
||||
for (let up = 0; up <= PHYS.MAX_STEP; up++) {
|
||||
if (!circleHits(t, nx, worm.y - up, r)) { ny = worm.y - up; break; }
|
||||
}
|
||||
if (ny < 0) return 'blocked';
|
||||
|
||||
// Step down: settle onto whatever is below the new position.
|
||||
let dropped = 0;
|
||||
while (dropped < PHYS.MAX_STEP && !circleHits(t, nx, ny + 1, r)) { ny += 1; dropped++; }
|
||||
|
||||
worm.x = nx;
|
||||
worm.y = ny;
|
||||
|
||||
if (dropped >= PHYS.MAX_STEP && !circleHits(t, nx, ny + 1, r)) {
|
||||
// Walked off a ledge — hand over to the ballistic path with a little
|
||||
// forward carry, the way stepping off a cliff looks in the original.
|
||||
worm.airborne = true;
|
||||
worm.grounded = false;
|
||||
worm.vx = dir * 40;
|
||||
worm.vy = 0;
|
||||
worm.peakY = worm.y;
|
||||
return 'fell';
|
||||
}
|
||||
return 'moved';
|
||||
}
|
||||
|
||||
// Drive a grounded worm horizontally. `dir` is -1, 0 or +1.
|
||||
export function walkWorm(t, worm, dir, dt) {
|
||||
if (dir !== 0) worm.facing = dir;
|
||||
if (dir === 0) { worm.walkAcc = 0; return 'idle'; }
|
||||
worm.walkAcc += PHYS.WALK_SPEED * dt;
|
||||
let result = 'idle';
|
||||
while (worm.walkAcc >= 1) {
|
||||
worm.walkAcc -= 1;
|
||||
result = walkPixel(t, worm, dir);
|
||||
if (result !== 'moved') break;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function jumpWorm(worm, kind = 'forward') {
|
||||
if (!worm.grounded) return false;
|
||||
if (kind === 'backflip') {
|
||||
worm.vx = PHYS.BACKFLIP_VX * worm.facing;
|
||||
worm.vy = PHYS.BACKFLIP_VY;
|
||||
} else {
|
||||
worm.vx = PHYS.JUMP_VX * worm.facing;
|
||||
worm.vy = PHYS.JUMP_VY;
|
||||
}
|
||||
worm.grounded = false;
|
||||
worm.airborne = true;
|
||||
worm.peakY = worm.y;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Ballistic worm integration for one substep. Returns an event string when
|
||||
// something worth reacting to happened.
|
||||
function flyWorm(t, worm, dt, events) {
|
||||
const r = PHYS.WORM_R;
|
||||
worm.vy += PHYS.GRAVITY * dt;
|
||||
if (worm.vy > PHYS.TERMINAL_V) worm.vy = PHYS.TERMINAL_V;
|
||||
|
||||
const dx = worm.vx * dt, dy = worm.vy * dt;
|
||||
const dist = Math.hypot(dx, dy);
|
||||
const steps = Math.max(1, Math.ceil(dist));
|
||||
const sx = dx / steps, sy = dy / steps;
|
||||
|
||||
for (let i = 0; i < steps; i++) {
|
||||
const nx = worm.x + sx, ny = worm.y + sy;
|
||||
if (!circleHits(t, nx, ny, r)) {
|
||||
worm.x = nx; worm.y = ny;
|
||||
if (worm.y < worm.peakY) worm.peakY = worm.y;
|
||||
continue;
|
||||
}
|
||||
// Contact. Reflect about the surface normal.
|
||||
const n = normalAt(t, Math.round(nx), Math.round(ny), PHYS.SURFACE_PROBE_R)
|
||||
?? { x: 0, y: -1 };
|
||||
const speed = Math.hypot(worm.vx, worm.vy);
|
||||
const fall = worm.y - worm.peakY;
|
||||
|
||||
if (speed < PHYS.WORM_REST_SPEED || (n.y < -0.5 && Math.abs(worm.vx) < 60)) {
|
||||
// Settle. Land on top of whatever we hit.
|
||||
worm.vx = 0; worm.vy = 0;
|
||||
worm.airborne = false;
|
||||
worm.grounded = true;
|
||||
resolveOverlap(t, worm, r);
|
||||
snapToGround(t, worm);
|
||||
if (fall > PHYS.FALL_SAFE) {
|
||||
events.push({ type: 'wormLanded', worm, fall, damage: fallDamage(fall) });
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const dot = worm.vx * n.x + worm.vy * n.y;
|
||||
let rvx = worm.vx - (1 + PHYS.WORM_RESTITUTION) * dot * n.x;
|
||||
let rvy = worm.vy - (1 + PHYS.WORM_RESTITUTION) * dot * n.y;
|
||||
rvx *= PHYS.WORM_FRICTION;
|
||||
rvy *= PHYS.WORM_FRICTION;
|
||||
worm.vx = rvx; worm.vy = rvy;
|
||||
// Back off along the normal so we don't re-collide on the same pixel.
|
||||
worm.x += n.x * 1.5;
|
||||
worm.y += n.y * 1.5;
|
||||
if (fall > PHYS.FALL_SAFE) {
|
||||
events.push({ type: 'wormLanded', worm, fall, damage: fallDamage(fall) });
|
||||
}
|
||||
worm.peakY = worm.y;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Landing snaps to integer pixels. Sub-pixel residue left over from the
|
||||
// ballistic path otherwise rides along through every subsequent walk step —
|
||||
// the mask is only sampled at integers, so a worm resting at y=290.625 sits a
|
||||
// visible pixel higher than one resting at y=291 and reports a different
|
||||
// standing height for the rest of the match.
|
||||
function snapToGround(t, worm) {
|
||||
const r = PHYS.WORM_R;
|
||||
worm.x = Math.round(worm.x);
|
||||
worm.y = Math.round(worm.y);
|
||||
if (circleHits(t, worm.x, worm.y, r)) resolveOverlap(t, worm, r, 16);
|
||||
let n = 0;
|
||||
while (n < PHYS.MAX_STEP && !circleHits(t, worm.x, worm.y + 1, r)) { worm.y += 1; n++; }
|
||||
}
|
||||
|
||||
export function fallDamage(fallPx) {
|
||||
if (fallPx <= PHYS.FALL_SAFE) return 0;
|
||||
const d = Math.round((fallPx - PHYS.FALL_SAFE) * PHYS.FALL_DAMAGE_PER_PX);
|
||||
return Math.max(0, Math.min(PHYS.FALL_DAMAGE_MAX, d));
|
||||
}
|
||||
|
||||
// Advance one worm by one substep. `input` is { move: -1|0|1, } and only
|
||||
// applies to the worm whose turn it is.
|
||||
export function stepWorm(t, worm, dt, events, input = null) {
|
||||
if (worm.dead) return;
|
||||
|
||||
if (worm.rope) { stepRope(t, worm, dt, input, events); return; }
|
||||
|
||||
if (worm.airborne) {
|
||||
flyWorm(t, worm, dt, events);
|
||||
// Safety net. A glancing bounce backs off along the normal, which is not
|
||||
// always enough to clear a concave corner, and terrain can be built or
|
||||
// blown up around a worm mid-flight. One extra disc test per frame buys
|
||||
// the invariant that a worm is NEVER inside terrain at the end of a step.
|
||||
if (circleHits(t, worm.x, worm.y, PHYS.WORM_R)) resolveOverlap(t, worm, PHYS.WORM_R, 24);
|
||||
return;
|
||||
}
|
||||
|
||||
// Grounded: keep it honest — terrain under the worm may have been blown away.
|
||||
if (!circleHits(t, worm.x, worm.y + 2, PHYS.WORM_R)) {
|
||||
worm.airborne = true;
|
||||
worm.grounded = false;
|
||||
worm.vx = 0;
|
||||
worm.vy = 0;
|
||||
worm.peakY = worm.y;
|
||||
return;
|
||||
}
|
||||
worm.grounded = true;
|
||||
if (input && input.move) walkWorm(t, worm, input.move, dt);
|
||||
}
|
||||
|
||||
export function settleWorm(t, worm, maxSeconds = 6) {
|
||||
const events = [];
|
||||
const steps = Math.ceil(maxSeconds / PHYS.SUBSTEP);
|
||||
for (let i = 0; i < steps; i++) {
|
||||
stepWorm(t, worm, PHYS.SUBSTEP, events);
|
||||
if (!worm.airborne && !worm.rope) break;
|
||||
}
|
||||
return events;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Projectiles
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function makeProjectile(x, y, vx, vy, spec = {}) {
|
||||
return {
|
||||
x, y, vx, vy,
|
||||
born: 0,
|
||||
age: 0,
|
||||
bounces: 0,
|
||||
resting: false,
|
||||
spec, // the WormsWeapons entry driving it
|
||||
...(spec.projectileExtra ?? {}),
|
||||
};
|
||||
}
|
||||
|
||||
// Integrate one projectile for one substep.
|
||||
// Returns null, or a terminating event: { type: 'detonate'|'expire', x, y, nx, ny }.
|
||||
export function stepProjectile(t, p, dt, opts = {}) {
|
||||
const { wind = 0, homingTarget = null } = opts;
|
||||
const spec = p.spec ?? {};
|
||||
p.age += dt;
|
||||
|
||||
if (p.resting) {
|
||||
// A grenade at rest still counts down its fuse.
|
||||
if (spec.fuse != null && p.age >= spec.fuse) return { type: 'detonate', x: p.x, y: p.y, nx: 0, ny: -1 };
|
||||
return null;
|
||||
}
|
||||
|
||||
if (spec.homing && homingTarget && p.age > (spec.homingDelay ?? 0.35)) {
|
||||
const dx = homingTarget.x - p.x, dy = homingTarget.y - p.y;
|
||||
const d = Math.hypot(dx, dy) || 1;
|
||||
const speed = Math.hypot(p.vx, p.vy) || 1;
|
||||
const turn = (spec.homingTurn ?? 4.0) * dt;
|
||||
p.vx += (dx / d) * speed * turn;
|
||||
p.vy += (dy / d) * speed * turn;
|
||||
const ns = Math.hypot(p.vx, p.vy) || 1;
|
||||
p.vx = (p.vx / ns) * speed;
|
||||
p.vy = (p.vy / ns) * speed;
|
||||
}
|
||||
|
||||
if (spec.gravity !== false) p.vy += PHYS.GRAVITY * dt;
|
||||
if (spec.windAffected) p.vx += wind * PHYS.WIND_ACCEL * dt;
|
||||
if (spec.drag) {
|
||||
const k = Math.max(0, 1 - spec.drag * dt);
|
||||
p.vx *= k; p.vy *= k;
|
||||
}
|
||||
if (p.vy > PHYS.TERMINAL_V) p.vy = PHYS.TERMINAL_V;
|
||||
|
||||
// Swept move, chunked so no probe skips more than PROJ_STEP_MAX px.
|
||||
let remaining = Math.hypot(p.vx * dt, p.vy * dt);
|
||||
const totalDist = remaining;
|
||||
if (totalDist < 1e-6) return checkExpiry(p, spec);
|
||||
const ux = (p.vx * dt) / totalDist, uy = (p.vy * dt) / totalDist;
|
||||
|
||||
while (remaining > 1e-6) {
|
||||
const seg = Math.min(remaining, PHYS.PROJ_STEP_MAX);
|
||||
const tx = p.x + ux * seg, ty = p.y + uy * seg;
|
||||
const hit = raycast(t, p.x, p.y, tx, ty);
|
||||
if (!hit.hit) {
|
||||
p.x = tx; p.y = ty;
|
||||
remaining -= seg;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Contact.
|
||||
p.x = hit.x; p.y = hit.y;
|
||||
const n = normalAt(t, Math.round(hit.hitX), Math.round(hit.hitY), PHYS.SURFACE_PROBE_R)
|
||||
?? { x: 0, y: -1 };
|
||||
|
||||
if (!spec.bounce) return { type: 'detonate', x: p.x, y: p.y, nx: n.x, ny: n.y };
|
||||
|
||||
const speed = Math.hypot(p.vx, p.vy);
|
||||
p.bounces++;
|
||||
if (spec.maxBounces != null && p.bounces > spec.maxBounces) {
|
||||
return { type: 'detonate', x: p.x, y: p.y, nx: n.x, ny: n.y };
|
||||
}
|
||||
if (speed < PHYS.BOUNCE_MIN_SPEED) {
|
||||
p.vx = 0; p.vy = 0; p.resting = true;
|
||||
p.x += n.x * 1.2; p.y += n.y * 1.2;
|
||||
return checkExpiry(p, spec);
|
||||
}
|
||||
|
||||
const dot = p.vx * n.x + p.vy * n.y;
|
||||
const e = spec.restitution ?? 0.45;
|
||||
const f = spec.tangentFriction ?? 0.82;
|
||||
let rvx = p.vx - (1 + e) * dot * n.x;
|
||||
let rvy = p.vy - (1 + e) * dot * n.y;
|
||||
// Tangential friction: scrub the component along the surface.
|
||||
const tanx = -n.y, tany = n.x;
|
||||
const tanDot = rvx * tanx + rvy * tany;
|
||||
rvx += tanx * tanDot * (f - 1);
|
||||
rvy += tany * tanDot * (f - 1);
|
||||
p.vx = rvx; p.vy = rvy;
|
||||
p.x += n.x * 1.5; p.y += n.y * 1.5;
|
||||
return { type: 'bounce', x: p.x, y: p.y, nx: n.x, ny: n.y, speed };
|
||||
}
|
||||
|
||||
return checkExpiry(p, spec);
|
||||
}
|
||||
|
||||
function checkExpiry(p, spec) {
|
||||
if (spec.fuse != null && p.age >= spec.fuse) {
|
||||
return { type: 'detonate', x: p.x, y: p.y, nx: 0, ny: -1 };
|
||||
}
|
||||
if (spec.maxAge != null && p.age >= spec.maxAge) {
|
||||
return { type: 'expire', x: p.x, y: p.y, nx: 0, ny: -1 };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Where would this shot land, ignoring worms? The AI's whole scoring loop is
|
||||
// built on this, so it is a plain loop with a step cap and no allocation
|
||||
// beyond the returned point.
|
||||
export function simulateShot(t, x, y, vx, vy, spec, opts = {}) {
|
||||
const p = makeProjectile(x, y, vx, vy, spec);
|
||||
const maxSteps = Math.ceil((opts.maxSeconds ?? 12) / PHYS.SUBSTEP);
|
||||
const trace = opts.trace ? [] : null;
|
||||
for (let i = 0; i < maxSteps; i++) {
|
||||
const ev = stepProjectile(t, p, PHYS.SUBSTEP, opts);
|
||||
if (trace && (i % 4 === 0)) trace.push({ x: p.x, y: p.y });
|
||||
if (p.y > t.h + 400 || p.x < -600 || p.x > t.w + 600) {
|
||||
return { outcome: 'lost', x: p.x, y: p.y, time: p.age, trace };
|
||||
}
|
||||
if (ev && (ev.type === 'detonate' || ev.type === 'expire')) {
|
||||
return { outcome: ev.type, x: ev.x, y: ev.y, time: p.age, trace };
|
||||
}
|
||||
}
|
||||
return { outcome: 'timeout', x: p.x, y: p.y, time: p.age, trace };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Explosions
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Geometry only — how hard each body is hit and from where. Damage numbers and
|
||||
// who is allowed to be hurt are WormsLogic's business.
|
||||
export function blastEffect(cx, cy, radius, power, bodies) {
|
||||
const out = [];
|
||||
for (const b of bodies) {
|
||||
if (b.dead) continue;
|
||||
const dx = b.x - cx, dy = b.y - cy;
|
||||
const d = Math.hypot(dx, dy);
|
||||
if (d > radius) continue;
|
||||
// Linear falloff. A zero-radius blast would divide by zero, so treat it as
|
||||
// a point hit at full strength rather than letting NaN into the sim.
|
||||
const f = radius <= 0 ? 1 : 1 - d / radius;
|
||||
const inv = d < 1e-3 ? 0 : 1 / d;
|
||||
// Straight up on a dead-centre hit, so a worm standing on a mine launches.
|
||||
const ux = d < 1e-3 ? 0 : dx * inv;
|
||||
const uy = d < 1e-3 ? -1 : dy * inv;
|
||||
out.push({ body: b, dist: d, falloff: f, ux, uy, impulse: power * f });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function applyImpulse(worm, ux, uy, impulse) {
|
||||
worm.vx += ux * impulse;
|
||||
worm.vy += uy * impulse;
|
||||
worm.airborne = true;
|
||||
worm.grounded = false;
|
||||
worm.rope = null;
|
||||
worm.peakY = worm.y;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Ninja rope
|
||||
// ---------------------------------------------------------------------------
|
||||
//
|
||||
// The rope is a polyline: anchors[0] is the pin in the terrain, the last anchor
|
||||
// is whatever corner the rope currently bends around, and the worm swings on
|
||||
// the final segment. Corners are pushed when the taut segment clips terrain and
|
||||
// popped when the bend straightens out again — that push/pop pair is the whole
|
||||
// trick to wrapping, and getting it wrong shows up as a rope that either cuts
|
||||
// through rock or locks solid.
|
||||
|
||||
export function fireRope(t, worm, angleRad, maxLen = PHYS.ROPE_MAX_LEN) {
|
||||
const dx = Math.cos(angleRad), dy = Math.sin(angleRad);
|
||||
const hit = raycast(t, worm.x, worm.y, worm.x + dx * maxLen, worm.y + dy * maxLen);
|
||||
if (!hit.hit) return false;
|
||||
// The root anchor must land on an actually-solid pixel: rounding the
|
||||
// sub-pixel contact point can put it in the air, and then the "was my anchor
|
||||
// blown up?" check fires on the very next step.
|
||||
const anchor = nearestSolidPixel(t, Math.round(hit.hitX), Math.round(hit.hitY));
|
||||
if (!anchor) return false;
|
||||
worm.rope = {
|
||||
anchors: [anchor],
|
||||
length: Math.max(PHYS.ROPE_MIN_LEN, Math.hypot(worm.x - anchor.x, worm.y - anchor.y)),
|
||||
};
|
||||
worm.airborne = true;
|
||||
worm.grounded = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
function nearestSolidPixel(t, x, y, r = 3) {
|
||||
if (isSolid(t, x, y)) return { x, y };
|
||||
for (let d = 1; d <= r; d++) {
|
||||
for (let dy = -d; dy <= d; dy++) {
|
||||
for (let dx = -d; dx <= d; dx++) {
|
||||
if (Math.max(Math.abs(dx), Math.abs(dy)) !== d) continue;
|
||||
if (isSolid(t, x + dx, y + dy)) return { x: x + dx, y: y + dy };
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function releaseRope(worm) {
|
||||
if (!worm.rope) return false;
|
||||
worm.rope = null;
|
||||
worm.airborne = true;
|
||||
worm.grounded = false;
|
||||
worm.peakY = worm.y;
|
||||
return true;
|
||||
}
|
||||
|
||||
function ropeTip(rope) { return rope.anchors[rope.anchors.length - 1]; }
|
||||
|
||||
// Total length used by the fixed bends, so the free segment is length - that.
|
||||
function bendLength(rope) {
|
||||
let sum = 0;
|
||||
for (let i = 1; i < rope.anchors.length; i++) {
|
||||
const a = rope.anchors[i - 1], b = rope.anchors[i];
|
||||
sum += Math.hypot(b.x - a.x, b.y - a.y);
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
function stepRope(t, worm, dt, input, events) {
|
||||
const rope = worm.rope;
|
||||
const tip = ropeTip(rope);
|
||||
|
||||
// Reel in/out.
|
||||
if (input && input.rope) {
|
||||
rope.length += input.rope * PHYS.ROPE_REEL_SPEED * dt;
|
||||
}
|
||||
const freeMax = Math.max(PHYS.ROPE_MIN_LEN, rope.length - bendLength(rope));
|
||||
|
||||
// Only the ROOT anchor is an attachment to terrain; every later anchor is a
|
||||
// corner the rope merely bends around and sits in AIR by construction, so
|
||||
// validating those would drop the rope the instant it wrapped anything.
|
||||
const root = rope.anchors[0];
|
||||
if (!isSolid(t, root.x, root.y)) {
|
||||
releaseRope(worm);
|
||||
events.push({ type: 'ropeLost', worm });
|
||||
return;
|
||||
}
|
||||
|
||||
// Gravity + swing input, then the length constraint.
|
||||
worm.vy += PHYS.GRAVITY * dt;
|
||||
if (input && input.move) worm.vx += input.move * PHYS.ROPE_SWING_ACCEL * dt;
|
||||
const damp = Math.max(0, 1 - PHYS.ROPE_DAMPING * dt * 60 * dt);
|
||||
worm.vx *= damp; worm.vy *= damp;
|
||||
|
||||
let nx = worm.x + worm.vx * dt;
|
||||
let ny = worm.y + worm.vy * dt;
|
||||
|
||||
// Constrain to the circle around the current tip.
|
||||
let dx = nx - tip.x, dy = ny - tip.y;
|
||||
let d = Math.hypot(dx, dy);
|
||||
if (d > freeMax && d > 1e-6) {
|
||||
const k = freeMax / d;
|
||||
nx = tip.x + dx * k;
|
||||
ny = tip.y + dy * k;
|
||||
// Kill the radial component; a rope cannot push.
|
||||
const ux = dx / d, uy = dy / d;
|
||||
const radial = worm.vx * ux + worm.vy * uy;
|
||||
if (radial > 0) { worm.vx -= radial * ux; worm.vy -= radial * uy; }
|
||||
}
|
||||
|
||||
// Terrain in the way of the worm itself: slide along it rather than stopping,
|
||||
// which is what makes climbing a cliff on the rope feel right.
|
||||
if (circleHits(t, nx, ny, PHYS.WORM_R)) {
|
||||
const n = normalAt(t, Math.round(nx), Math.round(ny), PHYS.SURFACE_PROBE_R);
|
||||
if (n) {
|
||||
const dot = worm.vx * n.x + worm.vy * n.y;
|
||||
if (dot < 0) { worm.vx -= dot * n.x; worm.vy -= dot * n.y; }
|
||||
nx = worm.x + n.x * 1.2;
|
||||
ny = worm.y + n.y * 1.2;
|
||||
} else {
|
||||
nx = worm.x; ny = worm.y;
|
||||
}
|
||||
}
|
||||
|
||||
worm.x = nx; worm.y = ny;
|
||||
// Reeling in against a wall can still bury the worm a pixel or two deep.
|
||||
resolveOverlap(t, worm, PHYS.WORM_R, 12);
|
||||
worm.peakY = Math.min(worm.peakY, worm.y);
|
||||
|
||||
updateRopeWrap(t, worm);
|
||||
}
|
||||
|
||||
// Push a new bend where the taut segment has cut into terrain; pop the last one
|
||||
// when the rope has swung back past it.
|
||||
function updateRopeWrap(t, worm) {
|
||||
const rope = worm.rope;
|
||||
if (!rope) return;
|
||||
const tip = ropeTip(rope);
|
||||
|
||||
// POP first: if the segment from the previous anchor straight to the worm is
|
||||
// clear, this bend is no longer doing anything.
|
||||
if (rope.anchors.length > 1) {
|
||||
const prev = rope.anchors[rope.anchors.length - 2];
|
||||
const clear = !raycast(t, prev.x, prev.y, worm.x, worm.y).hit;
|
||||
if (clear) { rope.anchors.pop(); return; }
|
||||
}
|
||||
|
||||
// PUSH: the straight line from the tip to the worm is blocked, so the rope is
|
||||
// lying over a corner. Pin the corner one pixel back from the contact.
|
||||
const hit = raycast(t, tip.x, tip.y, worm.x, worm.y);
|
||||
if (hit.hit) {
|
||||
const cx = Math.round(hit.x), cy = Math.round(hit.y);
|
||||
if (Math.hypot(cx - tip.x, cy - tip.y) > PHYS.ROPE_CORNER_EPS && rope.anchors.length < 24) {
|
||||
rope.anchors.push({ x: cx, y: cy });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Total rope path length, for drawing and for the reel-in limit.
|
||||
export function ropePoints(worm) {
|
||||
if (!worm.rope) return null;
|
||||
return [...worm.rope.anchors, { x: worm.x, y: worm.y }];
|
||||
}
|
||||
|
|
@ -1,542 +0,0 @@
|
|||
// Worms — presentation helpers.
|
||||
//
|
||||
// Everything here is Phaser-side and holds no game state. The two jobs that
|
||||
// matter are painting the terrain mask into a texture, and drawing worms
|
||||
// procedurally so the game is playable before any art exists.
|
||||
//
|
||||
// Terrain lives in a RenderTexture, not a CanvasTexture: craters are erased on
|
||||
// the GPU with a brush, so a blast costs one draw call instead of re-uploading
|
||||
// a 10 MB canvas every time something explodes.
|
||||
|
||||
import * as Phaser from 'phaser';
|
||||
import { AIR, ROCK } from './WormsTerrain.js';
|
||||
import { getTheme, artKeys } from './WormsThemes.js';
|
||||
|
||||
const CRUST = 11; // px of surface band painted along the top of terrain
|
||||
const BRUSH_R = 128; // radius of the source crater brush, scaled per blast
|
||||
|
||||
// Pixel classes, computed once per map.
|
||||
const C_AIR = 0, C_FILL = 1, C_CRUST = 2, C_ROCK = 3;
|
||||
|
||||
// One pass over the mask, row-major so it stays cache-friendly, tracking how
|
||||
// far each column is below the last air pixel. That distance is what makes a
|
||||
// crust band possible without an O(w*h*depth) probe per pixel.
|
||||
function classifyTerrain(terrain) {
|
||||
const { w, h, mask } = terrain;
|
||||
const cls = new Uint8Array(w * h);
|
||||
const since = new Int16Array(w).fill(9999);
|
||||
for (let y = 0; y < h; y++) {
|
||||
const row = y * w;
|
||||
for (let x = 0; x < w; x++) {
|
||||
const v = mask[row + x];
|
||||
if (v === AIR) { since[x] = 0; cls[row + x] = C_AIR; continue; }
|
||||
if (since[x] < 9999) since[x] += 1;
|
||||
cls[row + x] = v === ROCK ? C_ROCK : (since[x] <= CRUST ? C_CRUST : C_FILL);
|
||||
}
|
||||
}
|
||||
return cls;
|
||||
}
|
||||
|
||||
const rgb = (hex) => ({ r: (hex >> 16) & 0xff, g: (hex >> 8) & 0xff, b: hex & 0xff });
|
||||
|
||||
// Cheap deterministic per-pixel grain, so dirt does not read as a flat slab.
|
||||
function grainAt(x, y) {
|
||||
let n = (Math.imul(x, 73856093) ^ Math.imul(y, 19349663)) >>> 0;
|
||||
n = Math.imul(n ^ (n >>> 13), 1274126177) >>> 0;
|
||||
return ((n >>> 16) & 0xff) / 255;
|
||||
}
|
||||
|
||||
// Paint the whole terrain into a CanvasTexture. This is the one expensive
|
||||
// operation per map (~100 ms at 2560x1000) and happens behind the loading bar.
|
||||
export function paintTerrainBase(scene, terrain, themeId) {
|
||||
const theme = getTheme(themeId);
|
||||
const keys = artKeys(themeId);
|
||||
const key = 'worms-terrain-base';
|
||||
if (scene.textures.exists(key)) scene.textures.remove(key);
|
||||
|
||||
const { w, h } = terrain;
|
||||
const tex = scene.textures.createCanvas(key, w, h);
|
||||
const ctx = tex.getContext();
|
||||
const cls = classifyTerrain(terrain);
|
||||
|
||||
const hasFillArt = scene.textures.exists(keys.fill);
|
||||
const hasSurfaceArt = scene.textures.exists(keys.surface);
|
||||
|
||||
if (hasFillArt) {
|
||||
// Tile the supplied dirt texture across the whole rect, then knock out the
|
||||
// air with an alpha pass. Cheaper and better looking than per-pixel work.
|
||||
const src = scene.textures.get(keys.fill).getSourceImage();
|
||||
const pat = ctx.createPattern(src, 'repeat');
|
||||
ctx.fillStyle = pat;
|
||||
ctx.fillRect(0, 0, w, h);
|
||||
if (hasSurfaceArt) {
|
||||
const ssrc = scene.textures.get(keys.surface).getSourceImage();
|
||||
const spat = ctx.createPattern(ssrc, 'repeat-x');
|
||||
// Draw the crust strip only where the class map says crust.
|
||||
const strip = document.createElement('canvas');
|
||||
strip.width = w; strip.height = h;
|
||||
const sctx = strip.getContext('2d');
|
||||
sctx.fillStyle = spat;
|
||||
sctx.fillRect(0, 0, w, h);
|
||||
const sdata = sctx.getImageData(0, 0, w, h);
|
||||
for (let i = 0, p = 0; i < cls.length; i++, p += 4) {
|
||||
if (cls[i] !== C_CRUST) sdata.data[p + 3] = 0;
|
||||
}
|
||||
sctx.putImageData(sdata, 0, 0);
|
||||
ctx.drawImage(strip, 0, 0);
|
||||
}
|
||||
const img = ctx.getImageData(0, 0, w, h);
|
||||
const d = img.data;
|
||||
for (let i = 0, p = 0; i < cls.length; i++, p += 4) {
|
||||
if (cls[i] === C_AIR) d[p + 3] = 0;
|
||||
else if (cls[i] === C_ROCK) {
|
||||
const c = rgb(theme.rock);
|
||||
d[p] = c.r; d[p + 1] = c.g; d[p + 2] = c.b; d[p + 3] = 255;
|
||||
}
|
||||
}
|
||||
ctx.putImageData(img, 0, 0);
|
||||
} else {
|
||||
const img = ctx.createImageData(w, h);
|
||||
const d = img.data;
|
||||
const cFill = rgb(theme.fill), cLight = rgb(theme.fillLight), cDark = rgb(theme.fillDark);
|
||||
const cCrust = rgb(theme.surface), cCrustD = rgb(theme.surfaceDark);
|
||||
const cRock = rgb(theme.rock);
|
||||
const g = theme.grain ?? 0.14;
|
||||
|
||||
for (let y = 0, i = 0, p = 0; y < h; y++) {
|
||||
// Horizontal strata, so dirt reads as layered rather than as noise.
|
||||
const strata = Math.sin(y * 0.09) * 0.5 + Math.sin(y * 0.021) * 0.5;
|
||||
for (let x = 0; x < w; x++, i++, p += 4) {
|
||||
const k = cls[i];
|
||||
if (k === C_AIR) { d[p + 3] = 0; continue; }
|
||||
d[p + 3] = 255;
|
||||
if (k === C_ROCK) {
|
||||
const n = (grainAt(x, y) - 0.5) * 0.25;
|
||||
d[p] = cRock.r * (1 + n); d[p + 1] = cRock.g * (1 + n); d[p + 2] = cRock.b * (1 + n);
|
||||
continue;
|
||||
}
|
||||
const n = (grainAt(x, y) - 0.5) * g + strata * g * 0.35;
|
||||
if (k === C_CRUST) {
|
||||
const t = n > 0 ? n : 0, u = n < 0 ? -n : 0;
|
||||
d[p] = cCrust.r + (255 - cCrust.r) * t * 0.5 - (cCrust.r - cCrustD.r) * u * 2;
|
||||
d[p + 1] = cCrust.g + (255 - cCrust.g) * t * 0.5 - (cCrust.g - cCrustD.g) * u * 2;
|
||||
d[p + 2] = cCrust.b + (255 - cCrust.b) * t * 0.5 - (cCrust.b - cCrustD.b) * u * 2;
|
||||
} else {
|
||||
const t = n > 0 ? n : 0, u = n < 0 ? -n : 0;
|
||||
d[p] = cFill.r + (cLight.r - cFill.r) * t * 3 - (cFill.r - cDark.r) * u * 3;
|
||||
d[p + 1] = cFill.g + (cLight.g - cFill.g) * t * 3 - (cFill.g - cDark.g) * u * 3;
|
||||
d[p + 2] = cFill.b + (cLight.b - cFill.b) * t * 3 - (cFill.b - cDark.b) * u * 3;
|
||||
}
|
||||
}
|
||||
}
|
||||
ctx.putImageData(img, 0, 0);
|
||||
}
|
||||
|
||||
tex.refresh();
|
||||
return key;
|
||||
}
|
||||
|
||||
// A soft-edged disc used as the eraser, and a scorched ring stamped around each
|
||||
// crater so a fresh hole reads as burnt rather than as a clean cut.
|
||||
export function makeBrushes(scene, themeId) {
|
||||
const theme = getTheme(themeId);
|
||||
const eraseKey = 'worms-brush-erase';
|
||||
const scorchKey = 'worms-brush-scorch';
|
||||
|
||||
if (!scene.textures.exists(eraseKey)) {
|
||||
const tex = scene.textures.createCanvas(eraseKey, BRUSH_R * 2, BRUSH_R * 2);
|
||||
const ctx = tex.getContext();
|
||||
// Hard core with a 2px feather: any softer and the visible hole drifts out
|
||||
// of step with the collision mask, which is a hard-edged circle.
|
||||
const grad = ctx.createRadialGradient(BRUSH_R, BRUSH_R, 0, BRUSH_R, BRUSH_R, BRUSH_R);
|
||||
grad.addColorStop(0, 'rgba(255,255,255,1)');
|
||||
grad.addColorStop(0.97, 'rgba(255,255,255,1)');
|
||||
grad.addColorStop(1, 'rgba(255,255,255,0)');
|
||||
ctx.fillStyle = grad;
|
||||
ctx.fillRect(0, 0, BRUSH_R * 2, BRUSH_R * 2);
|
||||
tex.refresh();
|
||||
}
|
||||
|
||||
if (scene.textures.exists(scorchKey)) scene.textures.remove(scorchKey);
|
||||
const stex = scene.textures.createCanvas(scorchKey, BRUSH_R * 2, BRUSH_R * 2);
|
||||
const sctx = stex.getContext();
|
||||
const c = rgb(theme.scorch);
|
||||
const sgrad = sctx.createRadialGradient(BRUSH_R, BRUSH_R, BRUSH_R * 0.62,
|
||||
BRUSH_R, BRUSH_R, BRUSH_R);
|
||||
sgrad.addColorStop(0, `rgba(${c.r},${c.g},${c.b},0)`);
|
||||
sgrad.addColorStop(0.78, `rgba(${c.r},${c.g},${c.b},0.85)`);
|
||||
sgrad.addColorStop(1, `rgba(${c.r},${c.g},${c.b},0)`);
|
||||
sctx.fillStyle = sgrad;
|
||||
sctx.fillRect(0, 0, BRUSH_R * 2, BRUSH_R * 2);
|
||||
stex.refresh();
|
||||
|
||||
return { eraseKey, scorchKey, brushRadius: BRUSH_R };
|
||||
}
|
||||
|
||||
// The live terrain surface. Draw the painted base once, then erase craters and
|
||||
// draw girders straight into it.
|
||||
export function makeTerrainSurface(scene, terrain, themeId, depth = 10) {
|
||||
const baseKey = paintTerrainBase(scene, terrain, themeId);
|
||||
const brushes = makeBrushes(scene, themeId);
|
||||
|
||||
const rt = scene.add.renderTexture(0, 0, terrain.w, terrain.h).setOrigin(0, 0).setDepth(depth);
|
||||
rt.draw(baseKey, 0, 0);
|
||||
|
||||
// Reusable stamps. Created once and re-scaled per blast.
|
||||
const eraser = scene.make.image({ key: brushes.eraseKey, add: false }).setOrigin(0.5);
|
||||
const scorch = scene.make.image({ key: brushes.scorchKey, add: false }).setOrigin(0.5);
|
||||
|
||||
return {
|
||||
rt, baseKey, brushes,
|
||||
crater(x, y, r) {
|
||||
if (r <= 0) return;
|
||||
const s = (r * 1.02) / brushes.brushRadius;
|
||||
eraser.setScale(s);
|
||||
rt.erase(eraser, x, y);
|
||||
scorch.setScale((r + 9) / brushes.brushRadius).setAlpha(0.9);
|
||||
rt.draw(scorch, x, y);
|
||||
},
|
||||
girder(x, y, len, thick, angle, color) {
|
||||
const g = scene.make.graphics({ add: false });
|
||||
g.fillStyle(color ?? 0x9a8b6a, 1);
|
||||
g.fillRect(-len / 2, -thick / 2, len, thick);
|
||||
g.lineStyle(2, 0x5d523d, 1);
|
||||
g.strokeRect(-len / 2, -thick / 2, len, thick);
|
||||
const tmp = 'worms-girder-stamp';
|
||||
if (scene.textures.exists(tmp)) scene.textures.remove(tmp);
|
||||
g.generateTexture(tmp, len, thick);
|
||||
const img = scene.make.image({ key: tmp, add: false }).setOrigin(0.5).setRotation(angle);
|
||||
rt.draw(img, x, y);
|
||||
g.destroy();
|
||||
},
|
||||
repaint() {
|
||||
rt.clear();
|
||||
rt.draw(paintTerrainBase(scene, terrain, themeId), 0, 0);
|
||||
},
|
||||
destroy() {
|
||||
eraser.destroy(); scorch.destroy(); rt.destroy();
|
||||
if (scene.textures.exists(baseKey)) scene.textures.remove(baseKey);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Backdrop
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// A parallax sky. Uses the supplied backdrop if it exists, otherwise a
|
||||
// procedural gradient with theme-appropriate scenery silhouettes.
|
||||
//
|
||||
// Returns a flat ARRAY of root game objects rather than a container on purpose:
|
||||
// a Phaser Container's children ignore their own scrollFactor (the container's
|
||||
// governs), so parallax layers parented to one all move together — which is
|
||||
// exactly the bug that makes a backdrop look painted onto the terrain.
|
||||
export function makeBackdrop(scene, terrain, themeId, depth = 0) {
|
||||
const theme = getTheme(themeId);
|
||||
const keys = artKeys(themeId);
|
||||
const out = [];
|
||||
|
||||
if (scene.textures.exists(keys.backdrop)) {
|
||||
const img = scene.add.image(0, 0, keys.backdrop).setOrigin(0, 0).setDepth(depth);
|
||||
img.setDisplaySize(terrain.w * 1.15, terrain.h * 1.15);
|
||||
img.setScrollFactor(0.4);
|
||||
out.push(img);
|
||||
} else {
|
||||
const key = `worms-sky-${themeId}`;
|
||||
if (!scene.textures.exists(key)) {
|
||||
const tex = scene.textures.createCanvas(key, 8, 256);
|
||||
const ctx = tex.getContext();
|
||||
const grad = ctx.createLinearGradient(0, 0, 0, 256);
|
||||
const top = theme.sky[0], bot = theme.sky[1];
|
||||
grad.addColorStop(0, `#${top.toString(16).padStart(6, '0')}`);
|
||||
grad.addColorStop(1, `#${bot.toString(16).padStart(6, '0')}`);
|
||||
ctx.fillStyle = grad;
|
||||
ctx.fillRect(0, 0, 8, 256);
|
||||
tex.refresh();
|
||||
}
|
||||
const sky = scene.add.image(0, 0, key).setOrigin(0, 0).setDepth(depth);
|
||||
sky.setDisplaySize(terrain.w * 1.4, terrain.h * 1.4);
|
||||
sky.setScrollFactor(0.15);
|
||||
out.push(sky);
|
||||
|
||||
// Two rows of rolling hill silhouettes, drawn from the theme palette.
|
||||
for (const [i, alpha, scale] of [[0, 0.22, 0.55], [1, 0.34, 0.34]]) {
|
||||
const g = scene.add.graphics().setDepth(depth + 1 + i);
|
||||
g.fillStyle(theme.fillDark, alpha);
|
||||
const baseY = terrain.h * (0.62 + i * 0.10);
|
||||
g.beginPath();
|
||||
g.moveTo(0, terrain.h);
|
||||
for (let x = 0; x <= terrain.w; x += 40) {
|
||||
const y = baseY - Math.sin(x * 0.0018 + i * 2.1) * terrain.h * 0.09 * (1 - i * 0.4)
|
||||
- Math.sin(x * 0.0005 + i) * terrain.h * 0.06;
|
||||
g.lineTo(x, y);
|
||||
}
|
||||
g.lineTo(terrain.w, terrain.h);
|
||||
g.closePath();
|
||||
g.fillPath();
|
||||
g.setScrollFactor(scale);
|
||||
out.push(g);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Worms
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const WORM_R = 8;
|
||||
|
||||
// One Graphics object redrawn every frame for all worms. With at most a couple
|
||||
// of dozen worms this is far cheaper than keeping per-worm display lists in
|
||||
// sync with a simulation that can kill or launch any of them at any moment.
|
||||
export function drawWorms(g, state, { activeId = null, time = 0, aim = 0, teams = [] } = {}) {
|
||||
g.clear();
|
||||
for (const w of state.worms) {
|
||||
if (w.dead) continue;
|
||||
const team = teams[w.team] ?? { color: 0xffffff };
|
||||
const isActive = w.id === activeId;
|
||||
|
||||
// Squash and stretch from vertical speed, so a falling worm reads as
|
||||
// falling without needing a single frame of animation.
|
||||
const speed = Math.min(1, Math.abs(w.vy) / 700);
|
||||
const sx = 1 - speed * 0.18, sy = 1 + speed * 0.22;
|
||||
const rw = WORM_R * sx, rh = WORM_R * sy;
|
||||
const face = w.facing >= 0 ? 1 : -1;
|
||||
|
||||
// Shadow.
|
||||
g.fillStyle(0x000000, 0.18);
|
||||
g.fillEllipse(w.x, w.y + rh + 2, rw * 2.1, 5);
|
||||
|
||||
// Body: a capsule with a slightly narrower head end.
|
||||
g.fillStyle(0x000000, 0.35);
|
||||
g.fillEllipse(w.x, w.y + 1, rw * 2.15, rh * 2.15);
|
||||
g.fillStyle(team.color, 1);
|
||||
g.fillEllipse(w.x, w.y, rw * 2, rh * 2);
|
||||
g.fillEllipse(w.x + face * rw * 0.35, w.y - rh * 0.45, rw * 1.55, rh * 1.35);
|
||||
|
||||
// Belly highlight.
|
||||
g.fillStyle(0xffffff, 0.16);
|
||||
g.fillEllipse(w.x - face * rw * 0.2, w.y - rh * 0.25, rw * 1.1, rh * 0.9);
|
||||
|
||||
// Eyes, tracking the aim when this worm is up.
|
||||
const look = isActive ? aim : 0;
|
||||
const lx = Math.cos(look) * 1.5 * (face < 0 ? -1 : 1);
|
||||
const ly = Math.sin(look) * 1.5;
|
||||
for (const s of [-1, 1]) {
|
||||
const ex = w.x + face * rw * 0.5 + s * rw * 0.30;
|
||||
const ey = w.y - rh * 0.62;
|
||||
g.fillStyle(0xffffff, 1);
|
||||
g.fillCircle(ex, ey, 2.7);
|
||||
g.fillStyle(0x101010, 1);
|
||||
g.fillCircle(ex + lx, ey + ly, 1.5);
|
||||
}
|
||||
|
||||
// The active worm gets a bobbing arrow so it is never ambiguous whose turn
|
||||
// it is — the single most important readability cue in the game.
|
||||
if (isActive) {
|
||||
const bob = Math.sin(time * 0.005) * 3;
|
||||
const ay = w.y - rh - 26 + bob;
|
||||
g.fillStyle(team.color, 1);
|
||||
g.fillTriangle(w.x, ay + 11, w.x - 8, ay - 3, w.x + 8, ay - 3);
|
||||
g.lineStyle(2, 0x000000, 0.5);
|
||||
g.strokeTriangle(w.x, ay + 11, w.x - 8, ay - 3, w.x + 8, ay - 3);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Name tags and health bars go in their own pass so they never end up behind
|
||||
// another worm's body.
|
||||
export function drawWormLabels(g, state, teams) {
|
||||
g.clear();
|
||||
for (const w of state.worms) {
|
||||
if (w.dead) continue;
|
||||
const team = teams[w.team] ?? { color: 0xffffff };
|
||||
const frac = Math.max(0, w.health / (w.maxHealth || 100));
|
||||
const bw = 34, bh = 5;
|
||||
const bx = w.x - bw / 2, by = w.y - 30;
|
||||
g.fillStyle(0x000000, 0.55);
|
||||
g.fillRect(bx - 1, by - 1, bw + 2, bh + 2);
|
||||
g.fillStyle(frac > 0.5 ? 0x4ad24a : frac > 0.25 ? 0xe0c040 : 0xe04a4a, 1);
|
||||
g.fillRect(bx, by, bw * frac, bh);
|
||||
g.lineStyle(1, team.color, 0.9);
|
||||
g.strokeRect(bx - 1, by - 1, bw + 2, bh + 2);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// World furniture
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function drawObjects(g, state, themeId) {
|
||||
const theme = getTheme(themeId);
|
||||
g.clear();
|
||||
|
||||
for (const b of state.barrels) {
|
||||
if (b.dead) continue;
|
||||
g.fillStyle(0x000000, 0.25); g.fillEllipse(b.x, b.y + 13, 24, 6);
|
||||
g.fillStyle(0xb5462a, 1);
|
||||
g.fillRoundedRect(b.x - 10, b.y - 13, 20, 26, 4);
|
||||
g.lineStyle(2, 0x6e2716, 1);
|
||||
g.strokeRoundedRect(b.x - 10, b.y - 13, 20, 26, 4);
|
||||
g.lineStyle(2, 0xe0e0e0, 0.55);
|
||||
g.lineBetween(b.x - 10, b.y - 5, b.x + 10, b.y - 5);
|
||||
g.lineBetween(b.x - 10, b.y + 5, b.x + 10, b.y + 5);
|
||||
}
|
||||
|
||||
for (const m of state.mines) {
|
||||
if (m.dead) continue;
|
||||
const hot = m.triggered;
|
||||
g.fillStyle(0x000000, 0.25); g.fillEllipse(m.x, m.y + 7, 14, 4);
|
||||
g.fillStyle(hot ? 0xe04a3a : 0x3a3a44, 1);
|
||||
g.fillCircle(m.x, m.y, 6);
|
||||
g.lineStyle(1.5, 0x15151c, 1);
|
||||
g.strokeCircle(m.x, m.y, 6);
|
||||
for (let i = 0; i < 6; i++) {
|
||||
const a = (i / 6) * Math.PI * 2;
|
||||
g.lineBetween(m.x + Math.cos(a) * 5, m.y + Math.sin(a) * 5,
|
||||
m.x + Math.cos(a) * 9, m.y + Math.sin(a) * 9);
|
||||
}
|
||||
if (m.armed && !hot) { g.fillStyle(0x50ff70, 1); g.fillCircle(m.x + 3, m.y - 3, 1.6); }
|
||||
}
|
||||
|
||||
for (const c of state.crates) {
|
||||
if (c.dead) continue;
|
||||
if (c.parachute) {
|
||||
g.fillStyle(0xf0f0f0, 0.92);
|
||||
g.fillEllipse(c.x, c.y - 26, 44, 26);
|
||||
g.lineStyle(1, 0x99a0aa, 1);
|
||||
g.lineBetween(c.x - 20, c.y - 24, c.x - 6, c.y - 10);
|
||||
g.lineBetween(c.x + 20, c.y - 24, c.x + 6, c.y - 10);
|
||||
}
|
||||
const col = c.kind === 'health' ? 0xd83b3b : c.kind === 'trap' ? 0x8a6a3a : 0x9a7a3a;
|
||||
g.fillStyle(0x000000, 0.25); g.fillEllipse(c.x, c.y + 12, 22, 5);
|
||||
g.fillStyle(col, 1);
|
||||
g.fillRoundedRect(c.x - 11, c.y - 11, 22, 22, 3);
|
||||
g.lineStyle(2, 0x2a1c10, 1);
|
||||
g.strokeRoundedRect(c.x - 11, c.y - 11, 22, 22, 3);
|
||||
if (c.kind === 'health') {
|
||||
g.fillStyle(0xffffff, 1);
|
||||
g.fillRect(c.x - 6, c.y - 2, 12, 4);
|
||||
g.fillRect(c.x - 2, c.y - 6, 4, 12);
|
||||
} else {
|
||||
g.lineStyle(2, 0xf0e0b0, 0.8);
|
||||
g.lineBetween(c.x - 7, c.y - 7, c.x + 7, c.y + 7);
|
||||
g.lineBetween(c.x + 7, c.y - 7, c.x - 7, c.y + 7);
|
||||
}
|
||||
}
|
||||
|
||||
for (const p of state.projectiles) {
|
||||
const spin = p.age * 12;
|
||||
g.fillStyle(0x000000, 0.3);
|
||||
g.fillCircle(p.x + 1, p.y + 1, 5);
|
||||
g.fillStyle(p.weaponId === 'hhg' ? 0xe8d070 : 0x3a3a44, 1);
|
||||
g.fillCircle(p.x, p.y, 4.5);
|
||||
g.lineStyle(2, theme.scorch, 0.9);
|
||||
g.lineBetween(p.x, p.y, p.x - Math.cos(spin) * 7, p.y - Math.sin(spin) * 7);
|
||||
}
|
||||
}
|
||||
|
||||
// Rope, drawn as the polyline the physics actually uses so what you see is
|
||||
// exactly what you are swinging on.
|
||||
export function drawRope(g, worm) {
|
||||
g.clear();
|
||||
if (!worm || !worm.rope) return;
|
||||
const pts = [...worm.rope.anchors, { x: worm.x, y: worm.y }];
|
||||
g.lineStyle(2, 0x2b2b30, 1);
|
||||
g.beginPath();
|
||||
g.moveTo(pts[0].x, pts[0].y);
|
||||
for (let i = 1; i < pts.length; i++) g.lineTo(pts[i].x, pts[i].y);
|
||||
g.strokePath();
|
||||
g.fillStyle(0x8a8a92, 1);
|
||||
g.fillCircle(pts[0].x, pts[0].y, 3);
|
||||
}
|
||||
|
||||
export function drawWater(g, terrain, waterY, themeId, time) {
|
||||
const theme = getTheme(themeId);
|
||||
g.clear();
|
||||
const h = terrain.h + 400 - waterY;
|
||||
g.fillStyle(theme.water, 0.72);
|
||||
g.fillRect(-200, waterY, terrain.w + 400, h);
|
||||
// Two offset sine crests, which reads as moving water for the cost of a
|
||||
// handful of line segments.
|
||||
for (const [amp, freq, speed, alpha] of [[5, 0.010, 0.0011, 0.55], [3, 0.017, -0.0017, 0.35]]) {
|
||||
g.lineStyle(3, theme.waterFoam, alpha);
|
||||
g.beginPath();
|
||||
for (let x = -200; x <= terrain.w + 200; x += 16) {
|
||||
const y = waterY + Math.sin(x * freq + time * speed) * amp;
|
||||
if (x === -200) g.moveTo(x, y); else g.lineTo(x, y);
|
||||
}
|
||||
g.strokePath();
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Effects
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function spawnExplosion(scene, layer, x, y, radius, themeId) {
|
||||
const theme = getTheme(themeId);
|
||||
|
||||
const flash = scene.add.circle(x, y, radius * 0.75, 0xfff0c0, 0.95);
|
||||
layer.add(flash);
|
||||
scene.tweens.add({
|
||||
targets: flash, scale: 1.7, alpha: 0, duration: 260,
|
||||
ease: 'Quad.easeOut', onComplete: () => flash.destroy(),
|
||||
});
|
||||
|
||||
const ring = scene.add.circle(x, y, radius * 0.4);
|
||||
ring.setStrokeStyle(4, 0xffb050, 0.9);
|
||||
layer.add(ring);
|
||||
scene.tweens.add({
|
||||
targets: ring, scale: 2.6, alpha: 0, duration: 380,
|
||||
ease: 'Cubic.easeOut', onComplete: () => ring.destroy(),
|
||||
});
|
||||
|
||||
const n = Math.min(26, 8 + Math.round(radius / 5));
|
||||
for (let i = 0; i < n; i++) {
|
||||
const a = (i / n) * Math.PI * 2 + Math.random() * 0.4;
|
||||
const sp = radius * (1.4 + Math.random() * 2.0);
|
||||
const size = 2 + Math.random() * 4;
|
||||
const bit = scene.add.circle(x, y, size, i % 3 === 0 ? 0xffc060 : theme.fillDark, 1);
|
||||
layer.add(bit);
|
||||
scene.tweens.add({
|
||||
targets: bit,
|
||||
x: x + Math.cos(a) * sp,
|
||||
y: y + Math.sin(a) * sp + radius * 0.8,
|
||||
alpha: 0, scale: 0.3,
|
||||
duration: 420 + Math.random() * 320,
|
||||
ease: 'Quad.easeOut',
|
||||
onComplete: () => bit.destroy(),
|
||||
});
|
||||
}
|
||||
|
||||
const smoke = scene.add.circle(x, y, radius * 0.6, theme.scorch, 0.55);
|
||||
layer.add(smoke);
|
||||
scene.tweens.add({
|
||||
targets: smoke, scale: 1.9, alpha: 0, y: y - radius * 0.7,
|
||||
duration: 900, ease: 'Sine.easeOut', onComplete: () => smoke.destroy(),
|
||||
});
|
||||
}
|
||||
|
||||
export function spawnDamageNumber(scene, layer, x, y, amount, color = '#ffffff') {
|
||||
const txt = scene.add.text(x, y - 34, `${amount}`, {
|
||||
fontFamily: '"Julius Sans One"', fontSize: '26px', color,
|
||||
stroke: '#000000', strokeThickness: 4,
|
||||
}).setOrigin(0.5);
|
||||
layer.add(txt);
|
||||
scene.tweens.add({
|
||||
targets: txt, y: y - 78, alpha: 0, duration: 900,
|
||||
ease: 'Quad.easeOut', onComplete: () => txt.destroy(),
|
||||
});
|
||||
}
|
||||
|
||||
export function spawnTracer(scene, layer, x0, y0, x1, y1) {
|
||||
const g = scene.add.graphics();
|
||||
g.lineStyle(2, 0xfff0b0, 0.9);
|
||||
g.lineBetween(x0, y0, x1, y1);
|
||||
layer.add(g);
|
||||
scene.tweens.add({
|
||||
targets: g, alpha: 0, duration: 170, onComplete: () => g.destroy(),
|
||||
});
|
||||
}
|
||||
|
|
@ -1,736 +0,0 @@
|
|||
// Worms — procedural, fully destructible terrain.
|
||||
//
|
||||
// Zero imports, Node-testable. This module owns the AUTHORITATIVE terrain
|
||||
// representation: a Uint8Array mask, one byte per world pixel. Physics, the AI
|
||||
// and the verifier all read this; the Phaser scene keeps a CanvasTexture in
|
||||
// lockstep purely for display and never reads pixels back.
|
||||
//
|
||||
// Why a bitmask and not polygons: Worms terrain is carved by every explosion,
|
||||
// leaves floating chunks, and is walked over pixel by pixel. Polygon booleans
|
||||
// would degrade after a few dozen blasts; a mask is O(r^2) per blast forever.
|
||||
//
|
||||
// Generation is seeded and byte-identical for a seed (mulberry32 + an integer
|
||||
// hash noise, no Math.random anywhere) because the campaign pins seeds and the
|
||||
// verifier replays recorded turns.
|
||||
|
||||
export const AIR = 0; // empty space
|
||||
export const SOLID = 1; // destructible dirt
|
||||
export const ROCK = 2; // indestructible border (cavern maps only)
|
||||
|
||||
// Out-of-bounds always reads AIR. Cavern maps bake a ROCK border into the mask
|
||||
// instead of relying on an OOB rule, so there is exactly one convention.
|
||||
|
||||
export const MAP_SIZES = {
|
||||
small: { id: 'small', name: 'Small', w: 1920, h: 900 },
|
||||
medium: { id: 'medium', name: 'Medium', w: 2560, h: 1000 },
|
||||
large: { id: 'large', name: 'Large', w: 3200, h: 1100 },
|
||||
};
|
||||
|
||||
export const MAP_SHAPES = ['island', 'cavern'];
|
||||
|
||||
export const TERRAIN_TUNING = {
|
||||
// Water sits this far up from the bottom of the world at match start.
|
||||
WATER_DEPTH: 90,
|
||||
|
||||
// --- island ---
|
||||
ISL_SURFACE_SCALE: 340, // px per noise cell for the top surface
|
||||
ISL_SURFACE_OCTAVES: 5,
|
||||
ISL_TOP_MIN: 0.20, // surface stays between these fractions of height
|
||||
ISL_TOP_MAX: 0.62,
|
||||
ISL_COAST_FRAC: 0.16, // fraction of width the land tapers into water over
|
||||
ISL_CAVE_SCALE: 170,
|
||||
ISL_CAVE_OCTAVES: 4,
|
||||
ISL_CAVE_THRESHOLD: 0.60, // higher = fewer caves
|
||||
ISL_CAVE_MARGIN: 34, // no caves within this many px of the surface
|
||||
ISL_SPECK_MIN: 260, // solid components smaller than this are dropped
|
||||
|
||||
// --- cavern ---
|
||||
CAV_BORDER: 26, // ROCK frame thickness
|
||||
CAV_CEIL_MIN: 0.10, // ceiling wanders between these fractions of height
|
||||
CAV_CEIL_MAX: 0.34,
|
||||
CAV_FLOOR_MIN: 0.60, // floor wanders between these
|
||||
CAV_FLOOR_MAX: 0.88,
|
||||
CAV_SURFACE_SCALE: 300,
|
||||
CAV_SURFACE_OCTAVES: 4,
|
||||
CAV_BLOB_SCALE: 150, // pillars, stalactites and ledges inside the void
|
||||
CAV_BLOB_OCTAVES: 4,
|
||||
CAV_BLOB_THRESHOLD: 0.615,
|
||||
CAV_POCKET_SCALE: 190, // extra pockets eaten out of the floor and ceiling
|
||||
CAV_POCKET_OCTAVES: 3,
|
||||
CAV_POCKET_THRESHOLD: 0.60,
|
||||
CAV_SPECK_MIN: 200,
|
||||
CAV_OPEN_MIN: 0.32, // reject a cavern outside this open-space band
|
||||
CAV_OPEN_MAX: 0.68,
|
||||
|
||||
// Density fields are evaluated on a coarse lattice and bilinearly upsampled.
|
||||
// Every feature we care about is >= 50px, so this is invisible and ~16x
|
||||
// cheaper than per-pixel fBm.
|
||||
FIELD_STEP: 4,
|
||||
|
||||
// --- spawn placement ---
|
||||
SPAWN_HEADROOM: 44, // clear air needed above a spawn
|
||||
SPAWN_FOOTING: 10, // solid depth needed beneath it
|
||||
SPAWN_FLAT_SPAN: 9, // half-width of the flatness probe
|
||||
SPAWN_FLAT_TOLERANCE: 16, // max surface height swing across that span
|
||||
SPAWN_MIN_SEP: 130, // min px between any two spawned worms
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Seeded randomness
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function mulberry32(seed) {
|
||||
let a = seed >>> 0;
|
||||
return function rng() {
|
||||
a = (a + 0x6d2b79f5) >>> 0;
|
||||
let t = a;
|
||||
t = Math.imul(t ^ (t >>> 15), t | 1);
|
||||
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
}
|
||||
|
||||
// Integer lattice hash — no permutation table, so it costs nothing to have as
|
||||
// many independent noise channels as we like (just vary `seed`).
|
||||
function hash2(x, y, seed) {
|
||||
let h = (seed ^ Math.imul(x, 374761393) ^ Math.imul(y, 668265263)) | 0;
|
||||
h = Math.imul(h ^ (h >>> 13), 1274126177);
|
||||
return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
|
||||
}
|
||||
|
||||
function smoothstep(t) { return t * t * (3 - 2 * t); }
|
||||
|
||||
function value2(x, y, seed) {
|
||||
const ix = Math.floor(x), iy = Math.floor(y);
|
||||
const fx = smoothstep(x - ix), fy = smoothstep(y - iy);
|
||||
const a = hash2(ix, iy, seed);
|
||||
const b = hash2(ix + 1, iy, seed);
|
||||
const c = hash2(ix, iy + 1, seed);
|
||||
const d = hash2(ix + 1, iy + 1, seed);
|
||||
const top = a + (b - a) * fx;
|
||||
const bot = c + (d - c) * fx;
|
||||
return top + (bot - top) * fy;
|
||||
}
|
||||
|
||||
// Fractional Brownian motion in [0,1].
|
||||
function fbm2(x, y, seed, octaves, lacunarity = 2, gain = 0.5) {
|
||||
let sum = 0, amp = 1, norm = 0, fx = x, fy = y;
|
||||
for (let o = 0; o < octaves; o++) {
|
||||
sum += amp * value2(fx, fy, seed + o * 1013);
|
||||
norm += amp;
|
||||
amp *= gain;
|
||||
fx *= lacunarity;
|
||||
fy *= lacunarity;
|
||||
}
|
||||
return sum / norm;
|
||||
}
|
||||
|
||||
// 1-D slice of the same noise, for surface height curves.
|
||||
function fbm1(x, seed, octaves) { return fbm2(x, 0.5, seed, octaves); }
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Terrain object
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function createTerrain(w, h, meta = {}) {
|
||||
return {
|
||||
w, h,
|
||||
mask: new Uint8Array(w * h),
|
||||
waterY: h - TERRAIN_TUNING.WATER_DEPTH,
|
||||
shape: meta.shape ?? 'island',
|
||||
theme: meta.theme ?? 'forest',
|
||||
seed: meta.seed ?? 0,
|
||||
size: meta.size ?? 'medium',
|
||||
};
|
||||
}
|
||||
|
||||
export function inBounds(t, x, y) { return x >= 0 && y >= 0 && x < t.w && y < t.h; }
|
||||
|
||||
export function cellAt(t, x, y) {
|
||||
if (x < 0 || y < 0 || x >= t.w || y >= t.h) return AIR;
|
||||
return t.mask[y * t.w + x];
|
||||
}
|
||||
|
||||
export function isSolid(t, x, y) { return cellAt(t, x | 0, y | 0) !== AIR; }
|
||||
|
||||
// True where a worm cannot stand and an explosion cannot dig.
|
||||
export function isRock(t, x, y) { return cellAt(t, x | 0, y | 0) === ROCK; }
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Destruction and construction
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Carve a circular hole. ROCK survives. Returns the dirty rect (for the
|
||||
// renderer) plus how many pixels actually went, which the crater FX scales off.
|
||||
export function carveCircle(t, cx, cy, r) {
|
||||
cx |= 0; cy |= 0; r |= 0;
|
||||
const x0 = Math.max(0, cx - r), x1 = Math.min(t.w - 1, cx + r);
|
||||
const y0 = Math.max(0, cy - r), y1 = Math.min(t.h - 1, cy + r);
|
||||
const r2 = r * r;
|
||||
let removed = 0;
|
||||
for (let y = y0; y <= y1; y++) {
|
||||
const dy = y - cy, row = y * t.w;
|
||||
const span = Math.floor(Math.sqrt(Math.max(0, r2 - dy * dy)));
|
||||
const sx = Math.max(x0, cx - span), ex = Math.min(x1, cx + span);
|
||||
for (let x = sx; x <= ex; x++) {
|
||||
if (t.mask[row + x] === SOLID) { t.mask[row + x] = AIR; removed++; }
|
||||
}
|
||||
}
|
||||
return { x0, y0, x1, y1, removed };
|
||||
}
|
||||
|
||||
export function addCircle(t, cx, cy, r, value = SOLID) {
|
||||
cx |= 0; cy |= 0; r |= 0;
|
||||
const r2 = r * r;
|
||||
const y0 = Math.max(0, cy - r), y1 = Math.min(t.h - 1, cy + r);
|
||||
for (let y = y0; y <= y1; y++) {
|
||||
const dy = y - cy, row = y * t.w;
|
||||
const span = Math.floor(Math.sqrt(Math.max(0, r2 - dy * dy)));
|
||||
const sx = Math.max(0, cx - span), ex = Math.min(t.w - 1, cx + span);
|
||||
for (let x = sx; x <= ex; x++) {
|
||||
if (t.mask[row + x] !== ROCK) t.mask[row + x] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The Girder weapon: an oriented solid slab. Placed over air only — girders
|
||||
// never overwrite existing terrain, matching the original.
|
||||
export function addGirder(t, cx, cy, len, thick, angleRad) {
|
||||
const ca = Math.cos(angleRad), sa = Math.sin(angleRad);
|
||||
const hl = len / 2, ht = thick / 2;
|
||||
const reach = Math.ceil(Math.hypot(hl, ht)) + 1;
|
||||
const x0 = Math.max(0, (cx - reach) | 0), x1 = Math.min(t.w - 1, (cx + reach) | 0);
|
||||
const y0 = Math.max(0, (cy - reach) | 0), y1 = Math.min(t.h - 1, (cy + reach) | 0);
|
||||
let placed = 0;
|
||||
for (let y = y0; y <= y1; y++) {
|
||||
const row = y * t.w;
|
||||
for (let x = x0; x <= x1; x++) {
|
||||
const dx = x - cx, dy = y - cy;
|
||||
const u = dx * ca + dy * sa; // along the girder
|
||||
const v = -dx * sa + dy * ca; // across it
|
||||
if (Math.abs(u) <= hl && Math.abs(v) <= ht && t.mask[row + x] === AIR) {
|
||||
t.mask[row + x] = SOLID;
|
||||
placed++;
|
||||
}
|
||||
}
|
||||
}
|
||||
return { x0, y0, x1, y1, placed };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Queries used by physics
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Outward surface normal at a contact point, from the solidity gradient over a
|
||||
// disc of radius `r`. Grenades bounce about this; a worm uses it to decide
|
||||
// which way a slope runs. Returns a unit vector, or null in open air / deep
|
||||
// inside solid rock where the gradient is degenerate.
|
||||
export function normalAt(t, x, y, r = 6) {
|
||||
x |= 0; y |= 0;
|
||||
let gx = 0, gy = 0;
|
||||
for (let dy = -r; dy <= r; dy++) {
|
||||
for (let dx = -r; dx <= r; dx++) {
|
||||
const d2 = dx * dx + dy * dy;
|
||||
if (d2 === 0 || d2 > r * r) continue;
|
||||
if (cellAt(t, x + dx, y + dy) !== AIR) {
|
||||
const inv = 1 / Math.sqrt(d2);
|
||||
gx -= dx * inv;
|
||||
gy -= dy * inv;
|
||||
}
|
||||
}
|
||||
}
|
||||
const len = Math.hypot(gx, gy);
|
||||
if (len < 1e-6) return null;
|
||||
return { x: gx / len, y: gy / len };
|
||||
}
|
||||
|
||||
// Walk a segment one pixel at a time and report the first solid pixel. This is
|
||||
// the swept test that stops fast projectiles tunnelling thin walls — a rocket
|
||||
// at 900 px/s moves 7.5px per 120Hz substep, and a girder is 8px thick.
|
||||
export function raycast(t, x0, y0, x1, y1) {
|
||||
const dx = x1 - x0, dy = y1 - y0;
|
||||
const dist = Math.hypot(dx, dy);
|
||||
const steps = Math.max(1, Math.ceil(dist));
|
||||
const sx = dx / steps, sy = dy / steps;
|
||||
let px = x0, py = y0;
|
||||
for (let i = 1; i <= steps; i++) {
|
||||
const nx = x0 + sx * i, ny = y0 + sy * i;
|
||||
if (isSolid(t, nx, ny)) {
|
||||
return { hit: true, x: px, y: py, hitX: nx, hitY: ny, t: i / steps };
|
||||
}
|
||||
px = nx; py = ny;
|
||||
}
|
||||
return { hit: false, x: x1, y: y1, hitX: x1, hitY: y1, t: 1 };
|
||||
}
|
||||
|
||||
// First solid pixel at or below (x, y). Returns -1 if the column is clear all
|
||||
// the way down, which on an island map means "over the water".
|
||||
export function firstSolidBelow(t, x, y) {
|
||||
x |= 0;
|
||||
if (x < 0 || x >= t.w) return -1;
|
||||
for (let yy = Math.max(0, y | 0); yy < t.h; yy++) {
|
||||
if (t.mask[yy * t.w + x] !== AIR) return yy;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Highest solid pixel in a column — the outdoor surface.
|
||||
export function surfaceY(t, x) {
|
||||
x |= 0;
|
||||
if (x < 0 || x >= t.w) return -1;
|
||||
for (let y = 0; y < t.h; y++) {
|
||||
if (t.mask[y * t.w + x] !== AIR) return y;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
export function solidCount(t) {
|
||||
let n = 0;
|
||||
for (let i = 0; i < t.mask.length; i++) if (t.mask[i] !== AIR) n++;
|
||||
return n;
|
||||
}
|
||||
|
||||
// FNV-1a over the mask. Determinism tests compare these.
|
||||
export function hashMask(t) {
|
||||
let h = 0x811c9dc5;
|
||||
const m = t.mask;
|
||||
for (let i = 0; i < m.length; i++) {
|
||||
h ^= m[i];
|
||||
h = Math.imul(h, 0x01000193);
|
||||
}
|
||||
return h >>> 0;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Connected components
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// 4-connected labelling over pixels satisfying `solidPred`. Scanline fill keeps
|
||||
// the stack tiny even on a 3.5M-pixel map.
|
||||
function labelComponents(w, h, mask, wantSolid) {
|
||||
const labels = new Int32Array(w * h).fill(-1);
|
||||
const sizes = [];
|
||||
const stack = [];
|
||||
const ok = (i) => (wantSolid ? mask[i] !== AIR : mask[i] === AIR);
|
||||
|
||||
for (let sy = 0; sy < h; sy++) {
|
||||
for (let sxi = 0; sxi < w; sxi++) {
|
||||
const start = sy * w + sxi;
|
||||
if (labels[start] !== -1 || !ok(start)) continue;
|
||||
const id = sizes.length;
|
||||
let count = 0;
|
||||
stack.push(sxi, sy);
|
||||
while (stack.length) {
|
||||
const y = stack.pop(), x = stack.pop();
|
||||
const row = y * w;
|
||||
if (labels[row + x] !== -1 || !ok(row + x)) continue;
|
||||
let xl = x;
|
||||
while (xl > 0 && labels[row + xl - 1] === -1 && ok(row + xl - 1)) xl--;
|
||||
let xr = x;
|
||||
while (xr < w - 1 && labels[row + xr + 1] === -1 && ok(row + xr + 1)) xr++;
|
||||
for (let i = xl; i <= xr; i++) { labels[row + i] = id; count++; }
|
||||
for (const ny of [y - 1, y + 1]) {
|
||||
if (ny < 0 || ny >= h) continue;
|
||||
const nrow = ny * w;
|
||||
let i = xl;
|
||||
while (i <= xr) {
|
||||
while (i <= xr && (labels[nrow + i] !== -1 || !ok(nrow + i))) i++;
|
||||
if (i > xr) break;
|
||||
stack.push(i, ny);
|
||||
while (i <= xr && labels[nrow + i] === -1 && ok(nrow + i)) i++;
|
||||
}
|
||||
}
|
||||
}
|
||||
sizes.push(count);
|
||||
}
|
||||
}
|
||||
return { labels, sizes };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Density fields
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Evaluate `fn(x, y)` on a lattice of FIELD_STEP and return a bilinear sampler
|
||||
// over full-resolution coordinates.
|
||||
function coarseField(w, h, step, fn) {
|
||||
const cw = Math.ceil(w / step) + 1;
|
||||
const ch = Math.ceil(h / step) + 1;
|
||||
const data = new Float32Array(cw * ch);
|
||||
for (let j = 0; j < ch; j++) {
|
||||
for (let i = 0; i < cw; i++) data[j * cw + i] = fn(i * step, j * step);
|
||||
}
|
||||
return function sample(x, y) {
|
||||
const gx = x / step, gy = y / step;
|
||||
const i = Math.min(cw - 2, Math.max(0, Math.floor(gx)));
|
||||
const j = Math.min(ch - 2, Math.max(0, Math.floor(gy)));
|
||||
const fx = gx - i, fy = gy - j;
|
||||
const a = data[j * cw + i], b = data[j * cw + i + 1];
|
||||
const c = data[(j + 1) * cw + i], d = data[(j + 1) * cw + i + 1];
|
||||
const top = a + (b - a) * fx;
|
||||
const bot = c + (d - c) * fx;
|
||||
return top + (bot - top) * fy;
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Island generation
|
||||
// ---------------------------------------------------------------------------
|
||||
//
|
||||
// A heightfield surface filled down to the bottom of the world, minus a noise
|
||||
// cave system and minus the coastline. Caves are held back from the surface so
|
||||
// the top crust never reads as swiss cheese; below that they cut arches,
|
||||
// tunnels and the overhangs that make rope play worthwhile.
|
||||
|
||||
function generateIsland(t, rng) {
|
||||
const T = TERRAIN_TUNING;
|
||||
const { w, h } = t;
|
||||
const seedA = (rng() * 0x7fffffff) | 0;
|
||||
const seedB = (rng() * 0x7fffffff) | 0;
|
||||
const seedC = (rng() * 0x7fffffff) | 0;
|
||||
|
||||
const topMin = h * T.ISL_TOP_MIN;
|
||||
const topMax = h * T.ISL_TOP_MAX;
|
||||
|
||||
// Coastline envelope: 1 inland, 0 at the very edges, so the landmass sinks
|
||||
// below the waterline before it reaches the world border.
|
||||
const coast = Math.max(1, Math.floor(w * T.ISL_COAST_FRAC));
|
||||
const envelope = (x) => {
|
||||
const d = Math.min(x, w - 1 - x);
|
||||
if (d >= coast) return 1;
|
||||
return smoothstep(d / coast);
|
||||
};
|
||||
|
||||
// Surface height per column.
|
||||
const top = new Int32Array(w);
|
||||
for (let x = 0; x < w; x++) {
|
||||
const n = fbm1(x / T.ISL_SURFACE_SCALE, seedA, T.ISL_SURFACE_OCTAVES);
|
||||
const base = topMin + (topMax - topMin) * n;
|
||||
// Sink to well below the water line at the coasts.
|
||||
const e = envelope(x);
|
||||
top[x] = Math.round(base * e + (h + 60) * (1 - e));
|
||||
}
|
||||
|
||||
// Fill from the surface to the bottom of the world.
|
||||
for (let x = 0; x < w; x++) {
|
||||
const y0 = Math.max(0, top[x]);
|
||||
for (let y = y0; y < h; y++) t.mask[y * w + x] = SOLID;
|
||||
}
|
||||
|
||||
// Cave field.
|
||||
const caves = coarseField(w, h, T.FIELD_STEP, (x, y) =>
|
||||
fbm2(x / T.ISL_CAVE_SCALE, y / T.ISL_CAVE_SCALE, seedB, T.ISL_CAVE_OCTAVES));
|
||||
for (let x = 0; x < w; x++) {
|
||||
const guard = top[x] + T.ISL_CAVE_MARGIN;
|
||||
for (let y = guard; y < h; y++) {
|
||||
const i = y * w + x;
|
||||
if (t.mask[i] === AIR) continue;
|
||||
// Caves fade out near the very bottom so the island keeps a floor.
|
||||
const depthFade = y > h - 80 ? (h - y) / 80 : 1;
|
||||
if (caves(x, y) > T.ISL_CAVE_THRESHOLD + (1 - depthFade) * 0.4) {
|
||||
t.mask[i] = AIR;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A couple of big bites out of the sides, so no two islands read alike.
|
||||
const bites = 2 + Math.floor(rng() * 3);
|
||||
for (let b = 0; b < bites; b++) {
|
||||
const bx = Math.floor(rng() * w);
|
||||
const byBase = surfaceY(t, bx);
|
||||
if (byBase < 0) continue;
|
||||
const by = byBase + 40 + Math.floor(rng() * (h * 0.4));
|
||||
const r = 50 + Math.floor(rng() * 110);
|
||||
carveCircle(t, bx, by, r);
|
||||
}
|
||||
|
||||
// One or two arches: a random walk of overlapping circles through the body.
|
||||
const arches = 1 + Math.floor(rng() * 2);
|
||||
for (let a = 0; a < arches; a++) {
|
||||
let ax = w * (0.15 + rng() * 0.7);
|
||||
const startY = surfaceY(t, Math.floor(ax));
|
||||
if (startY < 0) continue;
|
||||
let ay = startY + 70 + rng() * 120;
|
||||
let dir = rng() < 0.5 ? -1 : 1;
|
||||
const r = 18 + rng() * 14;
|
||||
const steps = 40 + Math.floor(rng() * 60);
|
||||
for (let s = 0; s < steps; s++) {
|
||||
carveCircle(t, ax | 0, ay | 0, r | 0);
|
||||
ax += dir * (6 + rng() * 6);
|
||||
ay += (rng() - 0.5) * 9;
|
||||
if (ax < r || ax > w - r) dir = -dir;
|
||||
ay = Math.max(startY + 50, Math.min(h - 60, ay));
|
||||
}
|
||||
}
|
||||
|
||||
// Drop specks. Floating chunks are authentic Worms and stay, but single-digit
|
||||
// pixel crumbs just look like dirt on the screen.
|
||||
pruneSpecks(t, T.ISL_SPECK_MIN);
|
||||
seedC; // reserved channel, keeps seed consumption stable across tweaks
|
||||
}
|
||||
|
||||
function pruneSpecks(t, minSize) {
|
||||
const { labels, sizes } = labelComponents(t.w, t.h, t.mask, true);
|
||||
let dropped = 0;
|
||||
for (let i = 0; i < t.mask.length; i++) {
|
||||
const id = labels[i];
|
||||
if (id >= 0 && sizes[id] < minSize && t.mask[i] === SOLID) { t.mask[i] = AIR; dropped++; }
|
||||
}
|
||||
return dropped;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Cavern generation
|
||||
// ---------------------------------------------------------------------------
|
||||
//
|
||||
// The inverse problem: start solid and carve. Everything is walled in by an
|
||||
// indestructible ROCK frame, so projectiles ricochet off the ceiling and no
|
||||
// worm can ever be knocked out of the world — the whole point of the shape.
|
||||
//
|
||||
// A plain noise threshold does NOT work here: the base octave decides huge
|
||||
// regions at once, so you get one usable chamber and two thirds of the map
|
||||
// welded shut. Instead the void is carved as a band between a wavy ceiling and
|
||||
// a wavy floor — connected across the full width by construction — and the
|
||||
// interest comes from what gets put BACK: pillars, stalactites and floating
|
||||
// ledges from a second noise field.
|
||||
|
||||
function generateCavern(t, rng) {
|
||||
const T = TERRAIN_TUNING;
|
||||
const { w, h } = t;
|
||||
const seedCeil = (rng() * 0x7fffffff) | 0;
|
||||
const seedFloor = (rng() * 0x7fffffff) | 0;
|
||||
const seedBlob = (rng() * 0x7fffffff) | 0;
|
||||
const seedPock = (rng() * 0x7fffffff) | 0;
|
||||
const b = T.CAV_BORDER;
|
||||
|
||||
t.mask.fill(SOLID);
|
||||
|
||||
// Ceiling and floor curves.
|
||||
const ceilY = new Int32Array(w);
|
||||
const floorY = new Int32Array(w);
|
||||
for (let x = 0; x < w; x++) {
|
||||
const nc = fbm1(x / T.CAV_SURFACE_SCALE, seedCeil, T.CAV_SURFACE_OCTAVES);
|
||||
const nf = fbm1(x / T.CAV_SURFACE_SCALE, seedFloor, T.CAV_SURFACE_OCTAVES);
|
||||
ceilY[x] = Math.round(h * (T.CAV_CEIL_MIN + (T.CAV_CEIL_MAX - T.CAV_CEIL_MIN) * nc));
|
||||
floorY[x] = Math.round(h * (T.CAV_FLOOR_MIN + (T.CAV_FLOOR_MAX - T.CAV_FLOOR_MIN) * nf));
|
||||
// Never let the two curves cross or pinch the cave shut.
|
||||
if (floorY[x] - ceilY[x] < 200) floorY[x] = ceilY[x] + 200;
|
||||
}
|
||||
|
||||
for (let x = 0; x < w; x++) {
|
||||
for (let y = ceilY[x]; y < floorY[x]; y++) t.mask[y * w + x] = AIR;
|
||||
}
|
||||
|
||||
// Put material back inside the void: stalactites hanging off the ceiling,
|
||||
// mounds rising off the floor, pillars, and slabs floating in mid-air. All
|
||||
// one noise field, so they read as one rock formation rather than props.
|
||||
const blobs = coarseField(w, h, T.FIELD_STEP, (x, y) =>
|
||||
fbm2(x / T.CAV_BLOB_SCALE, y / T.CAV_BLOB_SCALE, seedBlob, T.CAV_BLOB_OCTAVES));
|
||||
for (let x = 0; x < w; x++) {
|
||||
for (let y = ceilY[x]; y < floorY[x]; y++) {
|
||||
if (blobs(x, y) > T.CAV_BLOB_THRESHOLD) t.mask[y * w + x] = SOLID;
|
||||
}
|
||||
}
|
||||
|
||||
// ...and eat pockets back out of the floor and ceiling, so the rock body has
|
||||
// side caves and the floor has pits worth rope-swinging over.
|
||||
const pockets = coarseField(w, h, T.FIELD_STEP, (x, y) =>
|
||||
fbm2(x / T.CAV_POCKET_SCALE, y / T.CAV_POCKET_SCALE, seedPock, T.CAV_POCKET_OCTAVES));
|
||||
for (let x = 0; x < w; x++) {
|
||||
for (let y = b; y < h - b; y++) {
|
||||
const i = y * w + x;
|
||||
if (t.mask[i] !== SOLID) continue;
|
||||
// Only within reach of the main void — no sealed bubbles deep in the rock.
|
||||
const near = y > ceilY[x] - 160 && y < floorY[x] + 160;
|
||||
if (near && pockets(x, y) > T.CAV_POCKET_THRESHOLD) t.mask[i] = AIR;
|
||||
}
|
||||
}
|
||||
|
||||
// Keep only the largest air pocket; seal the rest. A cavern where half the
|
||||
// worms spawn in an unreachable bubble is not a level.
|
||||
const { labels, sizes } = labelComponents(w, h, t.mask, false);
|
||||
let best = -1, bestN = -1;
|
||||
for (let i = 0; i < sizes.length; i++) if (sizes[i] > bestN) { bestN = sizes[i]; best = i; }
|
||||
if (best >= 0) {
|
||||
for (let i = 0; i < t.mask.length; i++) {
|
||||
if (t.mask[i] === AIR && labels[i] !== best) t.mask[i] = SOLID;
|
||||
}
|
||||
}
|
||||
pruneSpecks(t, T.CAV_SPECK_MIN);
|
||||
|
||||
// Indestructible frame, drawn last so nothing carved it.
|
||||
for (let y = 0; y < h; y++) {
|
||||
for (let x = 0; x < w; x++) {
|
||||
if (x < b || y < b || x >= w - b || y >= h - b) t.mask[y * w + x] = ROCK;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Spawn points
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Every column that offers flat-enough footing with headroom above it, sampled
|
||||
// every few pixels. On a cavern map this finds ledges inside the chamber as
|
||||
// well as the floor.
|
||||
export function findFootholds(t, stride = 6) {
|
||||
const T = TERRAIN_TUNING;
|
||||
const out = [];
|
||||
for (let x = T.SPAWN_FLAT_SPAN; x < t.w - T.SPAWN_FLAT_SPAN; x += stride) {
|
||||
// Walk the column top-down looking for air->solid transitions (ledges).
|
||||
let y = 0;
|
||||
while (y < t.h) {
|
||||
// find next solid
|
||||
while (y < t.h && t.mask[y * t.w + x] === AIR) y++;
|
||||
if (y >= t.h) break;
|
||||
const surf = y;
|
||||
// measure solid depth
|
||||
let depth = 0;
|
||||
while (y < t.h && t.mask[y * t.w + x] !== AIR) { depth++; y++; }
|
||||
if (t.mask[surf * t.w + x] === ROCK) continue;
|
||||
if (depth < T.SPAWN_FOOTING) continue;
|
||||
if (surf >= t.waterY - 12) continue; // in or under the water
|
||||
if (!hasHeadroom(t, x, surf, T.SPAWN_HEADROOM)) continue;
|
||||
if (!isFlatEnough(t, x, surf)) continue;
|
||||
out.push({ x, y: surf });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function hasHeadroom(t, x, surfY, need) {
|
||||
const top = Math.max(0, surfY - need);
|
||||
for (let y = top; y < surfY; y++) if (t.mask[y * t.w + x] !== AIR) return false;
|
||||
return surfY - top >= need * 0.75;
|
||||
}
|
||||
|
||||
function isFlatEnough(t, x, surfY) {
|
||||
const T = TERRAIN_TUNING;
|
||||
let lo = surfY, hi = surfY;
|
||||
for (let d = -T.SPAWN_FLAT_SPAN; d <= T.SPAWN_FLAT_SPAN; d++) {
|
||||
const yy = nearestSurfaceNear(t, x + d, surfY);
|
||||
if (yy < 0) return false;
|
||||
if (yy < lo) lo = yy;
|
||||
if (yy > hi) hi = yy;
|
||||
}
|
||||
return hi - lo <= T.SPAWN_FLAT_TOLERANCE;
|
||||
}
|
||||
|
||||
// The surface of the ledge nearest `refY` in column x — not the topmost
|
||||
// surface, which on a cavern map is the ceiling.
|
||||
function nearestSurfaceNear(t, x, refY, window = 30) {
|
||||
if (x < 0 || x >= t.w) return -1;
|
||||
for (let d = 0; d <= window; d++) {
|
||||
for (const y of (d === 0 ? [refY] : [refY - d, refY + d])) {
|
||||
if (y <= 0 || y >= t.h) continue;
|
||||
if (t.mask[y * t.w + x] !== AIR && t.mask[(y - 1) * t.w + x] === AIR) return y;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Pick `count` spawn points, spread out, drawn from the available footholds.
|
||||
// Returns null if the map cannot seat them all with the required separation.
|
||||
export function pickSpawns(t, rng, count, minSep = TERRAIN_TUNING.SPAWN_MIN_SEP, pool = null) {
|
||||
pool = pool ?? findFootholds(t);
|
||||
if (pool.length < count) return null;
|
||||
|
||||
// Shuffle deterministically, then greedily accept anything far enough from
|
||||
// what we already took. Greedy on a shuffled pool spreads worms out without
|
||||
// the clumping a pure random draw gives.
|
||||
const shuffled = pool.slice();
|
||||
for (let i = shuffled.length - 1; i > 0; i--) {
|
||||
const j = Math.floor(rng() * (i + 1));
|
||||
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
|
||||
}
|
||||
|
||||
for (let relax = 0; relax < 4; relax++) {
|
||||
const sep = minSep * (1 - relax * 0.2);
|
||||
const taken = [];
|
||||
for (const p of shuffled) {
|
||||
if (taken.every((q) => Math.hypot(q.x - p.x, q.y - p.y) >= sep)) {
|
||||
taken.push(p);
|
||||
if (taken.length === count) return taken;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Generation entry point + fairness lint
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function generateMap({ seed, shape = 'island', size = 'medium', theme = 'forest' }) {
|
||||
const dims = MAP_SIZES[size] ?? MAP_SIZES.medium;
|
||||
const t = createTerrain(dims.w, dims.h, { shape, theme, seed, size });
|
||||
const rng = mulberry32(seed >>> 0);
|
||||
if (shape === 'cavern') generateCavern(t, rng);
|
||||
else generateIsland(t, rng);
|
||||
return t;
|
||||
}
|
||||
|
||||
// Everything a map must satisfy before a match is allowed to start on it.
|
||||
// The generator retries with the next seed until this passes, and the verifier
|
||||
// asserts it over thousands of seeds.
|
||||
export function lintMap(t, { worms = 8 } = {}) {
|
||||
const T = TERRAIN_TUNING;
|
||||
const reasons = [];
|
||||
const solid = solidCount(t);
|
||||
const frac = solid / (t.w * t.h);
|
||||
|
||||
if (t.shape === 'cavern') {
|
||||
const openFrac = 1 - frac;
|
||||
if (openFrac < T.CAV_OPEN_MIN) reasons.push(`cavern too cramped (${openFrac.toFixed(2)} open)`);
|
||||
if (openFrac > T.CAV_OPEN_MAX) reasons.push(`cavern too empty (${openFrac.toFixed(2)} open)`);
|
||||
// The frame must be intact all the way round or worms leak out of the world.
|
||||
for (let x = 0; x < t.w; x++) {
|
||||
if (t.mask[x] !== ROCK || t.mask[(t.h - 1) * t.w + x] !== ROCK) {
|
||||
reasons.push('cavern frame breached'); break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (frac < 0.12) reasons.push(`island too sparse (${frac.toFixed(2)} solid)`);
|
||||
if (frac > 0.70) reasons.push(`island too solid (${frac.toFixed(2)} solid)`);
|
||||
// Air strikes need open sky over a decent share of the surface.
|
||||
let openSky = 0, columns = 0;
|
||||
for (let x = 0; x < t.w; x += 8) {
|
||||
const s = surfaceY(t, x);
|
||||
columns++;
|
||||
if (s > 60) openSky++;
|
||||
}
|
||||
if (openSky / columns < 0.5) reasons.push('not enough open sky for air strikes');
|
||||
}
|
||||
|
||||
// Twice the footholds we need, so spawn placement has real choice.
|
||||
const pool = findFootholds(t);
|
||||
if (pool.length < worms * 2) reasons.push(`only ${pool.length} footholds for ${worms} worms`);
|
||||
|
||||
// And they must actually seat with separation.
|
||||
const spawns = pickSpawns(t, mulberry32(0xa11ce ^ (t.seed >>> 0)), worms, T.SPAWN_MIN_SEP, pool);
|
||||
if (!spawns) reasons.push(`cannot seat ${worms} worms ${T.SPAWN_MIN_SEP}px apart`);
|
||||
|
||||
// Spread: worms bunched into one third of the map is a firing-squad start.
|
||||
if (spawns) {
|
||||
const xs = spawns.map((s) => s.x);
|
||||
const span = Math.max(...xs) - Math.min(...xs);
|
||||
if (span < t.w * 0.45) reasons.push(`spawns span only ${(span / t.w).toFixed(2)} of the map`);
|
||||
}
|
||||
|
||||
return { ok: reasons.length === 0, reasons, spawns, solidFraction: frac, footholds: pool.length };
|
||||
}
|
||||
|
||||
// Generate until a map passes lint. Deterministic: the same starting seed
|
||||
// always lands on the same accepted map.
|
||||
export function generateValidMap(opts, { worms = 8, maxTries = 40 } = {}) {
|
||||
let seed = opts.seed >>> 0;
|
||||
let last = null;
|
||||
for (let i = 0; i < maxTries; i++) {
|
||||
const t = generateMap({ ...opts, seed });
|
||||
const lint = lintMap(t, { worms });
|
||||
if (lint.ok) return { terrain: t, lint, tries: i + 1, seed };
|
||||
last = { terrain: t, lint, tries: i + 1, seed };
|
||||
seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;
|
||||
}
|
||||
return last;
|
||||
}
|
||||
|
|
@ -1,115 +0,0 @@
|
|||
// Worms — level themes.
|
||||
//
|
||||
// Zero imports. Each theme carries a full procedural palette so the game is
|
||||
// playable and legible with no art at all, plus named art slots that Brian can
|
||||
// fill in later. The slots are resolved at runtime with `textures.exists()`
|
||||
// (never a flag), so dropping a PNG in is the only step needed to upgrade one.
|
||||
//
|
||||
// Art slots per theme, all optional:
|
||||
// worms-bg-<id> 1920x1080 backdrop, parallaxed
|
||||
// worms-fill-<id> seamless tile for the inside of the terrain (256x256)
|
||||
// worms-surface-<id> seamless strip for the top crust (256x48)
|
||||
// worms-objects-<id> spritesheet of background scenery, 160x160 cells
|
||||
//
|
||||
// Paths live in data/worms-artwork.json; anything still null renders
|
||||
// procedurally from the palette below.
|
||||
|
||||
export const THEMES = [
|
||||
{
|
||||
id: 'forest', name: 'Forest',
|
||||
sky: [0x6fb7e8, 0xbfe4f5],
|
||||
fill: 0x6b4a2a, fillDark: 0x4a3119, fillLight: 0x83603a,
|
||||
surface: 0x4f9d3a, surfaceDark: 0x37732a,
|
||||
rock: 0x54514c,
|
||||
water: 0x2f6fb0, waterFoam: 0x9fd0f0,
|
||||
scorch: 0x2a1c10,
|
||||
grain: 0.16, objects: ['tree', 'bush', 'rock', 'stump'],
|
||||
},
|
||||
{
|
||||
id: 'desert', name: 'Desert',
|
||||
sky: [0xe8b878, 0xf7e2bb],
|
||||
fill: 0xc79a5c, fillDark: 0x9c7440, fillLight: 0xdcb478,
|
||||
surface: 0xe6c98d, surfaceDark: 0xc0a066,
|
||||
rock: 0x8a7358,
|
||||
water: 0x3a8fa8, waterFoam: 0xbfe8ef,
|
||||
scorch: 0x5c3f22,
|
||||
grain: 0.10, objects: ['cactus', 'skull', 'dune', 'rock'],
|
||||
},
|
||||
{
|
||||
id: 'farm', name: 'Farm',
|
||||
sky: [0x86c4ea, 0xd8eef8],
|
||||
fill: 0x7a5233, fillDark: 0x543720, fillLight: 0x96683f,
|
||||
surface: 0x76b93f, surfaceDark: 0x53902c,
|
||||
rock: 0x6a655c,
|
||||
water: 0x3a76ab, waterFoam: 0xa8d6ef,
|
||||
scorch: 0x33220f,
|
||||
grain: 0.14, objects: ['haybale', 'fence', 'barn', 'scarecrow'],
|
||||
},
|
||||
{
|
||||
id: 'hell', name: 'Hell',
|
||||
sky: [0x3a0d0d, 0x8c2416],
|
||||
fill: 0x5a2320, fillDark: 0x3a1412, fillLight: 0x7b3226,
|
||||
surface: 0x9c3b1e, surfaceDark: 0x6d2712,
|
||||
rock: 0x4a3230,
|
||||
water: 0xd4491c, waterFoam: 0xffb057,
|
||||
scorch: 0x1b0705,
|
||||
grain: 0.20, objects: ['pillar', 'skullpile', 'spike', 'brazier'],
|
||||
},
|
||||
{
|
||||
id: 'arctic', name: 'Arctic',
|
||||
sky: [0x9dc6e0, 0xe8f4fb],
|
||||
fill: 0x8fa9bd, fillDark: 0x6b8296, fillLight: 0xaec5d6,
|
||||
surface: 0xf2fbff, surfaceDark: 0xcfe4f2,
|
||||
rock: 0x6e7d8a,
|
||||
water: 0x2f6d9e, waterFoam: 0xd8f0ff,
|
||||
scorch: 0x44525e,
|
||||
grain: 0.08, objects: ['iceberg', 'pine', 'igloo', 'floe'],
|
||||
},
|
||||
{
|
||||
id: 'jungle', name: 'Jungle',
|
||||
sky: [0x77bfa8, 0xd3ecdf],
|
||||
fill: 0x53412a, fillDark: 0x352a19, fillLight: 0x6d5637,
|
||||
surface: 0x2f8f4a, surfaceDark: 0x1f6a35,
|
||||
rock: 0x4b5347,
|
||||
water: 0x2b7f77, waterFoam: 0xa6e2d5,
|
||||
scorch: 0x1a1409,
|
||||
grain: 0.18, objects: ['palm', 'vine', 'idol', 'fern'],
|
||||
},
|
||||
{
|
||||
id: 'construction', name: 'Construction',
|
||||
sky: [0x8f9aa6, 0xd6dde3],
|
||||
fill: 0x7d7a72, fillDark: 0x585650, fillLight: 0x99968c,
|
||||
surface: 0xb8a24e, surfaceDark: 0x8d7b39,
|
||||
rock: 0x5f5d59,
|
||||
water: 0x4a6f86, waterFoam: 0xc2dbe8,
|
||||
scorch: 0x2c2b28,
|
||||
grain: 0.12, objects: ['girder', 'crane', 'pipe', 'barrelstack'],
|
||||
},
|
||||
{
|
||||
id: 'space', name: 'Space',
|
||||
sky: [0x080a1c, 0x1d2352],
|
||||
fill: 0x5a4f6e, fillDark: 0x3a3149, fillLight: 0x776a8d,
|
||||
surface: 0x9a86c4, surfaceDark: 0x6f5f94,
|
||||
rock: 0x413a52,
|
||||
water: 0x2b3f8c, waterFoam: 0x8fa6ff,
|
||||
scorch: 0x14101c,
|
||||
grain: 0.15, objects: ['satellite', 'crater', 'monolith', 'antenna'],
|
||||
},
|
||||
];
|
||||
|
||||
export const THEMES_BY_ID = Object.fromEntries(THEMES.map((t) => [t.id, t]));
|
||||
|
||||
export function getTheme(id) { return THEMES_BY_ID[id] ?? THEMES[0]; }
|
||||
|
||||
export const THEME_IDS = THEMES.map((t) => t.id);
|
||||
|
||||
// Art slot keys for a theme. `assetManifest.js` resolves these against
|
||||
// data/worms-artwork.json and skips anything still unpainted.
|
||||
export function artKeys(themeId) {
|
||||
return {
|
||||
backdrop: `worms-bg-${themeId}`,
|
||||
fill: `worms-fill-${themeId}`,
|
||||
surface: `worms-surface-${themeId}`,
|
||||
objects: `worms-objects-${themeId}`,
|
||||
};
|
||||
}
|
||||
|
|
@ -1,214 +0,0 @@
|
|||
// Worms — the weapon table.
|
||||
//
|
||||
// Zero imports. The canonical numbers live here rather than in data/*.json on
|
||||
// purpose: the verifier, the AI and the scene must all agree on them exactly,
|
||||
// and a plain ESM import gives that for free in both the browser and bare Node
|
||||
// with no fetch and no async boot ordering.
|
||||
//
|
||||
// `kind` decides which input flow the weapon needs, and it is the only switch
|
||||
// the scene and the AI branch on:
|
||||
//
|
||||
// charge hold to build power, fires a projectile along the aim angle
|
||||
// instant fires the moment you press, at the aim angle (hitscan)
|
||||
// melee hits whatever is directly in front of the worm
|
||||
// place drops at the worm's feet
|
||||
// target pick a point on the map first, then it happens
|
||||
// utility changes the worm's state rather than damaging anything
|
||||
// meta not a weapon at all (skip, surrender)
|
||||
//
|
||||
// Damage numbers are the Worms Armageddon defaults. `blastRadius` is the damage
|
||||
// radius; `crater` is how much terrain goes, and is deliberately a little
|
||||
// smaller so a hit that hurts does not always open a hole you can fall through.
|
||||
|
||||
export const WEAPON_KINDS = ['charge', 'instant', 'melee', 'place', 'target', 'utility', 'meta'];
|
||||
|
||||
// Shared projectile flight profiles.
|
||||
const ARC = { windAffected: true, gravity: true };
|
||||
const BOUNCY = {
|
||||
...ARC, bounce: true, restitution: 0.42, tangentFriction: 0.80,
|
||||
};
|
||||
|
||||
export const WEAPONS = [
|
||||
{
|
||||
id: 'bazooka', name: 'Bazooka', slot: 1, kind: 'charge',
|
||||
ammo: Infinity, damage: 45, blastRadius: 55, blastPower: 300, crater: 44,
|
||||
speedMin: 180, speedMax: 850, projectile: { ...ARC, maxAge: 12 },
|
||||
sfx: 'worms-launch', crateWeight: 0, endsTurn: true,
|
||||
tip: 'The workhorse. Watch the wind.',
|
||||
},
|
||||
{
|
||||
id: 'grenade', name: 'Grenade', slot: 2, kind: 'charge',
|
||||
ammo: Infinity, damage: 45, blastRadius: 55, blastPower: 300, crater: 44,
|
||||
speedMin: 150, speedMax: 700, fuseOptions: [1, 2, 3, 4, 5], defaultFuse: 3,
|
||||
projectile: { ...BOUNCY, windAffected: false, maxAge: 12 },
|
||||
sfx: 'worms-launch', crateWeight: 0, endsTurn: true,
|
||||
tip: 'Bounces. Set the fuse with 1-5.',
|
||||
},
|
||||
{
|
||||
id: 'cluster', name: 'Cluster Bomb', slot: 2, kind: 'charge',
|
||||
ammo: 5, damage: 25, blastRadius: 38, blastPower: 210, crater: 30,
|
||||
speedMin: 150, speedMax: 700, fuseOptions: [1, 2, 3, 4, 5], defaultFuse: 3,
|
||||
projectile: { ...BOUNCY, windAffected: false, maxAge: 12 },
|
||||
cluster: { count: 5, damage: 25, blastRadius: 34, blastPower: 190, crater: 26, speed: 260, fuse: 1.6 },
|
||||
sfx: 'worms-launch', crateWeight: 10, endsTurn: true,
|
||||
tip: 'Splits into five bomblets. Good over flat ground.',
|
||||
},
|
||||
{
|
||||
id: 'shotgun', name: 'Shotgun', slot: 3, kind: 'instant',
|
||||
ammo: 3, damage: 25, blastRadius: 28, blastPower: 150, crater: 22,
|
||||
shots: 2, range: 1400,
|
||||
sfx: 'worms-shotgun', crateWeight: 10, endsTurn: true, endsTurnAfterShots: true,
|
||||
tip: 'Two shots per turn. Fires straight, ignores wind.',
|
||||
},
|
||||
{
|
||||
id: 'uzi', name: 'Uzi', slot: 3, kind: 'instant',
|
||||
ammo: 3, damage: 5, blastRadius: 12, blastPower: 60, crater: 7,
|
||||
burst: 12, burstInterval: 0.06, spread: 0.05, range: 1400,
|
||||
sfx: 'worms-uzi', crateWeight: 10, endsTurn: true,
|
||||
tip: 'Twelve rounds of chip damage and a shove.',
|
||||
},
|
||||
{
|
||||
id: 'firepunch', name: 'Fire Punch', slot: 4, kind: 'melee',
|
||||
ammo: 3, damage: 30, blastRadius: 34, blastPower: 400, crater: 0,
|
||||
reach: 26, launchUp: 340,
|
||||
selfLaunch: { vx: 40, vy: -300 },
|
||||
sfx: 'worms-punch', crateWeight: 8, endsTurn: true,
|
||||
tip: 'Uppercut. Sends them up, not away — line up a drop.',
|
||||
},
|
||||
{
|
||||
id: 'dynamite', name: 'Dynamite', slot: 5, kind: 'place',
|
||||
ammo: 2, damage: 75, blastRadius: 90, blastPower: 480, crater: 72,
|
||||
fuse: 5,
|
||||
sfx: 'worms-fuse', crateWeight: 8, endsTurn: true,
|
||||
tip: 'Five second fuse. Plant it and run.',
|
||||
},
|
||||
{
|
||||
id: 'mine', name: 'Land Mine', slot: 5, kind: 'place',
|
||||
ammo: 2, damage: 50, blastRadius: 60, blastPower: 380, crater: 48,
|
||||
armDelay: 1.0, triggerRadius: 34, fuse: 2.0,
|
||||
sfx: 'worms-mine', crateWeight: 8, endsTurn: true,
|
||||
tip: 'Arms after a second, then waits.',
|
||||
},
|
||||
{
|
||||
id: 'airstrike', name: 'Air Strike', slot: 6, kind: 'target',
|
||||
ammo: 2, damage: 30, blastRadius: 44, blastPower: 250, crater: 36,
|
||||
bombs: 5, bombSpacing: 46, dropSpeed: 260, planeHeight: 40,
|
||||
projectile: { ...ARC, maxAge: 12 },
|
||||
sfx: 'worms-plane', crateWeight: 8, endsTurn: true, needsOpenSky: true,
|
||||
tip: 'Click a target. Needs open sky above it.',
|
||||
},
|
||||
{
|
||||
id: 'homing', name: 'Homing Missile', slot: 6, kind: 'target',
|
||||
ammo: 2, damage: 45, blastRadius: 55, blastPower: 300, crater: 44,
|
||||
speedMin: 200, speedMax: 700,
|
||||
projectile: { ...ARC, maxAge: 14, homing: true, homingDelay: 0.55, homingTurn: 3.4 },
|
||||
aimAfterTarget: true,
|
||||
sfx: 'worms-launch', crateWeight: 6, endsTurn: true,
|
||||
tip: 'Mark a target, then fire. It will come around.',
|
||||
},
|
||||
{
|
||||
id: 'hhg', name: 'Holy Hand Grenade', slot: 7, kind: 'charge',
|
||||
ammo: 1, damage: 90, blastRadius: 120, blastPower: 700, crater: 95,
|
||||
speedMin: 150, speedMax: 620, fuse: 5,
|
||||
projectile: { ...BOUNCY, windAffected: false, restitution: 0.30, maxAge: 12 },
|
||||
sfx: 'worms-hallelujah', crateWeight: 3, endsTurn: true, super: true,
|
||||
tip: 'And the Lord did grin.',
|
||||
},
|
||||
{
|
||||
id: 'blowtorch', name: 'Blowtorch', slot: 8, kind: 'utility',
|
||||
ammo: 2, damage: 0, blastRadius: 0, blastPower: 0, crater: 0,
|
||||
burnRadius: 13, burnSpeed: 150, fuel: 2.6,
|
||||
sfx: 'worms-torch', crateWeight: 6, endsTurn: false,
|
||||
tip: 'Dig a tunnel. Hold the direction you want to go.',
|
||||
},
|
||||
{
|
||||
id: 'girder', name: 'Girder', slot: 8, kind: 'target',
|
||||
ammo: 2, damage: 0, blastRadius: 0, blastPower: 0, crater: 0,
|
||||
length: 130, thickness: 9, angles: [0, Math.PI / 6, Math.PI / 3, Math.PI / 2,
|
||||
-Math.PI / 3, -Math.PI / 6],
|
||||
sfx: 'worms-girder', crateWeight: 6, endsTurn: false, buildsTerrain: true,
|
||||
tip: 'Build a platform. Rotate with the mouse wheel.',
|
||||
},
|
||||
{
|
||||
id: 'teleport', name: 'Teleport', slot: 9, kind: 'target',
|
||||
ammo: 2, damage: 0, blastRadius: 0, blastPower: 0, crater: 0,
|
||||
sfx: 'worms-teleport', crateWeight: 6, endsTurn: false,
|
||||
tip: 'Click anywhere you can fit. Best escape in the game.',
|
||||
},
|
||||
{
|
||||
id: 'ninjarope', name: 'Ninja Rope', slot: 9, kind: 'utility',
|
||||
ammo: 5, damage: 0, blastRadius: 0, blastPower: 0, crater: 0,
|
||||
sfx: 'worms-rope', crateWeight: 8, endsTurn: false, movement: true,
|
||||
tip: 'Aim, fire, swing. Reel with up and down, let go with the fire key.',
|
||||
},
|
||||
{
|
||||
id: 'skip', name: 'Skip Go', slot: 0, kind: 'meta',
|
||||
ammo: Infinity, damage: 0, blastRadius: 0, blastPower: 0, crater: 0,
|
||||
sfx: null, crateWeight: 0, endsTurn: true,
|
||||
tip: 'Pass the turn.',
|
||||
},
|
||||
{
|
||||
id: 'surrender', name: 'Surrender', slot: 0, kind: 'meta',
|
||||
ammo: Infinity, damage: 0, blastRadius: 0, blastPower: 0, crater: 0,
|
||||
sfx: null, crateWeight: 0, endsTurn: true, surrender: true,
|
||||
tip: 'Retire the whole team.',
|
||||
},
|
||||
];
|
||||
|
||||
export const WEAPONS_BY_ID = Object.fromEntries(WEAPONS.map((w) => [w.id, w]));
|
||||
|
||||
export function getWeapon(id) { return WEAPONS_BY_ID[id] ?? null; }
|
||||
|
||||
// The order weapons appear in the panel: by slot, then by table order.
|
||||
export const PANEL_ORDER = WEAPONS
|
||||
.filter((w) => w.id !== 'surrender')
|
||||
.slice()
|
||||
.sort((a, b) => (a.slot - b.slot) || WEAPONS.indexOf(a) - WEAPONS.indexOf(b))
|
||||
.map((w) => w.id);
|
||||
|
||||
// Starting ammo for a fresh team. Infinity stays infinite; everything else is
|
||||
// the table value, so a match config can scale it in one place.
|
||||
export function startingAmmo(scale = 1) {
|
||||
const out = {};
|
||||
for (const w of WEAPONS) {
|
||||
out[w.id] = w.ammo === Infinity ? Infinity : Math.max(0, Math.round(w.ammo * scale));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Weapons a crate can contain, weighted. Anything with crateWeight 0 (the
|
||||
// infinite-ammo staples and the meta entries) never drops.
|
||||
export const CRATE_TABLE = WEAPONS.filter((w) => (w.crateWeight ?? 0) > 0);
|
||||
|
||||
export function rollCrateWeapon(rng) {
|
||||
const total = CRATE_TABLE.reduce((s, w) => s + w.crateWeight, 0);
|
||||
let r = rng() * total;
|
||||
for (const w of CRATE_TABLE) {
|
||||
r -= w.crateWeight;
|
||||
if (r <= 0) return w.id;
|
||||
}
|
||||
return CRATE_TABLE[CRATE_TABLE.length - 1].id;
|
||||
}
|
||||
|
||||
// How much ammo a crate of this weapon grants.
|
||||
export function crateAmmoFor(id) {
|
||||
const w = getWeapon(id);
|
||||
if (!w) return 1;
|
||||
return w.super ? 1 : (w.ammo === Infinity ? 1 : Math.max(1, Math.min(3, w.ammo)));
|
||||
}
|
||||
|
||||
// Charge weapons map a 0..1 hold into a launch speed.
|
||||
export function launchSpeed(weapon, power) {
|
||||
const lo = weapon.speedMin ?? 200;
|
||||
const hi = weapon.speedMax ?? 800;
|
||||
return lo + (hi - lo) * Math.max(0, Math.min(1, power));
|
||||
}
|
||||
|
||||
// The flight profile handed to WormsPhysics, with the per-shot fuse folded in.
|
||||
export function projectileSpec(weapon, { fuse = null } = {}) {
|
||||
const base = weapon.projectile ?? {};
|
||||
const spec = { ...base };
|
||||
const f = fuse ?? weapon.fuse ?? null;
|
||||
if (f != null) spec.fuse = f;
|
||||
return spec;
|
||||
}
|
||||
|
|
@ -1,97 +0,0 @@
|
|||
# Worms
|
||||
|
||||
Two teams of worms take turns lobbing explosives at each other across a
|
||||
crumbling landscape. Last team standing wins. Everything you shoot at is
|
||||
destructible, including the ground you are standing on.
|
||||
|
||||
---
|
||||
|
||||
## The turn
|
||||
|
||||
You get **45 seconds** to move and take one shot. The moment you fire, a
|
||||
**5 second retreat timer** starts — use it to get somewhere safer, because the
|
||||
next worm to move will be aiming at wherever you stop.
|
||||
|
||||
Only one of your worms plays per turn, and it rotates through the team
|
||||
automatically. You do not get to pick.
|
||||
|
||||
---
|
||||
|
||||
## Controls
|
||||
|
||||
| Key | Action |
|
||||
|---|---|
|
||||
| **← →** | Walk |
|
||||
| **↑ ↓** | Aim up and down |
|
||||
| **Space** (hold) | Charge the shot — release to fire |
|
||||
| **Enter** | Jump forward |
|
||||
| **Backspace** | Backflip (higher, backwards) |
|
||||
| **1 – 9** | Weapon slots — press again to cycle within a slot |
|
||||
| **F** | Change the fuse on grenades and cluster bombs |
|
||||
| **Tab** | Open the weapon panel |
|
||||
| **K** | Skip your go |
|
||||
| **Esc** | Leave the match (press twice) |
|
||||
|
||||
**Mouse:** drag away from your worm to aim like a slingshot — the direction sets
|
||||
the angle, the distance sets the power. Release to fire. Right-drag pans the
|
||||
camera and the wheel zooms.
|
||||
|
||||
While on the **ninja rope**, ↑ and ↓ reel the rope in and out instead of aiming,
|
||||
← and → swing you, and the fire key lets go.
|
||||
|
||||
---
|
||||
|
||||
## Reading the screen
|
||||
|
||||
- The **arrow** bobs over the worm whose turn it is.
|
||||
- The **wind gauge** at the top right shows strength and direction. Wind pushes
|
||||
the bazooka and the air strike; it does **not** touch grenades, the shotgun or
|
||||
the uzi.
|
||||
- Each worm's **health bar** sits above it. Team totals are top left.
|
||||
|
||||
---
|
||||
|
||||
## Weapons worth knowing
|
||||
|
||||
- **Bazooka** — the workhorse. Arcs, and the wind matters.
|
||||
- **Grenade** — bounces, and detonates on its **fuse**, not on impact. Press
|
||||
**F** to change the fuse after selecting it.
|
||||
- **Cluster Bomb** — splits into five bomblets. Devastating over flat ground,
|
||||
wasted in a pit.
|
||||
- **Fire Punch** — sends a worm straight **up**, not away. Line one up next to a
|
||||
drop, or over water.
|
||||
- **Dynamite** — huge, five second fuse, planted at your feet. Plant and run.
|
||||
- **Holy Hand Grenade** — one per match. It ends arguments.
|
||||
- **Ninja Rope** — the skill weapon. Fire it at terrain, swing, and reach places
|
||||
nobody expects you to reach.
|
||||
|
||||
---
|
||||
|
||||
## Things that will kill you
|
||||
|
||||
- **Water.** Anything that touches it drowns, no matter how much health it has.
|
||||
Knocking a worm into the sea is usually cheaper than shooting it to death.
|
||||
- **Falling.** Long drops hurt, and being blasted upward then landing counts.
|
||||
- **Mines and oil drums.** Scattered around the map. Mines arm after a second
|
||||
and chase nothing — they just wait. Drums chain-detonate.
|
||||
- **Your own blast.** Standing next to your own explosion is a classic.
|
||||
- **Sudden Death.** After 15 rounds every worm drops to 1 health and the water
|
||||
starts rising every turn. Nothing survives a long game.
|
||||
|
||||
---
|
||||
|
||||
## Crates
|
||||
|
||||
Crates parachute in between turns:
|
||||
|
||||
- **Wooden crate** — a random weapon, often one you cannot get any other way.
|
||||
- **Red cross crate** — health.
|
||||
- Occasionally one is **booby-trapped**. Grabbing crates in the open, in front
|
||||
of an enemy worm, is how people lose winning positions.
|
||||
|
||||
---
|
||||
|
||||
## Two-player
|
||||
|
||||
Both players share the same controls and take turns, so there is nothing to
|
||||
learn twice. A banner announces whose go it is.
|
||||
|
|
@ -102,8 +102,8 @@ import TotalAnnihilationGame from './games/totalannihilation/TotalAnnihilationGa
|
|||
import BloxorzGame from './games/bloxorz/BloxorzGame.js';
|
||||
import GooTowerGame from './games/gootower/GooTowerGame.js';
|
||||
import GooTowerEditor from './games/gootower/GooTowerEditor.js';
|
||||
import AngryBirdsGame from './games/angrybirds/AngryBirdsGame.js';
|
||||
import ExcitebikeGame from './games/excitebike/ExcitebikeGame.js';
|
||||
import WormsGame from './games/worms/WormsGame.js';
|
||||
|
||||
const config = {
|
||||
type: Phaser.AUTO,
|
||||
|
|
@ -219,8 +219,8 @@ const config = {
|
|||
BloxorzGame,
|
||||
GooTowerGame,
|
||||
ExcitebikeGame,
|
||||
WormsGame,
|
||||
GooTowerEditor,
|
||||
AngryBirdsGame,
|
||||
],
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@ export default class GameRoomScene extends Phaser.Scene {
|
|||
}
|
||||
|
||||
create() {
|
||||
const slugDispatch = { backgammon: 'Backgammon', holdem: 'HoldemGame', blackjack: 'BlackjackGame', parchisi: 'ParchisiGame', yatzi: 'YatziGame', skipbo: 'SkipBoGame', phase10: 'Phase10Game', chinesecheckers: 'ChineseCheckersGame', gofish: 'GoFishGame', uno: 'UnoGame', craps: 'CrapsGame', roulette: 'RouletteGame', mexicantrain: 'MexicanTrainGame', hearts: 'HeartsGame', catan: 'CatanGame', tickettoride: 'TicketToRideGame', nerts: 'NertsGame', bingo: 'BingoGame', baccarat: 'BaccaratGame', dominion: 'DominionGame', checkers: 'CheckersGame', chess: 'ChessGame', wordle: 'WordleGame', scrabble: 'ScrabbleGame', ghost: 'GhostGame', wordladder: 'WordLadderGame', wordsearch: 'WordSearchGame', hangman: 'HangmanGame', sudoku: 'SudokuGame', othello: 'OthelloGame', go: 'GoGame', battleship: 'BattleshipGame', mastermind: 'MastermindGame', connect4: 'Connect4Game', boggle: 'BoggleGame', oldmaid: 'OldMaidGame', blokus: 'BlokusGame', spellingbee: 'SpellingBeeGame', minicrossword: 'MiniCrosswordGame', forbiddenisland: 'ForbiddenIslandGame', solitairetour: 'SolitaireTourGame', splendor: 'SplendorGame', tectonic: 'TectonicGame', labyrinth: 'LabyrinthGame', videopoker: 'VideoPokerGame', farkel: 'FarkelGame', stratego: 'StrategoGame', kiitos: 'KiitosGame', monopoly: 'MonopolyGame', triominoes: 'TriominoesGame', freecell: 'FreecellGame', rushhour: 'RushHourGame', hexsweeper: 'HexsweeperGame', puddingmonsters: 'PuddingMonstersGame', shift: 'ShiftGame', blockfighter: 'BlockFighterGame', mahjongmatch: 'MahjongMatchGame', mahjong: 'MahjongGame', jewelquest: 'JewelQuestGame', zuma: 'ZumaGame', bejeweled: 'BejeweledGame', minimotorways: 'MiniMotorwaysGame', slots: 'SlotsGame', cribbage: 'CribbageGame', canasta: 'CanastaGame', dotlink: 'DotLinkGame', '2048': '2048Game', rummikub: 'RummikubGame', ginrummy: 'GinRummyGame', risk: 'RiskGame', geniussquare: 'GeniusSquareGame', katamino: 'KataminoGame', bookwork: 'BookworkGame', paigow: 'PaiGowPokerGame', spireclimb: 'SpireClimbGame', azul: 'AzulGame', jumble: 'JumbleGame', dungeonboss: 'DungeonBossGame', swdbg: 'SWDBGGame', balatro: 'BalatroGame', peggle: 'PeggleGame', coloradodefense: 'ColoradoDefenseGame', starcontrol: 'StarControlGame', civilization: 'CivilizationGame', tempest: 'TempestGame', superkart: 'SuperKartGame', advancewars: 'AdvanceWarsGame', tetrisattack: 'TetrisAttackGame', totalannihilation: 'TotalAnnihilationGame', bloxorz: 'BloxorzGame', gootower: 'GooTowerGame', excitebike: 'ExcitebikeGame', worms: 'WormsGame' };
|
||||
const slugDispatch = { backgammon: 'Backgammon', holdem: 'HoldemGame', blackjack: 'BlackjackGame', parchisi: 'ParchisiGame', yatzi: 'YatziGame', skipbo: 'SkipBoGame', phase10: 'Phase10Game', chinesecheckers: 'ChineseCheckersGame', gofish: 'GoFishGame', uno: 'UnoGame', craps: 'CrapsGame', roulette: 'RouletteGame', mexicantrain: 'MexicanTrainGame', hearts: 'HeartsGame', catan: 'CatanGame', tickettoride: 'TicketToRideGame', nerts: 'NertsGame', bingo: 'BingoGame', baccarat: 'BaccaratGame', dominion: 'DominionGame', checkers: 'CheckersGame', chess: 'ChessGame', wordle: 'WordleGame', scrabble: 'ScrabbleGame', ghost: 'GhostGame', wordladder: 'WordLadderGame', wordsearch: 'WordSearchGame', hangman: 'HangmanGame', sudoku: 'SudokuGame', othello: 'OthelloGame', go: 'GoGame', battleship: 'BattleshipGame', mastermind: 'MastermindGame', connect4: 'Connect4Game', boggle: 'BoggleGame', oldmaid: 'OldMaidGame', blokus: 'BlokusGame', spellingbee: 'SpellingBeeGame', minicrossword: 'MiniCrosswordGame', forbiddenisland: 'ForbiddenIslandGame', solitairetour: 'SolitaireTourGame', splendor: 'SplendorGame', tectonic: 'TectonicGame', labyrinth: 'LabyrinthGame', videopoker: 'VideoPokerGame', farkel: 'FarkelGame', stratego: 'StrategoGame', kiitos: 'KiitosGame', monopoly: 'MonopolyGame', triominoes: 'TriominoesGame', freecell: 'FreecellGame', rushhour: 'RushHourGame', hexsweeper: 'HexsweeperGame', puddingmonsters: 'PuddingMonstersGame', shift: 'ShiftGame', blockfighter: 'BlockFighterGame', mahjongmatch: 'MahjongMatchGame', mahjong: 'MahjongGame', jewelquest: 'JewelQuestGame', zuma: 'ZumaGame', bejeweled: 'BejeweledGame', minimotorways: 'MiniMotorwaysGame', slots: 'SlotsGame', cribbage: 'CribbageGame', canasta: 'CanastaGame', dotlink: 'DotLinkGame', '2048': '2048Game', rummikub: 'RummikubGame', ginrummy: 'GinRummyGame', risk: 'RiskGame', geniussquare: 'GeniusSquareGame', katamino: 'KataminoGame', bookwork: 'BookworkGame', paigow: 'PaiGowPokerGame', spireclimb: 'SpireClimbGame', azul: 'AzulGame', jumble: 'JumbleGame', dungeonboss: 'DungeonBossGame', swdbg: 'SWDBGGame', balatro: 'BalatroGame', peggle: 'PeggleGame', coloradodefense: 'ColoradoDefenseGame', starcontrol: 'StarControlGame', civilization: 'CivilizationGame', tempest: 'TempestGame', superkart: 'SuperKartGame', advancewars: 'AdvanceWarsGame', tetrisattack: 'TetrisAttackGame', totalannihilation: 'TotalAnnihilationGame', bloxorz: 'BloxorzGame', gootower: 'GooTowerGame', excitebike: 'ExcitebikeGame', angrybirds: 'AngryBirdsGame' };
|
||||
if (slugDispatch[this.game.slug]) {
|
||||
const sceneKey = slugDispatch[this.game.slug];
|
||||
const startData = {
|
||||
|
|
|
|||
|
|
@ -55,6 +55,7 @@ export default class PreloadScene extends Phaser.Scene {
|
|||
this.load.json('bloxorz', 'data/bloxorz.json');
|
||||
this.load.json('puddingmonsters', 'data/puddingmonsters.json');
|
||||
this.load.json('gootower-levels', 'assets/gamedata/gootower/levels.json');
|
||||
this.load.json('angrybirds-levels', 'assets/gamedata/angrybirds/levels.json');
|
||||
this.load.json('shift-artwork', 'data/shift-artwork.json');
|
||||
this.load.json('slots-artwork', 'data/slots-artwork.json');
|
||||
this.load.json('blockfighter', 'data/blockfighter.json');
|
||||
|
|
@ -76,7 +77,6 @@ export default class PreloadScene extends Phaser.Scene {
|
|||
this.load.json('superkart-artwork', 'data/superkart-artwork.json');
|
||||
this.load.json('colorado-defense-cities', 'data/colorado-defense-cities.json');
|
||||
this.load.json('star-control-ships', 'data/star-control-ships.json');
|
||||
this.load.json('worms-artwork', 'data/worms-artwork.json');
|
||||
|
||||
this.load.audio('sfx-engine-start', 'assets/fx/engine-start.mp3');
|
||||
this.load.audio('sfx-engine-heavy', 'assets/fx/engine-heavy.mp3');
|
||||
|
|
|
|||
|
|
@ -54,12 +54,6 @@ export const SFX = {
|
|||
SQUISH: 'sfx-squish',
|
||||
SQUASH: 'sfx-squash',
|
||||
WOOSH: 'sfx-woosh',
|
||||
// Loaded in PreloadScene since the Zuma work; named here so games stop
|
||||
// reaching for the raw cache keys.
|
||||
WATER_SPLASH: 'sfx-water-splash',
|
||||
WATER_SINK: 'sfx-water-sink',
|
||||
WATER_RAISE: 'sfx-water-raise',
|
||||
WATER_DRY: 'sfx-water-dry',
|
||||
JELLO_MONSTERS: 'sfx-jello-monsters',
|
||||
COUNTDOWN_TICK: 'sfx-countdown-tick',
|
||||
COUNTDOWN_GO: 'sfx-countdown-go',
|
||||
|
|
|
|||
|
|
@ -0,0 +1,882 @@
|
|||
// Headless verification for Angry Birds.
|
||||
// node tools/verifyAngryBirds.js
|
||||
// Exits non-zero on any failure.
|
||||
//
|
||||
// 1. Physics invariants — mass properties, resting contacts, stack stability,
|
||||
// friction, restitution, anti-tunnel bound, explosion falloff.
|
||||
// 2. Determinism — seeded replay, frame-rate independence, clone independence.
|
||||
// 3. Robustness — random-impulse monkey test for NaN / overspeed / sinking.
|
||||
//
|
||||
// Rendering, slingshot feel, camera and the editor's Blob export are
|
||||
// browser-only and must be smoke-tested manually.
|
||||
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { dirname, join } from 'node:path';
|
||||
|
||||
import {
|
||||
PHYS, createWorld, addBox, addPoly, addCircle, removeBody,
|
||||
step, substep, settle, isSettled, applyImpulse, applyExplosion,
|
||||
cloneWorld, hashWorld, contactImpulses,
|
||||
} from '../src/games/angrybirds/AngryBirdsPhysics.js';
|
||||
import {
|
||||
TUNING, MATERIALS, PIG, BIRDS, SCORING,
|
||||
createState, slingAnchor, clampDraw, drawToVelocity, currentBird, birdsRemaining,
|
||||
launch, useAbility, stepSim, starsFor, cloneState, hashState, simulateShot,
|
||||
} from '../src/games/angrybirds/AngryBirdsLogic.js';
|
||||
|
||||
let failures = 0;
|
||||
let passes = 0;
|
||||
function check(name, cond, detail = '') {
|
||||
if (cond) { passes += 1; console.log(` ok ${name}`); }
|
||||
else { failures += 1; console.error(`FAIL ${name}${detail ? ` — ${detail}` : ''}`); }
|
||||
}
|
||||
const near = (a, b, tol) => Math.abs(a - b) <= tol;
|
||||
|
||||
function section(title) { console.log(`\n── ${title} ${'─'.repeat(Math.max(0, 60 - title.length))}`); }
|
||||
|
||||
// Deterministic RNG for the monkey test (never Math.random — see the header
|
||||
// contract in AngryBirdsPhysics.js).
|
||||
function mulberry32(seed) {
|
||||
let a = seed >>> 0;
|
||||
return () => {
|
||||
a = (a + 0x6d2b79f5) >>> 0;
|
||||
let t = Math.imul(a ^ (a >>> 15), 1 | a);
|
||||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
}
|
||||
|
||||
/** Ground plane spanning the test area. */
|
||||
function withGround(world, y = 800) {
|
||||
addBox(world, { x: 600, y: y + 50, w: 4000, h: 100, isStatic: true, friction: 0.7 });
|
||||
return world;
|
||||
}
|
||||
|
||||
// ── 1. Mass properties ──────────────────────────────────────────────────────
|
||||
|
||||
section('1. Mass properties');
|
||||
{
|
||||
const w = createWorld();
|
||||
const b = addBox(w, { x: 0, y: 0, w: 40, h: 20, density: 2 });
|
||||
const expectMass = 2 * 40 * 20;
|
||||
check('box mass = density x w x h', near(b.mass, expectMass, 1e-6), `${b.mass} vs ${expectMass}`);
|
||||
|
||||
const expectI = (expectMass * (40 * 40 + 20 * 20)) / 12;
|
||||
check('box inertia = m(w^2+h^2)/12', near(1 / b.invI, expectI, expectI * 1e-6),
|
||||
`${1 / b.invI} vs ${expectI}`);
|
||||
|
||||
const c = addCircle(w, { x: 0, y: 0, r: 10, density: 3 });
|
||||
const cMass = 3 * Math.PI * 100;
|
||||
check('circle mass = density x pi r^2', near(c.mass, cMass, 1e-6), `${c.mass} vs ${cMass}`);
|
||||
|
||||
const s = addBox(w, { x: 0, y: 0, w: 10, h: 10, isStatic: true });
|
||||
check('static body has zero inverse mass', s.invMass === 0 && s.invI === 0);
|
||||
}
|
||||
{
|
||||
// Winding must be normalized: a CW polygon must produce the same body as CCW.
|
||||
const w = createWorld();
|
||||
const ccw = addPoly(w, { x: 0, y: 0, verts: [[-10, -10], [10, -10], [10, 10], [-10, 10]], density: 1 });
|
||||
const cw = addPoly(w, { x: 0, y: 0, verts: [[-10, 10], [10, 10], [10, -10], [-10, -10]], density: 1 });
|
||||
check('polygon winding normalized', near(ccw.mass, cw.mass, 1e-9) && near(ccw.invI, cw.invI, 1e-12),
|
||||
`${ccw.mass}/${cw.mass}`);
|
||||
|
||||
// Outward normals must point away from the centroid.
|
||||
const outward = ccw.normals.every(([nx, ny], i) => {
|
||||
const [vx, vy] = ccw.verts[i];
|
||||
return vx * nx + vy * ny > 0;
|
||||
});
|
||||
check('polygon normals point outward', outward);
|
||||
}
|
||||
{
|
||||
// Verts are recentred on the centroid, so an off-centre polygon still
|
||||
// rotates about its true centre of mass.
|
||||
const w = createWorld();
|
||||
const b = addPoly(w, { x: 0, y: 0, verts: [[0, 0], [40, 0], [40, 20], [0, 20]], density: 1 });
|
||||
const cx = b.verts.reduce((s, v) => s + v[0], 0) / b.verts.length;
|
||||
const cy = b.verts.reduce((s, v) => s + v[1], 0) / b.verts.length;
|
||||
check('polygon recentred on centroid', near(cx, 0, 1e-9) && near(cy, 0, 1e-9), `${cx},${cy}`);
|
||||
}
|
||||
|
||||
// ── 2. Anti-tunnelling bound ────────────────────────────────────────────────
|
||||
|
||||
section('2. Anti-tunnelling');
|
||||
{
|
||||
const travel = PHYS.MAX_SPEED * PHYS.SUBSTEP_DT;
|
||||
check('MAX_SPEED x SUBSTEP_DT < MIN_HALF_EXTENT',
|
||||
travel < PHYS.MIN_HALF_EXTENT, `${travel.toFixed(2)} !< ${PHYS.MIN_HALF_EXTENT}`);
|
||||
}
|
||||
{
|
||||
// A fast circle fired at a thin static wall must not pass through it.
|
||||
const w = createWorld();
|
||||
addBox(w, { x: 400, y: 300, w: 20, h: 400, isStatic: true });
|
||||
const ball = addCircle(w, { x: 100, y: 300, r: 12, density: 1 });
|
||||
ball.vx = PHYS.MAX_SPEED;
|
||||
w.gravity = 0;
|
||||
for (let i = 0; i < 240; i += 1) substep(w, PHYS.SUBSTEP_DT);
|
||||
check('fast body does not tunnel through a wall', ball.x < 400, `x=${ball.x.toFixed(1)}`);
|
||||
}
|
||||
|
||||
// ── 3. Resting contacts and stack stability (THE WAVE 0 GATE) ───────────────
|
||||
|
||||
section('3. Resting contacts and stacks');
|
||||
{
|
||||
const w = withGround(createWorld());
|
||||
const b = addBox(w, { x: 600, y: 700, w: 60, h: 60, density: 1 });
|
||||
for (let i = 0; i < 600; i += 1) substep(w, PHYS.SUBSTEP_DT);
|
||||
// Ground top is y=800; a 60-tall box rests with its centre at 770.
|
||||
check('single box rests on ground', near(b.y, 770, PHYS.SLOP + 0.5), `y=${b.y.toFixed(3)}`);
|
||||
check('resting box does not sink', b.y < 772, `y=${b.y.toFixed(3)}`);
|
||||
check('resting box falls asleep', b.sleeping, `timer=${b.sleepTimer.toFixed(2)}`);
|
||||
}
|
||||
{
|
||||
// THE GATE: a 10-box tower must settle, sleep, and not drift.
|
||||
const w = withGround(createWorld());
|
||||
const boxes = [];
|
||||
// Ground top is y=800, boxes are 40 tall, so box i rests centred at 780-40i.
|
||||
// Spawning them exactly at rest isolates solver sag from free-fall settling.
|
||||
for (let i = 0; i < 10; i += 1) {
|
||||
boxes.push(addBox(w, { x: 600, y: 780 - i * 40, w: 60, h: 40, density: 1, friction: 0.6 }));
|
||||
}
|
||||
const startX = boxes.map((b) => b.x);
|
||||
|
||||
let sleptAt = -1;
|
||||
for (let i = 0; i < 720; i += 1) { // 3 simulated seconds at 1/240
|
||||
substep(w, PHYS.SUBSTEP_DT);
|
||||
if (sleptAt < 0 && isSettled(w)) sleptAt = i;
|
||||
}
|
||||
check('10-box tower settles within 3s', sleptAt >= 0, `never settled`);
|
||||
check('10-box tower is fully asleep', boxes.every((b) => b.sleeping),
|
||||
`${boxes.filter((b) => !b.sleeping).length} awake`);
|
||||
|
||||
const drift = Math.max(...boxes.map((b, i) => Math.abs(b.x - startX[i])));
|
||||
check('tower horizontal drift < 1px', drift < 1, `max drift ${drift.toFixed(3)}px`);
|
||||
|
||||
// Total sag is bounded by SLOP per contact — the solver deliberately stops
|
||||
// correcting once penetration is inside the slop band, so 10 stacked
|
||||
// contacts can each give up to SLOP. Anything beyond that is real sag.
|
||||
const sag = boxes[9].y - (780 - 9 * 40);
|
||||
const sagBudget = PHYS.SLOP * 10;
|
||||
check('tower sag within the slop budget', Math.abs(sag) < sagBudget,
|
||||
`sag ${sag.toFixed(3)}px vs budget ${sagBudget}px`);
|
||||
|
||||
const tilt = Math.max(...boxes.map((b) => Math.abs(b.angle)));
|
||||
check('tower stays upright', tilt < 0.02, `max |angle| ${tilt.toFixed(4)} rad`);
|
||||
}
|
||||
{
|
||||
// A pyramid is the harder stacking case: contacts are shared sideways.
|
||||
const w = withGround(createWorld());
|
||||
const bodies = [];
|
||||
for (let row = 0; row < 5; row += 1) {
|
||||
const n = 5 - row;
|
||||
for (let i = 0; i < n; i += 1) {
|
||||
bodies.push(addBox(w, {
|
||||
x: 600 - (n - 1) * 35 + i * 70,
|
||||
y: 770 - row * 40,
|
||||
w: 64, h: 40, density: 1, friction: 0.6,
|
||||
}));
|
||||
}
|
||||
}
|
||||
for (let i = 0; i < 600; i += 1) substep(w, PHYS.SUBSTEP_DT);
|
||||
check('pyramid settles and sleeps', bodies.every((b) => b.sleeping),
|
||||
`${bodies.filter((b) => !b.sleeping).length} awake`);
|
||||
const maxTilt = Math.max(...bodies.map((b) => Math.abs(b.angle)));
|
||||
check('pyramid stays upright', maxTilt < 0.05, `max |angle| ${maxTilt.toFixed(4)}`);
|
||||
}
|
||||
|
||||
// ── 4. Friction ─────────────────────────────────────────────────────────────
|
||||
|
||||
section('4. Friction');
|
||||
{
|
||||
// 15 degrees, mu = 0.8 -> tan(15) = 0.27 < 0.8, so the box must not creep.
|
||||
const w = createWorld();
|
||||
const slope = 15 * Math.PI / 180;
|
||||
addBox(w, { x: 600, y: 800, w: 2000, h: 60, angle: slope, isStatic: true, friction: 0.9 });
|
||||
const b = addBox(w, { x: 600, y: 745, w: 60, h: 40, angle: slope, density: 1, friction: 0.9 });
|
||||
const x0 = b.x;
|
||||
for (let i = 0; i < 900; i += 1) substep(w, PHYS.SUBSTEP_DT);
|
||||
check('box on 15deg slope does not creep', Math.abs(b.x - x0) < 2,
|
||||
`moved ${(b.x - x0).toFixed(2)}px`);
|
||||
check('box on slope sleeps', b.sleeping);
|
||||
}
|
||||
{
|
||||
// 40 degrees, mu = 0.2 -> tan(40) = 0.84 > 0.2, so it must slide.
|
||||
const w = createWorld();
|
||||
const slope = 40 * Math.PI / 180;
|
||||
addBox(w, { x: 600, y: 800, w: 3000, h: 60, angle: slope, isStatic: true, friction: 0.2 });
|
||||
const b = addBox(w, { x: 400, y: 800 - 200 * Math.tan(slope) - 52, w: 60, h: 40, angle: slope, density: 1, friction: 0.2 });
|
||||
const x0 = b.x;
|
||||
for (let i = 0; i < 600; i += 1) substep(w, PHYS.SUBSTEP_DT);
|
||||
check('low-friction box slides down a steep slope', b.x - x0 > 20,
|
||||
`moved ${(b.x - x0).toFixed(2)}px`);
|
||||
}
|
||||
|
||||
// ── 5. Restitution ──────────────────────────────────────────────────────────
|
||||
|
||||
section('5. Restitution');
|
||||
{
|
||||
const w = withGround(createWorld());
|
||||
const ball = addCircle(w, { x: 600, y: 400, r: 20, density: 1, restitution: 0.8 });
|
||||
let peakUp = 0;
|
||||
for (let i = 0; i < 400; i += 1) {
|
||||
substep(w, PHYS.SUBSTEP_DT);
|
||||
if (ball.vy < peakUp) peakUp = ball.vy;
|
||||
}
|
||||
check('bouncy ball rebounds upward', peakUp < -100, `peak vy ${peakUp.toFixed(1)}`);
|
||||
}
|
||||
{
|
||||
const w = withGround(createWorld());
|
||||
const dead = addCircle(w, { x: 600, y: 400, r: 20, density: 1, restitution: 0 });
|
||||
for (let i = 0; i < 900; i += 1) substep(w, PHYS.SUBSTEP_DT);
|
||||
check('zero-restitution ball comes to rest', dead.sleeping && near(dead.y, 780, 1.5),
|
||||
`y=${dead.y.toFixed(2)} sleeping=${dead.sleeping}`);
|
||||
}
|
||||
|
||||
// ── 6. Shape-pair coverage ──────────────────────────────────────────────────
|
||||
|
||||
section('6. Shape pairs');
|
||||
{
|
||||
const w = createWorld();
|
||||
w.gravity = 0;
|
||||
const a = addCircle(w, { x: 100, y: 300, r: 20, density: 1 });
|
||||
const b = addCircle(w, { x: 200, y: 300, r: 20, density: 1 });
|
||||
a.vx = 200;
|
||||
for (let i = 0; i < 200; i += 1) substep(w, PHYS.SUBSTEP_DT);
|
||||
check('circle-circle transfers momentum', b.vx > 50 && a.vx < 200, `a=${a.vx.toFixed(1)} b=${b.vx.toFixed(1)}`);
|
||||
}
|
||||
{
|
||||
const w = createWorld();
|
||||
w.gravity = 0;
|
||||
const c = addCircle(w, { x: 100, y: 300, r: 20, density: 1 });
|
||||
const p = addBox(w, { x: 300, y: 300, w: 60, h: 60, density: 1 });
|
||||
c.vx = 300;
|
||||
for (let i = 0; i < 240; i += 1) substep(w, PHYS.SUBSTEP_DT);
|
||||
check('circle-poly transfers momentum', p.vx > 20, `box vx=${p.vx.toFixed(1)}`);
|
||||
check('circle-poly does not overlap after impact',
|
||||
Math.hypot(c.x - p.x, c.y - p.y) > 40, `dist ${Math.hypot(c.x - p.x, c.y - p.y).toFixed(1)}`);
|
||||
}
|
||||
{
|
||||
// A circle dropped into a closed V must wedge, not squeeze through the seam.
|
||||
// Two slabs tilted toward each other, overlapping at the bottom so there is
|
||||
// no gap for the ball to slip through.
|
||||
const w = createWorld();
|
||||
addBox(w, { x: 480, y: 780, w: 400, h: 40, angle: -0.6, isStatic: true, friction: 0.6 });
|
||||
addBox(w, { x: 720, y: 780, w: 400, h: 40, angle: 0.6, isStatic: true, friction: 0.6 });
|
||||
const ball = addCircle(w, { x: 600, y: 300, r: 25, density: 1 });
|
||||
for (let i = 0; i < 1800; i += 1) substep(w, PHYS.SUBSTEP_DT);
|
||||
check('circle wedges in a V without escaping', ball.y < 820 && ball.sleeping,
|
||||
`y=${ball.y.toFixed(1)} sleeping=${ball.sleeping}`);
|
||||
}
|
||||
|
||||
// ── 7. Sleeping and waking ──────────────────────────────────────────────────
|
||||
|
||||
section('7. Sleeping');
|
||||
{
|
||||
const w = withGround(createWorld());
|
||||
const stack = [];
|
||||
for (let i = 0; i < 4; i += 1) stack.push(addBox(w, { x: 600, y: 770 - i * 40, w: 60, h: 40, density: 1 }));
|
||||
for (let i = 0; i < 600; i += 1) substep(w, PHYS.SUBSTEP_DT);
|
||||
check('stack asleep before impact', stack.every((b) => b.sleeping));
|
||||
|
||||
// A projectile must wake the whole island, not just the box it touches.
|
||||
const shot = addCircle(w, { x: 200, y: 700, r: 16, density: 4 });
|
||||
shot.vx = 1200;
|
||||
let allAwake = false;
|
||||
for (let i = 0; i < 240; i += 1) {
|
||||
substep(w, PHYS.SUBSTEP_DT);
|
||||
if (stack.every((b) => !b.sleeping)) { allAwake = true; break; }
|
||||
}
|
||||
check('impact wakes the whole island', allAwake,
|
||||
`${stack.filter((b) => b.sleeping).length} still asleep`);
|
||||
}
|
||||
{
|
||||
const w = withGround(createWorld());
|
||||
const b = addBox(w, { x: 600, y: 700, w: 60, h: 60, density: 1 });
|
||||
settle(w, 10);
|
||||
check('settle() reaches rest', isSettled(w) && b.sleeping);
|
||||
const yRest = b.y;
|
||||
for (let i = 0; i < 600; i += 1) substep(w, PHYS.SUBSTEP_DT);
|
||||
check('sleeping body does not drift', near(b.y, yRest, 1e-9), `${b.y} vs ${yRest}`);
|
||||
}
|
||||
|
||||
// ── 8. Explosions ───────────────────────────────────────────────────────────
|
||||
|
||||
section('8. Explosions');
|
||||
{
|
||||
const w = withGround(createWorld());
|
||||
const near1 = addBox(w, { x: 620, y: 700, w: 40, h: 40, density: 1 });
|
||||
const far1 = addBox(w, { x: 900, y: 700, w: 40, h: 40, density: 1 });
|
||||
const outside = addBox(w, { x: 1400, y: 700, w: 40, h: 40, density: 1 });
|
||||
const hit = applyExplosion(w, 600, 700, 400, 600);
|
||||
check('explosion hits bodies inside the radius', hit.length === 2, `hit ${hit.length}`);
|
||||
check('explosion falls off with distance',
|
||||
Math.hypot(near1.vx, near1.vy) > Math.hypot(far1.vx, far1.vy),
|
||||
`${Math.hypot(near1.vx, near1.vy).toFixed(1)} vs ${Math.hypot(far1.vx, far1.vy).toFixed(1)}`);
|
||||
check('explosion spares bodies outside the radius',
|
||||
outside.vx === 0 && outside.vy === 0);
|
||||
check('explosion pushes away from the centre', near1.vx > 0 && far1.vx > 0);
|
||||
check('explosion wakes sleeping bodies', !near1.sleeping);
|
||||
}
|
||||
|
||||
// ── 9. Determinism ──────────────────────────────────────────────────────────
|
||||
|
||||
section('9. Determinism');
|
||||
function scene() {
|
||||
const w = withGround(createWorld());
|
||||
for (let i = 0; i < 6; i += 1) addBox(w, { x: 600, y: 770 - i * 40, w: 60, h: 40, density: 1 });
|
||||
addBox(w, { x: 660, y: 730, w: 30, h: 120, density: 0.8 });
|
||||
const ball = addCircle(w, { x: 200, y: 600, r: 16, density: 4 });
|
||||
ball.vx = 900; ball.vy = -120;
|
||||
return w;
|
||||
}
|
||||
{
|
||||
const a = scene();
|
||||
const b = scene();
|
||||
for (let i = 0; i < 300; i += 1) { substep(a, PHYS.SUBSTEP_DT); substep(b, PHYS.SUBSTEP_DT); }
|
||||
check('identical scenes replay bit-identically', hashWorld(a) === hashWorld(b),
|
||||
`${hashWorld(a)} vs ${hashWorld(b)}`);
|
||||
}
|
||||
{
|
||||
// Frame-rate independence: one 1/60 frame must equal exactly N substeps.
|
||||
const perFrame = Math.round((1 / 60) / PHYS.SUBSTEP_DT);
|
||||
const c = scene();
|
||||
const d = scene();
|
||||
for (let i = 0; i < 300; i += 1) {
|
||||
step(c, 1 / 60);
|
||||
for (let k = 0; k < perFrame; k += 1) substep(d, PHYS.SUBSTEP_DT);
|
||||
}
|
||||
check(`1/60 step == ${perFrame}x substep`, hashWorld(c) === hashWorld(d),
|
||||
`${hashWorld(c)} vs ${hashWorld(d)}`);
|
||||
}
|
||||
{
|
||||
// Ragged frame pacing: the accumulator only ever runs WHOLE substeps, so N
|
||||
// substeps reached through jittery frame times must be bit-identical to N
|
||||
// substeps reached evenly. (Total elapsed time can differ by up to one
|
||||
// substep's worth of carry — that leftover is the accumulator's whole job —
|
||||
// so the comparison is on substeps run, not on wall time.)
|
||||
const e = scene();
|
||||
const f = scene();
|
||||
const rng = mulberry32(99);
|
||||
let ran = 0;
|
||||
for (let i = 0; i < 400; i += 1) ran += step(e, 0.004 + rng() * 0.02);
|
||||
for (let i = 0; i < ran; i += 1) substep(f, PHYS.SUBSTEP_DT);
|
||||
check('ragged frame pacing matches even pacing', hashWorld(e) === hashWorld(f),
|
||||
`${ran} substeps: ${hashWorld(e)} vs ${hashWorld(f)}`);
|
||||
}
|
||||
{
|
||||
const src = scene();
|
||||
for (let i = 0; i < 60; i += 1) substep(src, PHYS.SUBSTEP_DT);
|
||||
const before = hashWorld(src);
|
||||
const copy = cloneWorld(src);
|
||||
check('clone starts hash-identical', before === hashWorld(copy));
|
||||
|
||||
// Stepping the clone must not disturb the original by any route — including
|
||||
// through the body references cached on contacts. simulatePreview and the
|
||||
// winnability bot both depend on this being airtight.
|
||||
for (let i = 0; i < 120; i += 1) substep(copy, PHYS.SUBSTEP_DT);
|
||||
check('stepping a clone leaves the original untouched', hashWorld(src) === before,
|
||||
`${hashWorld(src)} vs ${before}`);
|
||||
check('clone diverges from a stationary original', hashWorld(copy) !== before);
|
||||
|
||||
for (let i = 0; i < 120; i += 1) substep(src, PHYS.SUBSTEP_DT);
|
||||
check('clone and original converge when stepped equally', hashWorld(src) === hashWorld(copy),
|
||||
`${hashWorld(src)} vs ${hashWorld(copy)}`);
|
||||
}
|
||||
{
|
||||
// Sequential impulses are Gauss-Seidel, so solve order genuinely affects the
|
||||
// answer — bit-identical results across creation orders are NOT achievable
|
||||
// and not required. What matters is that the dependence stays sub-pixel, so
|
||||
// an author reordering blocks in the editor can't change whether a level
|
||||
// works. Exact reproducibility of a GIVEN scene is covered above.
|
||||
const build = (reverse) => {
|
||||
const w = withGround(createWorld());
|
||||
const spec = [];
|
||||
for (let i = 0; i < 5; i += 1) spec.push({ x: 600, y: 770 - i * 40 });
|
||||
const order = reverse ? [...spec].reverse() : spec;
|
||||
for (const s of order) addBox(w, { ...s, w: 60, h: 40, density: 1 });
|
||||
return w;
|
||||
};
|
||||
const fwd = build(false);
|
||||
const rev = build(true);
|
||||
for (let i = 0; i < 480; i += 1) { substep(fwd, PHYS.SUBSTEP_DT); substep(rev, PHYS.SUBSTEP_DT); }
|
||||
const fy = [...fwd.bodies].filter((b) => !b.isStatic).map((b) => b.y).sort((a, b) => a - b);
|
||||
const ry = [...rev.bodies].filter((b) => !b.isStatic).map((b) => b.y).sort((a, b) => a - b);
|
||||
const worst = Math.max(...fy.map((v, i) => Math.abs(v - ry[i])));
|
||||
check('creation order shifts results by under 1px', worst < 1, `worst ${worst.toFixed(3)}px`);
|
||||
}
|
||||
|
||||
// ── 10. Robustness monkey test ──────────────────────────────────────────────
|
||||
|
||||
section('10. Robustness');
|
||||
{
|
||||
const seeds = Number((process.argv.find((a) => a.startsWith('--seeds=')) ?? '--seeds=12').split('=')[1]);
|
||||
let bad = 0;
|
||||
let sank = 0;
|
||||
let overspeed = 0;
|
||||
for (let s = 0; s < seeds; s += 1) {
|
||||
const rng = mulberry32(1000 + s);
|
||||
const w = withGround(createWorld());
|
||||
const bodies = [];
|
||||
for (let i = 0; i < 14; i += 1) {
|
||||
const b = rng() < 0.3
|
||||
? addCircle(w, { x: 400 + rng() * 400, y: 300 + rng() * 400, r: 10 + rng() * 18, density: 0.5 + rng() })
|
||||
: addBox(w, { x: 400 + rng() * 400, y: 300 + rng() * 400, w: 24 + rng() * 60, h: 24 + rng() * 60, angle: rng() * Math.PI, density: 0.5 + rng() });
|
||||
bodies.push(b);
|
||||
}
|
||||
for (let i = 0; i < 900; i += 1) {
|
||||
if (i % 60 === 0) {
|
||||
const b = bodies[Math.floor(rng() * bodies.length)];
|
||||
applyImpulse(b, (rng() - 0.5) * 4e5, (rng() - 0.5) * 4e5, b.x, b.y);
|
||||
}
|
||||
substep(w, PHYS.SUBSTEP_DT);
|
||||
for (const b of bodies) {
|
||||
if (!Number.isFinite(b.x) || !Number.isFinite(b.y) || !Number.isFinite(b.angle)
|
||||
|| !Number.isFinite(b.vx) || !Number.isFinite(b.vy) || !Number.isFinite(b.omega)) bad += 1;
|
||||
if (Math.hypot(b.vx, b.vy) > PHYS.MAX_SPEED + 1e-6) overspeed += 1;
|
||||
if (b.y > 1000) sank += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
check(`no NaN across ${seeds} monkey seeds`, bad === 0, `${bad} non-finite samples`);
|
||||
check('nothing exceeds MAX_SPEED', overspeed === 0, `${overspeed} samples`);
|
||||
check('nothing sinks through the ground', sank === 0, `${sank} samples`);
|
||||
}
|
||||
{
|
||||
// Bodies must be removable mid-sim without leaving dangling contacts.
|
||||
const w = withGround(createWorld());
|
||||
const boxes = [];
|
||||
for (let i = 0; i < 5; i += 1) boxes.push(addBox(w, { x: 600, y: 770 - i * 40, w: 60, h: 40, density: 1 }));
|
||||
for (let i = 0; i < 120; i += 1) substep(w, PHYS.SUBSTEP_DT);
|
||||
removeBody(w, boxes[2]);
|
||||
let threw = false;
|
||||
try { for (let i = 0; i < 480; i += 1) substep(w, PHYS.SUBSTEP_DT); } catch (e) { threw = true; }
|
||||
check('removing a mid-stack body is safe', !threw);
|
||||
check('stack recovers after a removal', boxes.filter((b, i) => i !== 2).every((b) => b.sleeping),
|
||||
`${boxes.filter((b, i) => i !== 2 && !b.sleeping).length} awake`);
|
||||
}
|
||||
{
|
||||
// contactImpulses is the damage signal the rules layer reads — a hard hit
|
||||
// must report a much larger impulse than a resting contact.
|
||||
const w = withGround(createWorld());
|
||||
const target = addBox(w, { x: 600, y: 770, w: 60, h: 60, density: 1 });
|
||||
settle(w, 5);
|
||||
substep(w, PHYS.SUBSTEP_DT);
|
||||
const resting = contactImpulses(w).get(target.id) ?? 0;
|
||||
|
||||
const shot = addCircle(w, { x: 200, y: 740, r: 16, density: 6 });
|
||||
shot.vx = 1800;
|
||||
let peak = 0;
|
||||
for (let i = 0; i < 240; i += 1) {
|
||||
substep(w, PHYS.SUBSTEP_DT);
|
||||
peak = Math.max(peak, contactImpulses(w).get(target.id) ?? 0);
|
||||
}
|
||||
check('impact impulse exceeds resting impulse', peak > resting * 3,
|
||||
`peak ${peak.toFixed(0)} vs resting ${resting.toFixed(0)}`);
|
||||
}
|
||||
|
||||
// ── 11. Materials and damage ────────────────────────────────────────────────
|
||||
|
||||
section('11. Materials and damage');
|
||||
{
|
||||
const order = ['ice', 'wood', 'stone'];
|
||||
const dens = order.map((m) => MATERIALS[m].density);
|
||||
const hps = order.map((m) => MATERIALS[m].hp);
|
||||
const thr = order.map((m) => MATERIALS[m].threshold);
|
||||
check('material densities are distinct and ordered ice<wood<stone',
|
||||
dens[0] < dens[1] && dens[1] < dens[2], dens.join(' < '));
|
||||
check('material hp ordered ice<wood<stone', hps[0] < hps[1] && hps[1] < hps[2], hps.join(' < '));
|
||||
check('damage thresholds ordered ice<wood<stone', thr[0] < thr[1] && thr[1] < thr[2], thr.join(' < '));
|
||||
check('ice is the most slippery', MATERIALS.ice.friction < MATERIALS.wood.friction);
|
||||
check('TNT is fragile and carries a blast',
|
||||
MATERIALS.tnt.hp < MATERIALS.wood.hp && !!MATERIALS.tnt.blast);
|
||||
}
|
||||
{
|
||||
// THE self-crush guard. A tall stone tower left alone must take no damage —
|
||||
// the reason damage reads impactImpulse and not the accumulated normal
|
||||
// impulse. Regressing this makes towers quietly disintegrate at rest.
|
||||
const blocks = [];
|
||||
for (let i = 0; i < 10; i += 1) blocks.push({ x: 1200, y: 880 - i * 40, w: 120, h: 40, material: 'stone' });
|
||||
const st = createState({
|
||||
world: { w: 1920, h: 1080, groundY: 900 },
|
||||
birds: ['red'], blocks, pigs: [{ x: 1700, y: 878, r: 22 }], stars: [1, 2, 3],
|
||||
});
|
||||
const hp0 = [...st.blocks.values()].map((b) => b.hp);
|
||||
for (let i = 0; i < 300; i += 1) stepSim(st, 1 / 60);
|
||||
const hp1 = [...st.blocks.values()].map((b) => b.hp);
|
||||
check('a tall stone tower does not damage itself at rest',
|
||||
hp1.length === hp0.length && hp1.every((h, i) => h === hp0[i]),
|
||||
`${hp0.length} blocks -> ${hp1.length}, min hp ${Math.min(...hp1).toFixed(1)}`);
|
||||
|
||||
const restPeak = Math.max(0, ...st.world.contactList.map((c) => c.impactImpulse));
|
||||
check('settled resting impact impulse is below every threshold',
|
||||
restPeak < MATERIALS.ice.threshold,
|
||||
`${restPeak.toExponential(2)} vs ice ${MATERIALS.ice.threshold.toExponential(2)}`);
|
||||
}
|
||||
{
|
||||
// Damage must be graded: the same hit shatters ice, hurts wood, barely
|
||||
// marks stone. This is what makes material choice matter to a level author.
|
||||
const results = {};
|
||||
for (const material of ['ice', 'wood', 'stone']) {
|
||||
const st = createState({
|
||||
world: { w: 1920, h: 1080, groundY: 900 },
|
||||
birds: ['red'],
|
||||
blocks: [{ x: 1000, y: 850, w: 120, h: 100, material }],
|
||||
pigs: [{ x: 1700, y: 878, r: 22 }], stars: [1, 2, 3],
|
||||
});
|
||||
const a = slingAnchor(st);
|
||||
launch(st, a.x - 90, a.y);
|
||||
const bird = st.world.byId.get(st.activeBirds[0]);
|
||||
bird.x = 700; bird.y = 850; bird.vx = 900; bird.vy = 0;
|
||||
for (let i = 0; i < 200 && st.phase === 'flight'; i += 1) stepSim(st, 1 / 60);
|
||||
const rec = [...st.blocks.values()][0];
|
||||
results[material] = rec ? rec.hp / rec.maxHp : 0;
|
||||
}
|
||||
check('one medium hit destroys ice', results.ice === 0, `ice left ${results.ice}`);
|
||||
check('the same hit leaves stone standing', results.stone > 0, `stone left ${results.stone.toFixed(2)}`);
|
||||
check('stone survives better than wood', results.stone > results.wood,
|
||||
`stone ${results.stone.toFixed(2)} vs wood ${results.wood.toFixed(2)}`);
|
||||
}
|
||||
{
|
||||
// Pigs must die to debris, not only to direct hits — the collapse doing the
|
||||
// killing is the core feel of the game.
|
||||
const st = createState({
|
||||
world: { w: 1920, h: 1080, groundY: 900 },
|
||||
birds: ['red'],
|
||||
blocks: [{ x: 1200, y: 600, w: 200, h: 60, material: 'stone' }],
|
||||
pigs: [{ x: 1200, y: 878, r: 22 }],
|
||||
stars: [1, 2, 3],
|
||||
});
|
||||
let killed = false;
|
||||
for (let i = 0; i < 400; i += 1) {
|
||||
for (const e of stepSim(st, 1 / 60)) if (e.t === 'pigKilled') killed = true;
|
||||
if (killed) break;
|
||||
}
|
||||
check('a stone slab dropped on a pig kills it', killed);
|
||||
}
|
||||
{
|
||||
// Crack stages must fire in order as hp falls.
|
||||
const st = createState({
|
||||
world: { w: 1920, h: 1080, groundY: 900 },
|
||||
birds: ['red', 'red', 'red'],
|
||||
blocks: [{ x: 1000, y: 850, w: 140, h: 100, material: 'stone' }],
|
||||
pigs: [{ x: 1700, y: 878, r: 22 }], stars: [1, 2, 3],
|
||||
});
|
||||
const stages = [];
|
||||
for (let shot = 0; shot < 3; shot += 1) {
|
||||
const a = slingAnchor(st);
|
||||
if (!launch(st, a.x - 60, a.y)) break;
|
||||
const bird = st.world.byId.get(st.activeBirds[0]);
|
||||
bird.x = 780; bird.y = 850; bird.vx = 780; bird.vy = 0;
|
||||
for (let i = 0; i < 300 && st.phase === 'flight'; i += 1) {
|
||||
for (const e of stepSim(st, 1 / 60)) {
|
||||
if (e.t === 'blockCracked') stages.push(e.stage);
|
||||
if (e.t === 'blockDestroyed') stages.push(3);
|
||||
}
|
||||
}
|
||||
}
|
||||
check('crack stages fire in increasing order',
|
||||
stages.length > 0 && stages.every((s, i) => i === 0 || s >= stages[i - 1]), stages.join(','));
|
||||
}
|
||||
|
||||
// ── 12. Birds ───────────────────────────────────────────────────────────────
|
||||
|
||||
section('12. Birds');
|
||||
{
|
||||
check('all 8 birds are defined', Object.keys(BIRDS).length === 8, Object.keys(BIRDS).join(','));
|
||||
check('Terence is the heaviest', Object.values(BIRDS).every((b) => b.density <= BIRDS.terence.density));
|
||||
check('every ability is implemented',
|
||||
Object.values(BIRDS).every((b) => ['none', 'dart', 'split', 'blast', 'egg', 'boomerang', 'inflate'].includes(b.ability)));
|
||||
}
|
||||
function flightState(birdId) {
|
||||
const st = createState({
|
||||
world: { w: 1920, h: 1080, groundY: 900 },
|
||||
birds: [birdId],
|
||||
blocks: [{ x: 1400, y: 850, w: 120, h: 100, material: 'wood' }],
|
||||
pigs: [{ x: 1700, y: 878, r: 22 }], stars: [1, 2, 3],
|
||||
});
|
||||
const a = slingAnchor(st);
|
||||
launch(st, a.x - 100, a.y - 40);
|
||||
return st;
|
||||
}
|
||||
{
|
||||
const st = flightState('chuck');
|
||||
const b = st.world.byId.get(st.activeBirds[0]);
|
||||
const before = Math.hypot(b.vx, b.vy);
|
||||
useAbility(st);
|
||||
const after = Math.hypot(b.vx, b.vy);
|
||||
check('Chuck darts faster', after > before * 2, `${before.toFixed(0)} -> ${after.toFixed(0)}`);
|
||||
}
|
||||
{
|
||||
const st = flightState('blue');
|
||||
const before = st.activeBirds.length;
|
||||
useAbility(st);
|
||||
check('Blue splits into three', st.activeBirds.length === before + 2, `${before} -> ${st.activeBirds.length}`);
|
||||
}
|
||||
{
|
||||
const st = flightState('bomb');
|
||||
useAbility(st);
|
||||
const evs = st.events.map((e) => e.t);
|
||||
check('Bomb detonates', evs.includes('explosion'), evs.join(','));
|
||||
check('Bomb consumes itself', st.activeBirds.length === 0);
|
||||
}
|
||||
{
|
||||
const st = flightState('matilda');
|
||||
const b = st.world.byId.get(st.activeBirds[0]);
|
||||
const vy0 = b.vy;
|
||||
useAbility(st);
|
||||
check('Matilda kicks upward', b.vy < vy0, `${vy0.toFixed(0)} -> ${b.vy.toFixed(0)}`);
|
||||
check('Matilda drops an egg', st.events.some((e) => e.t === 'explosion'));
|
||||
}
|
||||
{
|
||||
const st = flightState('hal');
|
||||
const b = st.world.byId.get(st.activeBirds[0]);
|
||||
const vx0 = b.vx;
|
||||
useAbility(st);
|
||||
check('Hal reverses direction', Math.sign(b.vx) === -Math.sign(vx0), `${vx0.toFixed(0)} -> ${b.vx.toFixed(0)}`);
|
||||
}
|
||||
{
|
||||
const st = flightState('bubbles');
|
||||
const r0 = st.world.byId.get(st.activeBirds[0]).radius;
|
||||
useAbility(st);
|
||||
const r1 = st.world.byId.get(st.activeBirds[0]).radius;
|
||||
check('Bubbles inflates', r1 > r0 * 2, `${r0} -> ${r1}`);
|
||||
}
|
||||
{
|
||||
const st = flightState('red');
|
||||
check('Red has no ability to use', useAbility(st) === false);
|
||||
}
|
||||
{
|
||||
const st = flightState('chuck');
|
||||
check('ability fires once', useAbility(st) === true);
|
||||
check('ability cannot fire twice in one shot', useAbility(st) === false);
|
||||
}
|
||||
|
||||
// ── 13. Rules and scoring ───────────────────────────────────────────────────
|
||||
|
||||
section('13. Rules and scoring');
|
||||
function winnableLevel(birds = ['red', 'red', 'red']) {
|
||||
return {
|
||||
world: { w: 1920, h: 1080, groundY: 900 },
|
||||
birds,
|
||||
blocks: [{ x: 1000, y: 850, w: 40, h: 100, material: 'ice' }],
|
||||
pigs: [{ x: 1060, y: 878, r: 22 }],
|
||||
stars: [5000, 12000, 20000],
|
||||
};
|
||||
}
|
||||
{
|
||||
const st = createState(winnableLevel());
|
||||
check('starts in aim phase', st.phase === 'aim');
|
||||
check('birds remaining matches the queue', birdsRemaining(st) === 3);
|
||||
|
||||
const a = slingAnchor(st);
|
||||
check('a tap-sized draw does not launch', launch(st, a.x - 3, a.y) === false);
|
||||
check('a full draw launches', launch(st, a.x - 150, a.y - 60) === true);
|
||||
check('launching consumes a bird', birdsRemaining(st) === 2);
|
||||
check('phase is flight after launch', st.phase === 'flight');
|
||||
}
|
||||
{
|
||||
// Draw is clamped to MAX_DRAW in every direction.
|
||||
const st = createState(winnableLevel());
|
||||
const a = slingAnchor(st);
|
||||
const c = clampDraw(st, a.x - 9000, a.y - 9000);
|
||||
check('draw clamps to MAX_DRAW', near(Math.hypot(c.x - a.x, c.y - a.y), TUNING.MAX_DRAW, 1e-6),
|
||||
`${Math.hypot(c.x - a.x, c.y - a.y).toFixed(2)}`);
|
||||
const v = drawToVelocity(st, a.x - 150, a.y);
|
||||
check('bird flies opposite the pull', v.vx > 0, `vx=${v.vx.toFixed(0)}`);
|
||||
check('launch speed matches SPEED_PER_DRAW',
|
||||
near(Math.hypot(v.vx, v.vy), TUNING.MAX_DRAW * TUNING.SPEED_PER_DRAW, 1),
|
||||
`${Math.hypot(v.vx, v.vy).toFixed(0)}`);
|
||||
}
|
||||
{
|
||||
// A shot that clears the only pig wins, and unused birds pay a bonus.
|
||||
const st = createState(winnableLevel());
|
||||
const a = slingAnchor(st);
|
||||
launch(st, a.x - 150, a.y - 30);
|
||||
const bird = st.world.byId.get(st.activeBirds[0]);
|
||||
bird.x = 900; bird.y = 860; bird.vx = 1500; bird.vy = 0;
|
||||
let won = false;
|
||||
let bonus = 0;
|
||||
for (let i = 0; i < 900; i += 1) {
|
||||
for (const e of stepSim(st, 1 / 60)) {
|
||||
if (e.t === 'won') { won = true; bonus = e.birdBonus; }
|
||||
}
|
||||
if (won) break;
|
||||
}
|
||||
check('clearing every pig wins', won, `phase=${st.phase}`);
|
||||
check('unused birds pay 10,000 each', bonus === 2 * SCORING.BIRD_LEFT, `bonus ${bonus}`);
|
||||
check('score includes the pig', st.score >= SCORING.PIG + bonus, `score ${st.score}`);
|
||||
check('stars awarded on a win', starsFor(st) >= 1, `stars ${starsFor(st)}`);
|
||||
}
|
||||
{
|
||||
// Running out of birds with a pig alive loses.
|
||||
const st = createState({
|
||||
world: { w: 1920, h: 1080, groundY: 900 },
|
||||
birds: ['red'],
|
||||
blocks: [],
|
||||
pigs: [{ x: 1700, y: 878, r: 22 }],
|
||||
stars: [5000, 12000, 20000],
|
||||
});
|
||||
const a = slingAnchor(st);
|
||||
launch(st, a.x - 20, a.y); // deliberately feeble
|
||||
let lost = false;
|
||||
for (let i = 0; i < 2000; i += 1) {
|
||||
for (const e of stepSim(st, 1 / 60)) if (e.t === 'lost') lost = true;
|
||||
if (lost || st.phase === 'won') break;
|
||||
}
|
||||
check('running out of birds loses', lost, `phase=${st.phase}`);
|
||||
check('no stars on a loss', starsFor(st) === 0);
|
||||
}
|
||||
{
|
||||
const st = createState(winnableLevel());
|
||||
st.score = 13000;
|
||||
st.phase = 'won';
|
||||
check('star cuts are thresholds', starsFor(st) === 2, `${starsFor(st)}`);
|
||||
st.score = 99999;
|
||||
check('stars cap at 3', starsFor(st) === 3);
|
||||
}
|
||||
{
|
||||
// Shot bookkeeping: the trail is retained for the next shot's aiming ghost.
|
||||
const st = createState(winnableLevel());
|
||||
const a = slingAnchor(st);
|
||||
launch(st, a.x - 150, a.y - 60);
|
||||
for (let i = 0; i < 1200 && st.phase === 'flight'; i += 1) stepSim(st, 1 / 60);
|
||||
check('a resolved shot records a trail', st.trails.length === 1, `${st.trails.length}`);
|
||||
check('a resolved shot returns to aim', ['aim', 'won', 'lost'].includes(st.phase), st.phase);
|
||||
}
|
||||
|
||||
// ── 14. Rules-layer determinism ─────────────────────────────────────────────
|
||||
|
||||
section('14. Rules determinism');
|
||||
{
|
||||
const mk = () => {
|
||||
const st = createState(winnableLevel(['red', 'chuck', 'bomb']));
|
||||
const a = slingAnchor(st);
|
||||
launch(st, a.x - 140, a.y - 50);
|
||||
return st;
|
||||
};
|
||||
const a1 = mk();
|
||||
const b1 = mk();
|
||||
for (let i = 0; i < 300; i += 1) { stepSim(a1, 1 / 60); stepSim(b1, 1 / 60); }
|
||||
check('rules state replays bit-identically', hashState(a1) === hashState(b1),
|
||||
`${hashState(a1)} vs ${hashState(b1)}`);
|
||||
}
|
||||
{
|
||||
const st = createState(winnableLevel(['red', 'red']));
|
||||
const before = hashState(st);
|
||||
const a = slingAnchor(st);
|
||||
const res = simulateShot(st, a.x - 150, a.y - 40);
|
||||
check('simulateShot returns a result', !!res);
|
||||
check('simulateShot does not touch the live state', hashState(st) === before,
|
||||
`${hashState(st)} vs ${before}`);
|
||||
check('simulateShot reports damage done', res.pigsKilled + res.blocksDestroyed >= 0);
|
||||
|
||||
const res2 = simulateShot(st, a.x - 150, a.y - 40);
|
||||
check('simulateShot is repeatable', res.score === res2.score && res.pigsKilled === res2.pigsKilled,
|
||||
`${res.score} vs ${res2.score}`);
|
||||
}
|
||||
{
|
||||
// cloneState must deep-copy the damage bookkeeping too, not just the world.
|
||||
const st = createState(winnableLevel());
|
||||
const copy = cloneState(st);
|
||||
const firstBlock = [...copy.blocks.keys()][0];
|
||||
copy.blocks.get(firstBlock).hp = 1;
|
||||
check('cloneState deep-copies block hp',
|
||||
st.blocks.get(firstBlock).hp !== 1, `${st.blocks.get(firstBlock).hp}`);
|
||||
}
|
||||
|
||||
// ── 15. Level bank ──────────────────────────────────────────────────────────
|
||||
|
||||
section('15. Level bank');
|
||||
{
|
||||
const DATA_DIR = join(dirname(fileURLToPath(import.meta.url)), '..', 'assets', 'gamedata', 'angrybirds');
|
||||
const manifest = JSON.parse(readFileSync(join(DATA_DIR, 'levels.json'), 'utf8'));
|
||||
const entries = manifest.levels ?? [];
|
||||
check('manifest lists levels', entries.length > 0, `${entries.length}`);
|
||||
check('level numbers are contiguous from 1',
|
||||
entries.every((m, i) => m.level === i + 1), entries.map((m) => m.level).join(','));
|
||||
|
||||
const defs = [];
|
||||
let missing = 0;
|
||||
for (const m of entries) {
|
||||
try { defs.push(JSON.parse(readFileSync(join(DATA_DIR, m.file), 'utf8'))); } catch (_) { missing += 1; }
|
||||
}
|
||||
check('every manifest entry has a level file', missing === 0, `${missing} missing`);
|
||||
check('level files agree with the manifest',
|
||||
defs.every((d, i) => d.level === entries[i].level && d.name === entries[i].name));
|
||||
|
||||
// Every episode range must cover real levels.
|
||||
for (const ep of manifest.episodes ?? []) {
|
||||
const inRange = entries.filter((m) => m.level >= ep.from && m.level <= ep.to);
|
||||
check(`episode "${ep.name}" covers its range`, inRange.length === ep.to - ep.from + 1,
|
||||
`${inRange.length} of ${ep.to - ep.from + 1}`);
|
||||
}
|
||||
|
||||
// Data lint: materials, birds and star cuts must all be real.
|
||||
let badMat = 0; let badBird = 0; let badStars = 0; let thin = 0;
|
||||
for (const d of defs) {
|
||||
for (const b of d.blocks ?? []) {
|
||||
if (!MATERIALS[b.material]) badMat += 1;
|
||||
if (Math.min(b.w, b.h) / 2 < PHYS.MIN_HALF_EXTENT) thin += 1;
|
||||
}
|
||||
for (const id of d.birds ?? []) if (!BIRDS[id]) badBird += 1;
|
||||
const s = d.stars ?? [];
|
||||
if (s.length !== 3 || s[0] >= s[1] || s[1] >= s[2]) badStars += 1;
|
||||
}
|
||||
check('every block uses a known material', badMat === 0, `${badMat} bad`);
|
||||
check('every bird id is known', badBird === 0, `${badBird} bad`);
|
||||
check('star cuts are three ascending values', badStars === 0, `${badStars} bad`);
|
||||
check('no block is thinner than the anti-tunnel bound', thin === 0,
|
||||
`${thin} blocks under ${PHYS.MIN_HALF_EXTENT * 2}px`);
|
||||
|
||||
// Structural integrity: a level must stand on its own. If a structure
|
||||
// collapses or damages itself on load, the author saw something different
|
||||
// from what the player gets.
|
||||
let unstable = [];
|
||||
let selfDamaged = [];
|
||||
for (const d of defs) {
|
||||
const st = createState(d);
|
||||
const hp0 = [...st.blocks.values()].map((b) => b.hp);
|
||||
const nBlocks = st.blocks.size;
|
||||
const nPigs = st.pigs.size;
|
||||
for (let i = 0; i < 240; i += 1) stepSim(st, 1 / 60);
|
||||
if (st.blocks.size !== nBlocks || st.pigs.size !== nPigs) unstable.push(d.level);
|
||||
else if ([...st.blocks.values()].some((b, i) => b.hp < hp0[i])) selfDamaged.push(d.level);
|
||||
}
|
||||
check('every level stands up unaided', unstable.length === 0, `levels ${unstable.join(',')}`);
|
||||
check('no level damages itself on load', selfDamaged.length === 0, `levels ${selfDamaged.join(',')}`);
|
||||
|
||||
// Winnability: a coarse aim sweep must find a shot that clears every pig
|
||||
// within the bird budget. One-directional gate — a sweep failure means
|
||||
// "redesign or hand-verify", never "impossible".
|
||||
const unwinnable = [];
|
||||
for (const d of defs) {
|
||||
let st = createState(d);
|
||||
const a = slingAnchor(st);
|
||||
let guard = 0;
|
||||
while (st.phase === 'aim' && guard < 12) {
|
||||
guard += 1;
|
||||
let best = null;
|
||||
for (let ang = -85; ang <= 15; ang += 5) {
|
||||
for (const pw of [1, 0.85, 0.7, 0.55]) {
|
||||
const r = (Math.PI * ang) / 180;
|
||||
const res = simulateShot(st, a.x - Math.cos(r) * TUNING.MAX_DRAW * pw,
|
||||
a.y - Math.sin(r) * TUNING.MAX_DRAW * pw);
|
||||
if (!res) continue;
|
||||
if (!best || res.score > best.score) best = res;
|
||||
if (res.won) { best = res; break; }
|
||||
}
|
||||
if (best?.won) break;
|
||||
}
|
||||
if (!best) break;
|
||||
st = best.state;
|
||||
}
|
||||
if (st.phase !== 'won') unwinnable.push(d.level);
|
||||
}
|
||||
check('a greedy aim sweep clears every level', unwinnable.length === 0,
|
||||
`levels ${unwinnable.join(',')}`);
|
||||
}
|
||||
|
||||
// ── Summary ─────────────────────────────────────────────────────────────────
|
||||
|
||||
console.log(`\n${passes} passed, ${failures} failed`);
|
||||
process.exit(failures ? 1 : 0);
|
||||
1071
tools/verifyWorms.js
1071
tools/verifyWorms.js
File diff suppressed because it is too large
Load Diff
Loading…
Reference in New Issue