Compare commits

4 Commits
115 changed files with 7546 additions and 3109 deletions

No files matched your search

+67 -2028
View File
File diff suppressed because it is too large. Load diff
+9
View File
@@ -0,0 +1,9 @@
# Arte provisional de decoracion
SVG sencillos y autocontenidos para los nuevos presets de escenario. No contienen
imagenes enlazadas ni fuentes. Son recursos de prototipado, no una promesa de arte
final ni de colisiones ajustadas a la silueta.
Los presets permiten reemplazar Texture y ajustar Display Size sin tocar codigo.
Revisa Collision Dimensions y Collision Offset si cambias las proporciones.
La farola y las fachadas reutilizan los PNG originales de assets/city.
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="80" viewBox="0 0 64 80" shape-rendering="crispEdges"><rect x="9" y="4" width="46" height="72" fill="#352b38"/><rect x="5" y="12" width="54" height="56" fill="#803e40"/><rect x="12" y="12" width="13" height="56" fill="#ad5450"/><rect x="5" y="17" width="54" height="8" fill="#87929c"/><rect x="5" y="54" width="54" height="8" fill="#87929c"/><rect x="13" y="4" width="38" height="8" fill="#505266"/><rect x="18" y="5" width="14" height="4" fill="#a7a5ac"/><rect x="10" y="72" width="44" height="6" fill="#252538"/></svg>

After

Width:  |  Height:  |  Size: 579 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="160" height="84" viewBox="0 0 160 84" shape-rendering="crispEdges"><rect x="10" y="8" width="140" height="12" fill="#be8758"/><rect x="10" y="26" width="140" height="12" fill="#ae734e"/><rect x="18" y="8" width="8" height="48" fill="#55434b"/><rect x="134" y="8" width="8" height="48" fill="#55434b"/><rect x="4" y="48" width="152" height="12" fill="#daa067"/><rect x="16" y="60" width="10" height="24" fill="#3b3d50"/><rect x="134" y="60" width="10" height="24" fill="#3b3d50"/></svg>

After

Width:  |  Height:  |  Size: 533 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64" shape-rendering="crispEdges"><rect x="2" y="2" width="60" height="60" fill="#463336"/><rect x="7" y="7" width="50" height="50" fill="#aa7550"/><path d="M7 7L57 57M57 7L7 57" stroke="#5d4140" stroke-width="10"/><path d="M8 4H56M8 60H56M4 8V56M60 8V56" stroke="#d69b5f" stroke-width="6"/><path d="M7 7H11M53 7H57M7 57H11M53 57H57" stroke="#39323e" stroke-width="4"/></svg>

After

Width:  |  Height:  |  Size: 454 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="80" height="48" viewBox="0 0 80 48" shape-rendering="crispEdges"><path d="M2 38L13 15L34 3L61 8L78 35L70 46H10Z" fill="#535b71"/><path d="M13 15L34 3L61 8L48 21L25 25Z" fill="#87929e"/><path d="M25 25L48 21L70 46H10Z" fill="#687284"/><path d="M2 38L10 46H70L78 35L70 39Z" fill="#353f57"/></svg>

After

Width:  |  Height:  |  Size: 342 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="240" height="144" viewBox="0 0 240 144" shape-rendering="crispEdges"><rect x="108" y="77" width="24" height="67" fill="#4b3943"/><rect x="114" y="81" width="7" height="63" fill="#927057"/><rect x="0" y="0" width="240" height="86" fill="#4b3943"/><rect x="5" y="5" width="230" height="76" fill="#886044"/><rect x="9" y="9" width="222" height="68" fill="#302f42"/><path d="M5 4H235M5 82H235" stroke="#bd9365" stroke-width="3"/></svg>

After

Width:  |  Height:  |  Size: 479 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="64" viewBox="0 0 48 64" shape-rendering="crispEdges"><path d="M20 3H28L39 52H9Z" fill="#df753b"/><path d="M17 17H31L33 26H15ZM12 38H36L38 46H10Z" fill="#f3d9a5"/><rect x="3" y="52" width="42" height="9" fill="#353246"/><rect x="9" y="52" width="30" height="4" fill="#aa543a"/></svg>

After

Width:  |  Height:  |  Size: 342 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="56" height="76" viewBox="0 0 56 76" shape-rendering="crispEdges"><rect x="9" y="16" width="38" height="58" fill="#385a57"/><rect x="14" y="18" width="7" height="50" fill="#527e6c"/><rect x="27" y="18" width="5" height="50" fill="#263e45"/><rect x="38" y="18" width="5" height="50" fill="#263e45"/><rect x="4" y="9" width="48" height="9" fill="#769481"/><rect x="20" y="3" width="16" height="6" fill="#334a50"/><rect x="9" y="70" width="38" height="6" fill="#273644"/></svg>

After

Width:  |  Height:  |  Size: 521 B

+7
View File
@@ -0,0 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 40 40">
<path d="M9 5H32L25 16H35L8 39L15 24H5Z" fill="#29382a" stroke="#060a0c" stroke-width="2"/>
<path d="M10 3H30L22 16H32L11 35L17 22H7Z" fill="#bde345"/>
<path d="M10 3H30L27 7H13L10 18H20L16 27L11 35L17 22H7Z" fill="#ecf5a1"/>
<path d="M22 16H32L28 20H20Z" fill="#6f9c26"/>
<path d="M3 9L1 16M36 23L39 18M30 33L35 29" stroke="#667c40" stroke-width="2"/>
</svg>

After

Width:  |  Height:  |  Size: 454 B

+32
View File
@@ -0,0 +1,32 @@
<svg xmlns="http://www.w3.org/2000/svg" width="344" height="64" viewBox="0 0 344 64">
<defs>
<linearGradient id="steel" x2="0" y2="1">
<stop stop-color="#b3b8b5"/>
<stop offset=".16" stop-color="#414b51"/>
<stop offset=".53" stop-color="#20272c"/>
<stop offset="1" stop-color="#697275"/>
</linearGradient>
<linearGradient id="panel" x2="0" y2="1">
<stop stop-color="#252b30"/>
<stop offset="1" stop-color="#111519"/>
</linearGradient>
</defs>
<path d="M12 2H59L67 7H328L344 22V54L334 64H60L51 59H12L0 47V14Z" fill="#05070a"/>
<path d="M12 0H59L67 5H327L342 20V52L332 62H60L51 57H12L0 45V12Z" fill="url(#steel)"/>
<path d="M13 2H58L66 7H326L340 21V51L331 60H61L52 55H13L2 44V13Z" fill="url(#panel)"/>
<path d="M64 10H323L335 22V51L329 56H64Z" fill="#101519"/>
<path d="M14 5H48L57 14V44L48 52H14L6 43V14Z" fill="#080c10" stroke="#5e686c"/>
<path d="M9 16L17 8H47M65 9H321L331 19" fill="none" stroke="#89918a" stroke-opacity=".42"/>
<path d="M168 56H327M59 14V48" fill="none" stroke="#000" stroke-width="2"/>
<path d="M251 58H296M305 58H325" stroke="#89918a" stroke-opacity=".34"/>
<path d="M18 3L26 3M284 7L290 9M305 7L309 9M335 43L339 39M9 48L14 50" stroke="#c4c4b2" stroke-opacity=".38"/>
<g fill="#a4aaa1" stroke="#090d10" stroke-width="1">
<path d="M7 8L10 5L13 8L10 11Z"/>
<path d="M49 8L52 5L55 8L52 11Z"/>
<path d="M7 48L10 45L13 48L10 51Z"/>
<path d="M49 48L52 45L55 48L52 51Z"/>
<path d="M332 25L335 22L338 25L335 28Z"/>
<path d="M332 49L335 46L338 49L335 52Z"/>
</g>
<path d="M9 8H11M51 8H53M9 48H11M51 48H53M334 25H336M334 49H336" stroke="#303a3e"/>
</svg>

After

Width:  |  Height:  |  Size: 1.6 KiB

+11
View File
@@ -0,0 +1,11 @@
<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 40 40">
<path d="M8 10L0 2L3 17L10 23M32 10L40 2L37 17L30 23" fill="#78817d"/>
<path d="M12 4L20 1L29 4L34 11L33 25L28 29L27 37H13L12 29L7 25L6 12Z" fill="#7e8986"/>
<path d="M12 4L20 2L28 5L32 12L31 24L26 28L25 34H15L14 28L9 24L8 12Z" fill="#e3dfbd"/>
<path d="M11 15L18 17L17 23L11 21ZM29 15L22 17L23 23L29 21Z" fill="#121518"/>
<path d="M14 18L17 19L16 21L13 20M23 19L26 18L27 20L24 21" fill="#ce3440"/>
<path d="M20 22L17 27H23Z" fill="#171b1d"/>
<path d="M16 30V35M20 29V36M24 30V35" stroke="#171b1d" stroke-width="2"/>
<path d="M19 3L17 9L21 12L18 15" fill="none" stroke="#858e86"/>
<path d="M11 8L15 6M25 7L28 10" stroke="#fff7da"/>
</svg>

After

Width:  |  Height:  |  Size: 741 B

+694
View File
@@ -0,0 +1,694 @@
{
"format": "overlay-package-v1",
"base": "project.zip supplied for this revision",
"original_archive_sha256": "9613331c8de2c81fc3ffe599d08634cfec3cebde5a90c94d241c8c37b84fd0f2",
"requires_original_project": true,
"delete_files": [],
"validation": {
"python_static_tests_passed": 37,
"core_modules_executable_lines_unchanged": 10,
"godot_engine_executed": false,
"android_export_tested": false
},
"files": [
{
"path": "README.md",
"status": "modified",
"original_sha256": "54f6c4f84e31de99f25d9eb25183549e1144850f0fd726c39f81cd8fdcf07615",
"sha256": "28a364d763bc11a9809b160354f96ff2527a35d7d5a8bff45001d4857bfac9e5",
"bytes": 3503
},
{
"path": "README_LEVEL_KIT.md",
"status": "added",
"original_sha256": null,
"sha256": "b30511e12364c83cc758f37ee5b39ebb47531196fdb893448c4b7052bfe8a65f",
"bytes": 2958
},
{
"path": "assets/props/README.md",
"status": "added",
"original_sha256": null,
"sha256": "fe2246cf1869fb583ce1a634df057db5e6d1dac26ebf50a3518ea3539403e8d1",
"bytes": 475
},
{
"path": "assets/props/barrel.svg",
"status": "added",
"original_sha256": null,
"sha256": "c29c10a8c7fbc40cf6934f3defb24c7bfa4cbc65ff6aa39099517d329196ade4",
"bytes": 579
},
{
"path": "assets/props/bench.svg",
"status": "added",
"original_sha256": null,
"sha256": "54f381103de091a20d78a548c96e0f6cf54bbd2fbae5f75c8c3945b84e5d7f83",
"bytes": 533
},
{
"path": "assets/props/crate.svg",
"status": "added",
"original_sha256": null,
"sha256": "bc3a63dd371a7b45e13874e032a2891c1c63b3adb1ae3151d3272a4e3ed0a9ad",
"bytes": 454
},
{
"path": "assets/props/rock.svg",
"status": "added",
"original_sha256": null,
"sha256": "52aaa234443a891335b8b073be7f686b182e24d3151d3955650dcbcee5d7f21b",
"bytes": 342
},
{
"path": "assets/props/sign_board.svg",
"status": "added",
"original_sha256": null,
"sha256": "739d086a6f9122e78229b0fb8a545cfe918573bcbffffc77d6a833beaffef7db",
"bytes": 479
},
{
"path": "assets/props/traffic_cone.svg",
"status": "added",
"original_sha256": null,
"sha256": "b193bf41109334aee2eea5f0ae26dc0c78ffb4683a705e3a514b8ba7d1543105",
"bytes": 342
},
{
"path": "assets/props/trash_bin.svg",
"status": "added",
"original_sha256": null,
"sha256": "6c1d036ac8050f3e49fbd75d87c0cdde449c153d9beac844dca63e2066c621bf",
"bytes": 521
},
{
"path": "docs/architecture.md",
"status": "added",
"original_sha256": null,
"sha256": "e4a62ab0332fee5e8bbc52b8b009b6844af6ccc3d94dd14b7e639ecbafa65499",
"bytes": 7820
},
{
"path": "docs/design_vision.md",
"status": "added",
"original_sha256": null,
"sha256": "d03778e825d3c2166c38a390e0499b840199cdc91bf8691cef163cfedeade865",
"bytes": 39567
},
{
"path": "docs/level_02.md",
"status": "modified",
"original_sha256": "81d078b1d4acf738525126d5f6beec465e737fab40d3c69044789cc05ad6d0b7",
"sha256": "d0f71a26bc5fe8c79057a16ff6213e7b9080220c4fdf00c802189cd76d5a4346",
"bytes": 7642
},
{
"path": "docs/level_design.md",
"status": "added",
"original_sha256": null,
"sha256": "bc28aaff2632a238ee0a35c34698f0dec9207a3cda065cf2f03a502b9b31d882",
"bytes": 10318
},
{
"path": "docs/reorganization.md",
"status": "added",
"original_sha256": null,
"sha256": "ec0965a12f102ffe87fef9890327aaf55431f88b4c844cafee42058a39966e03",
"bytes": 8051
},
{
"path": "docs/tuning.md",
"status": "added",
"original_sha256": null,
"sha256": "869933091c2a88cba11c6c671aee30aa8d0495e906f3dedddd87bbdc69912198",
"bytes": 5260
},
{
"path": "docs/validation_audit.txt",
"status": "added",
"original_sha256": null,
"sha256": "839d57b1e776bad5e3af08924e8a8513b2c5289901e3d15e10868c426a43f1c1",
"bytes": 523
},
{
"path": "docs/validation_static.txt",
"status": "added",
"original_sha256": null,
"sha256": "2401020b2a898d61b31e270f18947fe5b99b3270654c2d2ef9d1b89a2730cf08",
"bytes": 5691
},
{
"path": "effects/combat_fx.gd",
"status": "modified",
"original_sha256": "77132a459ddd07af85bc721d0b6acead33ca8c4ba19d67e233a64daf4b4ba769",
"sha256": "19c168ab23eebc42ac20fe9e589bcb3b8d718d2df5a75310692b8ec2a175b693",
"bytes": 5130
},
{
"path": "enemies/walker/walker.gd",
"status": "modified",
"original_sha256": "8cb0b71946cf26ee3f92fe106205fe470cc0ed4e5d628a6b6e1cfad9784c7da5",
"sha256": "830c397b77d107cb5e10f27679349a6c9cce294c9a6c22b6bd298518513c4437",
"bytes": 33016
},
{
"path": "levels/examples/scenery_catalog.tscn",
"status": "added",
"original_sha256": null,
"sha256": "a0b0fe9484bb2572fce83d751022bb6f54236e65bf163fdda82ad82d1fc1639e",
"bytes": 5251
},
{
"path": "levels/level_01.gd",
"status": "modified",
"original_sha256": "d58fcdd7c7e359539108b380e3cc323086949c532a54c8f3f6ea0c30b422154a",
"sha256": "8bb255e96219a0daae9394e6fd75aa9930da5f09c8bdb375ed5c9029099040b8",
"bytes": 5907
},
{
"path": "levels/level_01.tscn",
"status": "modified",
"original_sha256": "948c56e18b5aa7846044de9addb9271106bda9be5640dd07a44ec17bb7d3738f",
"sha256": "48ea7fb42151217519bea250aba7606ed819d7e21508ae60bab567e312d98eda",
"bytes": 17487
},
{
"path": "levels/level_02.gd",
"status": "modified",
"original_sha256": "9746537ee1459762acc6e414f930aa5bc6330b5e4d595dab766483ed6d9a8851",
"sha256": "7d622788849131e7a16572ce5cc8cd0efb490a239ebe065aaf2734f1ec632b87",
"bytes": 2199
},
{
"path": "levels/level_02.tscn",
"status": "modified",
"original_sha256": "54354fe636254ee247e537354f38a946544f88f1445845d98a03205fec41bf05",
"sha256": "5427198c9abc884ec22fb2f151e110c9f4b954482b41d9bdbea8ecf1c2266a38",
"bytes": 21624
},
{
"path": "levels/level_root.gd",
"status": "added",
"original_sha256": null,
"sha256": "502965ea6446d08e78d7afef7597aa50c4fac9d9d920f4c0a4296428024d41fd",
"bytes": 3050
},
{
"path": "levels/templates/level_template.tscn",
"status": "added",
"original_sha256": null,
"sha256": "2b3608d2f928d46f1c8c2c528c0e50a08efb07e713259c64e40d68b905f753cb",
"bytes": 1839
},
{
"path": "levels/test/combat_test.tscn",
"status": "modified",
"original_sha256": "53b6c9f1d8e5fd85e315512ce69b2efe4b2536ddf12d22762d952a73d5909b3d",
"sha256": "58199c47913bf5a9e20916052d496957892ec953e56c36cbaad93e9171a96610",
"bytes": 1846
},
{
"path": "pickups/drop_manager.gd",
"status": "modified",
"original_sha256": "2c5f919ae4c6c272ec87f720af52ae13e228bf3450df11ac0a41dff1c4b54293",
"sha256": "c5c6c0addc50278423fa98ef9f61677d3467f24dd8b4d83e450e35bdee6e6cda",
"bytes": 1980
},
{
"path": "pickups/pickup.gd",
"status": "modified",
"original_sha256": "c6d6a5aa2969aad444efb6522c7d363911eb8474db2c72598d633ccaf03e0852",
"sha256": "af448b8660bc620524511113c665f658a9856e1b197f7d7c65f988198a65aad4",
"bytes": 5427
},
{
"path": "pickups/pickup_data.gd",
"status": "modified",
"original_sha256": "c381e0905da1b339e162dc716ddc1d3240d4877c39ddaa8d97c355744875f22e",
"sha256": "cca5454a23216561f037f0b4f3f91110fad6d14caf985f509bae36cd45a0d380",
"bytes": 905
},
{
"path": "pickups/pickup_drop.gd",
"status": "modified",
"original_sha256": "e0361b22dc95e9f4c7cfe72b96af4443d4e85aee17944f238c9880703b4d18ba",
"sha256": "beddfdd0799b3e46b3be798017d71795b6b6db4bec069421094b9df266812537",
"bytes": 261
},
{
"path": "pickups/pickup_drop_table.gd",
"status": "modified",
"original_sha256": "a7915274c8d4e166b9783b29ed8c08129b78727ccf986081355cc926701f1aff",
"sha256": "00a2d22535adfa3f30b721d9d08ba485a874029cd5ea7dee95684b8fc4be38fb",
"bytes": 506
},
{
"path": "pickups/variants/amplifier_11.tscn",
"status": "added",
"original_sha256": null,
"sha256": "b26a143a76bc0907106644c358fe9cca5abfef79fb8b1c85085d1a36b37a8277",
"bytes": 287
},
{
"path": "pickups/variants/apocalypse_pick.tscn",
"status": "added",
"original_sha256": null,
"sha256": "3de45888f2e42ccd7a2454572d76cdfcbb418efd8b90dd1d12daf0dc590a18f8",
"bytes": 290
},
{
"path": "pickups/variants/beer.tscn",
"status": "added",
"original_sha256": null,
"sha256": "943192c8dabc270bb105d186511332bb43066dd59064962b2374897ce0c663c3",
"bytes": 269
},
{
"path": "pickups/variants/coffee.tscn",
"status": "added",
"original_sha256": null,
"sha256": "65e3fb3e9a8c69ebb6750c2ea43829de04da0facf0a6368b53e34106de2a0088",
"bytes": 273
},
{
"path": "pickups/variants/demo_tape.tscn",
"status": "added",
"original_sha256": null,
"sha256": "0cc513b5007730f2bd13956da3c2f17d79d54d60ab41223313afc4582d2c77d1",
"bytes": 280
},
{
"path": "pickups/variants/distortion_pedal.tscn",
"status": "added",
"original_sha256": null,
"sha256": "37dbdef8778a62f3fb5d0185b0faf94303f4bbb4aa97afae2bcd6bbead5ab70b",
"bytes": 292
},
{
"path": "pickups/variants/double_kick_boots.tscn",
"status": "added",
"original_sha256": null,
"sha256": "3602225bb3cd0099d24fb62e5db6af2cdf68160d4f14238a92ee6bec67b0eb3a",
"bytes": 293
},
{
"path": "pickups/variants/drummer_lunch.tscn",
"status": "added",
"original_sha256": null,
"sha256": "526ef76ff7f3713c25386a3196f87b1f657a60d4b568f73a56ff3e1f6b1ef36a",
"bytes": 287
},
{
"path": "pickups/variants/duct_tape.tscn",
"status": "added",
"original_sha256": null,
"sha256": "20a28639b99244fa177652eb20ac8aaf797367c5b0090fa58bbc581184ea70b8",
"bytes": 284
},
{
"path": "pickups/variants/feedback_can.tscn",
"status": "added",
"original_sha256": null,
"sha256": "0e23dedd77ca2b8f1a4978290c8a803b4b913eef87c8faacd7e3478b953cecaa",
"bytes": 285
},
{
"path": "pickups/variants/final_setlist.tscn",
"status": "added",
"original_sha256": null,
"sha256": "3f19e74a0a4713e135a56b2a5938e5e858e77408ff7e9141c60e4a657bb06fef",
"bytes": 284
},
{
"path": "pickups/variants/post_show_pizza.tscn",
"status": "added",
"original_sha256": null,
"sha256": "53af68bc939683ff74db0570af1a8a27a7a6b45c119175a824d28528fb8b6ded",
"bytes": 289
},
{
"path": "pickups/variants/roadie_sandwich.tscn",
"status": "added",
"original_sha256": null,
"sha256": "645b0fc4e1c2bc387019346a571e79177ae99e29f102ffbedaade4da80b4023f",
"bytes": 288
},
{
"path": "pickups/variants/seismic_drumstick.tscn",
"status": "added",
"original_sha256": null,
"sha256": "23b8bfd4ef97bd9d29c9646867b2b9535dc7a5c1e8debf7d108008669f98fae5",
"bytes": 292
},
{
"path": "pickups/variants/stage_springs.tscn",
"status": "added",
"original_sha256": null,
"sha256": "9d05527db48edad81bfde5388eddd53bccac2573620b1e8dd90634808cc81e09",
"bytes": 286
},
{
"path": "pickups/variants/technician_earplugs.tscn",
"status": "added",
"original_sha256": null,
"sha256": "9aeedc8f4a925d71641d98212061c85d9177d58e5685d258d01f4e32a026faac",
"bytes": 294
},
{
"path": "pickups/variants/titanium_string.tscn",
"status": "added",
"original_sha256": null,
"sha256": "6dfaa5d218af525340400b9c1f79aad7b9f1df240d787492bfa24fd1c0ff93a4",
"bytes": 289
},
{
"path": "player/camera_2d.gd",
"status": "modified",
"original_sha256": "5e7d35ea7a78b36d5b74476620585459e8d3e6cdfbb42aab0f6bd7a84bfcdd13",
"sha256": "ad2612adbb7643e216a66bedfa357151b308789759307ffb1ddb19df1c52be8e",
"bytes": 3318
},
{
"path": "player/character_data.gd",
"status": "modified",
"original_sha256": "99d82b0a13edc26a180361f2c79de672e5ca26b28cdca53410172cfaa2282f14",
"sha256": "2fa2d83209ce62b17fe73343037344a877de3b263d5e59dfdad5ebc2d2924b4c",
"bytes": 1279
},
{
"path": "player/player.gd",
"status": "modified",
"original_sha256": "c0673d619438eb0760feb79bd20163c5330d2538838a9fd5882338b865e5600c",
"sha256": "e98a378013f5a073c5300cfd40170d53115c03df1bad6c8c2da8004aef0e4875",
"bytes": 37604
},
{
"path": "player/player.tscn",
"status": "modified",
"original_sha256": "5d6921704727a784fdbc07d9544b7f0b599aa7bc71a5472344a196bd121493d9",
"sha256": "1a1272eee528bfde1741efcb0525954266badc02fdc34cf1e25e04917b337342",
"bytes": 2422
},
{
"path": "tests/fixtures/legacy_level_geometry.json",
"status": "added",
"original_sha256": null,
"sha256": "3c69076680eeeda0170811db8e9f3da801af34c51340c0e149c2e82e611c5e93",
"bytes": 5598
},
{
"path": "tests/test_enemy_ai_runtime.gd",
"status": "modified",
"original_sha256": "3347b827329b2362dd7bca16544b7303fbbc3cfe7547a27c8605e4ffa57f57ed",
"sha256": "0591ba33534ee12bf86b828bbfc15eda8e1ffb5273596d9629c40091d1b50d71",
"bytes": 9503
},
{
"path": "tests/test_enemy_profiles.py",
"status": "modified",
"original_sha256": "e2b19f0cba83ad8bd20b7d6480715d840c92e05da5b037823fd3e897a7975791",
"sha256": "65028609ebc08338b7fd278fdac9d301e65740374ecf1eb5b3083042ff71f234",
"bytes": 4993
},
{
"path": "tests/test_level_01_resources.py",
"status": "modified",
"original_sha256": "ea37c0a0a5198ce9bf5b7a2cc336fcbf9cf39c2e8d1dfcaba93dbf17988fadf6",
"sha256": "60b14f188105638ff29a3dcf59fcb446154612317bec0c1dbd753569da0fb95f",
"bytes": 4308
},
{
"path": "tests/test_level_02_resources.py",
"status": "modified",
"original_sha256": "340f65c9f01b8845a456806e2758a48fd33c7c8196fac930119af4dde1f50b13",
"sha256": "93ca32d011dea1a852d2cf0920a1577bedea5d315815c5f2b7172df344d03c2c",
"bytes": 4087
},
{
"path": "tests/test_level_02_runtime.gd",
"status": "modified",
"original_sha256": "569871a61c3281d6e65822754c849f7a27d81ed93dbf6aec37f9e5d7c3193a89",
"sha256": "f787e1d5455313f8f28183b85d3f7d9cb31a1d05c304213632b78f1d564256b6",
"bytes": 2910
},
{
"path": "tests/test_level_kit_resources.py",
"status": "added",
"original_sha256": null,
"sha256": "c2b47170f71dabfbeac8889063de94c7298c5cd572f1392ae4fc99fbf61946d1",
"bytes": 5867
},
{
"path": "tests/test_level_kit_runtime.gd",
"status": "added",
"original_sha256": null,
"sha256": "e724327679bb493d0f5087bc64e4ec5c34334fa2866a85d8d139d34cfa2a867b",
"bytes": 7822
},
{
"path": "tests/test_pickup_resources.py",
"status": "modified",
"original_sha256": "e01e960f3a6adf62a267de321673058ef6b949f8237a95700375c7fdb8c3d445",
"sha256": "0fc44dd0f29442a00025e47a008b3c00f008cd05b8b38273e9ffe9d1216f15fc",
"bytes": 3860
},
{
"path": "tests/test_pickup_runtime.gd",
"status": "modified",
"original_sha256": "3a07b4f41691d70169978be9f8046b1129a3026fb7b2b7069e22e9797157f816",
"sha256": "dc321d83f42c693457e13d96495d1a2f89711552e9634147c1a1d719737b8865",
"bytes": 6991
},
{
"path": "tests/test_pixel_combat_resources.py",
"status": "modified",
"original_sha256": "bdb2c8261cfaf0d551e31fc03ac1f06f7e6a03b3ee262baf48a661657f407091",
"sha256": "940199b98582654246100cf3397d099a633f9717c9bd6da2ca0473bc4183f10d",
"bytes": 3089
},
{
"path": "tests/test_pixel_combat_runtime.gd",
"status": "modified",
"original_sha256": "c3a94e5dc46180a01431825d5622e2ac49132dab7d90d11c24f457d5f6346b7e",
"sha256": "789143474710448f61663096e1c98333452766db749cd372b9c3b7936bedc618",
"bytes": 6082
},
{
"path": "tools/generate_city_art.py",
"status": "modified",
"original_sha256": "61f09ccc196ea8986925265c2613928a828516bb2b1322a7d23e03313755662b",
"sha256": "b08a33cb4699d1cdf4c08febd49e7b2a4e3c164d1a009f7b37a2de0e3b107285",
"bytes": 9204
},
{
"path": "tools/run_checks.py",
"status": "added",
"original_sha256": null,
"sha256": "e4d891bc4822a36d9cfc0f8a59961cd941b719dba8ad375c1202e851808bcdf2",
"bytes": 2746
},
{
"path": "ui/hud/player_health_hud.gd",
"status": "modified",
"original_sha256": "b11a403b29b3227b6e9743c73f52312fae9ba13f6b6950969011664c8405ea7a",
"sha256": "48ad8ebb0dabae3d863de259187df5e16b16c390b0aa04e8f9f8caa77809fa41",
"bytes": 2237
},
{
"path": "ui/hud/special_charge_hud.gd",
"status": "modified",
"original_sha256": "68ed51c6d3aa8352528f63750da896b6b0c6bf05fc7d3f05f26b9bbf67e459ec",
"sha256": "494519100ba4b489913ae9e22130b4efd22859c123fdc8185b70250a2b1fbf3e",
"bytes": 1031
},
{
"path": "ui/mobile_controls/mobile_controls.gd",
"status": "modified",
"original_sha256": "01775c29f8345e3842a4d8cd75b23cecc431345c214b4812a1e1d30a85b824b7",
"sha256": "00be4870038fbf9a93f10efe52547d31f446041db8cf1f49d9637d0a7557731f",
"bytes": 3706
},
{
"path": "world/README.md",
"status": "added",
"original_sha256": null,
"sha256": "471d3c707040b96676935e84d69b62f7770852c646bcc29d21a9879cd6f805f5",
"bytes": 861
},
{
"path": "world/backgrounds/city_background.tscn",
"status": "added",
"original_sha256": null,
"sha256": "bb3c0a68c3b92ce973b17fd193339f9c18d76a3822916b6f7afd9a4a69280f68",
"bytes": 1566
},
{
"path": "world/props/barrel.tscn",
"status": "added",
"original_sha256": null,
"sha256": "a72d7bf32edaccf4c243540521c947ddd556e1a110d348f2a0f66a018d514212",
"bytes": 431
},
{
"path": "world/props/bench.tscn",
"status": "added",
"original_sha256": null,
"sha256": "3e1e8014c607cb18f8373308b41e93e5de3aee9fd852b4eedacdf7f36e231608",
"bytes": 432
},
{
"path": "world/props/crate.tscn",
"status": "added",
"original_sha256": null,
"sha256": "5ffe505c794390b3cc2847beb5622998c9f5b2ed6a4ce9006c6386e0c5e6ade3",
"bytes": 429
},
{
"path": "world/props/facade_01.tscn",
"status": "added",
"original_sha256": null,
"sha256": "fd052b8b7cb8310c99d688d2a75e4f5eb4da147dad648191cb003714246b19a6",
"bytes": 443
},
{
"path": "world/props/facade_02.tscn",
"status": "added",
"original_sha256": null,
"sha256": "fce8b66daee567024ac65484c1dc20b40535f5377d29e3cc5cd1a9f5f283e582",
"bytes": 443
},
{
"path": "world/props/facade_03.tscn",
"status": "added",
"original_sha256": null,
"sha256": "3e53a1cc2ca650317423a24f90c524acebd16bffdb8d3d23ed4258825807fbc8",
"bytes": 443
},
{
"path": "world/props/facade_04.tscn",
"status": "added",
"original_sha256": null,
"sha256": "14ed1f7b74b307388b1bcf54403afe6104b71afcd065803905b07c738181a59c",
"bytes": 443
},
{
"path": "world/props/facade_05.tscn",
"status": "added",
"original_sha256": null,
"sha256": "f1dc8ef4d1000c25bbf96f68c5e41de0f96feecab1796da91a58748810f13119",
"bytes": 443
},
{
"path": "world/props/facade_06.tscn",
"status": "added",
"original_sha256": null,
"sha256": "bd0934af274c2cf3dc24c31118ce94670cfc78efa5c467a3c3adeff963cc9e3a",
"bytes": 443
},
{
"path": "world/props/rock.tscn",
"status": "added",
"original_sha256": null,
"sha256": "f247d994dd257dec6f2586abdc965115915879787932a4aa96aa351557736e76",
"bytes": 427
},
{
"path": "world/props/scenery_prop.gd",
"status": "added",
"original_sha256": null,
"sha256": "f81bbc4f1f4a5950d324d9673ed3517ff02eb153872fc71989b5f7d6fab38ba7",
"bytes": 3560
},
{
"path": "world/props/scenery_prop.tscn",
"status": "added",
"original_sha256": null,
"sha256": "9b19321e275756742df937944f794a014ae2bbdaf09318d5a5f524eb65f1ea97",
"bytes": 649
},
{
"path": "world/props/streetlamp.tscn",
"status": "added",
"original_sha256": null,
"sha256": "b380e8583fb46054c8c2cfdf493e6ae6fb62840655b99c2f303aee7e381543a2",
"bytes": 442
},
{
"path": "world/props/traffic_cone.tscn",
"status": "added",
"original_sha256": null,
"sha256": "ff1796f04d47de2ee0b4799b45e242352e9484539dc39dc6e47889120d98d519",
"bytes": 443
},
{
"path": "world/props/trash_bin.tscn",
"status": "added",
"original_sha256": null,
"sha256": "bae0a87ddfdbebaea3328c71621a1ba0df3c6d1eefe34080f4636a359c945254",
"bytes": 436
},
{
"path": "world/signs/sign_post.tscn",
"status": "added",
"original_sha256": null,
"sha256": "e4b40744714c52025a8fec2c841391046fd13d5e658e6b2190e75d1a38c98c36",
"bytes": 1025
},
{
"path": "world/signs/text_label.tscn",
"status": "added",
"original_sha256": null,
"sha256": "8c19b27e6ac9a7366c24caea22a4c743e0f9ce4e39d1cedaf1ff29e3c3f87d8e",
"bytes": 556
},
{
"path": "world/signs/world_sign.gd",
"status": "added",
"original_sha256": null,
"sha256": "88284de900374b4282f6badb27ad303fcddec58c10e1827b6c99dbbabef2ed61",
"bytes": 1137
},
{
"path": "world/terrain/ground.tscn",
"status": "added",
"original_sha256": null,
"sha256": "834af3440933b0fa89e7299e107420fb4bf04912bc9c6df3571bbf30a41e545c",
"bytes": 426
},
{
"path": "world/terrain/platform.tscn",
"status": "added",
"original_sha256": null,
"sha256": "2323746b3f1a6d3e8ce81ba104b40a8f75ab5cd07871744339d7bb9792c3f461",
"bytes": 334
},
{
"path": "world/terrain/solid_block.tscn",
"status": "added",
"original_sha256": null,
"sha256": "a67c94b39b3f52cf1b819ff73eacb6ecd6fb2f602b73a3853f71831b26731f52",
"bytes": 220
},
{
"path": "world/terrain/terrain_piece.gd",
"status": "added",
"original_sha256": null,
"sha256": "1ab88bd8bd1cc5bda7d742958fa095ab55ff3c51b05ab290952519e02c10cbf2",
"bytes": 3663
},
{
"path": "world/terrain/terrain_piece.tscn",
"status": "added",
"original_sha256": null,
"sha256": "41ad2b4b9602d1c991f429c0c76796ff8f96f00e189b2700a1980f3506c0fd8c",
"bytes": 885
},
{
"path": "world/terrain/wall.tscn",
"status": "added",
"original_sha256": null,
"sha256": "cd6b24366001a03219edf699f025c221cdc310bd0451aa343f9961402b364766",
"bytes": 315
}
]
}
+62
View File
@@ -0,0 +1,62 @@
# Kit de edicion visual de niveles
## Aplicar el paquete
Este ZIP contiene SOLO archivos nuevos y modificados. No es un proyecto
independiente: necesita el proyecto original del ZIP que se envio para la revision.
1. Haz una copia de ese proyecto y cierra Godot.
2. Extrae este paquete en una carpeta temporal.
3. Copia el contenido sobre la raiz de la copia del proyecto, al lado de
`project.godot`, combinando carpetas y sustituyendo archivos del mismo nombre.
NO elimines carpetas completas: deben conservarse los archivos originales
que este paquete no incluye.
4. Abre el proyecto con Godot 4.7 y deja terminar la importacion.
5. Abre `levels/examples/scenery_catalog.tscn` para ver las piezas o
`levels/templates/level_template.tscn` para guardar una copia y crear un nivel.
Ejecuta la escena abierta con F6. F5 mantiene el nivel 02 original como entrada.
No se requiere borrar archivos ni instalar un plugin nuevo. Los recursos
originales, incluidas las fuentes tipograficas, deben permanecer en su sitio.
Si has modificado el proyecto desde el ZIP enviado, compara y combina tus cambios
antes de sobrescribir. El manifiesto contiene los hashes anteriores y nuevos.
## Donde empezar
| Necesidad | Archivo o carpeta |
|---|---|
| Guia de edicion paso a paso | `docs/level_design.md` |
| Suelos, plataformas y paredes | `world/terrain/` |
| Barriles, farolas, cajas y otros adornos | `world/props/` |
| Carteles y texto | `world/signs/` |
| Objetos para recoger | `pickups/variants/` |
| Enemigos | `enemies/variants/` |
| Velocidad, salto y otros ajustes | `docs/tuning.md` |
| Mapa de codigo y responsabilidades | `docs/architecture.md` |
| Alcance, limitaciones y validacion | `docs/reorganization.md` |
## Estado de las pruebas
Se han ejecutado y superado **37 pruebas estaticas de Python**. Tambien se han
comprobado referencias y estructura de escenas, sintaxis Python y conservacion
de lineas ejecutables en diez modulos centrales.
**No se ha ejecutado Godot en este entorno.** La importacion, el analisis de
GDScript, la edicion visual, la fisica y las partidas requieren validacion en el
motor. No se ha exportado ni probado Android. Las cinco suites de motor estan
incluidas, pero NO se presentan como ejecutadas.
```bash
python tools/run_checks.py --static-only
python tools/run_checks.py --godot /ruta/al/ejecutable/godot
```
El segundo comando importa el proyecto y ejecuta las cinco suites. En Windows,
pasa la ruta entre comillas al ejecutable de consola de Godot. Las pruebas no son
necesarias para editar niveles, pero conviene ejecutarlas antes de integrar los
cambios en tu copia principal.
La geometria anterior se conserva en una referencia de regresion. La logica
central de combate no se ha reescrito. Se ha anadido recuperacion configurable al
caer fuera del mapa. Los adornos nuevos son recursos sencillos para prototipado,
con colisiones rectangulares opcionales, no objetos destructibles ni moviles.
+157
View File
@@ -0,0 +1,157 @@
# Arquitectura y mapa de codigo
## Problema corregido
Antes, Level01 y Level02 dibujaban el terreno recorriendo CollisionShape2D de sus
propios escenarios. Una colision suelta no era una pieza visual reutilizable y un
nuevo nivel necesitaba reproducir esa logica de dibujo. La camara tambien
sobrescribia limites al iniciar, que luego cada nivel tenia que corregir.
Ahora cada pieza contiene su arte, su colision y sus propiedades de autor. Los
niveles colocan instancias; sus scripts no dibujan el terreno. La plantilla puede
abrirse y ejecutarse directamente sin un generador ni un plugin de edicion.
## Responsabilidades
| Archivo / carpeta | Responsabilidad |
|---|---|
| `world/terrain/terrain_piece.gd` | Sincronizar tamano, texturas y colision de una superficie |
| `world/terrain/*.tscn` | Presets de suelo, plataforma, pared y bloque |
| `world/props/scenery_prop.gd` | Imagen anclada al suelo, profundidad y colision opcional |
| `world/props/*.tscn` | Presets decorativos y fachadas |
| `world/signs/world_sign.gd` | Texto editable sobre SceneryProp; reutiliza su fisica y profundidad |
| `world/signs/text_label.tscn` | Texto libre mediante un Label nativo |
| `world/backgrounds/city_background.tscn` | Las cuatro capas originales de parallax, ahora reutilizables |
| `levels/level_root.gd` | Limites de camara, guia de editor y recuperacion de caidas |
| `levels/templates/level_template.tscn` | Punto de partida sin eventos especificos |
| `levels/examples/scenery_catalog.tscn` | Muestrario jugable para copiar instancias |
| `levels/level_01.gd` | Diagnostico de 17 estaciones, drops garantizados y meta del laboratorio |
| `levels/level_02.gd` | Sectores, enemigos derrotados y meta de la calle |
| `player/player.gd` | Movimiento, ataques, dano, mejoras y animacion del jugador |
| `player/character_data.gd` | Contrato de configuracion por integrante |
| `player/camera_2d.gd` | Sacudidas y feedback; no decide los limites del mapa |
| `enemies/walker/walker.gd` | IA local y combate compartidos por las cinco variantes |
| `pickups/pickup.gd` | Vista previa, movimiento del objeto y recogida confirmada |
| `pickups/pickup_data.gd` | Datos compartidos del objeto; emite cambios visuales para el editor |
| `pickups/drop_manager.gd` | Sorteo ponderado e instanciacion diferida de drops |
| `effects/combat_fx.gd` | Efectos breves de presentacion, sin autoridad sobre el dano |
| `ui/` | Interfaces y entrada tactil |
| `tools/` | Utilidades de desarrollo, no dependencias para montar niveles |
| `tests/` | Contratos estaticos y pruebas independientes que requieren Godot |
| `addons/godot_ai/` | Dependencia de terceros, mantenida sin reescribir |
## Decisiones de modularizacion
Se han extraido componentes donde existia una reutilizacion concreta: varias
superficies, varios adornos, texto sobre adornos y varios niveles con limites de
camara. Los scripts de piezas no conocen al jugador, sus ataques ni el nivel.
No se han creado gestores globales, registros de prefabs, fabricas de niveles,
sistemas de eventos o un plugin propio para sustituir el flujo de escenas de
Godot. El catalogo es una escena normal que puedes editar.
Player y Walker siguen siendo controladores relativamente largos. En esta entrega
se han documentado por bloques y funciones, pero no se han partido artificialmente
en envoltorios que tengan que intercambiar todo su estado. Sus calculos y reglas
centrales de juego se han conservado. Una extraccion futura deberia responder a
una segunda reutilizacion real o a una responsabilidad con estado propio.
## Navegar por Player
La primera parte de `player.gd` contiene los ajustes exportados y sus ayudas.
Despues aparecen nodos y estado de partida. Las funciones estan documentadas:
- Movimiento y salto: `_physics_process`, `_handle_horizontal_movement`,
`_apply_gravity`, `_update_jump_windows`, `_handle_jump`, `get_move_speed`.
- Ataques: `_start_punch`, `_update_punch_damage`, `_start_ground_pound`,
`_ground_pound_impact`, `_start_special_attack`, `_update_special_attack`,
`_apply_special_attack`.
- Vida y objetos: `collect_pickup`, `_damage_target`, `take_damage`, `_die`,
`_update_timers`.
- Presentacion: `_update_animation`, `_update_visual_feedback`, `_draw`.
No dupliques la formula de velocidad en un HUD: ya existe `get_move_speed()`.
No modifiques CharacterData para aplicar un buff: el estado temporal vive en el
jugador y expira de forma independiente.
La conexion a muertes enemigas se hace al iniciar el nivel. Si en el futuro
anades enemigos dinamicamente, ese sistema debera conectar tambien sus senales;
la pertenencia al grupo no crea conexiones automaticamente.
## Navegar por Walker
`_physics_process` prioriza muerte, activacion, retroceso y estado ofensivo antes
de navegar. `_update_idle_behaviour`, `_move_towards`, `_try_jump` y
`_find_jump_landing` resuelven una navegacion local, no rutas globales.
Las fases ofensivas estan separadas en preparacion, barrido danino y recuperacion.
`take_damage` aplica vida, empuje y aturdimiento; `_die` resuelve la muerte logica
antes de su animacion. Los nodos derrotados se conservan porque los niveles usan
sus estados y el numero total de encuentros.
## Contrato de las piezas editables
Los nodos internos ya existen en los `.tscn`. Los scripts `@tool` actualizan esos
hijos; no crean ni destruyen nodos continuamente en el editor. Los setters agrupan
las actualizaciones diferidas para sincronizar varias propiedades sin un bucle
por fotograma.
Cada actualizacion de colision asigna un RectangleShape2D nuevo a esa pieza.
No se modifica una forma compartida. Duplicar una instancia y redimensionarla no
puede cambiar el tamano de otra a traves del mismo recurso.
Los nodos hijos son derivados: no edites su forma o textura a mano para ajustar
una instancia. Sus cambios se reemplazaran por los valores exportados de la raiz.
Para cambiar el comportamiento general, modifica el script base o crea otro preset.
La decoracion utiliza `z_as_relative = false`: su opcion Draw Layer tiene un
significado estable aunque cambies la instancia de carpeta de organizacion.
El terreno utiliza la capa fisica World (1); no se han cambiado las capas del
jugador, de los enemigos ni de sus zonas vulnerables.
Los scripts de nivel y de objetos distinguen editor y partida. En el editor no
se procesan recogidas, ataques, contadores de muertes ni reinicios. LevelRoot solo
dibuja sus guias; SceneryProp y TerrainPiece sincronizan su presentacion.
## Cambios funcionales deliberados
La recuperacion al caer fuera de Camera Bounds mas Fall Margin es infraestructura
nueva para evitar escenarios sin salida. La geometria migrada conserva sus
posiciones, medidas y flags one-way. El dibujo de las barreras ahora pertenece a
su propia pieza y sigue su caja, en vez de tener un rectangulo independiente en
el script del nivel.
Level02 agrupa el parallax bajo `CityBackground`. Su antigua ruta `Sky` pasa a
`CityBackground/Sky`, y lo mismo ocurre con las otras tres capas. Las pruebas que
inspeccionaban esas rutas se han actualizado. Las fachadas y farolas cambian su
origen de esquina superior izquierda a pies centrados, compensando sus posiciones
para conservar donde se veian.
Las reglas especificas de meta permanecen en Level01/Level02. No se aplica una
meta global a la plantilla: los eventos futuros siguen siendo una tarea separada.
## Convenciones
Nombres de codigo, archivos nuevos, nodos y propiedades: ingles. Comentarios y
documentacion: espanol. Los identificadores de objetos ya existentes se conservan,
aunque algunos esten en espanol, para no romper recursos ni registros anteriores.
No se ha traducido ni reformateado el addon externo. Modificar sus fuentes solo
para igualar comentarios dificultaria actualizarlo y mezclar cambios propios con
los del proveedor.
## Presentacion del HUD
- `ui/editor_ui_visibility.gd`: visibilidad de cada CanvasLayer segun se edite un
nivel, la propia UI o se ejecute el juego. No contiene logica de combate.
- `ui/hud/thrash_meter.gd`: ProgressBar visual compartida, con segmentos, estela,
marca del minimo y animacion opcional. Es @tool para previsualizarla.
- `ui/hud/player_health_hud.gd` y `special_charge_hud.gd`: conectan las senales del
jugador con textos y medidores. No se ejecutan dentro del editor.
- `ui/hud/thrash_hud_theme.tres` y `assets/ui/hud/`: tipografia, marco e iconos.
La economia del especial permanece exclusivamente en `player/player.gd`. El HUD
no concede ni consume carga. `_applying_special_damage` delimita la llamada
sincronica a `take_damage`; el Walker actual emite `died` antes de devolverla.
Si en el futuro se retrasa esa senal o se anaden danos persistentes, habra que
transportar la causa del dano en la recompensa en lugar de ampliar este contexto.
File diff suppressed because it is too large. Load diff
+99
View File
@@ -0,0 +1,99 @@
# Interfaz oculta mientras se construyen niveles
## Comportamiento del cambio
El componente `ui/editor_ui_visibility.gd` es un nodo auxiliar llamado
`EditorVisibility`, hijo directo de cada CanvasLayer de interfaz.
- Dentro de un nivel o de la escena del personaje oculta esa capa en el editor.
- Al abrir directamente la escena de esa interfaz, la muestra para editarla.
- Al iniciar la partida muestra la capa aunque se haya guardado oculta.
- Una vez iniciada la partida deja de procesar. El juego puede ocultar la
interfaz normalmente y los mensajes ocultos individualmente siguen ocultos.
El componente de visibilidad no mueve ni redimensiona controles. Los scripts
del jugador, HUD y controles tactiles no se convierten en @tool. El nuevo
componente visual ThrashMeter tambien usa @tool para mostrar su diseno, pero
no ejecuta combate ni entradas dentro del editor.
## Aplicacion
La ocultacion ya esta incluida en `mortal_maze_thrash_hud.patch`, junto al HUD
nuevo y al balance de carga. Este parche parte del proyecto con el kit de niveles
aplicado y SIN el parche anterior de ocultacion. No apliques ambos parches.
Con Godot cerrado, desde la raiz del repositorio:
```sh
git apply --check /ruta/mortal_maze_thrash_hud.patch
git apply /ruta/mortal_maze_thrash_hud.patch
```
Si la comprobacion falla, no fuerces la aplicacion ni sustituyas escenas enteras.
Consulta el diff para conservar tus ediciones locales.
## Conexion manual para no reemplazar niveles ya editados
Despues de copiar `ui/editor_ui_visibility.gd` al proyecto, se necesita
un Node llamado `EditorVisibility` como hijo directo de cada CanvasLayer
que quieras ocultar mientras montas el escenario. Asigna a ese Node el script
`res://ui/editor_ui_visibility.gd`.
En las tres escenas de UI, el padre es su nodo raiz:
- `ui/hud/player_health_hud.tscn`
- `ui/hud/special_charge_hud.tscn`
- `ui/mobile_controls/mobile_controls.tscn`
En los niveles existentes, los padres son:
- `levels/level_01.tscn`: nodo `TestHUD`.
- `levels/level_02.tscn`: nodo `LevelHUD`.
La plantilla, el catalogo, las pruebas de combate y los niveles nuevos que
instancien esas escenas de jugador/controles reciben el cambio sin modificar
sus propios archivos. Las capas de UI nuevas necesitan su propio componente.
## Editar la interfaz
Abre directamente cualquiera de las tres escenas de UI anteriores. Se muestra
su diseno aunque permanezca oculto cuando se instancia dentro de un nivel.
Para ver el HUD que esta definido directamente en `level_01` o `level_02`,
selecciona `TestHUD/EditorVisibility` o `LevelHUD/EditorVisibility` y activa
`Preview In Editor` en el Inspector. Desactivalo al terminar.
El mismo ajuste permite previsualizar las otras capas dentro del nivel.
Para cambiarlo por instancia puedes habilitar los hijos editables de esa
instancia y seleccionar su nodo `EditorVisibility`. Cambiarlo en la escena
original afecta a todas sus instancias que no lo sobrescriban.
No uses el ojo del CanvasLayer como ajuste permanente del editor: este
componente gestiona su visibilidad. Para ocultar la interfaz durante la partida,
la logica del juego puede llamar a hide() despues de entrar en el arbol.
El componente no vuelve a mostrarla cada frame mientras juegas.
## Verificacion realizada y pendiente
El registro de esta entrega esta en `docs/thrash_hud.md`. Se han ejecutado las
49 pruebas estaticas, incluida la conexion de estas cinco capas. El redisenado
del HUD cambia sus escenas y controladores; la logica de controles tactiles y
los scripts de los niveles siguen sin cambios.
No se ha podido ejecutar Godot aqui. La prueba `tests/test_editor_ui_runtime.gd`
y la nueva `tests/test_thrash_hud_runtime.gd` estan incluidas, pero pendientes.
```sh
python tools/run_checks.py --godot /ruta/al/ejecutable/godot
```
La comprobacion visual pendiente es abrir un nivel (UI oculta), abrir una escena
de UI por separado (UI visible), volver al nivel (UI oculta) y ejecutar el nivel
(HUD y controles visibles). Repite despues de guardar para comprobar tambien
que una capa serializada como oculta reaparece correctamente durante el juego.
## Referencias de Godot
- https://docs.godotengine.org/en/stable/tutorials/plugins/running_code_in_the_editor.html
- https://docs.godotengine.org/en/stable/classes/class_canvaslayer.html
- https://docs.godotengine.org/en/stable/classes/class_scenetree.html
+202
View File
@@ -0,0 +1,202 @@
# Crear niveles sin escribir codigo
Esta guia se refiere al proyecto reorganizado. Los nombres de archivos, nodos y
propiedades estan en ingles; las explicaciones y ayudas de las propiedades estan
en espanol. No hace falta ejecutar los generadores de `tools/` para crear niveles.
## 1. Empezar por una escena que ya se puede jugar
Abre `levels/templates/level_template.tscn` y usa **Scene > Save As** para guardarla
como `levels/level_03.tscn`, o duplica el archivo desde FileSystem. Trabaja sobre la
copia, no sobre la plantilla. No es necesario crear una escena heredada.
La copia ya incluye jugador, camara, interfaz de vida/especial, controles tactiles,
fondo urbano, suelo, dos paredes y un cartel. Se prueba con **F6**, que ejecuta la
escena abierta. **F5** conserva la entrada anterior del proyecto: `level_02.tscn`.
No hay que cambiar el menu principal ni escribir un controlador para cada nivel.
El arbol de la plantilla organiza las piezas asi:
```text
NewLevel # Limites de camara y recuperacion de caidas
CityBackground # Fondo con cuatro capas de parallax
World # Suelo, plataformas y paredes
Scenery # Decoracion, con o sin colision
Signs # Carteles y textos
Player # Mover esta instancia para elegir el punto de inicio
Enemies # Instancias de enemies/variants
Items # Instancias de pickups/variants
Triggers # Reservado para tus futuros eventos; no tiene logica
MobileControls # Controles que ya utilizaba el proyecto
```
Conserva `Player` como hijo directo de la raiz y con ese nombre. Puedes renombrar
la raiz del nivel. Las otras carpetas de nodos organizan el contenido; no son un
sistema oculto de generacion.
## 2. Arrastrar, colocar y duplicar
Localiza una escena `.tscn` del catalogo en **FileSystem** y arrastrala al visor 2D.
Mueve la instancia y ajusta sus propiedades en el **Inspector**. Puedes duplicarla
con **Ctrl+D** o copiarla entre escenas con **Ctrl+C / Ctrl+V**.
Comprueba en el arbol de la escena que quede en el grupo deseado; puedes
reorganizarla alli. No es necesario que un objeto tenga un nombre especial.
Mantener `World`, `Scenery`, `Signs`, `Enemies` e `Items` facilita encontrar cosas.
Selecciona siempre la **raiz de la pieza instanciada**, no sus nodos internos.
No necesitas activar `Editable Children`, deshacer la instancia ni editar formas
fisicas a mano. Los hijos se sincronizan desde las propiedades de esa raiz.
El ajuste a una cuadricula de 16 px facilita alinear objetos. Es una ayuda de
edicion, no un requisito del juego: puedes desactivarlo para colocar detalles.
## 3. Suelo, plataformas y paredes
| Escena para arrastrar | Uso inicial |
|---|---|
| `world/terrain/ground.tscn` | Suelo solido con asfalto y borde superior |
| `world/terrain/platform.tscn` | Plataforma atravesable desde abajo |
| `world/terrain/wall.tscn` | Pared o barrera solida |
| `world/terrain/solid_block.tscn` | Bloque de color, util para bocetar escenarios |
En todas ellas, **Dimensions** controla anchura y altura. Actualiza tanto la imagen
como la colision, tambien dentro del editor. No hay que abrir un script del nivel
para dibujar la nueva pieza. Las texturas se repiten en vez de estirarse.
El origen del terreno esta en su **centro**. Por ejemplo, una pieza de 512 x 256 px
con posicion `(256, 1028)` ocupa desde X=0 hasta X=512, y su superficie esta en
Y=900. La relacion es:
```text
superficie del suelo = Position.Y - Dimensions.Y / 2
```
Para alargar suelo, cambia `Dimensions.X` y recoloca su centro si quieres conservar
el borde izquierdo. Para crear escalones, duplica tramos y ajusta su posicion Y.
**Collision Enabled** decide si la pieza bloquea. **One Way** permite pasar desde
abajo y aterrizar desde arriba. Una plataforma deja de ser atravesable si
desactivas `One Way`; un bloque tambien puede convertirse en plataforma activandolo.
No se ha anadido una accion para bajar voluntariamente a traves de plataformas.
Utiliza `Dimensions`, no `Transform > Scale`, para redimensionar terreno. El
controlador avisa de escalas que pueden hacer menos predecible su fisica.
## 4. Decoracion: barriles, farolas, cajas y mas
| Escena | Colision inicial |
|---|---|
| `world/props/barrel.tscn` | Activada |
| `world/props/crate.tscn` | Activada |
| `world/props/trash_bin.tscn` | Activada |
| `world/props/rock.tscn` | Activada |
| `world/props/streetlamp.tscn` | Desactivada |
| `world/props/bench.tscn` | Desactivada |
| `world/props/traffic_cone.tscn` | Desactivada |
| `world/props/facade_01.tscn` ... `facade_06.tscn` | Desactivada, capa de fondo |
El origen de estos objetos esta **abajo, en el centro**. Si el suelo esta en Y=900,
coloca el objeto en Y=900. No tienes que descontar la altura de su imagen.
Cada instancia tiene dos decisiones independientes:
| Resultado deseado | Collision Enabled | Draw Layer |
|---|---|---|
| Barril que obliga a saltar | Activado | Behind characters o At world depth |
| Decoracion por detras del jugador | Desactivado | Behind characters |
| Objeto que tapa al jugador al pasar | Desactivado | In front of characters |
| Fachada lejana | Desactivado | Background |
`Draw Layer` cambia solamente el orden de dibujo. No convierte por si solo un
objeto en atravesable. Es un plataformas lateral: no se ha implementado movimiento
en profundidad ni un sistema automatico para rodear objetos por diferentes planos.
Propiedades adicionales:
- **Display Size**: tamano de la imagen. **Tint**: color. **Flip H**: reflejo horizontal.
- **Collision Dimensions** y **Collision Offset**: tamano y posicion de la caja fisica.
- **Preview Collision**: muestra esa caja en el editor; no se muestra en la partida.
El tamano visible y la caja fisica son independientes deliberadamente: una farola
necesita una colision estrecha para el poste, no una caja tan ancha como la lampara.
Al cambiar mucho `Display Size`, revisa tambien la colision. Para una caja apoyada
en el origen, su desplazamiento Y suele ser `-Collision Dimensions.Y / 2`.
Las colisiones de estos adornos son rectangulos simplificados, no siluetas exactas.
Los nuevos dibujos SVG son recursos sencillos de prototipado y se pueden sustituir
por arte definitivo sin cambiar la logica. No son objetos destructibles ni fisicos
moviles: son decoracion o barreras estaticas.
## 5. Carteles y texto
Arrastra `world/signs/sign_post.tscn`. En su raiz, edita **Sign > Text**; admite
saltos de linea. `Font Size` y `Text Color` cambian la letra. `Display Size` amplia
el cartel, y `Collision Enabled` permite decidir si tambien es un obstaculo.
El texto se actualiza en el editor. El panel no reduce automaticamente la letra
para mensajes largos: amplia el cartel, introduce saltos de linea o reduce el
tamano de fuente. Revisa que el mensaje quepa antes de darlo por terminado.
Para texto suelto sin poste ni tabla, usa `world/signs/text_label.tscn`. Es un
`Label` nativo: edita `Text`, las dimensiones y las opciones de tema del Inspector.
Ese texto no tiene colision. No hay interaccion ni cuadro de dialogo automatico.
## 6. Enemigos y objetos para recoger
Los cinco enemigos siguen en `enemies/variants/`. Arrastra la variante que quieras
a `Enemies`; mueve su raiz y ajusta en el Inspector velocidad, vida, alcance,
salto o recompensa. No necesitas copiar `walker.gd`.
Los 17 objetos estan preparados en **`pickups/variants/`**, cada uno con sus datos
y su icono asignados. Arrastra uno a `Items` y colocalo sobre una superficie. Su
imagen y nombre ya aparecen en el editor, sin iniciar el juego. Durante la partida
conservan su comportamiento anterior de caida, oscilacion y recogida.
Las variantes apuntan a los recursos de `pickups/data/`. Cambiar un `.tres`
compartido cambia todos los objetos que lo usan. Para una excepcion local, utiliza
**Make Unique / Hacer unico** sobre el recurso antes de editarlo, o guarda una copia.
No arrastres los `.gd` ni los recursos `.tres` esperando colocar una pieza visual.
Para colocar contenido, utiliza las escenas `.tscn`. Las escenas base
`terrain_piece.tscn` y `scenery_prop.tscn` son infraestructura; empieza por sus presets.
## 7. Punto de inicio, camara y caidas
Mueve `Player` para elegir donde empieza. Su origen esta aproximadamente en el
centro del cuerpo: con la colision actual de 52 px de alto, sobre un suelo en Y=900
el centro se coloca en Y=874. No coloques el cuerpo dentro de una pared.
Selecciona la raiz del nivel y edita **Camera Bounds** para cambiar la region
que puede mostrar la camara. Su rectangulo azul solo aparece en el editor.
**Alargar el suelo no alarga automaticamente los limites de camara.**
En la plantilla, `Camera Bounds` empieza en `(0, 0)` y mide `(2400, 1280)`. Para
crear un nivel de 5000 px de ancho, cambia el ancho a 5000, amplia o duplica suelo y
mueve la pared derecha. Revisa los limites tambien al crear zonas altas o profundas.
`Reset After Fall` reinicia al caer por debajo del limite inferior mas `Fall Margin`.
La linea roja del editor indica ese umbral. Esta recuperacion evita quedar perdido
bajo el escenario y no depende de escudos ni de invulnerabilidad.
## 8. Un ejemplo para copiar
Abre `levels/examples/scenery_catalog.tscn` y prueba con F6. Contiene un barril
solido, otro que se atraviesa por delante, otro que se atraviesa por detras,
fachada, farola, banco, cono, papelera, roca, caja, plataformas y carteles.
Puedes copiar sus instancias completas a tu nivel.
El catalogo demuestra colocacion y configuracion; no genera el escenario mediante
codigo. Todo su contenido esta guardado como nodos e instancias en la escena.
## 9. Antes de compartir un nivel
Prueba con F6 que el jugador empieza apoyado, los saltos son alcanzables, las
plataformas se atraviesan solo como esperas, los carteles se leen y ninguna
decoracion oculta accidentalmente una zona peligrosa. Revisa la camara hasta ambos
extremos y comprueba la recuperacion de caidas. Guarda y vuelve a abrir la escena
para comprobar que todo conserva sus valores.
La plantilla no anade meta, victoria, dialogos, checkpoints, desbloqueos ni
transiciones. `Triggers` queda reservado para tu trabajo futuro. Los niveles 01 y
02 conservan sus propias metas y reglas anteriores.
+11 -2
View File
@@ -5,6 +5,15 @@ Este es el nivel de inicio (`run/main_scene` en `project.godot`), para que la
siguiente APK entre directamente en esta prueba de campo. El laboratorio de los siguiente APK entre directamente en esta prueba de campo. El laboratorio de los
17 drops sigue accesible en `levels/level_01.tscn`. 17 drops sigue accesible en `levels/level_01.tscn`.
## Edicion visual tras la reorganizacion
El trazado se ha migrado a instancias de `world/terrain/`; las fachadas y
farolas usan `world/props/`. Las capas del fondo estan ahora bajo
`CityBackground`, una instancia de `world/backgrounds/city_background.tscn`.
El script del nivel ya no dibuja el terreno. Para montar otro escenario, usa
`levels/templates/level_template.tscn` y sigue `docs/level_design.md`; no es
necesario regenerar los PNG ni copiar la logica de progreso de esta calle.
## Recorrido ## Recorrido
- **11.000 unidades** de izquierda a derecha, con meta en x=10.850. - **11.000 unidades** de izquierda a derecha, con meta en x=10.850.
@@ -23,8 +32,8 @@ siguiente APK entre directamente en esta prueba de campo. El laboratorio de los
- **Barreras de colisión** a x=0 y x=11.000, visibles en píxeles, para - **Barreras de colisión** a x=0 y x=11.000, visibles en píxeles, para
impedir salir por los extremos. impedir salir por los extremos.
- HUD de progreso (sector y bajas), meta con resultado y reinicio tras 9 s. - HUD de progreso (sector y bajas), meta con resultado y reinicio tras 9 s.
- El especial tiene un radio de 290 unidades **solo en este nivel**, para no - El especial mantiene un radio de 290 unidades en esta instancia del jugador
matar enemigos de zonas enteras a la vez. (el laboratorio tambien tiene esa sobrescritura), para limitar su alcance.
### Calle principal ### Calle principal
+202
View File
@@ -0,0 +1,202 @@
# Crear niveles sin escribir codigo
Esta guia se refiere al proyecto reorganizado. Los nombres de archivos, nodos y
propiedades estan en ingles; las explicaciones y ayudas de las propiedades estan
en espanol. No hace falta ejecutar los generadores de `tools/` para crear niveles.
## 1. Empezar por una escena que ya se puede jugar
Abre `levels/templates/level_template.tscn` y usa **Scene > Save As** para guardarla
como `levels/level_03.tscn`, o duplica el archivo desde FileSystem. Trabaja sobre la
copia, no sobre la plantilla. No es necesario crear una escena heredada.
La copia ya incluye jugador, camara, interfaz de vida/especial, controles tactiles,
fondo urbano, suelo, dos paredes y un cartel. Se prueba con **F6**, que ejecuta la
escena abierta. **F5** conserva la entrada anterior del proyecto: `level_02.tscn`.
No hay que cambiar el menu principal ni escribir un controlador para cada nivel.
El arbol de la plantilla organiza las piezas asi:
```text
NewLevel # Limites de camara y recuperacion de caidas
CityBackground # Fondo con cuatro capas de parallax
World # Suelo, plataformas y paredes
Scenery # Decoracion, con o sin colision
Signs # Carteles y textos
Player # Mover esta instancia para elegir el punto de inicio
Enemies # Instancias de enemies/variants
Items # Instancias de pickups/variants
Triggers # Reservado para tus futuros eventos; no tiene logica
MobileControls # Controles que ya utilizaba el proyecto
```
Conserva `Player` como hijo directo de la raiz y con ese nombre. Puedes renombrar
la raiz del nivel. Las otras carpetas de nodos organizan el contenido; no son un
sistema oculto de generacion.
## 2. Arrastrar, colocar y duplicar
Localiza una escena `.tscn` del catalogo en **FileSystem** y arrastrala al visor 2D.
Mueve la instancia y ajusta sus propiedades en el **Inspector**. Puedes duplicarla
con **Ctrl+D** o copiarla entre escenas con **Ctrl+C / Ctrl+V**.
Comprueba en el arbol de la escena que quede en el grupo deseado; puedes
reorganizarla alli. No es necesario que un objeto tenga un nombre especial.
Mantener `World`, `Scenery`, `Signs`, `Enemies` e `Items` facilita encontrar cosas.
Selecciona siempre la **raiz de la pieza instanciada**, no sus nodos internos.
No necesitas activar `Editable Children`, deshacer la instancia ni editar formas
fisicas a mano. Los hijos se sincronizan desde las propiedades de esa raiz.
El ajuste a una cuadricula de 16 px facilita alinear objetos. Es una ayuda de
edicion, no un requisito del juego: puedes desactivarlo para colocar detalles.
## 3. Suelo, plataformas y paredes
| Escena para arrastrar | Uso inicial |
|---|---|
| `world/terrain/ground.tscn` | Suelo solido con asfalto y borde superior |
| `world/terrain/platform.tscn` | Plataforma atravesable desde abajo |
| `world/terrain/wall.tscn` | Pared o barrera solida |
| `world/terrain/solid_block.tscn` | Bloque de color, util para bocetar escenarios |
En todas ellas, **Dimensions** controla anchura y altura. Actualiza tanto la imagen
como la colision, tambien dentro del editor. No hay que abrir un script del nivel
para dibujar la nueva pieza. Las texturas se repiten en vez de estirarse.
El origen del terreno esta en su **centro**. Por ejemplo, una pieza de 512 x 256 px
con posicion `(256, 1028)` ocupa desde X=0 hasta X=512, y su superficie esta en
Y=900. La relacion es:
```text
superficie del suelo = Position.Y - Dimensions.Y / 2
```
Para alargar suelo, cambia `Dimensions.X` y recoloca su centro si quieres conservar
el borde izquierdo. Para crear escalones, duplica tramos y ajusta su posicion Y.
**Collision Enabled** decide si la pieza bloquea. **One Way** permite pasar desde
abajo y aterrizar desde arriba. Una plataforma deja de ser atravesable si
desactivas `One Way`; un bloque tambien puede convertirse en plataforma activandolo.
No se ha anadido una accion para bajar voluntariamente a traves de plataformas.
Utiliza `Dimensions`, no `Transform > Scale`, para redimensionar terreno. El
controlador avisa de escalas que pueden hacer menos predecible su fisica.
## 4. Decoracion: barriles, farolas, cajas y mas
| Escena | Colision inicial |
|---|---|
| `world/props/barrel.tscn` | Activada |
| `world/props/crate.tscn` | Activada |
| `world/props/trash_bin.tscn` | Activada |
| `world/props/rock.tscn` | Activada |
| `world/props/streetlamp.tscn` | Desactivada |
| `world/props/bench.tscn` | Desactivada |
| `world/props/traffic_cone.tscn` | Desactivada |
| `world/props/facade_01.tscn` ... `facade_06.tscn` | Desactivada, capa de fondo |
El origen de estos objetos esta **abajo, en el centro**. Si el suelo esta en Y=900,
coloca el objeto en Y=900. No tienes que descontar la altura de su imagen.
Cada instancia tiene dos decisiones independientes:
| Resultado deseado | Collision Enabled | Draw Layer |
|---|---|---|
| Barril que obliga a saltar | Activado | Behind characters o At world depth |
| Decoracion por detras del jugador | Desactivado | Behind characters |
| Objeto que tapa al jugador al pasar | Desactivado | In front of characters |
| Fachada lejana | Desactivado | Background |
`Draw Layer` cambia solamente el orden de dibujo. No convierte por si solo un
objeto en atravesable. Es un plataformas lateral: no se ha implementado movimiento
en profundidad ni un sistema automatico para rodear objetos por diferentes planos.
Propiedades adicionales:
- **Display Size**: tamano de la imagen. **Tint**: color. **Flip H**: reflejo horizontal.
- **Collision Dimensions** y **Collision Offset**: tamano y posicion de la caja fisica.
- **Preview Collision**: muestra esa caja en el editor; no se muestra en la partida.
El tamano visible y la caja fisica son independientes deliberadamente: una farola
necesita una colision estrecha para el poste, no una caja tan ancha como la lampara.
Al cambiar mucho `Display Size`, revisa tambien la colision. Para una caja apoyada
en el origen, su desplazamiento Y suele ser `-Collision Dimensions.Y / 2`.
Las colisiones de estos adornos son rectangulos simplificados, no siluetas exactas.
Los nuevos dibujos SVG son recursos sencillos de prototipado y se pueden sustituir
por arte definitivo sin cambiar la logica. No son objetos destructibles ni fisicos
moviles: son decoracion o barreras estaticas.
## 5. Carteles y texto
Arrastra `world/signs/sign_post.tscn`. En su raiz, edita **Sign > Text**; admite
saltos de linea. `Font Size` y `Text Color` cambian la letra. `Display Size` amplia
el cartel, y `Collision Enabled` permite decidir si tambien es un obstaculo.
El texto se actualiza en el editor. El panel no reduce automaticamente la letra
para mensajes largos: amplia el cartel, introduce saltos de linea o reduce el
tamano de fuente. Revisa que el mensaje quepa antes de darlo por terminado.
Para texto suelto sin poste ni tabla, usa `world/signs/text_label.tscn`. Es un
`Label` nativo: edita `Text`, las dimensiones y las opciones de tema del Inspector.
Ese texto no tiene colision. No hay interaccion ni cuadro de dialogo automatico.
## 6. Enemigos y objetos para recoger
Los cinco enemigos siguen en `enemies/variants/`. Arrastra la variante que quieras
a `Enemies`; mueve su raiz y ajusta en el Inspector velocidad, vida, alcance,
salto o recompensa. No necesitas copiar `walker.gd`.
Los 17 objetos estan preparados en **`pickups/variants/`**, cada uno con sus datos
y su icono asignados. Arrastra uno a `Items` y colocalo sobre una superficie. Su
imagen y nombre ya aparecen en el editor, sin iniciar el juego. Durante la partida
conservan su comportamiento anterior de caida, oscilacion y recogida.
Las variantes apuntan a los recursos de `pickups/data/`. Cambiar un `.tres`
compartido cambia todos los objetos que lo usan. Para una excepcion local, utiliza
**Make Unique / Hacer unico** sobre el recurso antes de editarlo, o guarda una copia.
No arrastres los `.gd` ni los recursos `.tres` esperando colocar una pieza visual.
Para colocar contenido, utiliza las escenas `.tscn`. Las escenas base
`terrain_piece.tscn` y `scenery_prop.tscn` son infraestructura; empieza por sus presets.
## 7. Punto de inicio, camara y caidas
Mueve `Player` para elegir donde empieza. Su origen esta aproximadamente en el
centro del cuerpo: con la colision actual de 52 px de alto, sobre un suelo en Y=900
el centro se coloca en Y=874. No coloques el cuerpo dentro de una pared.
Selecciona la raiz del nivel y edita **Camera Bounds** para cambiar la region
que puede mostrar la camara. Su rectangulo azul solo aparece en el editor.
**Alargar el suelo no alarga automaticamente los limites de camara.**
En la plantilla, `Camera Bounds` empieza en `(0, 0)` y mide `(2400, 1280)`. Para
crear un nivel de 5000 px de ancho, cambia el ancho a 5000, amplia o duplica suelo y
mueve la pared derecha. Revisa los limites tambien al crear zonas altas o profundas.
`Reset After Fall` reinicia al caer por debajo del limite inferior mas `Fall Margin`.
La linea roja del editor indica ese umbral. Esta recuperacion evita quedar perdido
bajo el escenario y no depende de escudos ni de invulnerabilidad.
## 8. Un ejemplo para copiar
Abre `levels/examples/scenery_catalog.tscn` y prueba con F6. Contiene un barril
solido, otro que se atraviesa por delante, otro que se atraviesa por detras,
fachada, farola, banco, cono, papelera, roca, caja, plataformas y carteles.
Puedes copiar sus instancias completas a tu nivel.
El catalogo demuestra colocacion y configuracion; no genera el escenario mediante
codigo. Todo su contenido esta guardado como nodos e instancias en la escena.
## 9. Antes de compartir un nivel
Prueba con F6 que el jugador empieza apoyado, los saltos son alcanzables, las
plataformas se atraviesan solo como esperas, los carteles se leen y ninguna
decoracion oculta accidentalmente una zona peligrosa. Revisa la camara hasta ambos
extremos y comprueba la recuperacion de caidas. Guarda y vuelve a abrir la escena
para comprobar que todo conserva sus valores.
La plantilla no anade meta, victoria, dialogos, checkpoints, desbloqueos ni
transiciones. `Triggers` queda reservado para tu trabajo futuro. Los niveles 01 y
02 conservan sus propias metas y reglas anteriores.
+150
View File
@@ -0,0 +1,150 @@
# Reorganizacion: alcance y validacion
## Aplicar la entrega
`mortal_maze_level_kit_changes.zip` es un paquete de archivos nuevos y modificados,
**no un proyecto independiente**. Se aplica sobre el proyecto del ZIP facilitado
para esta revision. No contiene de nuevo los recursos originales sin cambios.
1. Haz una copia del proyecto original y cierra Godot antes de aplicar los cambios.
2. Extrae el paquete en una carpeta temporal. Copia su contenido sobre la raiz de
la copia del proyecto, donde esta `project.godot`, combinando las carpetas y
sustituyendo los archivos de igual nombre. No borres ni reemplaces carpetas
enteras: sus archivos originales no incluidos siguen siendo necesarios.
3. Abre esa copia con la version de Godot indicada por el proyecto (4.7) y deja que
importe los recursos nuevos. Abre la plantilla o el catalogo y ejecuta con F6.
No es necesario eliminar archivos antiguos. No se incluyen `.git`, `.godot`,
fuentes tipograficas, dependencias externas ni copias nuevas de los recursos
originales sin modificar. Las fuentes y demas recursos que ya trae tu proyecto
se conservan en su ubicacion original. El addon externo permanece intacto.
Si has cambiado el proyecto desde el ZIP enviado, revisa el manifiesto y combina
esos archivos en vez de sobrescribir tu trabajo. `LEVEL_KIT_MANIFEST.json` enumera
cada archivo entregado con su estado y SHA-256 anterior/nuevo cuando corresponde.
## Que se ha implementado
- Biblioteca `world/` con **20 escenas utilizables** y dos escenas base: cuatro
superficies, siete adornos, seis fachadas, dos tipos de texto/cartel y un fondo.
- `TerrainPiece`: dimensiones compartidas por dibujo y colision, texturas repetidas
y plataformas opcionalmente atravesables desde abajo.
- `SceneryProp`: posicion por los pies, tamano visual, color, reflejo, profundidad
y colision rectangular opcional. Cada instancia tiene su propia forma fisica.
- Cartel con texto multilinea, tamano de letra y color editables en la instancia.
- Siete SVG sencillos para prototipar barril, caja, cono, banco, papelera, roca y
cartel. No se presentan como arte definitivo.
- Plantilla `levels/templates/level_template.tscn` y muestrario
`levels/examples/scenery_catalog.tscn`, guardados como escenas editables.
- **17 variantes de objetos** listas para arrastrar, utilizando sus datos e iconos
existentes; vista previa de nombre e imagen en el editor.
- Raiz comun `LevelRoot` para limites de camara, guias de edicion y reinicio al
caer fuera del escenario. No se ha creado un gestor de eventos ni un autoload.
- Migracion de los dos niveles y la escena de combate a las piezas reutilizables.
- Comentarios en espanol, ayudas de propiedades y mapa de funciones para el codigo
propio. Los identificadores nuevos permanecen en ingles.
## Que se conserva
Las formulas y reglas centrales de `player.gd` y `walker.gd` no se han reescrito.
Se han comparado sus lineas ejecutables con las originales, excluyendo comentarios
y lineas vacias. Tambien se ha comprobado esa igualdad en datos de personaje,
sorteo de recompensas, efectos de combate, HUD y controles tactiles.
La geometria migrada se compara con un archivo de referencia capturado del
proyecto original: **mismas posiciones, medidas y flags one-way** en los tres
escenarios. Level02 conserva 8 calles, 11 plataformas, 2 barreras, 29 enemigos y
14 objetos colocados. El laboratorio conserva sus 17 estaciones. Las posiciones
de fachadas y farolas compensan su nuevo origen para mantener el mismo lugar.
La entrada del proyecto sigue siendo `levels/level_02.tscn`. Se mantienen los
recursos de personajes, recompensas y animaciones; las cinco variantes enemigas;
las reglas particulares de meta y reinicio; y la configuracion de exportacion.
La camara ya no impone limites ocultos desde `_ready`: conserva los anteriores
como valores de reserva en su escena y recibe los del nivel desde `LevelRoot`.
El fondo urbano esta ahora bajo `CityBackground`, por lo que las rutas a sus
capas pasan, por ejemplo, de `Sky` a `CityBackground/Sky`.
## Cambios funcionales intencionados
El reinicio al caer por debajo de `Camera Bounds` mas `Fall Margin` evita quedarse
atrapado bajo un escenario nuevo. Es configurable y puede desactivarse. No altera
el calculo de dano y no depende de la invulnerabilidad del personaje.
La presentacion y las colisiones de las piezas se sincronizan en el editor.
La decoracion usa profundidad de dibujo independiente de su colision. No hay
movimiento en un tercer eje, objetos destructibles, fisica de barriles moviles,
conversaciones, checkpoints, transiciones ni editor de eventos.
Se mantiene `air_attack_damage` por compatibilidad, pero se documenta que el
controlador actual no lo usa. El golpe aereo se ajusta en la categoria
`Ground Pound` del jugador. No se ha conectado ese campo ni cambiado el balance.
## Validacion realmente realizada
**37 pruebas estaticas de Python: correctas.** Antes de los cambios pasaban las
29 pruebas originales. La entrega conserva esas pruebas, actualiza las referencias
que han cambiado y anade ocho comprobaciones del kit.
Comprueban referencias a archivos y recursos, coherencia de la geometria migrada,
configuracion de niveles, variantes de objetos, recursos SVG, camara y contratos
textuales de las vistas previas. No ejecutan GDScript ni simulan el motor.
**No se ha ejecutado Godot en este entorno.** No se han validado con el motor la
importacion, el analisis de GDScript, la vista previa, las colisiones, el aspecto
final, el rendimiento ni los controles en Android. Tampoco se ha generado una APK.
Los resultados estaticos no permiten afirmar que esas comprobaciones hayan pasado.
## Pruebas incluidas para ejecutar con el motor
`tools/run_checks.py` importa los recursos y ejecuta las cinco suites independientes:
```text
tests/test_enemy_ai_runtime.gd
tests/test_level_02_runtime.gd
tests/test_level_kit_runtime.gd
tests/test_pickup_runtime.gd
tests/test_pixel_combat_runtime.gd
```
La suite nueva comprueba instancias independientes, actualizaciones de dimensiones,
colision y profundidad, texto, carga de presets, limites de camara y el paso real
desde abajo/aterrizaje desde arriba de una plataforma. Estas pruebas se han
escrito, pero **no se han ejecutado aqui**. Tampoco sustituyen a revisar el editor.
Desde la raiz del proyecto:
```bash
python tools/run_checks.py --static-only
python tools/run_checks.py --godot /ruta/al/ejecutable/godot
```
En Windows se puede pasar la ruta entre comillas al ejecutable de consola de Godot.
El runner devuelve un error si falta el motor (salvo con `--static-only`), si una
prueba falla o si aparecen errores del motor/script. No presenta una validacion
parcial como una ejecucion completa.
## Comprobacion manual pendiente
| Comprobar | Como |
|---|---|
| Importacion y scripts | Abrir el proyecto y revisar errores del editor y las cinco suites |
| Crear un nivel | Guardar una copia de la plantilla; probar con F6 |
| Edicion persistente | Duplicar una superficie, cambiar Dimensions, guardar y reabrir |
| Independencia | Confirmar que redimensionar una copia no cambia la otra |
| Colision | Saltar el barril solido y atravesar las variantes sin colision |
| Profundidad | Confirmar que un adorno aparece delante y otro detras del jugador |
| Plataforma | Subir desde abajo y aterrizar encima |
| Carteles | Editar varias lineas, comprobar ajuste y guardar/reabrir |
| Objetos | Ver iconos en editor y comprobar recogida en partida |
| Regresion | Jugar laboratorio y calle original: ataques, recompensas y metas |
| Camara y caida | Recorrer los limites y caer deliberadamente fuera del escenario |
| Android | Exportar y probar controles, legibilidad y rendimiento en un dispositivo |
## Documentos de entrada
`docs/level_design.md` explica el trabajo visual paso a paso.
`docs/tuning.md` indica donde cambiar cada parametro.
`docs/architecture.md` permite localizar responsabilidades y funciones.
El README anterior se conserva, marcado como historico, en `docs/design_vision.md`.
+150
View File
@@ -0,0 +1,150 @@
# Reorganizacion: alcance y validacion
## Aplicar la entrega
`mortal_maze_level_kit_changes.zip` es un paquete de archivos nuevos y modificados,
**no un proyecto independiente**. Se aplica sobre el proyecto del ZIP facilitado
para esta revision. No contiene de nuevo los recursos originales sin cambios.
1. Haz una copia del proyecto original y cierra Godot antes de aplicar los cambios.
2. Extrae el paquete en una carpeta temporal. Copia su contenido sobre la raiz de
la copia del proyecto, donde esta `project.godot`, combinando las carpetas y
sustituyendo los archivos de igual nombre. No borres ni reemplaces carpetas
enteras: sus archivos originales no incluidos siguen siendo necesarios.
3. Abre esa copia con la version de Godot indicada por el proyecto (4.7) y deja que
importe los recursos nuevos. Abre la plantilla o el catalogo y ejecuta con F6.
No es necesario eliminar archivos antiguos. No se incluyen `.git`, `.godot`,
fuentes tipograficas, dependencias externas ni copias nuevas de los recursos
originales sin modificar. Las fuentes y demas recursos que ya trae tu proyecto
se conservan en su ubicacion original. El addon externo permanece intacto.
Si has cambiado el proyecto desde el ZIP enviado, revisa el manifiesto y combina
esos archivos en vez de sobrescribir tu trabajo. `LEVEL_KIT_MANIFEST.json` enumera
cada archivo entregado con su estado y SHA-256 anterior/nuevo cuando corresponde.
## Que se ha implementado
- Biblioteca `world/` con **20 escenas utilizables** y dos escenas base: cuatro
superficies, siete adornos, seis fachadas, dos tipos de texto/cartel y un fondo.
- `TerrainPiece`: dimensiones compartidas por dibujo y colision, texturas repetidas
y plataformas opcionalmente atravesables desde abajo.
- `SceneryProp`: posicion por los pies, tamano visual, color, reflejo, profundidad
y colision rectangular opcional. Cada instancia tiene su propia forma fisica.
- Cartel con texto multilinea, tamano de letra y color editables en la instancia.
- Siete SVG sencillos para prototipar barril, caja, cono, banco, papelera, roca y
cartel. No se presentan como arte definitivo.
- Plantilla `levels/templates/level_template.tscn` y muestrario
`levels/examples/scenery_catalog.tscn`, guardados como escenas editables.
- **17 variantes de objetos** listas para arrastrar, utilizando sus datos e iconos
existentes; vista previa de nombre e imagen en el editor.
- Raiz comun `LevelRoot` para limites de camara, guias de edicion y reinicio al
caer fuera del escenario. No se ha creado un gestor de eventos ni un autoload.
- Migracion de los dos niveles y la escena de combate a las piezas reutilizables.
- Comentarios en espanol, ayudas de propiedades y mapa de funciones para el codigo
propio. Los identificadores nuevos permanecen en ingles.
## Que se conserva
Las formulas y reglas centrales de `player.gd` y `walker.gd` no se han reescrito.
Se han comparado sus lineas ejecutables con las originales, excluyendo comentarios
y lineas vacias. Tambien se ha comprobado esa igualdad en datos de personaje,
sorteo de recompensas, efectos de combate, HUD y controles tactiles.
La geometria migrada se compara con un archivo de referencia capturado del
proyecto original: **mismas posiciones, medidas y flags one-way** en los tres
escenarios. Level02 conserva 8 calles, 11 plataformas, 2 barreras, 29 enemigos y
14 objetos colocados. El laboratorio conserva sus 17 estaciones. Las posiciones
de fachadas y farolas compensan su nuevo origen para mantener el mismo lugar.
La entrada del proyecto sigue siendo `levels/level_02.tscn`. Se mantienen los
recursos de personajes, recompensas y animaciones; las cinco variantes enemigas;
las reglas particulares de meta y reinicio; y la configuracion de exportacion.
La camara ya no impone limites ocultos desde `_ready`: conserva los anteriores
como valores de reserva en su escena y recibe los del nivel desde `LevelRoot`.
El fondo urbano esta ahora bajo `CityBackground`, por lo que las rutas a sus
capas pasan, por ejemplo, de `Sky` a `CityBackground/Sky`.
## Cambios funcionales intencionados
El reinicio al caer por debajo de `Camera Bounds` mas `Fall Margin` evita quedarse
atrapado bajo un escenario nuevo. Es configurable y puede desactivarse. No altera
el calculo de dano y no depende de la invulnerabilidad del personaje.
La presentacion y las colisiones de las piezas se sincronizan en el editor.
La decoracion usa profundidad de dibujo independiente de su colision. No hay
movimiento en un tercer eje, objetos destructibles, fisica de barriles moviles,
conversaciones, checkpoints, transiciones ni editor de eventos.
Se mantiene `air_attack_damage` por compatibilidad, pero se documenta que el
controlador actual no lo usa. El golpe aereo se ajusta en la categoria
`Ground Pound` del jugador. No se ha conectado ese campo ni cambiado el balance.
## Validacion realmente realizada
**37 pruebas estaticas de Python: correctas.** Antes de los cambios pasaban las
29 pruebas originales. La entrega conserva esas pruebas, actualiza las referencias
que han cambiado y anade ocho comprobaciones del kit.
Comprueban referencias a archivos y recursos, coherencia de la geometria migrada,
configuracion de niveles, variantes de objetos, recursos SVG, camara y contratos
textuales de las vistas previas. No ejecutan GDScript ni simulan el motor.
**No se ha ejecutado Godot en este entorno.** No se han validado con el motor la
importacion, el analisis de GDScript, la vista previa, las colisiones, el aspecto
final, el rendimiento ni los controles en Android. Tampoco se ha generado una APK.
Los resultados estaticos no permiten afirmar que esas comprobaciones hayan pasado.
## Pruebas incluidas para ejecutar con el motor
`tools/run_checks.py` importa los recursos y ejecuta las cinco suites independientes:
```text
tests/test_enemy_ai_runtime.gd
tests/test_level_02_runtime.gd
tests/test_level_kit_runtime.gd
tests/test_pickup_runtime.gd
tests/test_pixel_combat_runtime.gd
```
La suite nueva comprueba instancias independientes, actualizaciones de dimensiones,
colision y profundidad, texto, carga de presets, limites de camara y el paso real
desde abajo/aterrizaje desde arriba de una plataforma. Estas pruebas se han
escrito, pero **no se han ejecutado aqui**. Tampoco sustituyen a revisar el editor.
Desde la raiz del proyecto:
```bash
python tools/run_checks.py --static-only
python tools/run_checks.py --godot /ruta/al/ejecutable/godot
```
En Windows se puede pasar la ruta entre comillas al ejecutable de consola de Godot.
El runner devuelve un error si falta el motor (salvo con `--static-only`), si una
prueba falla o si aparecen errores del motor/script. No presenta una validacion
parcial como una ejecucion completa.
## Comprobacion manual pendiente
| Comprobar | Como |
|---|---|
| Importacion y scripts | Abrir el proyecto y revisar errores del editor y las cinco suites |
| Crear un nivel | Guardar una copia de la plantilla; probar con F6 |
| Edicion persistente | Duplicar una superficie, cambiar Dimensions, guardar y reabrir |
| Independencia | Confirmar que redimensionar una copia no cambia la otra |
| Colision | Saltar el barril solido y atravesar las variantes sin colision |
| Profundidad | Confirmar que un adorno aparece delante y otro detras del jugador |
| Plataforma | Subir desde abajo y aterrizar encima |
| Carteles | Editar varias lineas, comprobar ajuste y guardar/reabrir |
| Objetos | Ver iconos en editor y comprobar recogida en partida |
| Regresion | Jugar laboratorio y calle original: ataques, recompensas y metas |
| Camara y caida | Recorrer los limites y caer deliberadamente fuera del escenario |
| Android | Exportar y probar controles, legibilidad y rendimiento en un dispositivo |
## Documentos de entrada
`docs/level_design.md` explica el trabajo visual paso a paso.
`docs/tuning.md` indica donde cambiar cada parametro.
`docs/architecture.md` permite localizar responsabilidades y funciones.
El README anterior se conserva, marcado como historico, en `docs/design_vision.md`.
+160
View File
@@ -0,0 +1,160 @@
# HUD thrash, editor despejado y carga del especial
## Base y aplicacion del parche
`mortal_maze_thrash_hud.patch` se aplica sobre el proyecto original con la
reorganizacion `mortal_maze_level_kit_changes.zip` ya integrada, pero SIN haber
aplicado `mortal_maze_editor_ui.patch`. Ya contiene ese cambio de ocultacion.
Guarda o confirma tus cambios y cierra Godot. Desde la raiz del repositorio,
con el parche descargado en esa carpeta:
```sh
git apply --check mortal_maze_thrash_hud.patch
git apply mortal_maze_thrash_hud.patch
git diff --check
```
El primer comando no modifica archivos. Si detecta conflictos, no lo fuerces:
compara los bloques afectados con tus ediciones. El parche no sustituye carpetas
completas, no incluye fuentes tipograficas ni caches y no modifica el addon.
Reabre el proyecto y deja terminar la importacion de los nuevos SVG y scripts.
## Cambios visibles
El conjunto ocupa 344 x 132 px con margen de 18 px en la esquina superior
izquierda. No se cambian la resolucion, el escalado del proyecto ni los botones
tactiles. Los textos de mejoras temporales comienzan debajo de ambas barras.
La vida usa una placa oscura con remaches, calavera y segmentos rojos. El numero
refleja la vida real inmediatamente; la parte perdida queda un instante en color
hueso antes de desaparecer. Al 25% de vida o menos aparece PELIGRO y un pulso lento.
Con vida cero se muestra SIN VIDA, sin mantener el aviso animado de peligro.
El solo usa el mismo marco con un rayo y segmentos verde acido. Hay una marca
sobre el umbral real de uso, una leyenda de puntos minimos y tres estados:
| Estado | Significado |
|---|---|
| CARGANDO | Todavia no hay carga suficiente |
| LISTO | Se ha alcanzado el minimo de carga |
| AL 11 | La capacidad esta completa |
| DESACTIVADO | Capacidad cero o minimo configurado por encima de la capacidad |
LISTO se refiere a la energia, no anula las restricciones temporales del combate.
La carga sube suavemente, pero al gastarla la barra se vacia inmediatamente para
no aparentar energia utilizable. No se anaden sonidos, combos ni ataques nuevos.
El diseno se apoya en tres SVG de texto y la fuente que ya habia en el proyecto.
No necesita shaders, plugins nuevos, servicios externos ni archivos de fuentes
adicionales. La logica de combate no se ejecuta dentro del editor.
## Balance
| Ajuste | Antes | Ahora |
|---|---:|---:|
| Capacidad inicial | 100 | 100 |
| Puntos por baja ordinaria | 25 | 10 |
| Minimo para usar el solo | 25 | 25 |
| Bajas para poder usarlo desde cero, sin objetos | 1 | 3 |
| Bajas para llenarlo desde cero, sin objetos | 4 | 10 |
| Recarga por bajas causadas por el propio solo | Si | No, configurable |
Se sigue consumiendo toda la carga acumulada y el dano sigue escalando con ella.
No es necesario esperar al 100%: con tres bajas tendras 30 puntos y podras usarlo,
pero con menos potencia que con la barra llena. Dano maximo, radio, duracion,
numero de pulsos, movimiento y salto permanecen como estaban.
Los objetos de recarga mantienen sus valores: casete 25, setlist 50 y amplificador
100. Por tanto, las diez bajas son la referencia SIN objetos. No se retocan los
drops ni su frecuencia. Es un punto de partida para probar jugando, no un balance
validado mediante partidas en este entorno.
La opcion `special_kills_grant_charge` filtra solo las muertes causadas por la
llamada de dano del solo. Una baja normal que coincida con su animacion sigue
otorgando puntos. Se aprovecha que Walker emite `died` dentro de `take_damage`;
si se introduce dano diferido, habra que transmitir su procedencia explicitamente.
## Ajustes sin codigo
En la raiz de `player/player.tscn`, categoria **Special Attack**:
```text
Special Max Charge 100
Special Charge Per Kill 10
Special Min Use Charge 25
Special Kills Grant Charge false
```
Poner el minimo a 100 obliga a llenar la barra. Activar la ultima opcion recupera
la recarga con bajas propias. Las sobrescrituras de una instancia de Player tienen
prioridad sobre el valor de su escena original, como el resto de sus parametros.
Para editar el diseno abre estas escenas directamente:
```text
ui/hud/player_health_hud.tscn
ui/hud/special_charge_hud.tscn
```
En `HUD/HealthBar` o `HUD/SpecialBar`:
| Propiedad | Para que sirve |
|---|---|
| Fill Color | Color de los segmentos |
| Segment Count | Numero de segmentos; no cambia la vida o la carga |
| Animations Enabled | Desactiva pulsos, estelas animadas y transiciones |
| Show Damage Trail | Presenta temporalmente la energia perdida; desactivado en el solo |
| Damage Trail Delay | Tiempo de espera antes de reducir la estela |
| Fill Transition Seconds | Duracion de cada subida visual de vida/carga |
`Activation Ratio` muestra una marca de maqueta en el editor; durante la partida
lo calcula el controlador con los valores reales del jugador. No debe utilizarse
como configuracion del coste del ataque. `value` y `max_value` de las escenas de UI
tambien son muestras: el jugador proporciona la lectura inicial al empezar.
En la raiz de `PlayerHealthHUD`, `Low Health Ratio` ajusta el umbral de PELIGRO.
El tema comun esta en `ui/hud/thrash_hud_theme.tres`; los textos, posiciones y
anclajes siguen siendo nodos editables. Cada barra es una escena reutilizable.
## Ocultacion al disenar niveles
El parche incluye `EditorVisibility` en vida, especial, controles tactiles y
los mensajes superpuestos de Level01/Level02. Esas capas se ocultan al construir
un escenario; se muestran al abrir su propia escena o al jugar. Los carteles del
mapa no se ocultan. El control de visibilidad no interfiere con paneles que deban
permanecer ocultos durante la partida.
`Preview In Editor` permite revisar una capa sin salir del nivel. Consulta
`docs/editor_ui_visibility.md` para editar ese ajuste por instancia.
## Comprobaciones
Realizado en esta entrega:
- Las 49 pruebas estaticas de Python pasan. Incluyen recursos, conexiones de UI,
rutas, aislamiento de entradas y contratos del nuevo balance.
- Se revisaron los SVG y la geometria con un render de referencia externo a Godot.
Ese render no valida el motor, sus fuentes, animaciones ni la experiencia jugable.
- Se comprobo la aplicacion del parche sobre una reconstruccion limpia de su base,
la coincidencia del resultado con los archivos entregados y su reversibilidad.
No se ha podido ejecutar Godot. La importacion real, las siete suites de motor,
la ocultacion interactiva, las animaciones y la validacion en Android quedan
pendientes. No se ha generado ni probado una APK. No se debe interpretar que
las pruebas estaticas compilan o ejecutan GDScript.
```sh
python tools/run_checks.py --static-only
python tools/run_checks.py --godot /ruta/al/ejecutable/godot
```
El segundo comando importa y descubre automaticamente todas las suites. La nueva
`tests/test_thrash_hud_runtime.gd` cubre vida inicial, perdida y curacion, modo sin
animaciones, carga por baja, saturacion, umbrales configurables, consumo, capacidad
cero, bajas reales por el solo y conservacion de objetos de recarga.
Para la revision visual, abre un nivel, abre luego cada escena de UI y ejecuta
el nivel con F6. Comprueba recibir dano, curarte, reunir tres y diez bajas sin
objetos y gastar el especial. Revisa tambien la composicion en los tamanos de
pantalla que utilices, sobre todo con controles tactiles.
+133
View File
@@ -0,0 +1,133 @@
# Donde ajustar cada parametro
No hay una copia nueva de los valores de movimiento en otro archivo. Se mantienen
dos ambitos existentes: recursos de personaje para diferencias entre integrantes,
y propiedades exportadas del jugador para reglas comunes. Los comentarios `##`
explican las propiedades desde el Inspector y la documentacion del script.
## Personaje: velocidad, salto, vida y dano base
Abre uno de estos recursos en el Inspector:
```text
player/characters/singer.tres
player/characters/guitarist.tres
player/characters/bassist.tres
player/characters/drummer.tres
```
| Propiedad | Significado |
|---|---|
| `move_speed` | Velocidad horizontal base en px/s |
| `jump_velocity` | Impulso vertical inicial; valores mas negativos suben mas |
| `max_health` | Vida maxima |
| `basic_attack_damage` | Dano base del punetazo |
| `air_attack_damage` | Campo heredado SIN USO actual en Player; modificarlo no cambia el golpe aereo |
| `sprite_frames` | Animaciones del integrante |
El recurso inicial de `player/player.tscn` sigue siendo `singer.tres`, con
`move_speed = 390`, `jump_velocity = -600` y `max_health = 50`. Esos valores no se
han cambiado en esta reorganizacion. Selecciona otro `Character Data` en la
instancia de Player para cambiar de integrante.
Un `.tres` externo es compartido: editarlo afecta a todas sus referencias. Para
probar solo en un nivel, haz unico el recurso de esa instancia o guarda una copia.
Las mejoras recogidas durante la partida siguen siendo estado temporal; no alteran
el recurso compartido.
## Jugador: reglas comunes
Abre **`player/player.tscn`**, selecciona su raiz y edita el Inspector. Es la forma
sin codigo de cambiar los valores comunes para las instancias que no tengan
sobrescrituras locales. No hace falta buscar una constante dentro del controlador.
| Categoria | Ajustes principales |
|---|---|
| Movement | Aceleracion, friccion, frenado al girar, control aereo |
| Jump | Margen de borde, memoria de salto, corte al soltar, gravedad, caida maxima |
| Double Jump | Activacion, numero de saltos y multiplicador del segundo impulso |
| Damage received | Invulnerabilidad e impulso al recibir dano |
| Punch | Preparacion, duracion activa, espera, tamano y desplazamiento del area |
| Ground Pound | Velocidad de inicio, gravedad, control horizontal, radio y limites de dano |
| Special Attack | Capacidad, carga por muerte, recarga con bajas del solo, minimo de uso, radio, dano, duracion y pulsos |
| Debug | Dibujo de colisiones y duracion del indicador de impacto |
La altura real de salto depende de `jump_velocity`, gravedad, corte al soltar y
segundo salto. `double_jump_multiplier` multiplica velocidad, no una altura medida
directamente en pixeles. Prueba los cambios con el mismo personaje y sin mejoras
activas para poder compararlos.
`air_attack_damage` se conserva para no alterar los recursos existentes, pero
no participa en el calculo actual. El golpe aereo se ajusta en **Ground Pound**:
`ground_pound_damage_per_pixel`, dano minimo y dano maximo. La formula usa la
altura de caida y las mejoras activas.
`fall_gravity_multiplier` sustituye a `gravity_multiplier` durante la caida; no
se multiplica por este. El golpe aereo utiliza su propio multiplicador.
La gravedad base permanece en los ajustes de fisica 2D del proyecto. No se ha
creado un segundo valor global que la sustituya.
**Sobrescrituras:** tanto el laboratorio como Level02 mantienen
`special_radius = 290` en su propia instancia. Cambiar el valor general de
player.tscn no elimina esas excepciones. El
Inspector permite restablecer una propiedad al valor heredado cuando corresponde.
## Carga del especial y aspecto del HUD
Los ajustes siguen en la raiz de `player/player.tscn`, categoria **Special Attack**:
| Propiedad | Valor inicial | Efecto |
|---|---:|---|
| `special_max_charge` | 100 | Capacidad en puntos; cero desactiva el ataque |
| `special_charge_per_kill` | 10 | Recompensa por una baja ordinaria |
| `special_min_use_charge` | 25 | Minimo de activacion; el solo consume toda la carga acumulada |
| `special_kills_grant_charge` | false | Activar para que las bajas del propio solo vuelvan a recargarlo |
Desde cero y sin recoger objetos: dos bajas suman 20 y no permiten usarlo; tres
suman 30 y si permiten; diez llenan los 100 puntos. El dano sigue dependiendo de
la carga consumida, igual que antes. Los objetos de recarga conservan 25/50/100
puntos segun su recurso; no se han modificado sus probabilidades de aparicion.
El HUD lee capacidad y minimo del jugador; no hay que sincronizar otros valores.
El texto `MIN 25 PT` son puntos, mientras el numero grande muestra el porcentaje
respecto a la capacidad configurada. `LISTO` significa carga suficiente, no que
se anulen bloqueos temporales como estar ejecutando otro ataque.
Para editar el aspecto abre las escenas de `ui/hud/` directamente. En `HUD/HealthBar`
o `HUD/SpecialBar`, **Thrash Appearance** ajusta color y segmentos, y **Thrash Feedback**
permite desactivar las animaciones. En la raiz del HUD de vida, **Low Health Ratio**
controla el aviso de peligro sin alterar la vida del personaje. Mas detalles en
`docs/thrash_hud.md`.
## Camara y controles
Los limites del mapa estan en `Camera Bounds` de la raiz de cada nivel. El zoom
esta en `Player/Camera2D`, dentro de `player/player.tscn`. `Feedback Strength`
controla sacudidas y superposiciones; cero las desactiva.
La camara ya no impone por codigo el antiguo limite de 4000 px al arrancar. Los
valores de reserva siguen en su escena, y `LevelRoot` aplica los del escenario.
Las teclas se conservan en `project.godot`, accesibles desde Project Settings >
Input Map. Los controles tactiles activan esas mismas acciones, no otra logica de
movimiento. No se han cambiado sus asociaciones.
## Enemigos, recompensas y escenario
| Que quieres cambiar | Donde hacerlo |
|---|---|
| Perfil normal de un enemigo | Raiz de `enemies/variants/*.tscn` |
| Solo un enemigo de un nivel | Propiedades de esa instancia en la escena |
| Probabilidad y pesos de drops | `enemies/walker/walker_drop.tres` |
| Recompensa fija | `Guaranteed Drop` en la instancia del enemigo |
| Potencia/duracion de un objeto | `pickups/data/*.tres` |
| Caida y oscilacion de objetos | `pickups/pickup.tscn` o una variante/instancia |
| Tamano de suelo y plataformas | `Dimensions` de la pieza colocada |
| Colision de una decoracion | `Collision Enabled`, `Collision Dimensions`, `Collision Offset` |
| Decoracion delante/detras | `Draw Layer`, independientemente de la colision |
| Texto de cartel | `Text` en la raiz de la instancia |
Las constantes que siguen dentro de las reglas especificas del laboratorio o de
la meta de Level02 no se han convertido en un sistema de eventos configurable.
Ese trabajo queda separado de la construccion de escenarios.
+8
View File
@@ -0,0 +1,8 @@
PASS: lineas ejecutables de 10 modulos centrales identicas al original.
PASS: datos originales, variantes enemigas, addon, entrada y exportacion sin cambios.
PASS: sintaxis Python de tests y herramientas.
PASS: padres y rutas de nodos explicitos en 56 escenas propias.
PASS: contador de recursos load_steps del nuevo catalogo.
PASS: enlaces relativos de las guias de entrada.
PASS: ningun archivo original requiere eliminacion.
PENDIENTE: importacion, analisis de GDScript, editor, fisica, partida y Android en Godot real.
+45
View File
@@ -0,0 +1,45 @@
> /opt/pyvenv/bin/python -m unittest discover -s tests -v
test_attack_phases_leave_a_readable_pause (test_enemy_profiles.EnemyProfileTests.test_attack_phases_leave_a_readable_pause) ... ok
test_chase_is_longer_but_not_unlimited (test_enemy_profiles.EnemyProfileTests.test_chase_is_longer_but_not_unlimited) ... ok
test_damage_api_keeps_old_callers_compatible (test_enemy_profiles.EnemyProfileTests.test_damage_api_keeps_old_callers_compatible) ... ok
test_difficulty_damage_and_push_are_distinct (test_enemy_profiles.EnemyProfileTests.test_difficulty_damage_and_push_are_distinct) ... ok
test_first_enemy_relocated_without_deleting_encounters (test_enemy_profiles.EnemyProfileTests.test_first_enemy_relocated_without_deleting_encounters) ... ok
test_heavy_enemies_do_not_take_two_second_stun_from_each_punch (test_enemy_profiles.EnemyProfileTests.test_heavy_enemies_do_not_take_two_second_stun_from_each_punch) ... ok
test_jumps_can_climb_the_street_steps (test_enemy_profiles.EnemyProfileTests.test_jumps_can_climb_the_street_steps) ... ok
test_lab_keeps_its_small_leash (test_enemy_profiles.EnemyProfileTests.test_lab_keeps_its_small_leash) ... ok
test_only_two_agile_variants_jump (test_enemy_profiles.EnemyProfileTests.test_only_two_agile_variants_jump) ... ok
test_all_external_scene_references_exist (test_level_01_resources.Level01ConfigurationTests.test_all_external_scene_references_exist) ... ok
test_control_pickup_and_death_tracking_are_separate (test_level_01_resources.Level01ConfigurationTests.test_control_pickup_and_death_tracking_are_separate) ... ok
test_enemy_variants_disable_respawn (test_level_01_resources.Level01ConfigurationTests.test_enemy_variants_disable_respawn) ... ok
test_every_enemy_svg_is_valid_and_present (test_level_01_resources.Level01ConfigurationTests.test_every_enemy_svg_is_valid_and_present) ... ok
test_finish_and_death_areas_detect_player_layer (test_level_01_resources.Level01ConfigurationTests.test_finish_and_death_areas_detect_player_layer) ... ok
test_floor_covers_all_encounters_and_finish (test_level_01_resources.Level01ConfigurationTests.test_floor_covers_all_encounters_and_finish) ... ok
test_seventeen_different_guaranteed_drops (test_level_01_resources.Level01ConfigurationTests.test_seventeen_different_guaranteed_drops) ... ok
test_50_hp_all_characters_and_12_point_ground_pound (test_level_02_resources.Level02ResourceTests.test_50_hp_all_characters_and_12_point_ground_pound) ... ok
test_asset_references_exist (test_level_02_resources.Level02ResourceTests.test_asset_references_exist) ... ok
test_multiple_encounters_and_optional_items (test_level_02_resources.Level02ResourceTests.test_multiple_encounters_and_optional_items) ... ok
test_pixel_art_is_real_rgba_png_and_parallax_is_repeated (test_level_02_resources.Level02ResourceTests.test_pixel_art_is_real_rgba_png_and_parallax_is_repeated) ... ok
test_road_is_continuous_and_has_end_walls (test_level_02_resources.Level02ResourceTests.test_road_is_continuous_and_has_end_walls) ... ok
test_all_seventeen_collectibles_have_drag_ready_variants (test_level_kit_resources.LevelKitResourceTests.test_all_seventeen_collectibles_have_drag_ready_variants) ... ok
test_camera_has_no_hidden_runtime_limits (test_level_kit_resources.LevelKitResourceTests.test_camera_has_no_hidden_runtime_limits) ... ok
test_every_own_resource_reference_resolves (test_level_kit_resources.LevelKitResourceTests.test_every_own_resource_reference_resolves) ... ok
test_legacy_geometry_has_identical_positions_sizes_and_one_way_flags (test_level_kit_resources.LevelKitResourceTests.test_legacy_geometry_has_identical_positions_sizes_and_one_way_flags) ... ok
test_levels_no_longer_render_their_terrain (test_level_kit_resources.LevelKitResourceTests.test_levels_no_longer_render_their_terrain) ... ok
test_preview_code_guards_runtime_and_keeps_shapes_per_instance (test_level_kit_resources.LevelKitResourceTests.test_preview_code_guards_runtime_and_keeps_shapes_per_instance) ... ok
test_prop_art_is_self_contained_and_valid_svg (test_level_kit_resources.LevelKitResourceTests.test_prop_art_is_self_contained_and_valid_svg) ... ok
test_template_and_example_are_playable_scenes_not_generators (test_level_kit_resources.LevelKitResourceTests.test_template_and_example_are_playable_scenes_not_generators) ... ok
test_all_pickups_have_serializable_colors (test_pickup_resources.PickupResourceTests.test_all_pickups_have_serializable_colors) ... ok
test_item_resources_have_valid_identifiers_names_and_images (test_pickup_resources.PickupResourceTests.test_item_resources_have_valid_identifiers_names_and_images) ... ok
test_moving_across_a_drop_cannot_lose_the_pickup (test_pickup_resources.PickupResourceTests.test_moving_across_a_drop_cannot_lose_the_pickup) ... ok
test_runtime_pickups_detect_player_and_only_drops_have_a_delay (test_pickup_resources.PickupResourceTests.test_runtime_pickups_detect_player_and_only_drops_have_a_delay) ... ok
test_all_animation_cells_exist_and_fit_atlas (test_pixel_combat_resources.PixelCombatResourceTests.test_all_animation_cells_exist_and_fit_atlas) ... ok
test_new_asset_has_no_external_dependencies (test_pixel_combat_resources.PixelCombatResourceTests.test_new_asset_has_no_external_dependencies) ... ok
test_player_poses_and_pixel_scale (test_pixel_combat_resources.PixelCombatResourceTests.test_player_poses_and_pixel_scale) ... ok
test_pulse_rounding_preserves_the_damage_budget (test_pixel_combat_resources.PixelCombatResourceTests.test_pulse_rounding_preserves_the_damage_budget) ... ok
----------------------------------------------------------------------
Ran 37 tests in 0.037s
OK
OK: pruebas estaticas. No se ha ejecutado Godot ni validado su fisica.
+10 -3
View File
@@ -1,8 +1,8 @@
class_name CombatFX class_name CombatFX
extends Node2D extends Node2D
## Short-lived world-space effects shared by the player and enemies. ## Efectos breves en coordenadas del mundo, compartidos por jugador y enemigos.
## Pixel shapes only: no particles plugin, imported effect textures or fonts. ## Usan figuras geometricas, sin plugins ni recursos externos de efectos.
var kind: StringName = &"hit" var kind: StringName = &"hit"
var direction: float = 1.0 var direction: float = 1.0
@@ -11,6 +11,7 @@ var _age: float = 0.0
var _lifetime: float = 0.28 var _lifetime: float = 0.28
## Crea un efecto transitorio en coordenadas globales bajo el padre indicado.
static func spawn(parent: Node, origin: Vector2, effect_kind: StringName, static func spawn(parent: Node, origin: Vector2, effect_kind: StringName,
effect_direction: float = 1.0, effect_radius: float = 54.0) -> void: effect_direction: float = 1.0, effect_radius: float = 54.0) -> void:
if not is_instance_valid(parent): if not is_instance_valid(parent):
@@ -23,6 +24,7 @@ static func spawn(parent: Node, origin: Vector2, effect_kind: StringName,
effect.global_position = origin effect.global_position = origin
## Selecciona la duracion visual segun el tipo de efecto.
func _ready() -> void: func _ready() -> void:
z_index = 12 z_index = 12
texture_filter = CanvasItem.TEXTURE_FILTER_NEAREST texture_filter = CanvasItem.TEXTURE_FILTER_NEAREST
@@ -37,6 +39,7 @@ func _ready() -> void:
_lifetime = 0.32 _lifetime = 0.32
## Solicita redibujado hasta agotar la duracion y eliminar el efecto.
func _process(delta: float) -> void: func _process(delta: float) -> void:
_age += delta _age += delta
if _age >= _lifetime: if _age >= _lifetime:
@@ -45,6 +48,7 @@ func _process(delta: float) -> void:
queue_redraw() queue_redraw()
## Genera el efecto segun su tipo y progreso, sin participar en el calculo de dano.
func _draw() -> void: func _draw() -> void:
var progress: float = clampf(_age / _lifetime, 0.0, 1.0) var progress: float = clampf(_age / _lifetime, 0.0, 1.0)
var fade: float = 1.0 - progress var fade: float = 1.0 - progress
@@ -53,7 +57,7 @@ func _draw() -> void:
_draw_ring(lerpf(8.0, radius, progress), 0.24, Color(1.0, 0.72, 0.34, fade), 3.0) _draw_ring(lerpf(8.0, radius, progress), 0.24, Color(1.0, 0.72, 0.34, fade), 3.0)
_draw_ring(lerpf(3.0, radius * 0.72, progress), 0.32, Color(1.0, 0.94, 0.68, fade), 2.0) _draw_ring(lerpf(3.0, radius * 0.72, progress), 0.32, Color(1.0, 0.94, 0.68, fade), 2.0)
_draw_debris(progress, 16, Color(0.84, 0.71, 0.56, fade), radius) _draw_debris(progress, 16, Color(0.84, 0.71, 0.56, fade), radius)
# Ground cracks appear at the landing point, not attached to the player. # Las grietas permanecen donde ocurrio el impacto, no se desplazan con el jugador.
for side: float in [-1.0, 1.0]: for side: float in [-1.0, 1.0]:
var crack := PackedVector2Array([ var crack := PackedVector2Array([
Vector2(3.0 * side, 0.0), Vector2(14.0 * side, 3.0), Vector2(3.0 * side, 0.0), Vector2(14.0 * side, 3.0),
@@ -88,6 +92,7 @@ func _draw() -> void:
draw_rect(Rect2(-8, -3, 16, 6), Color(1.0, 0.98, 0.88, fade)) draw_rect(Rect2(-8, -3, 16, 6), Color(1.0, 0.98, 0.88, fade))
## Aproxima un anillo eliptico con segmentos de estilo pixelado.
func _draw_ring(ring_radius: float, height_ratio: float, color: Color, width: float) -> void: func _draw_ring(ring_radius: float, height_ratio: float, color: Color, width: float) -> void:
var points := PackedVector2Array() var points := PackedVector2Array()
for index: int in range(33): for index: int in range(33):
@@ -106,6 +111,7 @@ func _draw_sparks(progress: float, color: Color, count: int, spread: float) -> v
draw_line(tail, point, color, 2.0) draw_line(tail, point, color, 2.0)
## Dibuja fragmentos que se separan del punto de impacto.
func _draw_debris(progress: float, count: int, color: Color, spread: float) -> void: func _draw_debris(progress: float, count: int, color: Color, spread: float) -> void:
for index: int in range(count): for index: int in range(count):
var side: float = -1.0 if index % 2 == 0 else 1.0 var side: float = -1.0 if index % 2 == 0 else 1.0
@@ -117,6 +123,7 @@ func _draw_debris(progress: float, count: int, color: Color, spread: float) -> v
draw_rect(Rect2(point.round(), Vector2.ONE * size), color) draw_rect(Rect2(point.round(), Vector2.ONE * size), color)
## Dibuja una nota musical geometrica sin depender de una fuente.
func _draw_note(point: Vector2, color: Color) -> void: func _draw_note(point: Vector2, color: Color) -> void:
draw_rect(Rect2(point, Vector2(5, 4)), color) draw_rect(Rect2(point, Vector2(5, 4)), color)
draw_rect(Rect2(point + Vector2(4, -10), Vector2(2, 13)), color) draw_rect(Rect2(point + Vector2(4, -10), Vector2(2, 13)), color)
+126 -110
View File
@@ -1,11 +1,14 @@
extends CharacterBody2D extends CharacterBody2D
## Controlador comun de enemigos. Configura variantes en enemies/variants/*.tscn.
## Navegacion local y combate comparten estado; no dependen del codigo de los niveles.
signal died signal died
# The five scene variants share this controller. Their movement, jump and # Las cinco variantes comparten controlador. Sus ajustes viven en enemies/variants;
# attack settings live in enemies/variants; no separate AI hierarchy is needed. # no hace falta duplicar la IA ni crear una jerarquia por cada enemigo.
const PLAYER_HURTBOX_MASK: int = 1 << 3 const PLAYER_HURTBOX_MASK: int = 1 << 3
const DROP_MANAGER := preload("res://pickups/drop_manager.gd") const DROP_MANAGER := preload("res://pickups/drop_manager.gd")
@@ -21,7 +24,7 @@ enum AttackState {
# ============================================================================ # ============================================================================
# MOVEMENT # MOVIMIENTO
# ============================================================================ # ============================================================================
@export_category("Movement") @export_category("Movement")
@@ -29,22 +32,22 @@ enum AttackState {
@export var move_speed: float = 78.0 @export var move_speed: float = 78.0
@export var max_fall_speed: float = 800.0 @export var max_fall_speed: float = 800.0
## Seeing an enemy on screen wakes it, but proximity starts the pursuit. ## Ver al enemigo lo activa; la proximidad inicia la persecucion.
## Once engaged it keeps chasing up to 1.5 times this distance, within its leash. ## Una vez iniciada, continua hasta 1,5 veces esta distancia, sin exceder Chase Radius.
@export_range(80.0, 1200.0, 10.0) var aggro_range: float = 340.0 @export_range(80.0, 1200.0, 10.0) var aggro_range: float = 340.0
## Only agile variants jump. Others still stop at walls and platform edges. ## Solo las variantes agiles saltan. Las demas se detienen ante paredes y bordes.
@export var can_jump: bool = false @export var can_jump: bool = false
@export_range(-900.0, -100.0, 10.0) var jump_velocity: float = -560.0 @export_range(-900.0, -100.0, 10.0) var jump_velocity: float = -560.0
@export_range(0.2, 3.0, 0.05) var jump_cooldown: float = 0.9 @export_range(0.2, 3.0, 0.05) var jump_cooldown: float = 0.9
@export var hop_while_chasing: bool = false @export var hop_while_chasing: bool = false
## A landing must exist within this drop; never jump into an unbounded pit. ## Desnivel maximo aceptado para un aterrizaje; no salta a un vacio sin suelo detectado.
@export_range(0.0, 400.0, 10.0) var max_jump_drop: float = 200.0 @export_range(0.0, 400.0, 10.0) var max_jump_drop: float = 200.0
# ============================================================================ # ============================================================================
# COMBAT # COMBATE
# ============================================================================ # ============================================================================
@export_category("Combat") @export_category("Combat")
@@ -52,107 +55,99 @@ enum AttackState {
@export_range(1, 100, 1) var max_health: int = 20 @export_range(1, 100, 1) var max_health: int = 20
@export_range(0, 100, 1) var attack_damage: int = 1 @export_range(0, 100, 1) var attack_damage: int = 1
## Outgoing push on the player, independent of damage and enemy knockback. ## Empuje aplicado al jugador, independiente del dano y del retroceso recibido por el enemigo.
@export_range(0.0, 3.0, 0.05) var attack_knockback_multiplier: float = 1.0 @export_range(0.0, 3.0, 0.05) var attack_knockback_multiplier: float = 1.0
## Minimum time between the beginning of two attacks. ## Tiempo minimo entre el inicio de dos ataques.
@export var attack_interval: float = 2.0 @export var attack_interval: float = 2.0
## Horizontal distance at which the Walker stops chasing and prepares a hit. ## Distancia horizontal para preparar el ataque. Supera el area final
## This is intentionally wider than the final hitbox so entering range does not ## para ofrecer tiempo de reaccion antes de que el golpe alcance al jugador.
## mean taking unavoidable damage.
@export var attack_trigger_distance: float = 140.0 @export var attack_trigger_distance: float = 140.0
## Keeps the Walker from starting a ground attack against a player far above or ## Evita iniciar ataques de suelo contra un jugador situado demasiado arriba o abajo.
## below it.
@export var attack_vertical_tolerance: float = 80.0 @export var attack_vertical_tolerance: float = 80.0
## Readable pause before the dangerous part of the attack starts. During this ## Preparacion visible anterior al impacto. La direccion queda fijada y permite esquivar por detras.
## time the direction is locked, so moving behind the enemy is a valid dodge.
@export var attack_windup_duration: float = 0.35 @export var attack_windup_duration: float = 0.35
## Duration of the actual hit. The hitbox sweeps forward during this window. ## Duracion de la fase danina; el area de ataque avanza durante esta ventana.
@export var attack_duration: float = 0.22 @export var attack_duration: float = 0.22
## Small recovery after the hit before the enemy can hitbox again. ## Recuperacion tras el golpe antes de poder iniciar otro.
@export var attack_recovery_duration: float = 0.30 @export var attack_recovery_duration: float = 0.30
## Where the hitbox starts, relative to the enemy while facing right. ## Posicion inicial del area de ataque cuando el enemigo mira a la derecha.
@export var attack_start_offset: Vector2 = Vector2(34.0, 0.0) @export var attack_start_offset: Vector2 = Vector2(34.0, 0.0)
## Furthest horizontal position reached by the moving hitbox. ## Distancia horizontal maxima que alcanza el barrido ofensivo.
@export var attack_reach: float = 120.0 @export var attack_reach: float = 120.0
## A successful player hit briefly interrupts the Walker. This makes attacking ## Interrupcion breve al recibir un golpe. Permite defenderse atacando durante la preparacion enemiga.
## during its windup useful instead of forcing an unavoidable damage trade.
@export var hit_stun_duration: float = 0.18 @export var hit_stun_duration: float = 0.18
## Strength of the knockback applied per point of damage. The final push is ## Impulso por punto de dano, dividido por la vida maxima: los enemigos resistentes retroceden menos.
## divided by the enemy's max health, so tougher enemies move less.
@export var knockback_strength: float = 400.0 @export var knockback_strength: float = 400.0
## How long the knockback impulse lasts before friction brings the enemy to a halt. ## Duracion del retroceso antes de que el frenado detenga al enemigo.
@export var knockback_duration: float = 0.4 @export var knockback_duration: float = 0.4
## Damage threshold to trigger a longer stun (e.g. a fully charged special attack). ## Umbral de dano que provoca un aturdimiento prolongado.
@export_range(0, 100, 1) var stun_damage_threshold: int = 5 @export_range(0, 100, 1) var stun_damage_threshold: int = 5
## Stun duration when the received damage exceeds the threshold. ## Duracion del aturdimiento cuando el impacto supera el umbral.
@export var strong_hit_stun_duration: float = 2.0 @export var strong_hit_stun_duration: float = 2.0
# ============================================================================ # ============================================================================
# RESPAWN # RECOMPENSAS Y REAPARICION
# ============================================================================ # ============================================================================
@export_category("Drops") @export_category("Drops")
## Default weighted drops for normal encounters. ## Tabla de recompensas aleatorias para encuentros normales.
@export var drop_table: PickupDropTable @export var drop_table: PickupDropTable
## Optional fixed drop, used by the Level 01 test route. When assigned, this ## Recompensa fija opcional: reemplaza a la tabla aleatoria, no se suma a ella.
## object drops with 100% probability INSTEAD of the random table.
@export var guaranteed_drop: PickupData @export var guaranteed_drop: PickupData
## In the Android lab, Level01 watches deaths and spawns the fixed reward. ## El laboratorio observa las muertes y crea sus recompensas.
## Other levels keep using this enemy's own random/guaranteed drop logic. ## En los demas niveles el enemigo sigue gestionando sus propios objetos.
var drops_handled_by_level: bool = false var drops_handled_by_level: bool = false
@export_category("Respawn") @export_category("Respawn")
## A value of 0 disables respawn (one enemy = one test item). ## Cero desactiva la reaparicion: un enemigo muerto permanece derrotado.
@export var respawn_delay: float = 5.0 @export var respawn_delay: float = 5.0
## Visible launch, collapse and fade before the body disappears. ## Duracion de lanzamiento, caida y desvanecimiento antes de ocultar el cuerpo.
@export_range(0.3, 2.5, 0.05) var death_animation_duration: float = 0.9 @export_range(0.3, 2.5, 0.05) var death_animation_duration: float = 0.9
## Horizontal leash from spawn; 0 = unrestricted. Losing the target or ## Limite horizontal desde el origen; cero significa sin limite.
## reaching the leash makes the enemy return home rather than follow forever. ## Si pierde al jugador o supera este radio, vuelve a su posicion inicial.
@export var chase_radius: float = 0.0 @export var chase_radius: float = 0.0
## Only used to describe enemy variants in test HUDs. ## Nombre informativo para interfaces y pruebas de las variantes.
@export var enemy_display_name: String = "Walker" @export var enemy_display_name: String = "Walker"
# ============================================================================ # ============================================================================
# DEBUG # DEPURACION
# ============================================================================ # ============================================================================
@export_category("Debug") @export_category("Debug")
## Enabled while the enemy has no final sprite/animation. The grey rectangle is ## Dibuja zonas vulnerables y areas de ataque. La anticipacion naranja
## the temporary body. Red overlays are the hurtbox and active attack hitbox. ## es informacion de juego y permanece visible aunque esta opcion este desactivada.
## The orange area during windup previews the complete attack sweep.
@export var show_debug_hitboxes: bool = false @export var show_debug_hitboxes: bool = false
## Shows the enemy health bar above its head and floating damage numbers when ## Barra de vida y numeros de dano para depuracion; no cambia la logica de combate.
## it is hit. Purely debug: can be disabled once final art and UI exist.
@export var show_debug_enemy_info: bool = true @export var show_debug_enemy_info: bool = true
# ============================================================================ # ============================================================================
# NODES # NODOS
# ============================================================================ # ============================================================================
@onready var body_collision: CollisionShape2D = $CollisionShape2D @onready var body_collision: CollisionShape2D = $CollisionShape2D
@@ -165,7 +160,7 @@ var drops_handled_by_level: bool = false
# ============================================================================ # ============================================================================
# RUNTIME STATE # ESTADO DE LA PARTIDA
# ============================================================================ # ============================================================================
var current_health: int var current_health: int
@@ -187,14 +182,13 @@ var _jump_cooldown_timer: float = 0.0
var _jump_in_progress: bool = false var _jump_in_progress: bool = false
var _jump_target_x: float = 0.0 var _jump_target_x: float = 0.0
## Prevents one sweep from damaging the same target once per physics frame. ## Evita aplicar dano repetidamente al mismo objetivo durante un unico barrido.
var attack_hit_targets: Dictionary = {} var attack_hit_targets: Dictionary = {}
## Timer for the knockback impulse applied when the enemy is hit. ## Tiempo restante del impulso de retroceso.
var knockback_timer: float = 0.0 var knockback_timer: float = 0.0
## Floating damage numbers shown above the enemy when it takes damage. ## Numeros flotantes de dano. Cada entrada contiene texto, posicion local y tiempo restante.
## Each entry: { text: String, local_pos: Vector2, timer: float }
var _damage_texts: Array = [] var _damage_texts: Array = []
var _hit_flash_timer: float = 0.0 var _hit_flash_timer: float = 0.0
var _death_elapsed: float = 0.0 var _death_elapsed: float = 0.0
@@ -205,6 +199,7 @@ var _visual_rotation: float
var _visual_color: Color var _visual_color: Color
## Captura el punto de origen, resuelve al jugador y configura fisica, recompensas y activacion.
func _ready() -> void: func _ready() -> void:
_visual_position = visual.position _visual_position = visual.position
_visual_scale = visual.scale _visual_scale = visual.scale
@@ -230,6 +225,7 @@ func _ready() -> void:
queue_redraw() queue_redraw()
## Prioriza muerte, inactividad, retroceso, ataque y navegacion en ese orden.
func _physics_process(delta: float) -> void: func _physics_process(delta: float) -> void:
if is_dead: if is_dead:
_update_death_animation(delta) _update_death_animation(delta)
@@ -241,8 +237,8 @@ func _physics_process(delta: float) -> void:
_update_damage_texts(delta) _update_damage_texts(delta)
_apply_gravity(delta) _apply_gravity(delta)
# The enemy deliberately does nothing until the camera has shown it once. # Permanece inactivo hasta aparecer en pantalla una vez.
# After waking up it may pursue or return home even outside the screen. # Tras activarse puede perseguir o regresar aunque vuelva a quedar fuera de camara.
if not is_awake: if not is_awake:
velocity.x = 0.0 velocity.x = 0.0
move_and_slide() move_and_slide()
@@ -256,10 +252,8 @@ func _physics_process(delta: float) -> void:
queue_redraw() queue_redraw()
return return
# Being hit pauses both movement and attack. While the knockback impulse # Un impacto pausa movimiento y ataque. Primero aplica retroceso y luego frena.
# lasts the enemy is pushed back, then friction brings it to a halt. The # La espera entre ataques sigue avanzando para que la interrupcion no reinicie un golpe inmediato.
# cooldown keeps running, so interrupting an attack does not make the enemy
# immediately start another one.
if hit_stun_timer > 0.0: if hit_stun_timer > 0.0:
if knockback_timer > 0.0: if knockback_timer > 0.0:
knockback_timer = max(knockback_timer - delta, 0.0) knockback_timer = max(knockback_timer - delta, 0.0)
@@ -283,13 +277,15 @@ func _physics_process(delta: float) -> void:
# ============================================================================ # ============================================================================
# ACTIVATION AND TARGETING # ACTIVACION Y OBJETIVO
# ============================================================================ # ============================================================================
## Activa permanentemente al enemigo al entrar por primera vez en pantalla.
func _wake_up() -> void: func _wake_up() -> void:
is_awake = true is_awake = true
## Recupera una referencia valida al jugador sin buscar mientras la actual sigue viva.
func _acquire_target_if_needed() -> void: func _acquire_target_if_needed() -> void:
if target != null and is_instance_valid(target): if target != null and is_instance_valid(target):
return return
@@ -297,6 +293,7 @@ func _acquire_target_if_needed() -> void:
target = get_tree().get_first_node_in_group(&"player") as Node2D target = get_tree().get_first_node_in_group(&"player") as Node2D
## Orienta al enemigo hacia el objetivo si hay una diferencia horizontal significativa.
func _face_target() -> void: func _face_target() -> void:
var direction_to_target: float = signf(target.global_position.x - global_position.x) var direction_to_target: float = signf(target.global_position.x - global_position.x)
if direction_to_target == 0.0 or direction_to_target == facing_direction: if direction_to_target == 0.0 or direction_to_target == facing_direction:
@@ -306,21 +303,23 @@ func _face_target() -> void:
_update_facing() _update_facing()
## Sincroniza textura y sonda frontal; no altera la direccion de un ataque ya fijada.
func _update_facing() -> void: func _update_facing() -> void:
# The ledge probe follows the current movement direction. Attack direction is # La sonda del borde sigue el movimiento. La direccion ofensiva se guarda aparte
# stored separately once a windup starts so the enemy cannot rotate mid-hit. # para impedir que un ataque ya preparado gire siguiendo al jugador.
floor_probe.position.x = abs(floor_probe.position.x) * facing_direction floor_probe.position.x = abs(floor_probe.position.x) * facing_direction
if attack_state == AttackState.IDLE: if attack_state == AttackState.IDLE:
_reset_attack_hitbox_position() _reset_attack_hitbox_position()
# The five variants share one collision box and AI, but use different sprites. # Las variantes comparten caja de colision e IA, pero tienen texturas diferentes.
visual.flip_h = facing_direction < 0.0 visual.flip_h = facing_direction < 0.0
# ============================================================================ # ============================================================================
# MOVEMENT # MOVIMIENTO
# ============================================================================ # ============================================================================
## Aplica gravedad con limite de caida y sin acumular velocidad dentro del suelo.
func _apply_gravity(delta: float) -> void: func _apply_gravity(delta: float) -> void:
if is_on_floor(): if is_on_floor():
return return
@@ -329,6 +328,7 @@ func _apply_gravity(delta: float) -> void:
velocity.y = min(velocity.y, max_fall_speed) velocity.y = min(velocity.y, max_fall_speed)
## Decide entre perseguir, volver al origen o esperar, respetando los radios configurados.
func _update_idle_behaviour(delta: float) -> void: func _update_idle_behaviour(delta: float) -> void:
var offset_to_target: Vector2 = target.global_position - global_position var offset_to_target: Vector2 = target.global_position - global_position
var detection_distance: float = aggro_range * (1.5 if _is_pursuing else 1.0) var detection_distance: float = aggro_range * (1.5 if _is_pursuing else 1.0)
@@ -349,14 +349,13 @@ func _update_idle_behaviour(delta: float) -> void:
return return
_move_towards(target.global_position, delta) _move_towards(target.global_position, delta)
else: else:
# Return naturally, without teleporting or healing. Non-jumpers still # Regreso sin teletransporte ni curacion. Es navegacion local: no calcula rutas globales por el nivel.
# refuse ledges; this is local steering, not a global pathfinding system.
_move_towards(spawn_position, delta) _move_towards(spawn_position, delta)
## Navegacion local con deteccion de paredes, bordes y aterrizaje comprometido.
func _move_towards(destination: Vector2, delta: float) -> void: func _move_towards(destination: Vector2, delta: float) -> void:
# Commit to the chosen landing instead of homing onto a moving player in # Mantiene el aterrizaje elegido durante el salto. Un impacto cancela ese objetivo para respetar el retroceso.
# mid-air. A hit clears this goal so it never cancels received knockback.
if _jump_in_progress and not is_on_floor(): if _jump_in_progress and not is_on_floor():
velocity.x = clampf((_jump_target_x - global_position.x) / delta, -move_speed, move_speed) velocity.x = clampf((_jump_target_x - global_position.x) / delta, -move_speed, move_speed)
return return
@@ -375,8 +374,8 @@ func _move_towards(destination: Vector2, delta: float) -> void:
velocity.x = 0.0 velocity.x = 0.0
return return
# Refresh after turning: the previous physics frame's probe points the # Actualiza la sonda tras girar: su resultado anterior miraba hacia el otro lado.
# other way. Look ahead early enough to jump BEFORE touching a step. # Se anticipa al borde para saltar antes de chocar con el escalon.
floor_probe.force_raycast_update() floor_probe.force_raycast_update()
var edge_ahead: bool = not floor_probe.is_colliding() var edge_ahead: bool = not floor_probe.is_colliding()
var look_ahead: Vector2 = Vector2(facing_direction * maxf(32.0, move_speed * 0.25), 0.0) var look_ahead: Vector2 = Vector2(facing_direction * maxf(32.0, move_speed * 0.25), 0.0)
@@ -387,13 +386,14 @@ func _move_towards(destination: Vector2, delta: float) -> void:
if absf(offset.x) <= stopping_distance or edge_ahead: if absf(offset.x) <= stopping_distance or edge_ahead:
velocity.x = 0.0 velocity.x = 0.0
return return
# Use a fresh forward test, not is_on_wall() from the previous direction. # Consulta frontal nueva, no is_on_wall() calculado con la direccion anterior.
if test_move(global_transform, Vector2(facing_direction * 3.0, 0.0)): if test_move(global_transform, Vector2(facing_direction * 3.0, 0.0)):
velocity.x = 0.0 velocity.x = 0.0
return return
velocity.x = facing_direction * minf(move_speed, absf(offset.x) / delta) velocity.x = facing_direction * minf(move_speed, absf(offset.x) / delta)
## Comprueba capacidad, espera y aterrizaje antes de consumir un intento de salto.
func _try_jump(destination: Vector2, wall_ahead: bool, edge_ahead: bool) -> bool: func _try_jump(destination: Vector2, wall_ahead: bool, edge_ahead: bool) -> bool:
if not can_jump or not is_on_floor() or _jump_cooldown_timer > 0.0: if not can_jump or not is_on_floor() or _jump_cooldown_timer > 0.0:
return false return false
@@ -407,7 +407,7 @@ func _try_jump(destination: Vector2, wall_ahead: bool, edge_ahead: bool) -> bool
if not wall_ahead and not edge_ahead and not climb_needed and not wants_hop: if not wall_ahead and not edge_ahead and not climb_needed and not wants_hop:
return false return false
# Failed attempts are throttled too: no terrain scans every physics frame. # Tambien limita los intentos fallidos para no explorar el terreno en cada fotograma.
_jump_cooldown_timer = 0.25 _jump_cooldown_timer = 0.25
var gravity_y: float = get_gravity().y var gravity_y: float = get_gravity().y
if gravity_y <= 0.0 or jump_velocity >= 0.0: if gravity_y <= 0.0 or jump_velocity >= 0.0:
@@ -428,6 +428,7 @@ func _try_jump(destination: Vector2, wall_ahead: bool, edge_ahead: bool) -> bool
return true return true
## Busca un suelo cercano alcanzable, con hueco para el cuerpo y tiempo de vuelo suficiente.
func _find_jump_landing(destination: Vector2, max_rise: float, gravity_y: float, climbing: bool) -> Vector2: func _find_jump_landing(destination: Vector2, max_rise: float, gravity_y: float, climbing: bool) -> Vector2:
var body_shape: RectangleShape2D = body_collision.shape as RectangleShape2D var body_shape: RectangleShape2D = body_collision.shape as RectangleShape2D
var half_size: Vector2 = body_shape.size * 0.5 var half_size: Vector2 = body_shape.size * 0.5
@@ -435,8 +436,8 @@ func _find_jump_landing(destination: Vector2, max_rise: float, gravity_y: float,
var best_landing: Vector2 = Vector2.INF var best_landing: Vector2 = Vector2.INF
var best_score: float = INF var best_score: float = INF
var space: PhysicsDirectSpaceState2D = get_world_2d().direct_space_state var space: PhysicsDirectSpaceState2D = get_world_2d().direct_space_state
# A handful of local candidates covers steps, nearby platforms and small # Explora unos pocos aterrizajes locales: deben caber ambos pies
# gaps. Both feet must fit, and flight time must permit the horizontal move. # y el tiempo de vuelo debe permitir cubrir la distancia horizontal.
for distance: float in [48.0, 80.0, 120.0, 160.0, 200.0, 240.0]: for distance: float in [48.0, 80.0, 120.0, 160.0, 200.0, 240.0]:
var x: float = global_position.x + facing_direction * distance var x: float = global_position.x + facing_direction * distance
if chase_radius > 0.0 and absf(x - spawn_position.x) > chase_radius: if chase_radius > 0.0 and absf(x - spawn_position.x) > chase_radius:
@@ -482,6 +483,7 @@ func _find_jump_landing(destination: Vector2, max_rise: float, gravity_y: float,
return best_landing return best_landing
## Orienta ligeramente el sprite durante el vuelo sin cambiar su colision.
func _update_jump_visual() -> void: func _update_jump_visual() -> void:
if not _jump_in_progress: if not _jump_in_progress:
visual.scale = _visual_scale visual.scale = _visual_scale
@@ -491,14 +493,15 @@ func _update_jump_visual() -> void:
visual.scale = _visual_scale visual.scale = _visual_scale
COMBAT_FX.spawn(get_parent(), global_position + Vector2(0.0, 26.0), &"dust") COMBAT_FX.spawn(get_parent(), global_position + Vector2(0.0, 26.0), &"dust")
else: else:
# A small airborne pose without changing collision sizes or sprite art. # Pose aerea sin modificar las colisiones ni los recursos de imagen.
visual.scale = _visual_scale * Vector2(0.9, 1.08) visual.scale = _visual_scale * Vector2(0.9, 1.08)
# ============================================================================ # ============================================================================
# ATTACK # ATAQUE
# ============================================================================ # ============================================================================
## Comprueba distancia, altura y linea libre antes de permitir un ataque.
func _is_target_in_attack_trigger() -> bool: func _is_target_in_attack_trigger() -> bool:
var offset_to_target: Vector2 = target.global_position - global_position var offset_to_target: Vector2 = target.global_position - global_position
if ( if (
@@ -507,16 +510,16 @@ func _is_target_in_attack_trigger() -> bool:
or absf(offset_to_target.y) > attack_vertical_tolerance or absf(offset_to_target.y) > attack_vertical_tolerance
): ):
return false return false
# A player behind a step should trigger navigation, not attacks through it. # Una pared entre ambos exige navegar, no atacar a traves de ella.
var query := PhysicsRayQueryParameters2D.create( var query := PhysicsRayQueryParameters2D.create(
global_position, target.global_position, collision_mask, [get_rid()] global_position, target.global_position, collision_mask, [get_rid()]
) )
return get_world_2d().direct_space_state.intersect_ray(query).is_empty() return get_world_2d().direct_space_state.intersect_ray(query).is_empty()
## Fija la direccion y entra en la fase de anticipacion.
func _start_attack() -> void: func _start_attack() -> void:
# Lock the direction here. During windup/active frames the player can dodge # Fija la direccion al preparar el golpe; el jugador puede esquivar por detras sin que el area lo persiga.
# behind the enemy without the hitbox snapping around to follow them.
_face_target() _face_target()
attack_direction = facing_direction attack_direction = facing_direction
attack_state = AttackState.WINDUP attack_state = AttackState.WINDUP
@@ -527,6 +530,7 @@ func _start_attack() -> void:
_reset_attack_hitbox_position() _reset_attack_hitbox_position()
## Despacha la fase actual: preparacion, barrido danino o recuperacion.
func _update_attack(delta: float) -> void: func _update_attack(delta: float) -> void:
velocity.x = 0.0 velocity.x = 0.0
@@ -539,6 +543,7 @@ func _update_attack(delta: float) -> void:
_update_attack_recovery(delta) _update_attack_recovery(delta)
## Espera el tiempo de anticipacion antes de activar el barrido.
func _update_attack_windup(delta: float) -> void: func _update_attack_windup(delta: float) -> void:
attack_phase_timer = max(attack_phase_timer - delta, 0.0) attack_phase_timer = max(attack_phase_timer - delta, 0.0)
if attack_phase_timer > 0.0: if attack_phase_timer > 0.0:
@@ -549,11 +554,11 @@ func _update_attack_windup(delta: float) -> void:
_set_attack_hitbox_progress(0.0) _set_attack_hitbox_progress(0.0)
## Avanza el area danina y resuelve sus contactos.
func _update_active_attack(delta: float) -> void: func _update_active_attack(delta: float) -> void:
attack_phase_timer = max(attack_phase_timer - delta, 0.0) attack_phase_timer = max(attack_phase_timer - delta, 0.0)
# Sweep the actual physics hitbox from close to the enemy towards its maximum # Desplaza el area fisica desde cerca del cuerpo hasta su alcance maximo, dando margen para esquivar.
# reach. This gives the player time to jump, back away or move behind it.
var progress: float = 1.0 var progress: float = 1.0
if attack_duration > 0.0: if attack_duration > 0.0:
progress = 1.0 - (attack_phase_timer / attack_duration) progress = 1.0 - (attack_phase_timer / attack_duration)
@@ -567,6 +572,7 @@ func _update_active_attack(delta: float) -> void:
attack_phase_timer = attack_recovery_duration attack_phase_timer = attack_recovery_duration
## Finaliza la recuperacion y devuelve el control a la navegacion.
func _update_attack_recovery(delta: float) -> void: func _update_attack_recovery(delta: float) -> void:
attack_phase_timer = max(attack_phase_timer - delta, 0.0) attack_phase_timer = max(attack_phase_timer - delta, 0.0)
if attack_phase_timer > 0.0: if attack_phase_timer > 0.0:
@@ -577,6 +583,7 @@ func _update_attack_recovery(delta: float) -> void:
_reset_attack_hitbox_position() _reset_attack_hitbox_position()
## Interpola el barrido entre su origen y su alcance, reflejado por la direccion fijada.
func _set_attack_hitbox_progress(progress: float) -> void: func _set_attack_hitbox_progress(progress: float) -> void:
var start_x: float = abs(attack_start_offset.x) var start_x: float = abs(attack_start_offset.x)
var current_x: float = lerpf(start_x, attack_reach, progress) var current_x: float = lerpf(start_x, attack_reach, progress)
@@ -586,6 +593,7 @@ func _set_attack_hitbox_progress(progress: float) -> void:
) )
## Devuelve el area ofensiva a su posicion inicial.
func _reset_attack_hitbox_position() -> void: func _reset_attack_hitbox_position() -> void:
var direction: float = attack_direction var direction: float = attack_direction
if attack_state == AttackState.IDLE: if attack_state == AttackState.IDLE:
@@ -597,6 +605,7 @@ func _reset_attack_hitbox_position() -> void:
) )
## Aplica un solo impacto por objetivo y evita golpear a traves del escenario.
func _update_attack_damage() -> void: func _update_attack_damage() -> void:
for area in attack_hitbox.get_overlapping_areas(): for area in attack_hitbox.get_overlapping_areas():
var damage_target: Node = area.get_parent() var damage_target: Node = area.get_parent()
@@ -607,8 +616,7 @@ func _update_attack_damage() -> void:
if attack_hit_targets.has(target_id): if attack_hit_targets.has(target_id):
continue continue
# A swept hitbox must not reach through solid walls. Use the enemy's # El barrido no atraviesa paredes. El origen del empuje es el cuerpo enemigo, no su area adelantada.
# body as the source: a hitbox past the player could push them backwards.
var query := PhysicsRayQueryParameters2D.create( var query := PhysicsRayQueryParameters2D.create(
global_position, (damage_target as Node2D).global_position, global_position, (damage_target as Node2D).global_position,
collision_mask, [get_rid()] collision_mask, [get_rid()]
@@ -619,6 +627,7 @@ func _update_attack_damage() -> void:
damage_target.take_damage(attack_damage, global_position, attack_knockback_multiplier) damage_target.take_damage(attack_damage, global_position, attack_knockback_multiplier)
## Cancela el ataque y vacia su registro de impactos.
func _interrupt_attack() -> void: func _interrupt_attack() -> void:
if attack_state == AttackState.IDLE: if attack_state == AttackState.IDLE:
return return
@@ -629,13 +638,15 @@ func _interrupt_attack() -> void:
_reset_attack_hitbox_position() _reset_attack_hitbox_position()
## Descuenta los tiempos de ataque, salto, retroceso y aturdimiento.
func _update_timers(delta: float) -> void: func _update_timers(delta: float) -> void:
attack_cooldown_timer = max(attack_cooldown_timer - delta, 0.0) attack_cooldown_timer = max(attack_cooldown_timer - delta, 0.0)
hit_stun_timer = max(hit_stun_timer - delta, 0.0) hit_stun_timer = max(hit_stun_timer - delta, 0.0)
_jump_cooldown_timer = maxf(_jump_cooldown_timer - delta, 0.0) _jump_cooldown_timer = maxf(_jump_cooldown_timer - delta, 0.0)
# Updates floating damage numbers: they drift upward and fade out over time. # Los numeros de dano ascienden y pierden opacidad con el tiempo.
## Actualiza y elimina las entradas visuales de dano.
func _update_damage_texts(delta: float) -> void: func _update_damage_texts(delta: float) -> void:
for i in range(_damage_texts.size() - 1, -1, -1): for i in range(_damage_texts.size() - 1, -1, -1):
var entry: Dictionary = _damage_texts[i] var entry: Dictionary = _damage_texts[i]
@@ -645,9 +656,10 @@ func _update_damage_texts(delta: float) -> void:
_damage_texts.remove_at(i) _damage_texts.remove_at(i)
# ============================================================================ # ============================================================================
# DAMAGE AND RESPAWN # DANO Y REAPARICION
# ============================================================================ # ============================================================================
## Aplica vida, interrupcion, empuje y aturdimiento antes de comprobar muerte.
func take_damage(amount: int, source_position: Vector2) -> void: func take_damage(amount: int, source_position: Vector2) -> void:
if amount <= 0 or is_dead: if amount <= 0 or is_dead:
return return
@@ -666,7 +678,7 @@ func take_damage(amount: int, source_position: Vector2) -> void:
if camera != null and camera.has_method("impact"): if camera != null and camera.has_method("impact"):
camera.call("impact", 1.0, 0.12) camera.call("impact", 1.0, 0.12)
# Floating damage number (debug only). # Numero flotante de dano, exclusivamente visual.
if show_debug_enemy_info: if show_debug_enemy_info:
_damage_texts.append({ _damage_texts.append({
"text": str(amount), "text": str(amount),
@@ -678,12 +690,11 @@ func take_damage(amount: int, source_position: Vector2) -> void:
_die() _die()
return return
# Light enemies are interruptible. This makes a well-timed player attack a # Los golpes interrumpen al enemigo y permiten usarlos como defensa a corta distancia.
# defensive option and avoids mandatory damage trades at close range.
_interrupt_attack() _interrupt_attack()
# Knockback: stronger hits push harder, tougher enemies (more max health) # Los golpes mas fuertes empujan mas; la vida maxima amortigua ese retroceso.
# resist the push. Direction is away from the damage source. # La direccion siempre se aleja del origen del dano.
var knockback_dir: float = signf(global_position.x - source_position.x) var knockback_dir: float = signf(global_position.x - source_position.x)
if knockback_dir == 0.0: if knockback_dir == 0.0:
knockback_dir = 1.0 knockback_dir = 1.0
@@ -694,8 +705,7 @@ func take_damage(amount: int, source_position: Vector2) -> void:
knockback_timer = knockback_duration knockback_timer = knockback_duration
# Stun: normal hits use the brief hit stun; very strong hits (e.g. a fully # Un impacto normal causa una pausa breve; superar el umbral provoca aturdimiento prolongado.
# charged special attack) trigger a longer stun.
if amount >= stun_damage_threshold: if amount >= stun_damage_threshold:
hit_stun_timer = max(hit_stun_timer, strong_hit_stun_duration) hit_stun_timer = max(hit_stun_timer, strong_hit_stun_duration)
else: else:
@@ -707,6 +717,7 @@ func take_damage(amount: int, source_position: Vector2) -> void:
_update_facing() _update_facing()
## Emite la muerte una vez y delega la recompensa segun el modo del nivel.
func _die() -> void: func _die() -> void:
if is_dead: if is_dead:
return return
@@ -715,11 +726,10 @@ func _die() -> void:
_death_elapsed = 0.0 _death_elapsed = 0.0
velocity = Vector2(_last_hit_direction * 150.0, -210.0) velocity = Vector2(_last_hit_direction * 150.0, -210.0)
COMBAT_FX.spawn(get_parent(), global_position, &"death", _last_hit_direction) COMBAT_FX.spawn(get_parent(), global_position, &"death", _last_hit_direction)
# Logical death happens now, exactly once. Animation must not delay rewards. # La muerte logica y su senal ocurren una sola vez; la animacion no retrasa las recompensas.
died.emit() died.emit()
# Test encounters always drop their assigned item, including the two items # Los encuentros de laboratorio entregan su objeto asignado; el resto conserva su tabla aleatoria.
# absent from the normal Walker table. Other levels keep their random loot.
var drops: Array[PickupData] = [] var drops: Array[PickupData] = []
if not drops_handled_by_level: if not drops_handled_by_level:
if guaranteed_drop != null: if guaranteed_drop != null:
@@ -732,13 +742,14 @@ func _die() -> void:
parent = get_tree().root parent = get_tree().root
DROP_MANAGER.spawn_drops(drops, parent, global_position) DROP_MANAGER.spawn_drops(drops, parent, global_position)
# Disable combat immediately; keep the body colliding with the WORLD while it # Desactiva el combate inmediatamente pero conserva la colision con World durante la caida
# falls. Disabling the body now would let the death pose fall through streets. # para evitar que el cuerpo atraviese el suelo en la animacion de muerte.
hurtbox_collision.set_deferred("disabled", true) hurtbox_collision.set_deferred("disabled", true)
attack_collision.set_deferred("disabled", true) attack_collision.set_deferred("disabled", true)
queue_redraw() queue_redraw()
## Anima el cuerpo derrotado conservando el suelo y sin permitir nuevos ataques.
func _update_death_animation(delta: float) -> void: func _update_death_animation(delta: float) -> void:
_death_elapsed += delta _death_elapsed += delta
_update_damage_texts(delta) _update_damage_texts(delta)
@@ -762,12 +773,13 @@ func _update_death_animation(delta: float) -> void:
velocity = Vector2.ZERO velocity = Vector2.ZERO
body_collision.set_deferred("disabled", true) body_collision.set_deferred("disabled", true)
if respawn_delay <= 0.0: if respawn_delay <= 0.0:
# Keep the dead node for the lab's KO polling and Level02's total count. # Conserva el nodo muerto: el laboratorio lo consulta y el nivel 02 lo incluye en el total de enemigos.
set_physics_process(false) set_physics_process(false)
elif _death_elapsed >= maxf(respawn_delay, duration): elif _death_elapsed >= maxf(respawn_delay, duration):
_respawn() _respawn()
## Restaura el estado inicial y decide si debe estar activo al reaparecer.
func _respawn() -> void: func _respawn() -> void:
set_physics_process(true) set_physics_process(true)
_death_elapsed = 0.0 _death_elapsed = 0.0
@@ -801,22 +813,22 @@ func _respawn() -> void:
visible = true visible = true
is_dead = false is_dead = false
# If the spawn point is currently inside the camera, wake immediately. # Si reaparece dentro de la camara se activa inmediatamente; de lo contrario espera al notificador.
# Otherwise the notifier will wake the enemy when the camera reaches it.
is_awake = visibility_notifier.is_on_screen() is_awake = visibility_notifier.is_on_screen()
queue_redraw() queue_redraw()
# ============================================================================ # ============================================================================
# TEMPORARY VISUAL + DEBUG HITBOXES # PRESENTACION Y DEPURACION DE COLISIONES
# ============================================================================ # ============================================================================
## Dibuja anticipacion ofensiva y elementos opcionales de depuracion.
func _draw() -> void: func _draw() -> void:
if is_dead: if is_dead:
if show_debug_enemy_info: if show_debug_enemy_info:
_draw_damage_texts() _draw_damage_texts()
return return
# Retain a fallback body if an imported sprite is missing. # Dibujo de reserva si no se ha podido importar la textura del enemigo.
if visual.texture == null: if visual.texture == null:
_draw_rectangle_collision( _draw_rectangle_collision(
body_collision, body_collision,
@@ -824,27 +836,27 @@ func _draw() -> void:
Color(0.85, 0.85, 0.90, 1.0) Color(0.85, 0.85, 0.90, 1.0)
) )
# Enemy health bar and floating damage numbers (debug overlay). # Barra de vida y numeros flotantes de depuracion.
if show_debug_enemy_info: if show_debug_enemy_info:
_draw_enemy_health_bar() _draw_enemy_health_bar()
_draw_damage_texts() _draw_damage_texts()
# Orange windup is important gameplay feedback, not a debug hitbox. # La anticipacion naranja comunica un ataque real, no es una colision de depuracion.
# Keep it visible on Android even when red collision overlays are disabled. # Permanece visible tambien en Android sin las superposiciones rojas.
if attack_state == AttackState.WINDUP: if attack_state == AttackState.WINDUP:
_draw_attack_telegraph() _draw_attack_telegraph()
if not show_debug_hitboxes: if not show_debug_hitboxes:
return return
# Hurtbox: where punches / ground pound are allowed to damage the enemy. # Zona vulnerable a punetazos y golpes aereos.
_draw_rectangle_collision( _draw_rectangle_collision(
hurtbox_collision, hurtbox_collision,
Color(1.0, 0.05, 0.05, 0.12), Color(1.0, 0.05, 0.05, 0.12),
Color(1.0, 0.05, 0.05, 0.55) Color(1.0, 0.05, 0.05, 0.55)
) )
# Active attack: draw the real moving physics hitbox in strong red. # Area danina real del barrido, resaltada en rojo.
if attack_state == AttackState.ACTIVE: if attack_state == AttackState.ACTIVE:
_draw_rectangle_collision( _draw_rectangle_collision(
attack_collision, attack_collision,
@@ -854,6 +866,7 @@ func _draw() -> void:
) )
## Anticipa visualmente el recorrido peligroso del siguiente barrido.
func _draw_attack_telegraph() -> void: func _draw_attack_telegraph() -> void:
var rectangle: RectangleShape2D = attack_collision.shape as RectangleShape2D var rectangle: RectangleShape2D = attack_collision.shape as RectangleShape2D
if rectangle == null: if rectangle == null:
@@ -871,6 +884,7 @@ func _draw_attack_telegraph() -> void:
draw_rect(rect, Color(1.0, 0.55, 0.05, 0.85), false, 2.0) draw_rect(rect, Color(1.0, 0.55, 0.05, 0.85), false, 2.0)
## Dibuja una forma rectangular en las coordenadas locales del enemigo.
func _draw_rectangle_collision( func _draw_rectangle_collision(
collision: CollisionShape2D, collision: CollisionShape2D,
fill_color: Color, fill_color: Color,
@@ -886,25 +900,27 @@ func _draw_rectangle_collision(
draw_rect(rect, fill_color, true) draw_rect(rect, fill_color, true)
draw_rect(rect, outline_color, false, 2.0) draw_rect(rect, outline_color, false, 2.0)
# Draws a small horizontal health bar just above the enemy's head. # Barra horizontal de vida situada sobre la cabeza.
## Representa la proporcion de vida restante sobre el enemigo.
func _draw_enemy_health_bar() -> void: func _draw_enemy_health_bar() -> void:
var bar_width: float = 40.0 var bar_width: float = 40.0
var bar_height: float = 5.0 var bar_height: float = 5.0
var bar_pos: Vector2 = Vector2(-bar_width * 0.5, -48.0) var bar_pos: Vector2 = Vector2(-bar_width * 0.5, -48.0)
# Background. # Fondo de la barra.
draw_rect(Rect2(bar_pos, Vector2(bar_width, bar_height)), Color(0.2, 0.2, 0.2, 0.8), true) draw_rect(Rect2(bar_pos, Vector2(bar_width, bar_height)), Color(0.2, 0.2, 0.2, 0.8), true)
# Fill. # Relleno proporcional a la vida restante.
var fill_ratio: float = float(current_health) / float(max_health) if max_health > 0 else 0.0 var fill_ratio: float = float(current_health) / float(max_health) if max_health > 0 else 0.0
draw_rect( draw_rect(
Rect2(bar_pos, Vector2(bar_width * fill_ratio, bar_height)), Rect2(bar_pos, Vector2(bar_width * fill_ratio, bar_height)),
Color(0.85, 0.2, 0.2, 0.95), Color(0.85, 0.2, 0.2, 0.95),
true true
) )
# Border. # Borde de la barra.
draw_rect(Rect2(bar_pos, Vector2(bar_width, bar_height)), Color(1, 1, 1, 0.6), false, 1.0) draw_rect(Rect2(bar_pos, Vector2(bar_width, bar_height)), Color(1, 1, 1, 0.6), false, 1.0)
# Draws floating damage numbers that drift upward and fade out. # Numeros de dano que ascienden y se desvanecen.
## Muestra numeros de dano con opacidad dependiente de su tiempo restante.
func _draw_damage_texts() -> void: func _draw_damage_texts() -> void:
var font: Font = ThemeDB.get_default_theme().get_font("font", "Label") var font: Font = ThemeDB.get_default_theme().get_font("font", "Label")
if font == null: if font == null:
+140
View File
@@ -0,0 +1,140 @@
[gd_scene load_steps=19 format=3]
[ext_resource type="Script" path="res://levels/level_root.gd" id="level"]
[ext_resource type="PackedScene" path="res://player/player.tscn" id="player"]
[ext_resource type="PackedScene" path="res://ui/mobile_controls/mobile_controls.tscn" id="mobile"]
[ext_resource type="PackedScene" path="res://world/backgrounds/city_background.tscn" id="background"]
[ext_resource type="PackedScene" path="res://world/terrain/ground.tscn" id="ground"]
[ext_resource type="PackedScene" path="res://world/terrain/wall.tscn" id="wall"]
[ext_resource type="PackedScene" path="res://world/signs/sign_post.tscn" id="sign"]
[ext_resource type="PackedScene" path="res://world/terrain/platform.tscn" id="platform"]
[ext_resource type="PackedScene" path="res://world/props/barrel.tscn" id="barrel"]
[ext_resource type="PackedScene" path="res://world/props/crate.tscn" id="crate"]
[ext_resource type="PackedScene" path="res://world/props/streetlamp.tscn" id="lamp"]
[ext_resource type="PackedScene" path="res://world/props/bench.tscn" id="bench"]
[ext_resource type="PackedScene" path="res://world/props/traffic_cone.tscn" id="cone"]
[ext_resource type="PackedScene" path="res://world/props/trash_bin.tscn" id="bin"]
[ext_resource type="PackedScene" path="res://world/props/rock.tscn" id="rock"]
[ext_resource type="PackedScene" path="res://world/props/facade_01.tscn" id="facade"]
[ext_resource type="PackedScene" path="res://world/signs/text_label.tscn" id="label"]
[ext_resource type="PackedScene" path="res://pickups/variants/coffee.tscn" id="coffee"]
[node name="SceneryCatalog" type="Node2D"]
texture_filter = 1
script = ExtResource("level")
camera_bounds = Rect2(0, 0, 3800, 1280)
[node name="CityBackground" parent="." instance=ExtResource("background")]
[node name="World" type="Node2D" parent="."]
[node name="Ground" parent="World" instance=ExtResource("ground")]
position = Vector2(1900, 1030)
dimensions = Vector2(3800, 260)
[node name="LeftBoundary" parent="World" instance=ExtResource("wall")]
position = Vector2(0, 500)
dimensions = Vector2(48, 1000)
[node name="RightBoundary" parent="World" instance=ExtResource("wall")]
position = Vector2(3800, 500)
dimensions = Vector2(48, 1000)
[node name="Scenery" type="Node2D" parent="."]
[node name="Signs" type="Node2D" parent="."]
[node name="Welcome" parent="Signs" instance=ExtResource("sign")]
position = Vector2(330, 900)
text = "CATALOGO JUGABLE\nA/D: mover | W: saltar\nAvanza a la derecha"
[node name="Player" parent="." instance=ExtResource("player")]
position = Vector2(160, 874)
[node name="Enemies" type="Node2D" parent="."]
[node name="Items" type="Node2D" parent="."]
[node name="Triggers" type="Node2D" parent="."]
[node name="MobileControls" parent="." instance=ExtResource("mobile")]
[node name="SolidBarrel" parent="Scenery" instance=ExtResource("barrel")]
position = Vector2(670, 900)
collision_enabled = true
preview_collision = true
[node name="BackgroundBarrel" parent="Scenery" instance=ExtResource("barrel")]
position = Vector2(1050, 900)
collision_enabled = false
draw_layer = -2
[node name="ForegroundBarrel" parent="Scenery" instance=ExtResource("barrel")]
position = Vector2(1420, 900)
collision_enabled = false
draw_layer = 10
[node name="Crate" parent="Scenery" instance=ExtResource("crate")]
position = Vector2(1770, 900)
[node name="Bench" parent="Scenery" instance=ExtResource("bench")]
position = Vector2(2030, 900)
[node name="Lamp" parent="Scenery" instance=ExtResource("lamp")]
position = Vector2(2200, 900)
[node name="Cone" parent="Scenery" instance=ExtResource("cone")]
position = Vector2(2320, 900)
[node name="TrashBin" parent="Scenery" instance=ExtResource("bin")]
position = Vector2(2470, 900)
[node name="Rock" parent="Scenery" instance=ExtResource("rock")]
position = Vector2(2630, 900)
[node name="Facade" parent="Scenery" instance=ExtResource("facade")]
position = Vector2(2100, 900)
[node name="FirstPlatform" parent="World" instance=ExtResource("platform")]
position = Vector2(2910, 770)
dimensions = Vector2(240, 20)
[node name="SecondPlatform" parent="World" instance=ExtResource("platform")]
position = Vector2(3180, 650)
dimensions = Vector2(240, 20)
[node name="Coffee" parent="Items" instance=ExtResource("coffee")]
position = Vector2(3180, 620)
[node name="SolidLabel" parent="Signs" instance=ExtResource("label")]
offset_left = 560.0
offset_top = 690.0
offset_right = 800.0
offset_bottom = 750.0
text = "SOLIDO\nHay que saltarlo"
[node name="BackLabel" parent="Signs" instance=ExtResource("label")]
offset_left = 930.0
offset_top = 690.0
offset_right = 1190.0
offset_bottom = 750.0
text = "SIN COLISION\nPasas por delante"
[node name="FrontLabel" parent="Signs" instance=ExtResource("label")]
offset_left = 1300.0
offset_top = 690.0
offset_right = 1560.0
offset_bottom = 750.0
text = "SIN COLISION\nPasas por detras"
[node name="PlatformLabel" parent="Signs" instance=ExtResource("label")]
offset_left = 2800.0
offset_top = 490.0
offset_right = 3300.0
offset_bottom = 550.0
text = "PLATAFORMAS ONE WAY\nSe atraviesan desde abajo"
[node name="EndSign" parent="Signs" instance=ExtResource("sign")]
position = Vector2(3520, 900)
text = "COPIA ESTAS PIEZAS\na tu propio nivel\nCtrl+C / Ctrl+V"
+32 -49
View File
@@ -1,14 +1,13 @@
extends Node2D @tool
extends LevelRoot
## Android test course: 17 stations / 17 different guaranteed items. ## Laboratorio Android: 17 estaciones y 17 objetos garantizados distintos.
## Encounters are configured in the scene, not spawned by code. ## Los encuentros se colocan en la escena. Este nivel observa is_dead
## This laboratory intentionally owns fixed drops: each death is observed from ## y gestiona sus propias recompensas aunque no reciba alguna senal died.
## the actual is_dead state, even when a died signal is missed.
signal level_completed signal level_completed
const TEST_ITEM_COUNT: int = 17 const TEST_ITEM_COUNT: int = 17
const LEVEL_WIDTH: int = 8500
const FINISH_RESTART_SECONDS: float = 8.0 const FINISH_RESTART_SECONDS: float = 8.0
const LAB_BUILD: String = "LAB DROPS v4" const LAB_BUILD: String = "LAB DROPS v4"
const CONTROL_ITEM_ID: StringName = &"lab_control" const CONTROL_ITEM_ID: StringName = &"lab_control"
@@ -19,33 +18,32 @@ const PICKUP_SCENE: PackedScene = preload("res://pickups/pickup.tscn")
@onready var status_label: Label = $TestHUD/Overlay/Status @onready var status_label: Label = $TestHUD/Overlay/Status
@onready var finish_message: Label = $TestHUD/Overlay/FinishMessage @onready var finish_message: Label = $TestHUD/Overlay/FinishMessage
var collected_items: Dictionary = {} # PickupData.id -> true; count each only once var collected_items: Dictionary = {} # PickupData.id -> true; cuenta cada objeto una sola vez.
var defeated_enemies: int = 0 var defeated_enemies: int = 0
var death_signals: int = 0 var death_signals: int = 0
var spawned_drops: int = 0 var spawned_drops: int = 0
var _processed_deaths: Dictionary = {} # enemy instance id -> true var _processed_deaths: Dictionary = {} # Identificador de instancia enemiga -> muerte ya procesada.
var showing_victory: bool = false var showing_victory: bool = false
var victory_timer: float = 0.0 var victory_timer: float = 0.0
## Configura las estaciones sin alterar las recompensas del resto de niveles.
func _ready() -> void: func _ready() -> void:
# These two markers distinguish an actually loaded script from an old APK. super._ready()
if Engine.is_editor_hint():
return
# Estos marcadores distinguen la version cargada de una instalacion antigua del APK.
status_label.text = "%s: script iniciado" % LAB_BUILD status_label.text = "%s: script iniciado" % LAB_BUILD
print("%s: Level01 script iniciado" % LAB_BUILD) print("%s: Level01 script iniciado" % LAB_BUILD)
finish_message.visible = false finish_message.visible = false
# Player Camera2D sets its own provisional limit (4000) in _ready.
# Override it here, after child _ready, for the long Android route.
var camera: Camera2D = player.get_node("Camera2D") as Camera2D
camera.limit_right = LEVEL_WIDTH
$FinishZone.body_entered.connect(_on_finish_entered) $FinishZone.body_entered.connect(_on_finish_entered)
$DeathZone.body_entered.connect(_on_death_entered) $DeathZone.body_entered.connect(_on_death_entered)
player.connect(&"pickup_collected", _on_pickup_collected) player.connect(&"pickup_collected", _on_pickup_collected)
for enemy in test_enemies.get_children(): for enemy in test_enemies.get_children():
# Keep item-testing stations isolated despite the stronger game profiles. # Mantiene aisladas las estaciones aunque las variantes normales persigan a mayor distancia.
enemy.set("chase_radius", 135.0) enemy.set("chase_radius", 135.0)
# The laboratory, not Walker, owns the fixed drop. Only this level sets # Solo el laboratorio asume la recompensa fija; los enemigos normales conservan sus propios drops.
# the flag: normal enemies still generate their usual random drops.
enemy.set("drops_handled_by_level", true) enemy.set("drops_handled_by_level", true)
if enemy.get("guaranteed_drop") == null: if enemy.get("guaranteed_drop") == null:
push_error("%s has no guaranteed_drop assigned." % enemy.name) push_error("%s has no guaranteed_drop assigned." % enemy.name)
@@ -56,9 +54,12 @@ func _ready() -> void:
_update_status() _update_status()
## Observa muertes y actualiza el diagnostico; tras completar, cuenta hasta reiniciar.
func _process(delta: float) -> void: func _process(delta: float) -> void:
# Do not depend on the died signal to count KOs or create the object. super._process(delta)
# A transition to is_dead can only be processed once per enemy. if Engine.is_editor_hint():
return
# El recuento y las recompensas no dependen de died. Cada muerte se procesa una sola vez.
_process_station_deaths() _process_station_deaths()
if showing_victory: if showing_victory:
victory_timer += delta victory_timer += delta
@@ -69,9 +70,9 @@ func _process(delta: float) -> void:
_update_status() _update_status()
## Muestra progreso, estado de drops y siguiente recompensa.
func _update_status() -> void: func _update_status() -> void:
# Each station has one enemy and an assigned pickup. Look ahead to the first # Busca la primera estacion viva por delante para anticipar su recompensa en el HUD.
# living enemy so the player knows what to expect without opening a menu.
var next_item: String = "FIN DEL RECORRIDO" var next_item: String = "FIN DEL RECORRIDO"
for enemy in test_enemies.get_children(): for enemy in test_enemies.get_children():
if bool(enemy.get("is_dead")): if bool(enemy.get("is_dead")):
@@ -84,8 +85,7 @@ func _update_status() -> void:
next_item = data.display_name next_item = data.display_name
break break
# S is the number of died signals received. KOs come from is_dead, # Compara senales con muertes reales: una diferencia permite diagnosticar senales perdidas.
# not signals. A difference between them pinpoints a signal problem.
var loose_drops: int = get_tree().get_nodes_in_group("pickup").size() var loose_drops: int = get_tree().get_nodes_in_group("pickup").size()
status_label.text = "%s | %02d/%02d objetos\nKOs: %02d | Senales: %02d | Creados: %02d | Suelo: %02d\nSIGUIENTE: %s" % [ status_label.text = "%s | %02d/%02d objetos\nKOs: %02d | Senales: %02d | Creados: %02d | Suelo: %02d\nSIGUIENTE: %s" % [
LAB_BUILD, collected_items.size(), TEST_ITEM_COUNT, LAB_BUILD, collected_items.size(), TEST_ITEM_COUNT,
@@ -93,6 +93,7 @@ func _update_status() -> void:
] ]
## Convierte cada nueva muerte en un unico objeto garantizado.
func _process_station_deaths() -> void: func _process_station_deaths() -> void:
for enemy in test_enemies.get_children(): for enemy in test_enemies.get_children():
if not bool(enemy.get("is_dead")): if not bool(enemy.get("is_dead")):
@@ -108,8 +109,8 @@ func _process_station_deaths() -> void:
push_error("%s: %s ha muerto sin objeto asignado" % [LAB_BUILD, enemy.name]) push_error("%s: %s ha muerto sin objeto asignado" % [LAB_BUILD, enemy.name])
continue continue
# Adding an Area2D during a physics step is unsafe. Set position and # Prepara posicion y datos antes de diferir la entrada al arbol.
# data before adding it, then defer its entry into the scene tree. # No se debe anadir un Area2D durante la resolucion de contactos fisicos.
var pickup: Pickup = PICKUP_SCENE.instantiate() as Pickup var pickup: Pickup = PICKUP_SCENE.instantiate() as Pickup
pickup.pickup_data = data pickup.pickup_data = data
pickup.collection_delay_seconds = Pickup.DROP_COLLECTION_DELAY_SECONDS pickup.collection_delay_seconds = Pickup.DROP_COLLECTION_DELAY_SECONDS
@@ -119,22 +120,23 @@ func _process_station_deaths() -> void:
print("%s: KO %s -> %s" % [LAB_BUILD, enemy.name, data.display_name]) print("%s: KO %s -> %s" % [LAB_BUILD, enemy.name, data.display_name])
## Cuenta senales para compararlas con las muertes observadas.
func _on_station_enemy_died() -> void: func _on_station_enemy_died() -> void:
# Diagnostic counter only; the actual reward is managed above. # Contador diagnostico; la recompensa se procesa por separado al observar is_dead.
death_signals += 1 death_signals += 1
## Cuenta identificadores distintos de recompensas realmente aplicadas.
func _on_pickup_collected(data: PickupData) -> void: func _on_pickup_collected(data: PickupData) -> void:
# The extra pickup at the start checks rendering and collection independently # El objeto inicial verifica imagen y recogida sin matar enemigos; no cuenta entre las 17 recompensas.
# of enemy deaths. It is not one of the 17 rewards.
if data.id == CONTROL_ITEM_ID: if data.id == CONTROL_ITEM_ID:
return return
# A heal at full HP or a charge item with a full meter isn't consumed and # Una curacion con vida llena o carga ya completa no consume el objeto ni aumenta el recuento.
# doesn't count. The object remains on the floor for later collection.
collected_items[data.id] = true collected_items[data.id] = true
_update_status() _update_status()
## Completa el laboratorio al entrar el jugador en la meta.
func _on_finish_entered(body: Node2D) -> void: func _on_finish_entered(body: Node2D) -> void:
if body != player or showing_victory: if body != player or showing_victory:
return return
@@ -146,26 +148,7 @@ func _on_finish_entered(body: Node2D) -> void:
finish_message.visible = true finish_message.visible = true
## Aplica el comportamiento original del area de caida del laboratorio.
func _on_death_entered(body: Node2D) -> void: func _on_death_entered(body: Node2D) -> void:
if body == player and body.has_method("take_damage"): if body == player and body.has_method("take_damage"):
body.take_damage(9999, body.global_position) body.take_damage(9999, body.global_position)
func _draw() -> void:
# Temporary coloured geometry; collision shapes are the single source of
# truth for position and dimensions, so the visuals cannot desynchronise.
for child in $World.get_children():
if not child is CollisionShape2D:
continue
var collision: CollisionShape2D = child as CollisionShape2D
var rectangle: RectangleShape2D = collision.shape as RectangleShape2D
if rectangle == null:
continue
var color: Color = Color(0.32, 0.57, 0.79)
if collision.name == "Floor":
color = Color(0.20, 0.40, 0.25)
elif collision.name.begins_with("High"):
color = Color(0.68, 0.39, 0.76)
var rect: Rect2 = Rect2(collision.position - rectangle.size / 2.0, rectangle.size)
draw_rect(rect, color, true)
draw_rect(rect, Color(0.93, 0.94, 1.0, 0.6), false, 2.0)
+60 -29
View File
@@ -1,42 +1,63 @@
[gd_scene load_steps=33 format=3] [gd_scene load_steps=32 format=3]
[ext_resource type="Script" path="res://ui/editor_ui_visibility.gd" id="editor_ui_visibility"]
[ext_resource type="PackedScene" path="res://world/terrain/solid_block.tscn" id="kit_solid_block"]
[ext_resource type="PackedScene" path="res://player/player.tscn" id="1_player"] [ext_resource type="PackedScene" path="res://player/player.tscn" id="1_player"]
[ext_resource type="PackedScene" path="res://ui/mobile_controls/mobile_controls.tscn" id="2_mobile"] [ext_resource type="PackedScene" path="res://ui/mobile_controls/mobile_controls.tscn" id="2_mobile"]
[ext_resource type="Script" path="res://levels/level_01.gd" id="3_level"] [ext_resource type="Script" path="res://levels/level_01.gd" id="3_level"]
[ext_resource type="PackedScene" path="res://pickups/pickup.tscn" id="4_pickup"] [ext_resource type="PackedScene" path="res://pickups/pickup.tscn" id="4_pickup"]
[ext_resource type="Resource" path="res://pickups/data/lab_control.tres" id="lab_control"] [ext_resource type="Resource" path="res://pickups/data/lab_control.tres" id="lab_control"]
[ext_resource type="PackedScene" path="res://enemies/variants/roadie.tscn" id="v0"] [ext_resource type="PackedScene" path="res://enemies/variants/roadie.tscn" id="v0"]
[ext_resource type="PackedScene" path="res://enemies/variants/pogo_fan.tscn" id="v1"] [ext_resource type="PackedScene" path="res://enemies/variants/pogo_fan.tscn" id="v1"]
[ext_resource type="PackedScene" path="res://enemies/variants/feedback_tech.tscn" id="v2"] [ext_resource type="PackedScene" path="res://enemies/variants/feedback_tech.tscn" id="v2"]
[ext_resource type="PackedScene" path="res://enemies/variants/backstage_guard.tscn" id="v3"] [ext_resource type="PackedScene" path="res://enemies/variants/backstage_guard.tscn" id="v3"]
[ext_resource type="PackedScene" path="res://enemies/variants/rival_guitarist.tscn" id="v4"] [ext_resource type="PackedScene" path="res://enemies/variants/rival_guitarist.tscn" id="v4"]
[ext_resource type="Resource" path="res://pickups/data/pua_apocalipsis.tres" id="item_0"] [ext_resource type="Resource" path="res://pickups/data/pua_apocalipsis.tres" id="item_0"]
[ext_resource type="Resource" path="res://pickups/data/beer.tres" id="item_1"] [ext_resource type="Resource" path="res://pickups/data/beer.tres" id="item_1"]
[ext_resource type="Resource" path="res://pickups/data/coffee.tres" id="item_2"] [ext_resource type="Resource" path="res://pickups/data/coffee.tres" id="item_2"]
[ext_resource type="Resource" path="res://pickups/data/casete_demo.tres" id="item_3"] [ext_resource type="Resource" path="res://pickups/data/casete_demo.tres" id="item_3"]
[ext_resource type="Resource" path="res://pickups/data/bocata_roadie.tres" id="item_4"] [ext_resource type="Resource" path="res://pickups/data/bocata_roadie.tres" id="item_4"]
[ext_resource type="Resource" path="res://pickups/data/lata_feedback.tres" id="item_5"] [ext_resource type="Resource" path="res://pickups/data/lata_feedback.tres" id="item_5"]
[ext_resource type="Resource" path="res://pickups/data/pedal_distorsion.tres" id="item_6"] [ext_resource type="Resource" path="res://pickups/data/pedal_distorsion.tres" id="item_6"]
[ext_resource type="Resource" path="res://pickups/data/setlist_fin.tres" id="item_7"] [ext_resource type="Resource" path="res://pickups/data/setlist_fin.tres" id="item_7"]
[ext_resource type="Resource" path="res://pickups/data/pizza_post_bolo.tres" id="item_8"] [ext_resource type="Resource" path="res://pickups/data/pizza_post_bolo.tres" id="item_8"]
[ext_resource type="Resource" path="res://pickups/data/cuerda_titanio.tres" id="item_9"] [ext_resource type="Resource" path="res://pickups/data/cuerda_titanio.tres" id="item_9"]
[ext_resource type="Resource" path="res://pickups/data/cinta_americana.tres" id="item_10"] [ext_resource type="Resource" path="res://pickups/data/cinta_americana.tres" id="item_10"]
[ext_resource type="Resource" path="res://pickups/data/tapones_tecnico.tres" id="item_11"] [ext_resource type="Resource" path="res://pickups/data/tapones_tecnico.tres" id="item_11"]
[ext_resource type="Resource" path="res://pickups/data/tupper_bateria.tres" id="item_12"] [ext_resource type="Resource" path="res://pickups/data/tupper_bateria.tres" id="item_12"]
[ext_resource type="Resource" path="res://pickups/data/botas_doble_bombo.tres" id="item_13"] [ext_resource type="Resource" path="res://pickups/data/botas_doble_bombo.tres" id="item_13"]
[ext_resource type="Resource" path="res://pickups/data/muelles_stage.tres" id="item_14"] [ext_resource type="Resource" path="res://pickups/data/muelles_stage.tres" id="item_14"]
[ext_resource type="Resource" path="res://pickups/data/baqueta_sismica.tres" id="item_15"] [ext_resource type="Resource" path="res://pickups/data/baqueta_sismica.tres" id="item_15"]
[ext_resource type="Resource" path="res://pickups/data/amplificador_11.tres" id="item_16"] [ext_resource type="Resource" path="res://pickups/data/amplificador_11.tres" id="item_16"]
[sub_resource type="RectangleShape2D" id="FloorShape"]
size = Vector2(8500, 40)
[sub_resource type="RectangleShape2D" id="StepShape"]
size = Vector2(240, 20)
[sub_resource type="RectangleShape2D" id="HighShape"]
size = Vector2(180, 16)
[sub_resource type="RectangleShape2D" id="FinishShape"] [sub_resource type="RectangleShape2D" id="FinishShape"]
size = Vector2(70, 200) size = Vector2(70, 200)
@@ -45,42 +66,49 @@ size = Vector2(9000, 170)
[node name="Level01" type="Node2D"] [node name="Level01" type="Node2D"]
script = ExtResource("3_level") script = ExtResource("3_level")
camera_bounds = Rect2(0, 0, 8500, 2500)
[node name="World" type="StaticBody2D" parent="."] [node name="World" type="Node2D" parent="."]
collision_layer = 1
collision_mask = 0
[node name="Floor" type="CollisionShape2D" parent="World"] [node name="Floor" parent="World" instance=ExtResource("kit_solid_block")]
position = Vector2(4250, 620) position = Vector2(4250, 620)
shape = SubResource("FloorShape") dimensions = Vector2(8500, 40)
fill_color = Color(0.20, 0.40, 0.25, 1)
[node name="Step1" type="CollisionShape2D" parent="World"] [node name="Step1" parent="World" instance=ExtResource("kit_solid_block")]
position = Vector2(1530, 455) position = Vector2(1530, 455)
shape = SubResource("StepShape") dimensions = Vector2(240, 20)
fill_color = Color(0.32, 0.57, 0.79, 1)
[node name="High1" type="CollisionShape2D" parent="World"] [node name="High1" parent="World" instance=ExtResource("kit_solid_block")]
position = Vector2(1690, 291) position = Vector2(1690, 291)
shape = SubResource("HighShape") dimensions = Vector2(180, 16)
fill_color = Color(0.68, 0.39, 0.76, 1)
[node name="Step2" type="CollisionShape2D" parent="World"] [node name="Step2" parent="World" instance=ExtResource("kit_solid_block")]
position = Vector2(3370, 485) position = Vector2(3370, 485)
shape = SubResource("StepShape") dimensions = Vector2(240, 20)
fill_color = Color(0.32, 0.57, 0.79, 1)
[node name="High2" type="CollisionShape2D" parent="World"] [node name="High2" parent="World" instance=ExtResource("kit_solid_block")]
position = Vector2(3520, 338) position = Vector2(3520, 338)
shape = SubResource("HighShape") dimensions = Vector2(180, 16)
fill_color = Color(0.68, 0.39, 0.76, 1)
[node name="Step3" type="CollisionShape2D" parent="World"] [node name="Step3" parent="World" instance=ExtResource("kit_solid_block")]
position = Vector2(5600, 455) position = Vector2(5600, 455)
shape = SubResource("StepShape") dimensions = Vector2(240, 20)
fill_color = Color(0.32, 0.57, 0.79, 1)
[node name="High3" type="CollisionShape2D" parent="World"] [node name="High3" parent="World" instance=ExtResource("kit_solid_block")]
position = Vector2(5750, 291) position = Vector2(5750, 291)
shape = SubResource("HighShape") dimensions = Vector2(180, 16)
fill_color = Color(0.68, 0.39, 0.76, 1)
[node name="Step4" type="CollisionShape2D" parent="World"] [node name="Step4" parent="World" instance=ExtResource("kit_solid_block")]
position = Vector2(6890, 485) position = Vector2(6890, 485)
shape = SubResource("StepShape") dimensions = Vector2(240, 20)
fill_color = Color(0.32, 0.57, 0.79, 1)
[node name="Player" parent="." instance=ExtResource("1_player")] [node name="Player" parent="." instance=ExtResource("1_player")]
position = Vector2(140, 557) position = Vector2(140, 557)
@@ -412,6 +440,9 @@ shape = SubResource("DeathShape")
[node name="TestHUD" type="CanvasLayer" parent="."] [node name="TestHUD" type="CanvasLayer" parent="."]
layer = 87 layer = 87
[node name="EditorVisibility" type="Node" parent="TestHUD"]
script = ExtResource("editor_ui_visibility")
[node name="Overlay" type="Control" parent="TestHUD"] [node name="Overlay" type="Control" parent="TestHUD"]
layout_mode = 3 layout_mode = 3
anchors_preset = 15 anchors_preset = 15
+15 -46
View File
@@ -1,22 +1,15 @@
extends Node2D @tool
extends LevelRoot
## Alpha de campo: recorrido urbano con suelo a distintas alturas, plataformas, ## Alpha de campo: recorrido urbano con suelo a distintas alturas, plataformas,
## grupos de enemigos y objetos opcionales. Las posiciones y colisiones se editan ## grupos de enemigos y objetos opcionales. Las posiciones y colisiones se editan
## en level_02.tscn; este script solo dibuja las superficies y gestiona la meta. ## en level_02.tscn; este script solo gestiona el progreso y la meta.
## No interviene en los drops: los Walker usan su sistema habitual. ## No interviene en los drops: los Walker usan su sistema habitual.
signal level_completed signal level_completed
const WORLD_WIDTH: int = 11000
const FINISH_RESTART_SECONDS: float = 9.0 const FINISH_RESTART_SECONDS: float = 9.0
# El dibujo utiliza directamente los CollisionShape2D del escenario. Así no
# hay una segunda lista de coordenadas visuales que pueda desincronizarse.
const ASPHALT: Texture2D = preload("res://assets/city/asphalt.png")
const CURB: Texture2D = preload("res://assets/city/curb.png")
const WALKWAY: Texture2D = preload("res://assets/city/walkway.png")
const BARRIER: Texture2D = preload("res://assets/city/barrier.png")
@onready var player: CharacterBody2D = $Player @onready var player: CharacterBody2D = $Player
@onready var enemies: Node2D = $Enemies @onready var enemies: Node2D = $Enemies
@onready var status_label: Label = $LevelHUD/Overlay/Status @onready var status_label: Label = $LevelHUD/Overlay/Status
@@ -27,15 +20,11 @@ var completed: bool = false
var _finish_timer: float = 0.0 var _finish_timer: float = 0.0
## Conecta meta y derrotas; LevelRoot aplica los limites de camara.
func _ready() -> void: func _ready() -> void:
# Camera2D configura un límite provisional de 4000 en su propio _ready(). super._ready()
# El nivel lo sustituye después de que el jugador haya entrado en el árbol. if Engine.is_editor_hint():
var camera: Camera2D = player.get_node("Camera2D") as Camera2D return
camera.limit_left = 0
camera.limit_top = 0
camera.limit_right = WORLD_WIDTH
camera.limit_bottom = 1280
$FinishZone.body_entered.connect(_on_finish_entered) $FinishZone.body_entered.connect(_on_finish_entered)
finish_message.visible = false finish_message.visible = false
for enemy: Node in enemies.get_children(): for enemy: Node in enemies.get_children():
@@ -44,7 +33,11 @@ func _ready() -> void:
_update_status() _update_status()
## Actualiza el progreso o espera el reinicio tras completar la calle.
func _process(delta: float) -> void: func _process(delta: float) -> void:
super._process(delta)
if Engine.is_editor_hint():
return
if completed: if completed:
_finish_timer += delta _finish_timer += delta
if _finish_timer >= FINISH_RESTART_SECONDS: if _finish_timer >= FINISH_RESTART_SECONDS:
@@ -53,17 +46,20 @@ func _process(delta: float) -> void:
_update_status() _update_status()
## Incrementa el contador de enemigos derrotados.
func _on_enemy_died() -> void: func _on_enemy_died() -> void:
defeated_enemies += 1 defeated_enemies += 1
## Calcula el sector segun los limites editables del nivel.
func _update_status() -> void: func _update_status() -> void:
var sector: int = clampi(int(player.global_position.x / (WORLD_WIDTH / 8.0)) + 1, 1, 8) var sector: int = clampi(int((player.position.x - camera_bounds.position.x) / (camera_bounds.size.x / 8.0)) + 1, 1, 8)
status_label.text = "CALLE DEL FEEDBACK %02d/08\nKOs: %02d/%02d" % [ status_label.text = "CALLE DEL FEEDBACK %02d/08\nKOs: %02d/%02d" % [
sector, defeated_enemies, enemies.get_child_count() sector, defeated_enemies, enemies.get_child_count()
] ]
## Muestra el resultado una sola vez al alcanzar la meta.
func _on_finish_entered(body: Node2D) -> void: func _on_finish_entered(body: Node2D) -> void:
if body != player or completed: if body != player or completed:
return return
@@ -73,30 +69,3 @@ func _on_finish_entered(body: Node2D) -> void:
defeated_enemies, enemies.get_child_count() defeated_enemies, enemies.get_child_count()
] ]
finish_message.visible = true finish_message.visible = true
func _draw() -> void:
# Tiling GPU: dos pequeños PNG para miles de unidades de calle.
for collision: CollisionShape2D in $World/Ground.get_children():
var bounds: Rect2 = _collision_rect(collision)
if bounds.has_area():
draw_texture_rect(ASPHALT, bounds, true)
draw_texture_rect(CURB, Rect2(bounds.position.x, bounds.position.y, bounds.size.x, 24), true)
# Plataformas de una sola dirección: se atraviesan desde abajo, se aterriza
# sobre ellas desde arriba y un segundo salto abre rutas opcionales.
for collision: CollisionShape2D in $World/Walkways.get_children():
var bounds: Rect2 = _collision_rect(collision)
if bounds.has_area():
draw_texture_rect(WALKWAY, bounds, true)
# Barreras visibles y sólidas; el jugador no puede abandonar el mapa.
for wall_x: float in [0.0, WORLD_WIDTH - 48.0]:
draw_texture_rect(BARRIER, Rect2(wall_x, 280.0, 48.0, 820.0), true)
func _collision_rect(collision: CollisionShape2D) -> Rect2:
var shape: RectangleShape2D = collision.shape as RectangleShape2D
if shape == null:
return Rect2()
return Rect2(collision.position - shape.size * 0.5, shape.size)
+210 -495
View File
File diff suppressed because it is too large. Load diff
+84
View File
@@ -0,0 +1,84 @@
@tool
class_name LevelRoot
extends Node2D
## Infraestructura minima de un escenario, no un sistema de eventos.
## La plantilla contiene Player, terreno, decoracion, enemigos y controles.
## Los niveles con reglas propias pueden heredar y llamar a super en sus callbacks.
@export_category("Level")
## Limites locales de camara. El rectangulo se puede ver antes de ejecutar el juego.
@export var camera_bounds: Rect2 = Rect2(0.0, 0.0, 2400.0, 1280.0):
set(value):
camera_bounds = Rect2(value.position, Vector2(maxf(value.size.x, 1.0), maxf(value.size.y, 1.0)))
queue_redraw()
## Recuperacion al caer fuera del mapa. No depende de escudos o invulnerabilidad.
@export var reset_after_fall: bool = true:
set(value):
reset_after_fall = value
queue_redraw()
@export_range(0.0, 2000.0, 16.0) var fall_margin: float = 256.0:
set(value):
fall_margin = value
queue_redraw()
@export var show_editor_bounds: bool = true:
set(value):
show_editor_bounds = value
queue_redraw()
var _level_player: Node2D
var _reload_pending: bool = false
func _ready() -> void:
if Engine.is_editor_hint():
update_configuration_warnings()
return
_level_player = get_node_or_null("Player") as Node2D
if _level_player == null:
push_error("LevelRoot necesita una instancia de player/player.tscn llamada Player.")
return
apply_camera_bounds()
## Se ejecuta despues del _ready del jugador, sin limites ocultos en Camera2D.
func apply_camera_bounds() -> void:
var camera: Camera2D = _level_player.get_node_or_null("Camera2D") as Camera2D
if camera == null:
return
var top_left: Vector2 = to_global(camera_bounds.position)
var bottom_right: Vector2 = to_global(camera_bounds.end)
camera.limit_left = floori(top_left.x)
camera.limit_top = floori(top_left.y)
camera.limit_right = ceili(bottom_right.x)
camera.limit_bottom = ceili(bottom_right.y)
camera.reset_smoothing()
func _process(_delta: float) -> void:
if Engine.is_editor_hint() or not reset_after_fall or _reload_pending:
return
if not is_instance_valid(_level_player):
return
if _level_player.global_position.y > to_global(camera_bounds.end).y + fall_margin:
_reload_pending = true
# La recarga se difiere para no destruir nodos durante un paso de fisica.
get_tree().call_deferred("reload_current_scene")
func _draw() -> void:
if not Engine.is_editor_hint() or not show_editor_bounds:
return
draw_rect(camera_bounds, Color(0.25, 0.8, 1.0, 0.6), false, 2.0)
if reset_after_fall:
var y: float = camera_bounds.end.y + fall_margin
draw_line(Vector2(camera_bounds.position.x, y), Vector2(camera_bounds.end.x, y), Color(1.0, 0.3, 0.3, 0.7), 2.0)
func _get_configuration_warnings() -> PackedStringArray:
var warnings := PackedStringArray()
if not has_node("Player"):
warnings.append("Falta Player. Arrastra player/player.tscn y conserva ese nombre en la raiz del nivel.")
if not scale.is_equal_approx(Vector2.ONE) or not is_zero_approx(rotation):
warnings.append("No escales ni rotes la raiz del nivel; edita las piezas individualmente.")
return warnings
+49
View File
@@ -0,0 +1,49 @@
[gd_scene load_steps=8 format=3]
[ext_resource type="Script" path="res://levels/level_root.gd" id="level"]
[ext_resource type="PackedScene" path="res://player/player.tscn" id="player"]
[ext_resource type="PackedScene" path="res://ui/mobile_controls/mobile_controls.tscn" id="mobile"]
[ext_resource type="PackedScene" path="res://world/backgrounds/city_background.tscn" id="background"]
[ext_resource type="PackedScene" path="res://world/terrain/ground.tscn" id="ground"]
[ext_resource type="PackedScene" path="res://world/terrain/wall.tscn" id="wall"]
[ext_resource type="PackedScene" path="res://world/signs/sign_post.tscn" id="sign"]
[node name="NewLevel" type="Node2D"]
texture_filter = 1
script = ExtResource("level")
camera_bounds = Rect2(0, 0, 2400, 1280)
[node name="CityBackground" parent="." instance=ExtResource("background")]
[node name="World" type="Node2D" parent="."]
[node name="Ground" parent="World" instance=ExtResource("ground")]
position = Vector2(1200, 1030)
dimensions = Vector2(2400, 260)
[node name="LeftBoundary" parent="World" instance=ExtResource("wall")]
position = Vector2(0, 500)
dimensions = Vector2(48, 1000)
[node name="RightBoundary" parent="World" instance=ExtResource("wall")]
position = Vector2(2400, 500)
dimensions = Vector2(48, 1000)
[node name="Scenery" type="Node2D" parent="."]
[node name="Signs" type="Node2D" parent="."]
[node name="Welcome" parent="Signs" instance=ExtResource("sign")]
position = Vector2(330, 900)
text = "NUEVO ESCENARIO\nEdita este texto\nen el Inspector"
[node name="Player" parent="." instance=ExtResource("player")]
position = Vector2(160, 874)
[node name="Enemies" type="Node2D" parent="."]
[node name="Items" type="Node2D" parent="."]
[node name="Triggers" type="Node2D" parent="."]
[node name="MobileControls" parent="." instance=ExtResource("mobile")]
+13 -14
View File
@@ -1,16 +1,15 @@
[gd_scene load_steps=7 format=3] [gd_scene load_steps=6 format=3]
[ext_resource type="PackedScene" path="res://world/terrain/solid_block.tscn" id="kit_solid_block"]
[ext_resource type="Texture2D" uid="uid://jmadeu351yh6" path="res://assets/photo_5837080277660930029_w.jpg" id="1_background"] [ext_resource type="Texture2D" uid="uid://jmadeu351yh6" path="res://assets/photo_5837080277660930029_w.jpg" id="1_background"]
[ext_resource type="PackedScene" path="res://player/player.tscn" id="2_player"] [ext_resource type="PackedScene" path="res://player/player.tscn" id="2_player"]
[ext_resource type="PackedScene" path="res://enemies/walker/walker.tscn" id="3_walker"] [ext_resource type="PackedScene" path="res://enemies/walker/walker.tscn" id="3_walker"]
[ext_resource type="PackedScene" path="res://ui/mobile_controls/mobile_controls.tscn" id="4_mobile_controls"] [ext_resource type="PackedScene" path="res://ui/mobile_controls/mobile_controls.tscn" id="4_mobile_controls"]
[sub_resource type="RectangleShape2D" id="FloorShape"]
size = Vector2(1171, 20)
[sub_resource type="RectangleShape2D" id="WallShape"]
size = Vector2(136, 156)
[node name="CombatTest" type="Node2D"] [node name="CombatTest" type="Node2D"]
[node name="Background" type="Sprite2D" parent="."] [node name="Background" type="Sprite2D" parent="."]
@@ -18,17 +17,17 @@ position = Vector2(576, 324)
scale = Vector2(0.8181818, 0.84374994) scale = Vector2(0.8181818, 0.84374994)
texture = ExtResource("1_background") texture = ExtResource("1_background")
[node name="World" type="StaticBody2D" parent="."] [node name="World" type="Node2D" parent="."]
collision_layer = 1
collision_mask = 0
[node name="Floor" type="CollisionShape2D" parent="World"] [node name="Floor" parent="World" instance=ExtResource("kit_solid_block")]
position = Vector2(585, 465) position = Vector2(585, 465)
shape = SubResource("FloorShape") dimensions = Vector2(1171, 20)
fill_color = Color(0.20, 0.40, 0.25, 1)
[node name="LeftWall" type="CollisionShape2D" parent="World"] [node name="LeftWall" parent="World" instance=ExtResource("kit_solid_block")]
position = Vector2(77, 361) position = Vector2(77, 361)
shape = SubResource("WallShape") dimensions = Vector2(136, 156)
fill_color = Color(0.32, 0.57, 0.79, 1)
[node name="Player" parent="." instance=ExtResource("2_player")] [node name="Player" parent="." instance=ExtResource("2_player")]
position = Vector2(95, 215) position = Vector2(95, 215)
+4 -3
View File
@@ -4,6 +4,7 @@ class_name DropManager
const PICKUP_SCENE := preload("res://pickups/pickup.tscn") const PICKUP_SCENE := preload("res://pickups/pickup.tscn")
## Sortea una cantidad de objetos sin repetir entradas, usando pesos no negativos.
static func roll_drop(drop_table: PickupDropTable) -> Array[PickupData]: static func roll_drop(drop_table: PickupDropTable) -> Array[PickupData]:
var result: Array[PickupData] = [] var result: Array[PickupData] = []
if drop_table == null: if drop_table == null:
@@ -44,10 +45,10 @@ static func roll_drop(drop_table: PickupDropTable) -> Array[PickupData]:
return result return result
## Instancia recompensas desde coordenadas globales y difiere su entrada al arbol.
static func spawn_drops(drops_data: Array[PickupData], parent: Node, position: Vector2) -> void: static func spawn_drops(drops_data: Array[PickupData], parent: Node, position: Vector2) -> void:
# Death can happen inside a physics collision callback. Adding a new Area2D # La muerte puede ocurrir dentro de un contacto fisico. Se difiere la entrada
# immediately at that point is unsafe: defer its entry into the scene tree. # del nuevo Area2D al arbol y se prepara antes su posicion local para evitar aparecer en el origen.
# Set its local position first so it never briefly enters at the origin.
var local_position: Vector2 = position var local_position: Vector2 = position
if parent is Node2D: if parent is Node2D:
local_position = (parent as Node2D).to_local(position) local_position = (parent as Node2D).to_local(position)
+53 -10
View File
@@ -1,16 +1,30 @@
@tool
extends Area2D extends Area2D
class_name Pickup class_name Pickup
signal picked_up(pickup: Pickup, data: PickupData) signal picked_up(pickup: Pickup, data: PickupData)
# Enemies leave their reward on screen briefly. A player who touches it during # Los drops permanecen visibles brevemente antes de poder recogerse.
# that interval must still receive it, even if they keep running. # Se recuerda al jugador que los toque durante esa espera, aunque continue corriendo.
const DROP_COLLECTION_DELAY_SECONDS: float = 0.75 const DROP_COLLECTION_DELAY_SECONDS: float = 0.75
@export var pickup_data: PickupData ## Recurso compartido de efecto; para cambiar solo esta instancia, hazlo unico.
@export var pickup_data: PickupData:
set(value):
if pickup_data != null and pickup_data.changed.is_connected(_update_preview):
pickup_data.changed.disconnect(_update_preview)
pickup_data = value
if pickup_data != null and not pickup_data.changed.is_connected(_update_preview):
pickup_data.changed.connect(_update_preview)
if is_inside_tree():
call_deferred("_update_preview")
## Espera antes de permitir la recogida; los objetos colocados usan cero.
@export var collection_delay_seconds: float = 0.0 @export var collection_delay_seconds: float = 0.0
## Aceleracion de caida del objeto; conserva el comportamiento previo.
@export var fall_speed: float = 150.0 @export var fall_speed: float = 150.0
## Amplitud vertical de la oscilacion al apoyarse en el suelo.
@export var bob_amplitude: float = 4.0 @export var bob_amplitude: float = 4.0
## Velocidad angular de esa oscilacion.
@export var bob_speed: float = 3.0 @export var bob_speed: float = 3.0
var velocity: Vector2 = Vector2.ZERO var velocity: Vector2 = Vector2.ZERO
@@ -18,14 +32,18 @@ var time: float = 0.0
var start_y: float = 0.0 var start_y: float = 0.0
var grounded: bool = false var grounded: bool = false
var _can_collect: bool = false var _can_collect: bool = false
var _pending_collector: Node2D # Player who crossed the pickup during its delay. var _pending_collector: Node2D # Jugador que toco el objeto durante la espera.
@onready var label: Label = $Label @onready var label: Label = $Label
@onready var sprite: Sprite2D = $Sprite2D @onready var sprite: Sprite2D = $Sprite2D
@onready var placeholder: ColorRect = $Sprite2D/ColorRect @onready var placeholder: ColorRect = $Sprite2D/ColorRect
## Prepara la vista previa; solo en partida activa la recogida y sus senales.
func _ready() -> void: func _ready() -> void:
_update_preview()
if Engine.is_editor_hint():
return
add_to_group("pickup") add_to_group("pickup")
body_entered.connect(_on_body_entered) body_entered.connect(_on_body_entered)
@@ -47,20 +65,23 @@ func _ready() -> void:
_can_collect = true _can_collect = true
## Habilita el drop y resuelve un contacto que hubiera ocurrido durante la espera.
func _enable_collection_after_delay() -> void: func _enable_collection_after_delay() -> void:
await get_tree().create_timer(collection_delay_seconds).timeout await get_tree().create_timer(collection_delay_seconds).timeout
if not is_inside_tree(): if not is_inside_tree():
return return
_can_collect = true _can_collect = true
# A body_entered signal received during the delay is not lost. Crossing a # No se pierde un contacto recibido durante la espera: atravesar el objeto cuenta como haberlo tocado.
# spawning item counts as touching it, even if the player is now elsewhere.
if is_instance_valid(_pending_collector): if is_instance_valid(_pending_collector):
_on_body_entered(_pending_collector) _on_body_entered(_pending_collector)
_pending_collector = null _pending_collector = null
## Hace caer/flotar el objeto y reintenta aplicar efectos mientras el jugador lo toca.
func _physics_process(delta: float) -> void: func _physics_process(delta: float) -> void:
if Engine.is_editor_hint():
return
time += delta time += delta
if not grounded: if not grounded:
velocity.y += fall_speed * delta velocity.y += fall_speed * delta
@@ -72,9 +93,8 @@ func _physics_process(delta: float) -> void:
else: else:
position.y = start_y + sin(time * bob_speed) * bob_amplitude position.y = start_y + sin(time * bob_speed) * bob_amplitude
# body_entered only fires at the start of a contact. Rechecking overlaps # body_entered solo avisa al comenzar el contacto. Revisar solapamientos
# also handles moving pickups and effects that were unusable on first touch # permite recoger un objeto cuando pasa a ser util sin exigir salir y volver a entrar.
# (e.g. a heal while HP was full, then the player takes damage).
if pickup_data != null and not is_queued_for_deletion(): if pickup_data != null and not is_queued_for_deletion():
for body in get_overlapping_bodies(): for body in get_overlapping_bodies():
_on_body_entered(body) _on_body_entered(body)
@@ -82,6 +102,7 @@ func _physics_process(delta: float) -> void:
break break
## Sonda de suelo sobre la capa World; los objetos son areas, no cuerpos fisicos.
func is_on_floor() -> bool: func is_on_floor() -> bool:
var space = get_world_2d().direct_space_state var space = get_world_2d().direct_space_state
var params = PhysicsRayQueryParameters2D.create(global_position, global_position + Vector2(0, 12)) var params = PhysicsRayQueryParameters2D.create(global_position, global_position + Vector2(0, 12))
@@ -90,6 +111,7 @@ func is_on_floor() -> bool:
return result.size() > 0 return result.size() > 0
## Consume el objeto solo cuando Player confirma que se ha aplicado su efecto.
func _on_body_entered(body: Node2D) -> void: func _on_body_entered(body: Node2D) -> void:
if pickup_data == null or is_queued_for_deletion(): if pickup_data == null or is_queued_for_deletion():
return return
@@ -104,7 +126,28 @@ func _on_body_entered(body: Node2D) -> void:
picked_up.emit(self, pickup_data) picked_up.emit(self, pickup_data)
queue_free() queue_free()
elif pickup_data.effect_type == "heal": elif pickup_data.effect_type == "heal":
# This is not a collision failure: the player already has full HP. # No es un fallo de colision: el jugador ya tiene la vida completa.
label.text = "%s\n(HP LLENO)" % pickup_data.display_name label.text = "%s\n(HP LLENO)" % pickup_data.display_name
elif pickup_data.effect_type == "special_charge": elif pickup_data.effect_type == "special_charge":
label.text = "%s\n(ESPECIAL LLENO)" % pickup_data.display_name label.text = "%s\n(ESPECIAL LLENO)" % pickup_data.display_name
## Actualiza exclusivamente la presentacion; nunca consume objetos en el editor.
func _update_preview() -> void:
if not is_inside_tree() or not has_node("Label"):
return
var preview_label: Label = $Label
var preview_sprite: Sprite2D = $Sprite2D
var preview_placeholder: ColorRect = $Sprite2D/ColorRect
preview_label.text = pickup_data.display_name if pickup_data != null else "SIN DATOS"
preview_sprite.texture = pickup_data.icon if pickup_data != null else null
preview_placeholder.visible = preview_sprite.texture == null
preview_placeholder.color = pickup_data.color if pickup_data != null else Color.MAGENTA
update_configuration_warnings()
## Avisa en el arbol del editor cuando falta el recurso de datos.
func _get_configuration_warnings() -> PackedStringArray:
if pickup_data == null:
return PackedStringArray(["Asigna Pickup Data o arrastra una escena de pickups/variants."])
return PackedStringArray()
+15 -5
View File
@@ -1,18 +1,28 @@
@tool
extends Resource extends Resource
class_name PickupData class_name PickupData
@export_category("Identity") @export_category("Identity")
@export var id: StringName = &"pickup" @export var id: StringName = &"pickup"
@export var display_name: String = "Item" @export var display_name: String = "Item":
set(value):
display_name = value
emit_changed()
@export_multiline var description: String = "" @export_multiline var description: String = ""
@export_category("Visuals") @export_category("Visuals")
@export var icon: Texture2D @export var icon: Texture2D:
@export var color: Color = Color(1.0, 0.7, 0.2) set(value):
icon = value
emit_changed()
@export var color: Color = Color(1.0, 0.7, 0.2):
set(value):
color = value
emit_changed()
@export_category("Effect") @export_category("Effect")
## heal and special_charge are instant; shield absorbs one hit; others expire. ## heal y special_charge son instantaneos; shield absorbe golpes; las demas mejoras caducan.
## value is an absolute amount for heal/charge, a fractional bonus for timed buffs. ## Value expresa cantidad absoluta para vida/carga y fraccion adicional para mejoras temporales.
@export_enum("heal", "speed_boost", "damage_boost", "special_charge", "shield", "damage_reduction", "jump_boost", "air_damage_boost") var effect_type: String = "heal" @export_enum("heal", "speed_boost", "damage_boost", "special_charge", "shield", "damage_reduction", "jump_boost", "air_damage_boost") var effect_type: String = "heal"
@export var value: float = 0.0 @export var value: float = 0.0
@export var duration: float = 0.0 @export var duration: float = 0.0
+2
View File
@@ -1,5 +1,7 @@
extends Resource extends Resource
class_name PickupDrop class_name PickupDrop
## Recurso que se entregara si se selecciona esta entrada.
@export var pickup: PickupData @export var pickup: PickupData
## Peso relativo, no porcentaje. Cero excluye la entrada del sorteo normal.
@export_range(0.0, 100.0, 0.1) var weight: float = 1.0 @export_range(0.0, 100.0, 0.1) var weight: float = 1.0
+4
View File
@@ -1,7 +1,11 @@
extends Resource extends Resource
class_name PickupDropTable class_name PickupDropTable
## Entradas disponibles; un mismo sorteo no repite la misma entrada.
@export var drops: Array[PickupDrop] = [] @export var drops: Array[PickupDrop] = []
## Probabilidad de efectuar un sorteo: cero nunca, uno siempre.
@export_range(0.0, 1.0) var drop_chance: float = 0.5 @export_range(0.0, 1.0) var drop_chance: float = 0.5
## Cantidad minima solicitada, limitada por las entradas disponibles.
@export_range(0, 10, 1) var min_drops: int = 1 @export_range(0, 10, 1) var min_drops: int = 1
## Cantidad maxima solicitada; debe ser mayor o igual que Min Drops.
@export_range(0, 10, 1) var max_drops: int = 1 @export_range(0, 10, 1) var max_drops: int = 1
+5
View File
@@ -0,0 +1,5 @@
[gd_scene load_steps=3 format=3]
[ext_resource type="PackedScene" path="res://pickups/pickup.tscn" id="base"]
[ext_resource type="Resource" path="res://pickups/data/amplificador_11.tres" id="data"]
[node name="Amplifier11" instance=ExtResource("base")]
pickup_data = ExtResource("data")
+5
View File
@@ -0,0 +1,5 @@
[gd_scene load_steps=3 format=3]
[ext_resource type="PackedScene" path="res://pickups/pickup.tscn" id="base"]
[ext_resource type="Resource" path="res://pickups/data/pua_apocalipsis.tres" id="data"]
[node name="ApocalypsePick" instance=ExtResource("base")]
pickup_data = ExtResource("data")
+5
View File
@@ -0,0 +1,5 @@
[gd_scene load_steps=3 format=3]
[ext_resource type="PackedScene" path="res://pickups/pickup.tscn" id="base"]
[ext_resource type="Resource" path="res://pickups/data/beer.tres" id="data"]
[node name="Beer" instance=ExtResource("base")]
pickup_data = ExtResource("data")
+5
View File
@@ -0,0 +1,5 @@
[gd_scene load_steps=3 format=3]
[ext_resource type="PackedScene" path="res://pickups/pickup.tscn" id="base"]
[ext_resource type="Resource" path="res://pickups/data/coffee.tres" id="data"]
[node name="Coffee" instance=ExtResource("base")]
pickup_data = ExtResource("data")
+5
View File
@@ -0,0 +1,5 @@
[gd_scene load_steps=3 format=3]
[ext_resource type="PackedScene" path="res://pickups/pickup.tscn" id="base"]
[ext_resource type="Resource" path="res://pickups/data/casete_demo.tres" id="data"]
[node name="DemoTape" instance=ExtResource("base")]
pickup_data = ExtResource("data")
+5
View File
@@ -0,0 +1,5 @@
[gd_scene load_steps=3 format=3]
[ext_resource type="PackedScene" path="res://pickups/pickup.tscn" id="base"]
[ext_resource type="Resource" path="res://pickups/data/pedal_distorsion.tres" id="data"]
[node name="DistortionPedal" instance=ExtResource("base")]
pickup_data = ExtResource("data")
+5
View File
@@ -0,0 +1,5 @@
[gd_scene load_steps=3 format=3]
[ext_resource type="PackedScene" path="res://pickups/pickup.tscn" id="base"]
[ext_resource type="Resource" path="res://pickups/data/botas_doble_bombo.tres" id="data"]
[node name="DoubleKickBoots" instance=ExtResource("base")]
pickup_data = ExtResource("data")
+5
View File
@@ -0,0 +1,5 @@
[gd_scene load_steps=3 format=3]
[ext_resource type="PackedScene" path="res://pickups/pickup.tscn" id="base"]
[ext_resource type="Resource" path="res://pickups/data/tupper_bateria.tres" id="data"]
[node name="DrummerLunch" instance=ExtResource("base")]
pickup_data = ExtResource("data")
+5
View File
@@ -0,0 +1,5 @@
[gd_scene load_steps=3 format=3]
[ext_resource type="PackedScene" path="res://pickups/pickup.tscn" id="base"]
[ext_resource type="Resource" path="res://pickups/data/cinta_americana.tres" id="data"]
[node name="DuctTape" instance=ExtResource("base")]
pickup_data = ExtResource("data")
+5
View File
@@ -0,0 +1,5 @@
[gd_scene load_steps=3 format=3]
[ext_resource type="PackedScene" path="res://pickups/pickup.tscn" id="base"]
[ext_resource type="Resource" path="res://pickups/data/lata_feedback.tres" id="data"]
[node name="FeedbackCan" instance=ExtResource("base")]
pickup_data = ExtResource("data")
+5
View File
@@ -0,0 +1,5 @@
[gd_scene load_steps=3 format=3]
[ext_resource type="PackedScene" path="res://pickups/pickup.tscn" id="base"]
[ext_resource type="Resource" path="res://pickups/data/setlist_fin.tres" id="data"]
[node name="FinalSetlist" instance=ExtResource("base")]
pickup_data = ExtResource("data")
+5
View File
@@ -0,0 +1,5 @@
[gd_scene load_steps=3 format=3]
[ext_resource type="PackedScene" path="res://pickups/pickup.tscn" id="base"]
[ext_resource type="Resource" path="res://pickups/data/pizza_post_bolo.tres" id="data"]
[node name="PostShowPizza" instance=ExtResource("base")]
pickup_data = ExtResource("data")
+5
View File
@@ -0,0 +1,5 @@
[gd_scene load_steps=3 format=3]
[ext_resource type="PackedScene" path="res://pickups/pickup.tscn" id="base"]
[ext_resource type="Resource" path="res://pickups/data/bocata_roadie.tres" id="data"]
[node name="RoadieSandwich" instance=ExtResource("base")]
pickup_data = ExtResource("data")
+5
View File
@@ -0,0 +1,5 @@
[gd_scene load_steps=3 format=3]
[ext_resource type="PackedScene" path="res://pickups/pickup.tscn" id="base"]
[ext_resource type="Resource" path="res://pickups/data/baqueta_sismica.tres" id="data"]
[node name="SeismicDrumstick" instance=ExtResource("base")]
pickup_data = ExtResource("data")
+5
View File
@@ -0,0 +1,5 @@
[gd_scene load_steps=3 format=3]
[ext_resource type="PackedScene" path="res://pickups/pickup.tscn" id="base"]
[ext_resource type="Resource" path="res://pickups/data/muelles_stage.tres" id="data"]
[node name="StageSprings" instance=ExtResource("base")]
pickup_data = ExtResource("data")
@@ -0,0 +1,5 @@
[gd_scene load_steps=3 format=3]
[ext_resource type="PackedScene" path="res://pickups/pickup.tscn" id="base"]
[ext_resource type="Resource" path="res://pickups/data/tapones_tecnico.tres" id="data"]
[node name="TechnicianEarplugs" instance=ExtResource("base")]
pickup_data = ExtResource("data")
+5
View File
@@ -0,0 +1,5 @@
[gd_scene load_steps=3 format=3]
[ext_resource type="PackedScene" path="res://pickups/pickup.tscn" id="base"]
[ext_resource type="Resource" path="res://pickups/data/cuerda_titanio.tres" id="data"]
[node name="TitaniumString" instance=ExtResource("base")]
pickup_data = ExtResource("data")
+8 -7
View File
@@ -1,6 +1,6 @@
extends Camera2D extends Camera2D
## Set to zero to disable camera shake and screen overlays. ## Cero desactiva sacudidas y superposiciones. Los limites se configuran en la escena o en LevelRoot.
@export_range(0.0, 1.0, 0.05) var feedback_strength: float = 1.0 @export_range(0.0, 1.0, 0.05) var feedback_strength: float = 1.0
var _base_offset: Vector2 var _base_offset: Vector2
@@ -13,14 +13,11 @@ var _flash_color := Color(1.0, 0.82, 0.50)
var _overlay: Control var _overlay: Control
## Prepara la capa visual de feedback; no sobrescribe los limites de la camara.
func _ready() -> void: func _ready() -> void:
limit_left = 0
limit_top = 0
limit_right = 4000
limit_bottom = 2500
_base_offset = offset _base_offset = offset
# Below the existing HUDs. This Control never intercepts touch controls. # Capa inferior a los HUD. Este Control nunca intercepta los controles tactiles.
var layer := CanvasLayer.new() var layer := CanvasLayer.new()
layer.name = "CombatFeedback" layer.name = "CombatFeedback"
layer.layer = 80 layer.layer = 80
@@ -32,6 +29,7 @@ func _ready() -> void:
_overlay.draw.connect(_draw_feedback) _overlay.draw.connect(_draw_feedback)
## Acumula la sacudida mas intensa sin reiniciar a menor fuerza un impacto existente.
func impact(strength: float = 1.5, duration: float = 0.16, func impact(strength: float = 1.5, duration: float = 0.16,
color: Color = Color(1.0, 0.82, 0.50)) -> void: color: Color = Color(1.0, 0.82, 0.50)) -> void:
_shake_amplitude = maxf(_shake_amplitude, strength) _shake_amplitude = maxf(_shake_amplitude, strength)
@@ -40,10 +38,12 @@ func impact(strength: float = 1.5, duration: float = 0.16,
_flash_color = color _flash_color = color
## Activa la superposicion del especial durante el tiempo solicitado.
func start_solo(duration: float) -> void: func start_solo(duration: float) -> void:
_solo_remaining = duration _solo_remaining = duration
## Amortigua las sacudidas alrededor del desplazamiento inicial de la camara.
func _process(delta: float) -> void: func _process(delta: float) -> void:
_clock += delta _clock += delta
_shake_remaining = maxf(0.0, _shake_remaining - delta) _shake_remaining = maxf(0.0, _shake_remaining - delta)
@@ -56,12 +56,13 @@ func _process(delta: float) -> void:
_overlay.queue_redraw() _overlay.queue_redraw()
## Dibuja bordes y notas visuales sin afectar a entradas ni colisiones.
func _draw_feedback() -> void: func _draw_feedback() -> void:
if feedback_strength <= 0.0: if feedback_strength <= 0.0:
return return
var size: Vector2 = get_viewport_rect().size var size: Vector2 = get_viewport_rect().size
var pulse: float = (_shake_remaining / _shake_duration) * feedback_strength var pulse: float = (_shake_remaining / _shake_duration) * feedback_strength
# Subtle edge flashes, not full-white flashes or a strobing screen. # Destellos suaves en los bordes, sin flashes blancos a pantalla completa.
if pulse > 0.0: if pulse > 0.0:
var color: Color = _flash_color var color: Color = _flash_color
color.a = pulse * 0.14 color.a = pulse * 0.14
+6
View File
@@ -17,8 +17,14 @@ class_name CharacterData
@export var sprite_frames: SpriteFrames @export var sprite_frames: SpriteFrames
@export_category("Stats") @export_category("Stats")
## Vida maxima del integrante. Las mejoras temporales nunca modifican este recurso.
@export_range(1, 100, 1) var max_health: int = 5 @export_range(1, 100, 1) var max_health: int = 5
## Velocidad horizontal base en pixeles por segundo.
@export var move_speed: float = 400.0 @export var move_speed: float = 400.0
## Impulso vertical inicial: mas negativo significa saltar mas alto.
@export var jump_velocity: float = -600.0 @export var jump_velocity: float = -600.0
## Dano base de un punetazo.
@export_range(0, 100, 1) var basic_attack_damage: int = 5 @export_range(0, 100, 1) var basic_attack_damage: int = 5
## Campo heredado sin uso actual en Player; se conserva por compatibilidad.
## El golpe aereo usa Ground Pound (dano por altura y limites), no este valor.
@export_range(0, 100, 1) var air_attack_damage: int = 10 @export_range(0, 100, 1) var air_attack_damage: int = 10
+143 -116
View File
@@ -1,187 +1,196 @@
extends CharacterBody2D extends CharacterBody2D
## Controlador del jugador: movimiento, combate y estado temporal.
## Ajustes por personaje: player/characters/*.tres; ajustes comunes: player/player.tscn.
## Mapa de funciones y criterios de ampliacion: docs/architecture.md.
signal health_changed(current_health: int, max_health: int) signal health_changed(current_health: int, max_health: int)
signal died signal died
signal special_charge_changed(current_charge: int, max_charge: int) signal special_charge_changed(current_charge: int, max_charge: int)
## Emitted only after an object successfully applies its effect. ## Solo se emite cuando el objeto ha aplicado su efecto. El laboratorio cuenta recogidas reales, no simples contactos.
## The test level uses this signal to count items actually collected.
signal pickup_collected(data: PickupData) signal pickup_collected(data: PickupData)
# Collision layers used by this first playable slice. # Capas de fisica: 1 escenario, 2 cuerpo del jugador, 3 cuerpo enemigo,
# Keeping the numbers here makes the scene setup easier to understand: # 4 zona vulnerable del jugador y 5 zona vulnerable del enemigo.
# 1 -> world # Los bits de las mascaras empiezan en cero; no confundir bit con numero de capa.
# 2 -> player body
# 3 -> enemy body
# 4 -> player hurtbox
# 5 -> enemy hurtbox
const ENEMY_HURTBOX_MASK: int = 1 << 4 const ENEMY_HURTBOX_MASK: int = 1 << 4
const COMBAT_FX = preload("res://effects/combat_fx.gd") const COMBAT_FX = preload("res://effects/combat_fx.gd")
# ============================================================================ # ============================================================================
# CHARACTER # PERSONAJE
# ============================================================================ # ============================================================================
@export_category("Character") @export_category("Character")
## Resource that identifies the selected band member and contains the stats ## Identidad, animaciones y estadisticas propias del integrante.
## that are allowed to differ between characters. ## Los ajustes comunes de movimiento y combate se editan debajo, en player.tscn.
@export var character_data: CharacterData @export var character_data: CharacterData
# ============================================================================ # ============================================================================
# MOVEMENT # MOVIMIENTO
# ============================================================================ # ============================================================================
@export_category("Movement") @export_category("Movement")
## Reaches full running speed quickly, but not instantly. ## Aceleracion horizontal en el suelo; no alcanza la velocidad maxima instantaneamente.
@export var ground_acceleration: float = 4000.0 @export var ground_acceleration: float = 4000.0
## Used when there is no horizontal input. Slightly stronger than acceleration ## Frenado al soltar la direccion. Mayor que la aceleracion para evitar deslizamiento.
## so releasing the controls feels precise instead of slippery.
@export var ground_friction: float = 5000.0 @export var ground_friction: float = 5000.0
## Braking used only when the player asks for the opposite direction. The ## Frenado al invertir la direccion: primero elimina el impulso anterior y luego acelera al otro lado.
## character loses the old momentum first and then accelerates the other way,
## producing a small but turning is snappy enough.
@export var turn_braking: float = 5800.0 @export var turn_braking: float = 5800.0
## Air control stays responsive but weaker than movement on the floor. ## Control horizontal en el aire, deliberadamente menor que el del suelo.
@export var air_acceleration: float = 2000.0 @export var air_acceleration: float = 2000.0
# ============================================================================ # ============================================================================
# JUMP # SALTO
# ============================================================================ # ============================================================================
@export_category("Jump") @export_category("Jump")
## Allows a jump a few milliseconds after walking off a ledge. ## Margen en segundos para saltar justo despues de abandonar un borde (coyote time).
@export var coyote_time: float = 0.17 @export var coyote_time: float = 0.17
## Remembers an early jump press just before landing. ## Tiempo que se recuerda un salto pulsado poco antes de tocar suelo.
@export var jump_buffer_time: float = 0.17 @export var jump_buffer_time: float = 0.17
## Releasing jump while rising cuts the jump short. ## Multiplicador de la velocidad ascendente al soltar salto; permite saltos cortos.
@export_range(0.1, 1.0) var jump_cut_multiplier: float = 0.43 @export_range(0.1, 1.0) var jump_cut_multiplier: float = 0.43
## Escala la gravedad del proyecto durante el movimiento normal.
@export var gravity_multiplier: float = 1.0 @export var gravity_multiplier: float = 1.0
## Multiplicador usado al descender; sustituye al normal, no se multiplica por el.
@export var fall_gravity_multiplier: float = 1.6 @export var fall_gravity_multiplier: float = 1.6
## Limite de velocidad descendente en pixeles por segundo.
@export var max_fall_speed: float = 1400.0 @export var max_fall_speed: float = 1400.0
@export_category("Double Jump") @export_category("Double Jump")
## Enables a second jump while in the air. ## Permite un segundo salto sin haber vuelto al suelo.
@export var enable_double_jump: bool = true @export var enable_double_jump: bool = true
## Maximum number of jumps allowed (1 = only ground/coyote, 2 = double jump). ## Numero maximo de saltos: 1 en suelo/margen de borde; 2 incluye doble salto.
@export_range(1, 2, 1) var max_jumps: int = 2 @export_range(1, 2, 1) var max_jumps: int = 2
## Height multiplier applied to the second jump relative to the character's jump force. ## Multiplica el impulso vertical del segundo salto, no directamente su altura en pixeles.
@export_range(0.5, 0.95, 0.01) var double_jump_multiplier: float = 0.8 @export_range(0.5, 0.95, 0.01) var double_jump_multiplier: float = 0.8
# ============================================================================ # ============================================================================
# DAMAGE RECEIVED # DANO RECIBIDO
# ============================================================================ # ============================================================================
@export_category("Damage received") @export_category("Damage received")
## Short grace period so a contact hitbox cannot drain all health in one frame. ## Ventana de invulnerabilidad tras un golpe; evita recibir dano en cada fotograma de contacto.
@export var invulnerability_duration: float = 0.65 @export var invulnerability_duration: float = 0.65
## Horizontal and vertical impulse applied when the player is hit. ## Impulso horizontal y vertical al recibir dano, independiente de la velocidad de carrera.
@export var damage_knockback: Vector2 = Vector2(310.0, 270.0) @export var damage_knockback: Vector2 = Vector2(310.0, 270.0)
# ============================================================================ # ============================================================================
# PUNCH # PUNETAZO
# ============================================================================ # ============================================================================
@export_category("Punch") @export_category("Punch")
## Duracion visual total del punetazo en segundos.
@export var punch_duration: float = 0.28 @export var punch_duration: float = 0.28
## Tiempo antes de que el punetazo pueda causar dano.
@export var punch_windup: float = 0.055 @export var punch_windup: float = 0.055
## Ventana danina del punetazo en segundos.
@export var punch_active_duration: float = 0.11 @export var punch_active_duration: float = 0.11
## Espera minima entre inicios de punetazo.
@export var punch_cooldown: float = 0.34 @export var punch_cooldown: float = 0.34
## Cover the player's body too, so overlapping enemies can be hit from either side. ## El area cubre tambien el cuerpo para golpear enemigos superpuestos.
## Keep the forward edge at 42 pixels; only extend the hitbox inward. ## Se conserva el extremo frontal a 42 px; el area adicional se extiende hacia dentro.
@export var punch_hitbox_size: Vector2 = Vector2(56.0, 22.0) @export var punch_hitbox_size: Vector2 = Vector2(56.0, 22.0)
## Centro del punetazo relativo al jugador mirando a la derecha.
@export var punch_offset: Vector2 = Vector2(14.0, -4.0) @export var punch_offset: Vector2 = Vector2(14.0, -4.0)
# ============================================================================ # ============================================================================
# GROUND POUND # GOLPE AEREO
# ============================================================================ # ============================================================================
@export_category("Ground Pound") @export_category("Ground Pound")
## Minimum downward speed when the air attack starts. ## Velocidad descendente minima al iniciar el golpe aereo.
@export var ground_pound_start_speed: float = 450.0 @export var ground_pound_start_speed: float = 450.0
## Extra gravity while performing the air attack. ## Gravedad adicional mientras dura el golpe aereo.
@export var ground_pound_gravity_multiplier: float = 4.5 @export var ground_pound_gravity_multiplier: float = 4.5
## Small amount of steering kept during the fall. ## Fraccion del control horizontal que se mantiene durante la caida ofensiva.
@export_range(0.0, 1.0) var ground_pound_horizontal_control: float = 0.25 @export_range(0.0, 1.0) var ground_pound_horizontal_control: float = 0.25
## Radio del impacto al aterrizar, en pixeles.
@export var ground_pound_radius: float = 54.0 @export var ground_pound_radius: float = 54.0
## Centro del impacto respecto al cuerpo del jugador.
@export var ground_pound_offset: Vector2 = Vector2(0.0, 24.0) @export var ground_pound_offset: Vector2 = Vector2(0.0, 24.0)
## From 7 damage on a small jump to 12 on a high one; always stronger ## Dano entre 7 y 12 segun la altura alcanzada, superior al punetazo base de 5.
## than a standard 5-point punch, even without any pickup. ## Las mejoras no permiten superar el limite final configurado.
@export var ground_pound_damage_per_pixel: float = 0.065 @export var ground_pound_damage_per_pixel: float = 0.065
@export_range(1, 100, 1) var ground_pound_min_damage: int = 7 @export_range(1, 100, 1) var ground_pound_min_damage: int = 7
@export_range(1, 100, 1) var ground_pound_max_damage: int = 12 @export_range(1, 100, 1) var ground_pound_max_damage: int = 12
# ============================================================================ # ============================================================================
# SPECIAL ATTACK # ATAQUE ESPECIAL
# ============================================================================ # ============================================================================
@export_category("Special Attack") @export_category("Special Attack")
## Maximum charge of the special meter (0-100). ## Capacidad maxima del medidor especial, entre 0 y 100.
@export_range(0, 100, 1) var special_max_charge: int = 100 @export_range(0, 100, 1) var special_max_charge: int = 100
## Charge gained when an enemy dies. ## Puntos por baja: con capacidad 100, diez bajas llenan el medidor desde cero.
@export_range(0, 100, 1) var special_charge_per_kill: int = 25 @export_range(0, 100, 1) var special_charge_per_kill: int = 10
## Minimum charge required to use special attack. ## Desactivado evita que el solo se pague a si mismo al eliminar grupos de enemigos.
## Solo filtra bajas causadas por su dano, no otras muertes que coincidan durante el solo.
@export var special_kills_grant_charge: bool = false
## Carga minima necesaria para iniciar el ataque especial.
@export_range(0, 100, 1) var special_min_use_charge: int = 25 @export_range(0, 100, 1) var special_min_use_charge: int = 25
## Maximum damage dealt by the special (at full charge, closest to player). ## Dano maximo a plena carga y a la menor distancia del jugador.
@export_range(0, 100, 1) var special_max_damage: int = 30 @export_range(0, 100, 1) var special_max_damage: int = 30
## Optional hard cutoff for the special. Very large = previous full-screen behaviour. ## Radio adicional al filtro de pantalla. Un valor grande conserva el alcance visible original.
## The Level 01 test sets a smaller radius to keep encounters independent. ## El laboratorio usa un radio reducido para aislar sus estaciones.
@export var special_radius: float = 100000.0 @export var special_radius: float = 100000.0
## Guitar draw, sustained solo, then recovery. Damage is shared by all pulses. ## Duracion del solo: preparacion, pulsos y recuperacion. El dano total se reparte entre los pulsos.
@export_range(0.6, 6.0, 0.1) var special_duration: float = 2.4 @export_range(0.6, 6.0, 0.1) var special_duration: float = 2.4
@export_range(1, 8, 1) var special_pulse_count: int = 4 @export_range(1, 8, 1) var special_pulse_count: int = 4
# ============================================================================ # ============================================================================
# DEBUG # DEPURACION
# ============================================================================ # ============================================================================
@export_category("Debug") @export_category("Debug")
## Draws the actual hurtbox and attack areas used by gameplay. ## Muestra las areas fisicas reales. Los efectos visibles del combate no dependen de esta opcion.
## Combat effects do not depend on this debug overlay.
@export var show_debug_hitboxes: bool = false @export var show_debug_hitboxes: bool = false
## Keeps the ground-pound area visible briefly after impact. ## Tiempo que permanece visible el area de impacto despues del golpe aereo.
@export var debug_impact_duration: float = 0.18 @export var debug_impact_duration: float = 0.18
# ============================================================================ # ============================================================================
# NODES # NODOS
# ============================================================================ # ============================================================================
@onready var animated_sprite: AnimatedSprite2D = $AnimatedSprite2D @onready var animated_sprite: AnimatedSprite2D = $AnimatedSprite2D
@@ -194,7 +203,7 @@ const COMBAT_FX = preload("res://effects/combat_fx.gd")
# ============================================================================ # ============================================================================
# RUNTIME STATE # ESTADO DE LA PARTIDA
# ============================================================================ # ============================================================================
var current_health: int = 1 var current_health: int = 1
@@ -215,7 +224,7 @@ var jumps_remaining: int = 2
var _speed_boost_timer: float = 0.0 var _speed_boost_timer: float = 0.0
var _speed_boost_multiplier: float = 0.0 var _speed_boost_multiplier: float = 0.0
# Only runtime state changes: CharacterData remains immutable during pickups. # Las mejoras solo alteran estado temporal; nunca se modifica el recurso CharacterData compartido.
var _damage_boost_timer: float = 0.0 var _damage_boost_timer: float = 0.0
var _damage_boost_multiplier: float = 0.0 var _damage_boost_multiplier: float = 0.0
var _air_damage_boost_timer: float = 0.0 var _air_damage_boost_timer: float = 0.0
@@ -228,19 +237,19 @@ var _shield_hits: int = 0
var _floating_texts: Array = [] var _floating_texts: Array = []
# Tracks the highest point reached since leaving the ground, used to scale # Altura maxima desde el despegue: el golpe aereo escala por altura de salto, no por distancia de caida.
# ground pound damage by jump height instead of fall distance.
var _jump_height_tracking: bool = false var _jump_height_tracking: bool = false
var _jump_start_position: Vector2 var _jump_start_position: Vector2
var _jump_peak_height: float = 0.0 var _jump_peak_height: float = 0.0
## Prevents one target from receiving damage every physics frame during the ## Registro por ataque: cada objetivo recibe un solo impacto por punetazo, no uno por fotograma.
## same punch. A new punch starts with an empty set again.
var punch_hit_targets: Dictionary = {} var punch_hit_targets: Dictionary = {}
var special_charge: int = 0 var special_charge: int = 0
var _special_active: bool = false var _special_active: bool = false
# Contexto sincronico del dano: Walker emite died dentro de take_damage.
var _applying_special_damage: bool = false
var _special_elapsed: float = 0.0 var _special_elapsed: float = 0.0
var _special_charge_used: int = 0 var _special_charge_used: int = 0
var _special_pulses_sent: int = 0 var _special_pulses_sent: int = 0
@@ -251,6 +260,7 @@ var _landing_animation_timer: float = 0.0
var _punch_swing_shown: bool = false var _punch_swing_shown: bool = false
## Carga el personaje y prepara ataques, animacion y senales iniciales del HUD.
func _ready() -> void: func _ready() -> void:
if character_data == null: if character_data == null:
push_error("Player needs a CharacterData resource.") push_error("Player needs a CharacterData resource.")
@@ -267,11 +277,12 @@ func _ready() -> void:
_update_animation() _update_animation()
health_changed.emit(current_health, character_data.max_health) health_changed.emit(current_health, character_data.max_health)
special_charge_changed.emit(special_charge, special_max_charge) special_charge_changed.emit(special_charge, special_max_charge)
# Conecta a los enemigos que ya estén en el árbol. Si se añaden más tarde, # Conecta los enemigos que ya pertenecen al grupo al iniciar el nivel.
# se conectarán cuando mueran mediante el grupo "enemy". # Un futuro sistema de aparicion dinamica debera conectar tambien sus nuevas instancias.
_connect_to_enemies() _connect_to_enemies()
## Orden del fotograma: entradas, movimiento, colisiones, aterrizaje y presentacion.
func _physics_process(delta: float) -> void: func _physics_process(delta: float) -> void:
if character_data == null or is_dead: if character_data == null or is_dead:
return return
@@ -289,8 +300,7 @@ func _physics_process(delta: float) -> void:
move_and_slide() move_and_slide()
# Track the highest point reached since leaving the ground, so ground pound # Registra el punto mas alto desde el despegue para calcular el dano por altura de salto.
# damage is based on jump height rather than the current fall distance.
if not is_on_floor(): if not is_on_floor():
if not _jump_height_tracking: if not _jump_height_tracking:
_jump_height_tracking = true _jump_height_tracking = true
@@ -301,7 +311,7 @@ func _physics_process(delta: float) -> void:
elif _jump_height_tracking: elif _jump_height_tracking:
_jump_height_tracking = false _jump_height_tracking = false
# Landing is only reliable after move_and_slide() has resolved collisions. # El aterrizaje solo es fiable despues de resolver colisiones con move_and_slide().
if not was_on_floor and is_on_floor(): if not was_on_floor and is_on_floor():
jumps_remaining = max_jumps jumps_remaining = max_jumps
if ground_pound_active: if ground_pound_active:
@@ -317,11 +327,12 @@ func _physics_process(delta: float) -> void:
# ============================================================================ # ============================================================================
# MOVEMENT # MOVIMIENTO
# ============================================================================ # ============================================================================
## Combina aceleracion, frenado, control aereo y retroceso sin cambiar el limite de velocidad.
func _handle_horizontal_movement(delta: float) -> void: func _handle_horizontal_movement(delta: float) -> void:
# Let impulses decay instead of immediately overwriting them with input. # Durante el retroceso se conserva y amortigua el impulso, en lugar de anularlo con la entrada.
if _special_active or _hurt_animation_timer > 0.0: if _special_active or _hurt_animation_timer > 0.0:
var braking: float = 110.0 if _special_active else 550.0 var braking: float = 110.0 if _special_active else 550.0
velocity.x = move_toward(velocity.x, 0.0, braking * delta) velocity.x = move_toward(velocity.x, 0.0, braking * delta)
@@ -347,9 +358,7 @@ func _handle_horizontal_movement(delta: float) -> void:
if direction == 0.0: if direction == 0.0:
velocity.x = move_toward(velocity.x, 0.0, ground_friction * delta) velocity.x = move_toward(velocity.x, 0.0, ground_friction * delta)
elif velocity.x != 0.0 and signf(velocity.x) != signf(direction): elif velocity.x != 0.0 and signf(velocity.x) != signf(direction):
# Do not snap directly from full speed right to full speed left. Brake # Al invertir la direccion primero se frena; los siguientes fotogramas aplican la aceleracion normal.
# the previous momentum first; on the next frames normal acceleration
# takes over in the requested direction.
velocity.x = move_toward(velocity.x, 0.0, turn_braking * delta) velocity.x = move_toward(velocity.x, 0.0, turn_braking * delta)
else: else:
velocity.x = move_toward( velocity.x = move_toward(
@@ -361,8 +370,7 @@ func _handle_horizontal_movement(delta: float) -> void:
velocity.x = move_toward(velocity.x, target_speed, air_acceleration * delta) velocity.x = move_toward(velocity.x, target_speed, air_acceleration * delta)
## Horizontal running speed with active pickups applied. Keeping the HUD and ## Velocidad efectiva incluyendo mejoras. HUD y movimiento usan este mismo calculo.
## movement on the same calculation avoids showing a bonus that isn't used.
func get_move_speed() -> float: func get_move_speed() -> float:
if character_data == null: if character_data == null:
return 0.0 return 0.0
@@ -370,11 +378,11 @@ func get_move_speed() -> float:
return character_data.move_speed * (1.0 + bonus) return character_data.move_speed * (1.0 + bonus)
## Refleja imagen y areas de ataque segun la direccion actual.
func _update_facing() -> void: func _update_facing() -> void:
animated_sprite.flip_h = facing_direction < 0.0 animated_sprite.flip_h = facing_direction < 0.0
# Only the horizontal offset changes when turning around. The hitbox size # Al girar solo se refleja el desplazamiento horizontal; el tamano del ataque no cambia.
# stays identical for both directions.
punch_hitbox.position = Vector2( punch_hitbox.position = Vector2(
abs(punch_offset.x) * facing_direction, abs(punch_offset.x) * facing_direction,
punch_offset.y punch_offset.y
@@ -382,9 +390,10 @@ func _update_facing() -> void:
# ============================================================================ # ============================================================================
# GRAVITY AND JUMP # GRAVEDAD Y SALTO
# ============================================================================ # ============================================================================
## Distingue ascenso, caida normal y caida ofensiva; limita la velocidad vertical.
func _apply_gravity(delta: float) -> void: func _apply_gravity(delta: float) -> void:
if is_on_floor(): if is_on_floor():
return return
@@ -401,6 +410,7 @@ func _apply_gravity(delta: float) -> void:
velocity.y = min(velocity.y, max_fall_speed) velocity.y = min(velocity.y, max_fall_speed)
## Actualiza el margen de borde, la memoria de entrada y los saltos restantes.
func _update_jump_windows(delta: float) -> void: func _update_jump_windows(delta: float) -> void:
if is_on_floor(): if is_on_floor():
coyote_timer = coyote_time coyote_timer = coyote_time
@@ -414,6 +424,7 @@ func _update_jump_windows(delta: float) -> void:
jump_buffer_timer = max(jump_buffer_timer - delta, 0.0) jump_buffer_timer = max(jump_buffer_timer - delta, 0.0)
## Consume el salto permitido y aplica impulso variable al soltar el boton.
func _handle_jump() -> void: func _handle_jump() -> void:
if _special_active or _hurt_animation_timer > 0.0: if _special_active or _hurt_animation_timer > 0.0:
return return
@@ -436,9 +447,10 @@ func _handle_jump() -> void:
# ============================================================================ # ============================================================================
# ATTACK INPUT # ENTRADA DE ATAQUES
# ============================================================================ # ============================================================================
## Decide que ataque puede iniciarse con la entrada y el estado actuales.
func _handle_attack_input() -> void: func _handle_attack_input() -> void:
if _special_active or _hurt_animation_timer > 0.0: if _special_active or _hurt_animation_timer > 0.0:
return return
@@ -447,8 +459,7 @@ func _handle_attack_input() -> void:
return return
if Input.is_action_just_pressed("ground_pound"): if Input.is_action_just_pressed("ground_pound"):
# The ground pound is an air attack: it only triggers while jumping or # El golpe aereo solo comienza en el aire; no reemplaza un punetazo desde el suelo.
# falling, so it never replaces a grounded punch.
if not is_on_floor(): if not is_on_floor():
_start_ground_pound() _start_ground_pound()
return return
@@ -459,9 +470,10 @@ func _handle_attack_input() -> void:
# ============================================================================ # ============================================================================
# PUNCH # PUNETAZO
# ============================================================================ # ============================================================================
## Inicia una ventana de punetazo y vacia el registro de objetivos ya golpeados.
func _start_punch() -> void: func _start_punch() -> void:
if is_dead or _special_active or ground_pound_active or attack_cooldown_timer > 0.0: if is_dead or _special_active or ground_pound_active or attack_cooldown_timer > 0.0:
return return
@@ -471,6 +483,7 @@ func _start_punch() -> void:
punch_hit_targets.clear() punch_hit_targets.clear()
## Aplica impactos solo durante la fase activa del punetazo.
func _update_punch_damage() -> void: func _update_punch_damage() -> void:
if punch_timer <= 0.0: if punch_timer <= 0.0:
return return
@@ -486,9 +499,10 @@ func _update_punch_damage() -> void:
# ============================================================================ # ============================================================================
# GROUND POUND # GOLPE AEREO
# ============================================================================ # ============================================================================
## Cancela el ascenso y prepara el ataque de caida.
func _start_ground_pound() -> void: func _start_ground_pound() -> void:
if is_dead or _special_active or ground_pound_active: if is_dead or _special_active or ground_pound_active:
return return
@@ -497,11 +511,11 @@ func _start_ground_pound() -> void:
ground_pound_active = true ground_pound_active = true
attack_cooldown_timer = punch_cooldown attack_cooldown_timer = punch_cooldown
# If the player is still rising, the attack immediately turns the movement # Si aun estaba ascendiendo, convierte inmediatamente el salto en caida ofensiva.
# into a fall instead of waiting for the jump apex.
velocity.y = max(velocity.y, ground_pound_start_speed) velocity.y = max(velocity.y, ground_pound_start_speed)
## Calcula el dano y consulta objetivos en la posicion final del aterrizaje.
func _ground_pound_impact() -> void: func _ground_pound_impact() -> void:
ground_pound_active = false ground_pound_active = false
ground_pound_debug_timer = debug_impact_duration ground_pound_debug_timer = debug_impact_duration
@@ -510,8 +524,7 @@ func _ground_pound_impact() -> void:
&"ground_pound", facing_direction, ground_pound_radius) &"ground_pound", facing_direction, ground_pound_radius)
feedback_camera.call("impact", 2.8, 0.24) feedback_camera.call("impact", 2.8, 0.24)
# Damage scales with jump height: how high the player rose from the takeoff # Calcula el dano a partir de la altura maxima sobre el punto de despegue y aplica sus limites.
# point, clamped between the min and max damage.
var height_reached: float = _jump_start_position.y - _jump_peak_height var height_reached: float = _jump_start_position.y - _jump_peak_height
if height_reached < 0.0: if height_reached < 0.0:
height_reached = 0.0 height_reached = 0.0
@@ -524,13 +537,12 @@ func _ground_pound_impact() -> void:
var hit_targets: Dictionary = {} var hit_targets: Dictionary = {}
# The final damage is capped too: active buffs make the 12-point ceiling # El limite se aplica tambien tras las mejoras: facilitan alcanzar el maximo, pero no lo superan.
# easier to reach, rather than turning an alpha attack into a one-shot.
var final_damage: int = mini( var final_damage: int = mini(
roundi(damage * (1.0 + _damage_boost_multiplier + _air_damage_boost_multiplier)), roundi(damage * (1.0 + _damage_boost_multiplier + _air_damage_boost_multiplier)),
ground_pound_max_damage ground_pound_max_damage
) )
# Query at the resolved landing position, not last frame's cached overlaps. # Consulta la fisica en la posicion de aterrizaje ya resuelta, no los contactos del fotograma anterior.
var query := PhysicsShapeQueryParameters2D.new() var query := PhysicsShapeQueryParameters2D.new()
query.shape = ground_pound_collision.shape query.shape = ground_pound_collision.shape
query.transform = ground_pound_collision.global_transform query.transform = ground_pound_collision.global_transform
@@ -542,9 +554,10 @@ func _ground_pound_impact() -> void:
# ============================================================================ # ============================================================================
# SPECIAL ATTACK # ATAQUE ESPECIAL
# ============================================================================ # ============================================================================
## Consume la carga disponible e inicializa el reparto de dano por pulsos.
func _start_special_attack() -> void: func _start_special_attack() -> void:
if is_dead or _special_active or ground_pound_active or special_max_charge <= 0: if is_dead or _special_active or ground_pound_active or special_max_charge <= 0:
return return
@@ -565,6 +578,7 @@ func _start_special_attack() -> void:
_spawn_floating_text("GUITAR SOLO!", Color(0.76, 0.85, 1.0)) _spawn_floating_text("GUITAR SOLO!", Color(0.76, 0.85, 1.0))
## Avanza las fases visuales del solo y emite cada pulso una sola vez.
func _update_special_attack(delta: float) -> void: func _update_special_attack(delta: float) -> void:
if not _special_active: if not _special_active:
return return
@@ -572,7 +586,7 @@ func _update_special_attack(delta: float) -> void:
var pulse_count: int = maxi(special_pulse_count, 1) var pulse_count: int = maxi(special_pulse_count, 1)
var windup: float = special_duration * 0.15 var windup: float = special_duration * 0.15
var interval: float = special_duration * 0.65 / float(maxi(pulse_count - 1, 1)) var interval: float = special_duration * 0.65 / float(maxi(pulse_count - 1, 1))
# Catch up when a long frame spans a pulse, without replaying previous pulses. # Un fotograma largo puede abarcar varios pulsos; se recuperan los pendientes sin repetir los anteriores.
while _special_pulses_sent < pulse_count: while _special_pulses_sent < pulse_count:
if _special_elapsed < windup + interval * float(_special_pulses_sent): if _special_elapsed < windup + interval * float(_special_pulses_sent):
break break
@@ -588,6 +602,7 @@ func _update_special_attack(delta: float) -> void:
_special_damage_dealt.clear() _special_damage_dealt.clear()
## Mantiene un presupuesto de dano por enemigo para no multiplicarlo por el numero de pulsos.
func _apply_special_attack(charge_used: int, pulse_index: int = 0) -> void: func _apply_special_attack(charge_used: int, pulse_index: int = 0) -> void:
var charge_ratio: float = clampf(float(charge_used) / float(maxi(special_max_charge, 1)), 0.0, 1.0) var charge_ratio: float = clampf(float(charge_used) / float(maxi(special_max_charge, 1)), 0.0, 1.0)
var viewport_rect: Rect2 = get_viewport().get_visible_rect() var viewport_rect: Rect2 = get_viewport().get_visible_rect()
@@ -601,7 +616,7 @@ func _apply_special_attack(charge_used: int, pulse_index: int = 0) -> void:
var distance: float = global_position.distance_to(enemy.global_position) var distance: float = global_position.distance_to(enemy.global_position)
if special_radius > 0.0 and distance > special_radius: if special_radius > 0.0 and distance > special_radius:
continue continue
# A screen attack should not silently damage enemies at the far end of the map. # Solo afecta a enemigos visibles; no debe golpear a distancia al otro extremo del mapa.
if not viewport_rect.grow(28.0).has_point(enemy.get_global_transform_with_canvas().origin): if not viewport_rect.grow(28.0).has_point(enemy.get_global_transform_with_canvas().origin):
continue continue
@@ -609,16 +624,19 @@ func _apply_special_attack(charge_used: int, pulse_index: int = 0) -> void:
if not _special_damage_budgets.has(enemy_id): if not _special_damage_budgets.has(enemy_id):
var distance_factor: float = maxf(0.1, 1.0 - clampf(distance / max_distance, 0.0, 1.0)) var distance_factor: float = maxf(0.1, 1.0 - clampf(distance / max_distance, 0.0, 1.0))
_special_damage_budgets[enemy_id] = maxi(1, int(special_max_damage * charge_ratio * distance_factor)) _special_damage_budgets[enemy_id] = maxi(1, int(special_max_damage * charge_ratio * distance_factor))
# Freeze the budget on first contact: knockback must not change total damage. # Fija el presupuesto al primer contacto: el retroceso posterior no cambia el dano total.
var total_damage: int = int(_special_damage_budgets[enemy_id]) var total_damage: int = int(_special_damage_budgets[enemy_id])
var cumulative_damage: int = ceili(float(total_damage) * float(pulse_index + 1) / float(pulse_count)) var cumulative_damage: int = ceili(float(total_damage) * float(pulse_index + 1) / float(pulse_count))
var damage: int = cumulative_damage - int(_special_damage_dealt.get(enemy_id, 0)) var damage: int = cumulative_damage - int(_special_damage_dealt.get(enemy_id, 0))
if damage <= 0: if damage <= 0:
continue continue
_special_damage_dealt[enemy_id] = cumulative_damage _special_damage_dealt[enemy_id] = cumulative_damage
_applying_special_damage = true
enemy.call("take_damage", damage, global_position) enemy.call("take_damage", damage, global_position)
_applying_special_damage = false
## Devuelve true solo si se aplica el efecto. False conserva el objeto para otra oportunidad.
func collect_pickup(data: PickupData) -> bool: func collect_pickup(data: PickupData) -> bool:
if is_dead or data == null or character_data == null: if is_dead or data == null or character_data == null:
return false return false
@@ -640,7 +658,7 @@ func collect_pickup(data: PickupData) -> bool:
"damage_boost", "air_damage_boost", "damage_reduction", "jump_boost": "damage_boost", "air_damage_boost", "damage_reduction", "jump_boost":
if data.value <= 0.0 or data.duration <= 0.0: if data.value <= 0.0 or data.duration <= 0.0:
return false return false
# Repeated pickup refreshes time and keeps the strongest bonus. # Recoger la misma mejora renueva el tiempo y conserva la potencia mas alta.
match data.effect_type: match data.effect_type:
"damage_boost": "damage_boost":
_damage_boost_multiplier = max(_damage_boost_multiplier, data.value) if _damage_boost_timer > 0.0 else data.value _damage_boost_multiplier = max(_damage_boost_multiplier, data.value) if _damage_boost_timer > 0.0 else data.value
@@ -674,6 +692,7 @@ func collect_pickup(data: PickupData) -> bool:
return true return true
## Registra un mensaje visual sin crear nodos por cada aviso.
func _spawn_floating_text(text: String, color: Color) -> void: func _spawn_floating_text(text: String, color: Color) -> void:
var entry := { var entry := {
"text": text, "text": text,
@@ -685,6 +704,7 @@ func _spawn_floating_text(text: String, color: Color) -> void:
_floating_texts.append(entry) _floating_texts.append(entry)
## Mueve y elimina los mensajes cuyo tiempo de vida se ha agotado.
func _update_floating_texts(delta: float) -> void: func _update_floating_texts(delta: float) -> void:
for entry in _floating_texts: for entry in _floating_texts:
entry.pos += entry.velocity * delta entry.pos += entry.velocity * delta
@@ -692,16 +712,18 @@ func _update_floating_texts(delta: float) -> void:
_floating_texts = _floating_texts.filter(func(e): return e.timer > 0.0) _floating_texts = _floating_texts.filter(func(e): return e.timer > 0.0)
## Suscribe las muertes de los enemigos presentes para recargar el especial.
func _connect_to_enemies() -> void: func _connect_to_enemies() -> void:
for enemy in get_tree().get_nodes_in_group("enemy"): for enemy in get_tree().get_nodes_in_group("enemy"):
if is_instance_valid(enemy) and enemy.has_signal(&"died"): if is_instance_valid(enemy) and enemy.has_signal(&"died"):
# The group yields Node references, not a statically typed Walker. # El grupo entrega Node, no una clase concreta de enemigo.
# Node.connect also works with any future enemy exposing this signal. # La senal permite mantener el contrato sin depender del controlador Walker.
enemy.connect(&"died", _on_enemy_died.bind(enemy)) enemy.connect(&"died", _on_enemy_died.bind(enemy))
## Suma carga sin superar su capacidad maxima y notifica al HUD.
func _on_enemy_died(_enemy: Node) -> void: func _on_enemy_died(_enemy: Node) -> void:
if is_dead: if is_dead or (_applying_special_damage and not special_kills_grant_charge):
return return
special_charge = min(special_charge + special_charge_per_kill, special_max_charge) special_charge = min(special_charge + special_charge_per_kill, special_max_charge)
@@ -709,14 +731,14 @@ func _on_enemy_died(_enemy: Node) -> void:
# ============================================================================ # ============================================================================
# DEALING AND RECEIVING DAMAGE # APLICACION Y RECEPCION DE DANO
# ============================================================================ # ============================================================================
## Resuelve la entidad de una zona vulnerable y evita impactos duplicados del mismo ataque.
func _damage_target(collider: Node, damage: int, hit_targets: Dictionary) -> void: func _damage_target(collider: Node, damage: int, hit_targets: Dictionary) -> void:
var target: Node = collider var target: Node = collider
# Hurtboxes are Area2D children. Damage belongs to the entity that owns the # Las zonas vulnerables son areas hijas; el metodo de dano pertenece a la entidad que las contiene.
# hurtbox, so we ask the parent for take_damage().
if not target.has_method("take_damage"): if not target.has_method("take_damage"):
target = target.get_parent() target = target.get_parent()
@@ -731,6 +753,7 @@ func _damage_target(collider: Node, damage: int, hit_targets: Dictionary) -> voi
target.take_damage(damage, global_position) target.take_damage(damage, global_position)
## Valida invulnerabilidad y escudo antes de reducir vida, aplicar empuje y comprobar muerte.
func take_damage(amount: int, source_position: Vector2, knockback_multiplier: float = 1.0) -> void: func take_damage(amount: int, source_position: Vector2, knockback_multiplier: float = 1.0) -> void:
if amount <= 0 or is_dead or invulnerability_timer > 0.0: if amount <= 0 or is_dead or invulnerability_timer > 0.0:
return return
@@ -741,20 +764,18 @@ func take_damage(amount: int, source_position: Vector2, knockback_multiplier: fl
_spawn_floating_text("BLOCK!", Color(0.7, 0.9, 1.0)) _spawn_floating_text("BLOCK!", Color(0.7, 0.9, 1.0))
return return
# At least one point of damage passes through an active reduction. # La reduccion de dano conserva al menos un punto por impacto.
if _damage_reduction_timer > 0.0: if _damage_reduction_timer > 0.0:
amount = maxi(1, roundi(amount * (1.0 - clampf(_damage_reduction_fraction, 0.0, 0.95)))) amount = maxi(1, roundi(amount * (1.0 - clampf(_damage_reduction_fraction, 0.0, 0.95))))
current_health = max(current_health - amount, 0) current_health = max(current_health - amount, 0)
invulnerability_timer = invulnerability_duration invulnerability_timer = invulnerability_duration
# Knock the player away from the source. If both centers are aligned, use # Empuja alejandose del origen. Si los centros coinciden, usa la direccion contraria a la mirada.
# the opposite of the current facing direction as a deterministic fallback.
var knockback_direction: float = signf(global_position.x - source_position.x) var knockback_direction: float = signf(global_position.x - source_position.x)
if knockback_direction == 0.0: if knockback_direction == 0.0:
knockback_direction = -facing_direction knockback_direction = -facing_direction
# Enemy variants choose their push independently of HP damage. Existing # Cada enemigo ajusta su empuje sin cambiar el dano. Las llamadas antiguas de dos argumentos conservan su fuerza.
# two-argument calls (hazards, tests) retain the original impulse.
var push_scale: float = clampf(knockback_multiplier, 0.0, 3.0) var push_scale: float = clampf(knockback_multiplier, 0.0, 3.0)
velocity.x = knockback_direction * damage_knockback.x * push_scale velocity.x = knockback_direction * damage_knockback.x * push_scale
velocity.y = -damage_knockback.y * sqrt(push_scale) velocity.y = -damage_knockback.y * sqrt(push_scale)
@@ -770,25 +791,27 @@ func take_damage(amount: int, source_position: Vector2, knockback_multiplier: fl
_die() _die()
## Detiene el especial, emite la muerte y solicita la recarga fuera del paso de fisica.
func _die() -> void: func _die() -> void:
is_dead = true is_dead = true
_special_active = false _special_active = false
feedback_camera.call("start_solo", 0.0) feedback_camera.call("start_solo", 0.0)
died.emit() died.emit()
# Reloading from a deferred call avoids changing the scene tree while a # La recarga se difiere para no destruir el arbol mientras la fisica procesa un contacto.
# physics overlap is still being processed.
call_deferred("_reload_level") call_deferred("_reload_level")
## Reinicia la escena actual; no selecciona ni desbloquea niveles.
func _reload_level() -> void: func _reload_level() -> void:
get_tree().reload_current_scene() get_tree().reload_current_scene()
# ============================================================================ # ============================================================================
# TIMERS AND ANIMATION # TEMPORIZADORES Y ANIMACION
# ============================================================================ # ============================================================================
## Hace caducar ataques, invulnerabilidad y mejoras temporales de forma independiente.
func _update_timers(delta: float) -> void: func _update_timers(delta: float) -> void:
_hurt_animation_timer = maxf(0.0, _hurt_animation_timer - delta) _hurt_animation_timer = maxf(0.0, _hurt_animation_timer - delta)
_landing_animation_timer = maxf(0.0, _landing_animation_timer - delta) _landing_animation_timer = maxf(0.0, _landing_animation_timer - delta)
@@ -800,7 +823,7 @@ func _update_timers(delta: float) -> void:
_speed_boost_timer = max(_speed_boost_timer - delta, 0.0) _speed_boost_timer = max(_speed_boost_timer - delta, 0.0)
else: else:
_speed_boost_multiplier = 0.0 _speed_boost_multiplier = 0.0
# Each effect expires independently; no mutation of the character resource. # Cada mejora caduca por separado; nunca se muta el recurso de personaje.
_damage_boost_timer = maxf(0.0, _damage_boost_timer - delta) _damage_boost_timer = maxf(0.0, _damage_boost_timer - delta)
_air_damage_boost_timer = maxf(0.0, _air_damage_boost_timer - delta) _air_damage_boost_timer = maxf(0.0, _air_damage_boost_timer - delta)
_damage_reduction_timer = maxf(0.0, _damage_reduction_timer - delta) _damage_reduction_timer = maxf(0.0, _damage_reduction_timer - delta)
@@ -815,6 +838,7 @@ func _update_timers(delta: float) -> void:
_jump_boost_multiplier = 0.0 _jump_boost_multiplier = 0.0
## Selecciona la animacion con prioridad de estados; admite conjuntos de animaciones incompletos.
func _update_animation() -> void: func _update_animation() -> void:
var animation_name: StringName = &"idle" var animation_name: StringName = &"idle"
if _special_active: if _special_active:
@@ -837,16 +861,17 @@ func _update_animation() -> void:
elif absf(velocity.x) > 10.0: elif absf(velocity.x) > 10.0:
animation_name = &"walk" animation_name = &"walk"
# Custom CharacterData can still provide a smaller animation set. # Un personaje personalizado puede aportar menos animaciones; se mantiene una alternativa valida.
if not animated_sprite.sprite_frames.has_animation(animation_name): if not animated_sprite.sprite_frames.has_animation(animation_name):
animation_name = &"idle" animation_name = &"idle"
if animated_sprite.animation != animation_name or not animated_sprite.is_playing(): if animated_sprite.animation != animation_name or not animated_sprite.is_playing():
# Finished one-shot animations hold their last frame until the state changes. # Una animacion no repetitiva conserva su ultimo fotograma hasta que cambia el estado.
if animated_sprite.animation == animation_name and animated_sprite.frame > 0: if animated_sprite.animation == animation_name and animated_sprite.frame > 0:
return return
animated_sprite.play(animation_name) animated_sprite.play(animation_name)
## Aplica deformacion y desplazamientos visuales sin alterar el cuerpo fisico.
func _update_visual_feedback() -> void: func _update_visual_feedback() -> void:
if _hurt_animation_timer > 0.10: if _hurt_animation_timer > 0.10:
animated_sprite.self_modulate = Color(1.8, 1.8, 1.8) animated_sprite.self_modulate = Color(1.8, 1.8, 1.8)
@@ -857,9 +882,10 @@ func _update_visual_feedback() -> void:
# ============================================================================ # ============================================================================
# HITBOX SETUP # CONFIGURACION DE AREAS DE ATAQUE
# ============================================================================ # ============================================================================
## Crea formas propias de esta instancia usando las medidas editables del Inspector.
func _setup_attack_hitboxes() -> void: func _setup_attack_hitboxes() -> void:
var punch_shape: RectangleShape2D = RectangleShape2D.new() var punch_shape: RectangleShape2D = RectangleShape2D.new()
punch_shape.size = punch_hitbox_size punch_shape.size = punch_hitbox_size
@@ -878,16 +904,17 @@ func _setup_attack_hitboxes() -> void:
# ============================================================================ # ============================================================================
# DEBUG HITBOX DRAWING # DIBUJO DE COLISIONES PARA DEPURACION
# ============================================================================ # ============================================================================
## Dibuja mensajes y, cuando se solicita, las areas reales de combate.
func _draw() -> void: func _draw() -> void:
if is_on_floor(): if is_on_floor():
draw_rect(Rect2(-14, 24, 28, 3), Color(0.05, 0.06, 0.10, 0.25)) draw_rect(Rect2(-14, 24, 28, 3), Color(0.05, 0.06, 0.10, 0.25))
if ground_pound_active: if ground_pound_active:
for side: float in [-1.0, 1.0]: for side: float in [-1.0, 1.0]:
draw_line(Vector2(17 * side, -30), Vector2(17 * side, -9), Color(1.0, 0.8, 0.45, 0.75), 2.0) draw_line(Vector2(17 * side, -30), Vector2(17 * side, -9), Color(1.0, 0.8, 0.45, 0.75), 2.0)
# Pickup messages remain visible when collision debugging is disabled. # Los mensajes de objetos se muestran aunque este desactivada la depuracion de colisiones.
var font: Font = ThemeDB.get_default_theme().get_font("font", "Label") var font: Font = ThemeDB.get_default_theme().get_font("font", "Label")
if font != null: if font != null:
for entry: Dictionary in _floating_texts: for entry: Dictionary in _floating_texts:
@@ -897,14 +924,14 @@ func _draw() -> void:
if not show_debug_hitboxes: if not show_debug_hitboxes:
return return
# Player hurtbox: always visible and deliberately subtle. # Zona vulnerable del jugador, mostrada con baja opacidad.
_draw_rectangle_collision( _draw_rectangle_collision(
hurtbox_collision, hurtbox_collision,
Color(1.0, 0.08, 0.08, 0.10), Color(1.0, 0.08, 0.08, 0.10),
Color(1.0, 0.08, 0.08, 0.45) Color(1.0, 0.08, 0.08, 0.45)
) )
# Punch: only visible while it can actually deal damage. # El punetazo solo se dibuja mientras puede causar dano.
if punch_timer > 0.0: if punch_timer > 0.0:
_draw_rectangle_collision( _draw_rectangle_collision(
punch_collision, punch_collision,
@@ -913,8 +940,7 @@ func _draw() -> void:
punch_hitbox.position punch_hitbox.position
) )
# Ground pound: show the real damage radius throughout the fall, then make # Muestra el radio real durante la caida y lo resalta brevemente al impactar.
# it stronger for a few frames at the exact impact moment.
if ground_pound_active or ground_pound_debug_timer > 0.0: if ground_pound_active or ground_pound_debug_timer > 0.0:
var pound_fill_alpha: float = 0.14 if ground_pound_active else 0.28 var pound_fill_alpha: float = 0.14 if ground_pound_active else 0.28
var pound_outline_alpha: float = 0.60 if ground_pound_active else 0.95 var pound_outline_alpha: float = 0.60 if ground_pound_active else 0.95
@@ -933,7 +959,7 @@ func _draw() -> void:
2.0 2.0
) )
# Special: show full-screen effect indication. Brighter when fully charged. # Indicador visual del especial, mas intenso con carga completa.
var fill_alpha: float = 0.05 var fill_alpha: float = 0.05
var outline_alpha: float = 0.25 var outline_alpha: float = 0.25
if special_charge >= special_min_use_charge: if special_charge >= special_min_use_charge:
@@ -958,6 +984,7 @@ func _draw() -> void:
## Convierte una forma rectangular local a un rectangulo de depuracion.
func _draw_rectangle_collision( func _draw_rectangle_collision(
collision: CollisionShape2D, collision: CollisionShape2D,
fill_color: Color, fill_color: Color,
+4
View File
@@ -51,6 +51,10 @@ speed_scale = 1.0
[node name="Camera2D" type="Camera2D" parent="." unique_id=902833396] [node name="Camera2D" type="Camera2D" parent="." unique_id=902833396]
zoom = Vector2(2, 2) zoom = Vector2(2, 2)
limit_left = 0
limit_top = 0
limit_right = 4000
limit_bottom = 2500
script = ExtResource("3_camera") script = ExtResource("3_camera")
[node name="PlayerHealthHUD" parent="." unique_id=660684564 instance=ExtResource("5_health_hud")] [node name="PlayerHealthHUD" parent="." unique_id=660684564 instance=ExtResource("5_health_hud")]
+349
View File
@@ -0,0 +1,349 @@
{
"levels/level_01.tscn": {
"World/Floor": {
"position": [
4250.0,
620.0
],
"dimensions": [
8500.0,
40.0
],
"one_way": false
},
"World/Step1": {
"position": [
1530.0,
455.0
],
"dimensions": [
240.0,
20.0
],
"one_way": false
},
"World/High1": {
"position": [
1690.0,
291.0
],
"dimensions": [
180.0,
16.0
],
"one_way": false
},
"World/Step2": {
"position": [
3370.0,
485.0
],
"dimensions": [
240.0,
20.0
],
"one_way": false
},
"World/High2": {
"position": [
3520.0,
338.0
],
"dimensions": [
180.0,
16.0
],
"one_way": false
},
"World/Step3": {
"position": [
5600.0,
455.0
],
"dimensions": [
240.0,
20.0
],
"one_way": false
},
"World/High3": {
"position": [
5750.0,
291.0
],
"dimensions": [
180.0,
16.0
],
"one_way": false
},
"World/Step4": {
"position": [
6890.0,
485.0
],
"dimensions": [
240.0,
20.0
],
"one_way": false
}
},
"levels/level_02.tscn": {
"World/Ground/Street01": {
"position": [
740.0,
1095.0
],
"dimensions": [
1480.0,
500.0
],
"one_way": false
},
"World/Ground/Street02": {
"position": [
2145.0,
1005.0
],
"dimensions": [
1330.0,
500.0
],
"one_way": false
},
"World/Ground/Street03": {
"position": [
3480.0,
1140.0
],
"dimensions": [
1340.0,
500.0
],
"one_way": false
},
"World/Ground/Street04": {
"position": [
4825.0,
1055.0
],
"dimensions": [
1350.0,
500.0
],
"one_way": false
},
"World/Ground/Street05": {
"position": [
6150.0,
950.0
],
"dimensions": [
1300.0,
500.0
],
"one_way": false
},
"World/Ground/Street06": {
"position": [
7440.0,
1125.0
],
"dimensions": [
1280.0,
500.0
],
"one_way": false
},
"World/Ground/Street07": {
"position": [
8720.0,
1035.0
],
"dimensions": [
1280.0,
500.0
],
"one_way": false
},
"World/Ground/Street08": {
"position": [
10180.0,
1095.0
],
"dimensions": [
1640.0,
500.0
],
"one_way": false
},
"World/Walkways/Walkway01": {
"position": [
690.0,
720.0
],
"dimensions": [
270.0,
20.0
],
"one_way": true
},
"World/Walkways/Walkway02": {
"position": [
950.0,
625.0
],
"dimensions": [
230.0,
20.0
],
"one_way": true
},
"World/Walkways/Walkway03": {
"position": [
2135.0,
638.0
],
"dimensions": [
230.0,
20.0
],
"one_way": true
},
"World/Walkways/Walkway04": {
"position": [
3180.0,
775.0
],
"dimensions": [
220.0,
20.0
],
"one_way": true
},
"World/Walkways/Walkway05": {
"position": [
3405.0,
665.0
],
"dimensions": [
190.0,
20.0
],
"one_way": true
},
"World/Walkways/Walkway06": {
"position": [
4720.0,
685.0
],
"dimensions": [
260.0,
20.0
],
"one_way": true
},
"World/Walkways/Walkway07": {
"position": [
5780.0,
585.0
],
"dimensions": [
200.0,
20.0
],
"one_way": true
},
"World/Walkways/Walkway08": {
"position": [
5995.0,
485.0
],
"dimensions": [
190.0,
20.0
],
"one_way": true
},
"World/Walkways/Walkway09": {
"position": [
7360.0,
755.0
],
"dimensions": [
220.0,
20.0
],
"one_way": true
},
"World/Walkways/Walkway10": {
"position": [
8705.0,
655.0
],
"dimensions": [
230.0,
20.0
],
"one_way": true
},
"World/Walkways/Walkway11": {
"position": [
10035.0,
735.0
],
"dimensions": [
270.0,
20.0
],
"one_way": true
},
"World/Barriers/Left": {
"position": [
0.0,
690.0
],
"dimensions": [
60.0,
920.0
],
"one_way": false
},
"World/Barriers/Right": {
"position": [
11000.0,
690.0
],
"dimensions": [
60.0,
920.0
],
"one_way": false
}
},
"levels/test/combat_test.tscn": {
"World/Floor": {
"position": [
585.0,
465.0
],
"dimensions": [
1171.0,
20.0
],
"one_way": false
},
"World/LeftWall": {
"position": [
77.0,
361.0
],
"dimensions": [
136.0,
156.0
],
"one_way": false
}
}
}
+54
View File
@@ -0,0 +1,54 @@
"""Contratos de conexion de la visibilidad de UI; no sustituyen al motor."""
from pathlib import Path
import re
import unittest
ROOT = Path(__file__).resolve().parents[1]
UI_SCENES = {
"ui/hud/player_health_hud.tscn": ".",
"ui/hud/special_charge_hud.tscn": ".",
"ui/mobile_controls/mobile_controls.tscn": ".",
"levels/level_01.tscn": "TestHUD",
"levels/level_02.tscn": "LevelHUD",
}
class EditorUIResourceTests(unittest.TestCase):
def test_each_existing_overlay_has_a_visibility_component(self):
for relative, parent in UI_SCENES.items():
with self.subTest(scene=relative):
text = (ROOT / relative).read_text(encoding="utf-8")
self.assertIn('path="res://ui/editor_ui_visibility.gd"', text)
self.assertIn(
f'[node name="EditorVisibility" type="Node" parent="{parent}"]\n'
'script = ExtResource("editor_ui_visibility")', text,
)
def test_gameplay_ui_scripts_do_not_run_inside_the_editor(self):
for relative in (
"ui/hud/player_health_hud.gd",
"ui/hud/special_charge_hud.gd",
"ui/mobile_controls/mobile_controls.gd",
"player/player.gd",
):
with self.subTest(script=relative):
self.assertNotIn("@tool", (ROOT / relative).read_text(encoding="utf-8"))
def test_component_is_editor_aware_and_does_not_move_ui(self):
text = (ROOT / "ui/editor_ui_visibility.gd").read_text(encoding="utf-8")
self.assertTrue(text.startswith("@tool\n"))
self.assertIn("func _ready() -> void:\n\tset_process(Engine.is_editor_hint())", text)
self.assertIn("edited_scene_root == canvas_layer", text)
self.assertIn("@export var preview_in_editor: bool = false", text)
for property_name in ("position", "offset", "scale", "rotation", "layer"):
self.assertNotRegex(text, rf"canvas_layer\.{property_name}\s*=")
def test_component_does_not_modify_child_visibility(self):
text = (ROOT / "ui/editor_ui_visibility.gd").read_text(encoding="utf-8")
self.assertEqual(re.findall(r"^\s*(\w+)\.visible\s*=", text, re.MULTILINE), ["canvas_layer"])
self.assertNotIn("get_children()", text)
if __name__ == "__main__":
unittest.main()
+47
View File
@@ -0,0 +1,47 @@
extends SceneTree
## Ejecutar despues de importar el proyecto, igual que las otras suites.
## Comprueba restauracion, visibilidad de hijos y ausencia de interferencia al jugar.
## La previsualizacion en el editor se debe comprobar tambien abriendo las escenas.
const VISIBILITY_SCRIPT: Script = preload("res://ui/editor_ui_visibility.gd")
var _failures: int = 0
func _initialize() -> void:
call_deferred("_run")
func _run() -> void:
var canvas_layer := CanvasLayer.new()
canvas_layer.visible = false
var panel := Control.new()
canvas_layer.add_child(panel)
var hidden_message := Label.new()
hidden_message.visible = false
panel.add_child(hidden_message)
var visibility := Node.new()
visibility.set_script(VISIBILITY_SCRIPT)
canvas_layer.add_child(visibility)
root.add_child(canvas_layer)
await process_frame
_check(canvas_layer.visible, "La interfaz debe reaparecer al ejecutar una escena guardada oculta")
_check(panel.is_visible_in_tree(), "Los controles normales deben seguir visibles al jugar")
_check(not hidden_message.visible, "No se deben mostrar mensajes o paneles ocultos individualmente")
_check(not visibility.is_processing(), "El componente no debe procesar cada frame de la partida")
canvas_layer.hide()
visibility.set("preview_in_editor", true)
await process_frame
await process_frame
_check(not canvas_layer.visible, "El juego debe poder ocultar su UI sin que el componente la reactive")
canvas_layer.queue_free()
await process_frame
if _failures == 0:
print("OK EDITOR UI: restauracion, hijos y visibilidad de partida")
quit(0 if _failures == 0 else 1)
func _check(condition: bool, message: String) -> void:
if not condition:
_failures += 1
push_error(message)
+7 -7
View File
@@ -1,6 +1,6 @@
extends SceneTree extends SceneTree
## Real-engine integration checks; Python resource tests do not execute these. ## Pruebas de integracion con el motor real; las pruebas de Python no las ejecutan.
## godot --headless --path . --script res://tests/test_enemy_ai_runtime.gd ## godot --headless --path . --script res://tests/test_enemy_ai_runtime.gd
var _failures: int = 0 var _failures: int = 0
@@ -41,8 +41,8 @@ func _test_safe_start() -> void:
_check(enemies.get_child_count() == 29, "Keep all 29 encounters") _check(enemies.get_child_count() == 29, "Keep all 29 encounters")
_check(is_equal_approx((enemies.get_node("Enemy01") as Node2D).position.x, 1260.0), _check(is_equal_approx((enemies.get_node("Enemy01") as Node2D).position.x, 1260.0),
"First enemy was not relocated") "First enemy was not relocated")
# Notifier callbacks do not run in headless mode. Waking EVERY enemy also # Los avisos de visibilidad no se ejecutan sin ventana. Activar TODOS los enemigos
# proves that a wide window cannot bypass the new proximity check. # tambien comprueba que una ventana ancha no evita el filtro de proximidad.
for node: Node in enemies.get_children(): for node: Node in enemies.get_children():
node.set("is_awake", true) node.set("is_awake", true)
await _frames(90) await _frames(90)
@@ -124,8 +124,8 @@ func _test_damage_and_push() -> void:
_enemy.set("attack_direction", 1.0) _enemy.set("attack_direction", 1.0)
_enemy.call("_set_attack_hitbox_progress", 0.5) _enemy.call("_set_attack_hitbox_progress", 0.5)
await _frames(3) await _frames(3)
# This puts the sweep centre PAST the player. Push must still be away from # El centro del barrido queda MAS ALLA del jugador. El empuje debe alejarlo
# the enemy, not towards it. Exercise the real Area2D overlap path. # del enemigo, no acercarlo. Se prueba el solapamiento real de Area2D.
_enemy.call("_update_attack_damage") _enemy.call("_update_attack_damage")
_check(int(_player.get("current_health")) == 44, "Guard hit must deal six HP") _check(int(_player.get("current_health")) == 44, "Guard hit must deal six HP")
_check(is_equal_approx(_player.velocity.x, 558.0), "Guard must push away with 1.8x horizontal impulse") _check(is_equal_approx(_player.velocity.x, 558.0), "Guard must push away with 1.8x horizontal impulse")
@@ -181,8 +181,8 @@ func _arena(variant: String, floors: Array[Rect2], enemy_position: Vector2,
_enemy.set("show_debug_enemy_info", false) _enemy.set("show_debug_enemy_info", false)
_world.add_child(_enemy) _world.add_child(_enemy)
_enemy.set("is_awake", false) _enemy.set("is_awake", false)
# Settle onto the floor before enabling pursuit. Ground sweep checks use # Apoyar al enemigo antes de activar la persecucion. El barrido utiliza el
# the collision state from move_and_slide(), not merely the spawn position. # estado de colision de move_and_slide(), no solo la posicion de aparicion.
await _frames(10) await _frames(10)
_enemy.set("attack_cooldown_timer", 1000.0) _enemy.set("attack_cooldown_timer", 1000.0)
_enemy.set("is_awake", true) _enemy.set("is_awake", true)
+4 -3
View File
@@ -1,4 +1,4 @@
"""Configuration regressions only; actual physics is tested by the .gd suite.""" """Regresiones de configuracion; la fisica real se comprueba en la suite .gd."""
from pathlib import Path from pathlib import Path
import math import math
import re import re
@@ -67,14 +67,15 @@ class EnemyProfileTests(unittest.TestCase):
self.assertEqual(len({e[0] for e in enemies}), 29) self.assertEqual(len({e[0] for e in enemies}), 29)
first = next(e for e in enemies if e[0] == 'Enemy01') first = next(e for e in enemies if e[0] == 'Enemy01')
self.assertEqual((float(first[2]), float(first[3])), (1260, 811)) self.assertEqual((float(first[2]), float(first[3])), (1260, 811))
# Even with a wide screen waking every notifier, no enemy starts in aggro range. # Ningun enemigo comienza en rango de ataque aunque todos esten visibles.
for name, variant, x, y in enemies: for name, variant, x, y in enemies:
distance = math.hypot(float(x) - 125.0, float(y) - 795.0) distance = math.hypot(float(x) - 125.0, float(y) - 795.0)
self.assertGreater(distance - self.profiles[variant]['aggro_range'], 200.0, name) self.assertGreater(distance - self.profiles[variant]['aggro_range'], 200.0, name)
def test_jumps_can_climb_the_street_steps(self): def test_jumps_can_climb_the_street_steps(self):
heights = [float(y) - 250 for y in re.findall( heights = [float(y) - 250 for y in re.findall(
r'parent="World/Ground"\]\nposition = Vector2\([^,]+, ([^)]+)\)', LEVEL)] r'parent="World/Ground" instance=ExtResource\("kit_ground"\)\]\nposition = Vector2\([^,]+, ([^)]+)\)', LEVEL)]
self.assertEqual(len(heights), 8)
largest_step = max(a - b for a, b in zip(heights, heights[1:])) largest_step = max(a - b for a, b in zip(heights, heights[1:]))
for name in ('pogo_fan', 'rival_guitarist'): for name in ('pogo_fan', 'rival_guitarist'):
jump = self.profiles[name]['jump_velocity'] jump = self.profiles[name]['jump_velocity']
+8 -9
View File
@@ -1,8 +1,7 @@
"""Static checks for the Android item test course (no Godot runtime needed). """Pruebas estaticas del laboratorio de objetos, sin ejecutar Godot.
Run from the project root: python -m unittest discover -s tests -v Ejecutar: python -m unittest discover -s tests -v
These tests check references and test-course configuration, not gameplay. Comprueban referencias y configuracion del recorrido, no la jugabilidad."""
"""
from pathlib import Path from pathlib import Path
import re import re
@@ -20,7 +19,7 @@ class Level01ConfigurationTests(unittest.TestCase):
cls.resources = dict( cls.resources = dict(
re.findall(r'\[ext_resource [^\n]*path="res://([^"]+)" id="([^"]+)"\]', cls.scene) re.findall(r'\[ext_resource [^\n]*path="res://([^"]+)" id="([^"]+)"\]', cls.scene)
) )
# Format is path -> id; invert to follow ExtResource("item_N"). # El formato es ruta -> id; invertirlo para resolver ExtResource("item_N").
cls.by_id = {resource_id: path for path, resource_id in cls.resources.items()} cls.by_id = {resource_id: path for path, resource_id in cls.resources.items()}
cls.stations = re.findall( cls.stations = re.findall(
r'\[node name="Station(\d{2})" parent="TestEnemies" instance=ExtResource\("(v\d+)"\)\]' r'\[node name="Station(\d{2})" parent="TestEnemies" instance=ExtResource\("(v\d+)"\)\]'
@@ -50,9 +49,9 @@ class Level01ConfigurationTests(unittest.TestCase):
xs = [float(station[2]) for station in self.stations] xs = [float(station[2]) for station in self.stations]
self.assertEqual(xs, sorted(xs)) self.assertEqual(xs, sorted(xs))
self.assertTrue(all(0 <= x <= 8500 for x in xs)) self.assertTrue(all(0 <= x <= 8500 for x in xs))
self.assertIn("size = Vector2(8500, 40)", self.scene) self.assertIn("dimensions = Vector2(8500, 40)", self.scene)
self.assertIn("position = Vector2(8180, 535)", self.scene) self.assertIn("position = Vector2(8180, 535)", self.scene)
self.assertIn("camera.limit_right = LEVEL_WIDTH", (ROOT / "levels/level_01.gd").read_text()) self.assertIn("camera_bounds = Rect2(0, 0, 8500, 2500)", self.scene)
def test_finish_and_death_areas_detect_player_layer(self): def test_finish_and_death_areas_detect_player_layer(self):
for area in ("FinishZone", "DeathZone"): for area in ("FinishZone", "DeathZone"):
@@ -74,8 +73,8 @@ class Level01ConfigurationTests(unittest.TestCase):
self.assertTrue(len(root) > 20, svg.name) self.assertTrue(len(root) > 20, svg.name)
def test_control_pickup_and_death_tracking_are_separate(self): def test_control_pickup_and_death_tracking_are_separate(self):
# The independent control object distinguishes a rendering fault from # El objeto de control permite distinguir un fallo de dibujo de uno de
# a death/drop fault without relying on running the Python test in Godot. # muerte/recompensa, sin pretender que esta prueba de Python ejecute Godot.
self.assertIn('name="ControlPickup"', self.scene) self.assertIn('name="ControlPickup"', self.scene)
self.assertIn('pickup_data = ExtResource("lab_control")', self.scene) self.assertIn('pickup_data = ExtResource("lab_control")', self.scene)
self.assertTrue((ROOT / 'pickups/data/lab_control.tres').is_file()) self.assertTrue((ROOT / 'pickups/data/lab_control.tres').is_file())
+21 -23
View File
@@ -1,8 +1,7 @@
"""Fast, engine-independent checks of the Level 02 alpha route. """Pruebas rapidas de los recursos del recorrido de Level02, sin motor.
Run: python -m unittest discover -s tests -v Ejecutar: python -m unittest discover -s tests -v
A Godot playtest is still needed for physics, importing, and Android controls. La fisica, importacion y controles de Android requieren pruebas con Godot."""
"""
from pathlib import Path from pathlib import Path
import re import re
@@ -12,6 +11,7 @@ import struct
ROOT = Path(__file__).resolve().parents[1] ROOT = Path(__file__).resolve().parents[1]
LEVEL = (ROOT / "levels/level_02.tscn").read_text(encoding="utf-8") LEVEL = (ROOT / "levels/level_02.tscn").read_text(encoding="utf-8")
SCRIPT = (ROOT / "levels/level_02.gd").read_text(encoding="utf-8") SCRIPT = (ROOT / "levels/level_02.gd").read_text(encoding="utf-8")
BACKGROUND = (ROOT / "world/backgrounds/city_background.tscn").read_text(encoding="utf-8")
class Level02ResourceTests(unittest.TestCase): class Level02ResourceTests(unittest.TestCase):
@@ -30,34 +30,31 @@ class Level02ResourceTests(unittest.TestCase):
width, height = struct.unpack(">II", content[16:24]) width, height = struct.unpack(">II", content[16:24])
self.assertGreater(width, 15) self.assertGreater(width, 15)
self.assertGreater(height, 15) self.assertGreater(height, 15)
self.assertEqual(LEVEL.count('type="Parallax2D"'), 4) self.assertEqual(BACKGROUND.count('type="Parallax2D"'), 4)
self.assertEqual(LEVEL.count('repeat_size = Vector2(1024, 0)'), 4) self.assertEqual(BACKGROUND.count('repeat_size = Vector2(1024, 0)'), 4)
self.assertIn('autoscroll = Vector2(3, 0)', LEVEL) self.assertIn('autoscroll = Vector2(3, 0)', BACKGROUND)
self.assertIn('texture_repeat = 2', LEVEL) self.assertIn('texture_repeat = 2', LEVEL)
def test_road_is_continuous_and_has_end_walls(self): def test_road_is_continuous_and_has_end_walls(self):
widths = [float(w) for w in re.findall( # Las instancias conservan los mismos centros y medidas del suelo original.
r'\[sub_resource type="RectangleShape2D" id="Ground\d+"\]\nsize = Vector2\((\d+), 500\)', LEVEL
)]
# Each section uses a native CollisionShape2D with its own width.
sections = re.findall( sections = re.findall(
r'\[node name="Street\d+" type="CollisionShape2D" parent="World/Ground"\]\n' r'\[node name="Street\d+" parent="World/Ground" instance=ExtResource\("kit_ground"\)\]\s*'
r'position = Vector2\((\d+(?:\.\d+)?), (\d+(?:\.\d+)?)\)\n' r'position = Vector2\(([^,]+), ([^)]+)\)\s*'
r'shape = SubResource\("Ground\d+"\)', LEVEL, r'dimensions = Vector2\(([^,]+), ([^)]+)\)', LEVEL,
) )
self.assertEqual(len(sections), 8) self.assertEqual(len(sections), 8)
self.assertEqual(len(widths), len(sections)) left_edge = 0.0
left_edge = 0
tops = [] tops = []
for w, (center,y) in zip(widths, sections): for center, y, width, height in sections:
self.assertEqual(float(center) - w / 2, left_edge) center, y, width, height = map(float, (center, y, width, height))
left_edge += w self.assertEqual(center - width / 2, left_edge)
tops.append(float(y) - 250.0) left_edge += width
tops.append(y - height / 2)
self.assertEqual(left_edge, 11000) self.assertEqual(left_edge, 11000)
self.assertTrue(all(a-b <= 110 for a,b in zip(tops, tops[1:])), tops) self.assertTrue(all(a-b <= 110 for a,b in zip(tops, tops[1:])), tops)
for name in ('Left', 'Right'): for name in ('Left', 'Right'):
self.assertRegex(LEVEL, rf'\[node name="{name}" type="CollisionShape2D" parent="World/Barriers"\]') self.assertIn(f'[node name="{name}" parent="World/Barriers" instance=ExtResource("kit_wall")]', LEVEL)
self.assertIn('camera.limit_right = WORLD_WIDTH', SCRIPT) self.assertIn('camera_bounds = Rect2(0, 0, 11000, 1280)', LEVEL)
self.assertIn('collision_mask = 2', LEVEL) self.assertIn('collision_mask = 2', LEVEL)
def test_multiple_encounters_and_optional_items(self): def test_multiple_encounters_and_optional_items(self):
@@ -66,7 +63,8 @@ class Level02ResourceTests(unittest.TestCase):
self.assertEqual(len(enemies), 29) self.assertEqual(len(enemies), 29)
self.assertEqual(len(set(enemies)), 5) self.assertEqual(len(set(enemies)), 5)
self.assertEqual(len(pickups), 14) self.assertEqual(len(pickups), 14)
self.assertEqual(LEVEL.count('one_way_collision = true'), 11) self.assertEqual(LEVEL.count('instance=ExtResource("kit_platform")'), 11)
self.assertIn('one_way = true', (ROOT / 'world/terrain/platform.tscn').read_text())
self.assertIn('run/main_scene="res://levels/level_02.tscn"', (ROOT / 'project.godot').read_text()) self.assertIn('run/main_scene="res://levels/level_02.tscn"', (ROOT / 'project.godot').read_text())
self.assertIn('respawn_delay = 0.0', (ROOT / 'enemies/variants/roadie.tscn').read_text()) self.assertIn('respawn_delay = 0.0', (ROOT / 'enemies/variants/roadie.tscn').read_text())
+3 -3
View File
@@ -1,7 +1,7 @@
extends SceneTree extends SceneTree
## Godot integration smoke test. Engine required; not covered by Python tests. ## Comprobacion basica de integracion en Godot; no la ejecutan las pruebas de Python.
## Run after importing assets: godot --headless --path . --script res://tests/test_level_02_runtime.gd ## Ejecutar despues de importar los recursos: godot --headless --path . --script res://tests/test_level_02_runtime.gd
func _initialize() -> void: func _initialize() -> void:
@@ -53,7 +53,7 @@ func _run() -> void:
return return
for name: String in ["Sky", "HighClouds", "FarBuildings", "NearBuildings"]: for name: String in ["Sky", "HighClouds", "FarBuildings", "NearBuildings"]:
var layer: Parallax2D = level.get_node(name) as Parallax2D var layer: Parallax2D = level.get_node("CityBackground/" + name) as Parallax2D
if layer == null or layer.repeat_size.x != 1024: if layer == null or layer.repeat_size.x != 1024:
_fail("Falta la capa de parallax repetible: " + name) _fail("Falta la capa de parallax repetible: " + name)
return return
+112
View File
@@ -0,0 +1,112 @@
"""Contratos de recursos y geometria. No sustituyen a las pruebas dentro de Godot."""
from pathlib import Path
import json
import re
import unittest
from xml.etree import ElementTree
ROOT = Path(__file__).resolve().parents[1]
def sections(text: str) -> list[str]:
"""Separa las secciones textuales del formato de escenas, sin interpretar GDScript."""
return [part for part in re.split(r"(?=^\[)", text, flags=re.MULTILINE) if part.strip()]
def vector_property(block: str, name: str) -> list[float]:
match = re.search(rf"^{name} = Vector2\(([^,]+), ([^)]+)\)", block, re.MULTILINE)
if match is None:
raise AssertionError(f"Missing {name} in {block}")
return [float(match[1]), float(match[2])]
class LevelKitResourceTests(unittest.TestCase):
def test_every_own_resource_reference_resolves(self):
for extension in ("*.tscn", "*.tres"):
for path in ROOT.rglob(extension):
if "addons" in path.parts or ".godot" in path.parts:
continue
text = path.read_text(encoding="utf-8")
for relative in re.findall(r'path="res://([^"]+)"', text):
self.assertTrue((ROOT / relative).is_file(), (path, relative))
for kind, declaration in (("ExtResource", "ext_resource"), ("SubResource", "sub_resource")):
defined = re.findall(rf'^\[{declaration} [^\n]*id="([^"]+)"', text, re.MULTILINE)
self.assertEqual(len(defined), len(set(defined)), path)
for used in re.findall(rf'{kind}\("([^"]+)"\)', text):
self.assertIn(used, defined, (path, kind, used))
def test_legacy_geometry_has_identical_positions_sizes_and_one_way_flags(self):
fixtures = json.loads((ROOT / "tests/fixtures/legacy_level_geometry.json").read_text())
for relative, expected in fixtures.items():
nodes = {}
for block in sections((ROOT / relative).read_text(encoding="utf-8")):
match = re.match(r'\[node name="([^"]+)" parent="(World[^"]*)" instance=ExtResource\("kit_([^"]+)"\)\]', block)
if match:
name, parent, preset = match.groups()
preset_text = (ROOT / f"world/terrain/{preset}.tscn").read_text()
nodes[parent + "/" + name] = {
"position": vector_property(block, "position"),
"dimensions": vector_property(block, "dimensions"),
"one_way": "one_way = true" in preset_text,
}
self.assertEqual(nodes, expected, relative)
def test_levels_no_longer_render_their_terrain(self):
for relative in ("levels/level_01.gd", "levels/level_02.gd"):
text = (ROOT / relative).read_text()
self.assertNotIn("func _draw()", text)
self.assertIn("extends LevelRoot", text)
self.assertIn("Engine.is_editor_hint()", text)
def test_camera_has_no_hidden_runtime_limits(self):
camera = (ROOT / "player/camera_2d.gd").read_text()
self.assertNotRegex(camera, r"limit_(left|top|right|bottom)\s*=")
level = (ROOT / "levels/level_root.gd").read_text()
self.assertIn("camera_bounds", level)
self.assertIn('get_node_or_null("Player")', level)
def test_template_and_example_are_playable_scenes_not_generators(self):
for relative in ("levels/templates/level_template.tscn", "levels/examples/scenery_catalog.tscn"):
text = (ROOT / relative).read_text()
self.assertIn('path="res://levels/level_root.gd"', text)
self.assertIn('[node name="Player" parent="." instance=', text)
for container in ("World", "Scenery", "Signs", "Enemies", "Items", "Triggers"):
self.assertIn(f'[node name="{container}" type="Node2D" parent="."]', text)
self.assertIn('run/main_scene="res://levels/level_02.tscn"', (ROOT / "project.godot").read_text())
def test_all_seventeen_collectibles_have_drag_ready_variants(self):
variants = sorted((ROOT / "pickups/variants").glob("*.tscn"))
self.assertEqual(len(variants), 17)
assigned = set()
for path in variants:
text = path.read_text()
self.assertIn('pickup_data = ExtResource("data")', text)
assigned.add(re.search(r'path="res://(pickups/data/[^"]+)"', text)[1])
expected = {str(path.relative_to(ROOT)) for path in (ROOT / "pickups/data").glob("*.tres") if path.stem != "lab_control"}
self.assertEqual(assigned, expected)
def test_preview_code_guards_runtime_and_keeps_shapes_per_instance(self):
pickup = (ROOT / "pickups/pickup.gd").read_text()
self.assertTrue(pickup.startswith("@tool\n"))
self.assertRegex(pickup, r"func _physics_process\([^\n]+\n\tif Engine.is_editor_hint\(\):\n\t\treturn")
for relative in ("world/terrain/terrain_piece.gd", "world/props/scenery_prop.gd"):
text = (ROOT / relative).read_text()
self.assertTrue(text.startswith("@tool\n"))
self.assertIn("RectangleShape2D.new()", text)
self.assertIn("collision_enabled", text)
self.assertNotIn("func _process(", text)
def test_prop_art_is_self_contained_and_valid_svg(self):
assets = sorted((ROOT / "assets/props").glob("*.svg"))
self.assertEqual(len(assets), 7)
for asset in assets:
root = ElementTree.parse(asset).getroot()
self.assertEqual(root.attrib["shape-rendering"], "crispEdges")
self.assertFalse(list(root.iter("{http://www.w3.org/2000/svg}image")))
self.assertGreater(int(root.attrib["width"]), 0)
self.assertGreater(int(root.attrib["height"]), 0)
if __name__ == "__main__":
unittest.main()
+185
View File
@@ -0,0 +1,185 @@
extends SceneTree
## Pruebas reales de instanciacion, independencia, actualizacion y fisica.
## Ejecutar tras importar: godot --headless --path . --script res://tests/test_level_kit_runtime.gd
## Estas pruebas NO se ejecutan mediante unittest de Python.
var _failures: int = 0
func _initialize() -> void:
call_deferred("_run")
func _run() -> void:
await _verify_terrain()
await _verify_props_and_signs()
await _verify_one_way_physics()
await _verify_presets()
await _verify_levels()
if _failures == 0:
print("OK LEVEL KIT: superficies, independencia, props, carteles, one-way, presets y niveles")
quit(0 if _failures == 0 else 1)
## Un cambio de tamano no debe alterar otras instancias ni separar arte y fisica.
func _verify_terrain() -> void:
var packed: PackedScene = load("res://world/terrain/ground.tscn") as PackedScene
var first: TerrainPiece = packed.instantiate() as TerrainPiece
var second: TerrainPiece = packed.instantiate() as TerrainPiece
root.add_child(first)
root.add_child(second)
first.dimensions = Vector2(736.0, 160.0)
await process_frame
await process_frame
var first_shape: RectangleShape2D = first.get_node("CollisionShape2D").shape as RectangleShape2D
var second_shape: RectangleShape2D = second.get_node("CollisionShape2D").shape as RectangleShape2D
_check(first_shape != second_shape, "Las formas fisicas no pueden compartirse entre instancias")
_check(first_shape.size == Vector2(736.0, 160.0), "La colision debe seguir Dimensions")
_check(second_shape.size == Vector2(512.0, 256.0), "Editar una pieza no debe redimensionar otra")
_check((first.get_node("Texture") as Sprite2D).region_rect.size == first.dimensions, "La textura debe seguir Dimensions")
_check((first.get_node("Top") as Sprite2D).position == -first.dimensions * 0.5, "El borde superior debe conservar su anclaje")
first.collision_enabled = false
await process_frame
await process_frame
_check(first.collision_layer == 0 and (first.get_node("CollisionShape2D") as CollisionShape2D).disabled, "Una superficie decorativa no debe bloquear")
_check(second.collision_layer == 1, "Desactivar una pieza no debe afectar a la otra")
first.queue_free()
second.queue_free()
await process_frame
## Colision y profundidad son independientes; el texto pertenece a cada cartel.
func _verify_props_and_signs() -> void:
var packed: PackedScene = load("res://world/props/barrel.tscn") as PackedScene
var barrel: SceneryProp = packed.instantiate() as SceneryProp
var other: SceneryProp = packed.instantiate() as SceneryProp
root.add_child(barrel)
root.add_child(other)
barrel.draw_layer = 10
barrel.collision_dimensions = Vector2(40.0, 60.0)
await process_frame
await process_frame
_check(barrel.z_index == 10, "El barril debe poder dibujarse delante")
_check((barrel.get_node("Body") as StaticBody2D).collision_layer == 1, "Cambiar profundidad no debe eliminar colision")
var shape: RectangleShape2D = barrel.get_node("Body/CollisionShape2D").shape as RectangleShape2D
var other_shape: RectangleShape2D = other.get_node("Body/CollisionShape2D").shape as RectangleShape2D
_check(shape != other_shape and other_shape.size == Vector2(54.0, 76.0), "Las colisiones de decoracion deben ser independientes")
barrel.collision_enabled = false
await process_frame
await process_frame
_check((barrel.get_node("Body") as StaticBody2D).collision_layer == 0, "El barril decorativo debe atravesarse")
_check(barrel.z_index == 10, "Desactivar colision no debe cambiar profundidad")
var sign_scene: PackedScene = load("res://world/signs/sign_post.tscn") as PackedScene
var sign: Node2D = sign_scene.instantiate() as Node2D
root.add_child(sign)
sign.set("text", "TEST\nSECOND LINE")
sign.set("font_size", 18)
await process_frame
await process_frame
var label: Label = sign.get_node("Text") as Label
_check(label.text == "TEST\nSECOND LINE", "El cartel debe mostrar el texto editado")
_check(label.get_theme_font_size("font_size") == 18, "El cartel debe actualizar el tamano de letra")
sign.queue_free()
barrel.queue_free()
other.queue_free()
await process_frame
## Comprueba el comportamiento de la fisica, no solo el flag guardado en la escena.
func _verify_one_way_physics() -> void:
var packed: PackedScene = load("res://world/terrain/platform.tscn") as PackedScene
var platform: TerrainPiece = packed.instantiate() as TerrainPiece
platform.position = Vector2(300.0, 100.0)
root.add_child(platform)
var body := CharacterBody2D.new()
body.position = Vector2(300.0, 170.0)
body.collision_layer = 2
body.collision_mask = 1
var collision := CollisionShape2D.new()
var shape := RectangleShape2D.new()
shape.size = Vector2(20.0, 20.0)
collision.shape = shape
body.add_child(collision)
root.add_child(body)
await physics_frame
await physics_frame
# La velocidad depende del paso de fisica del motor; no se cambia su configuracion.
var frames: int = ceili(float(Engine.physics_ticks_per_second) * 0.5)
for _frame: int in range(frames):
await physics_frame
body.velocity = Vector2(0.0, -300.0)
body.move_and_slide()
_check(body.position.y < 70.0, "La plataforma debe atravesarse desde abajo")
for _frame: int in range(frames):
await physics_frame
body.velocity = Vector2(0.0, 300.0)
body.move_and_slide()
_check(body.is_on_floor(), "El cuerpo debe aterrizar sobre la plataforma")
_check(absf(body.position.y - 80.0) < 2.0, "El aterrizaje debe coincidir con la cara superior")
body.queue_free()
platform.queue_free()
await process_frame
## Carga recursivamente las piezas y verifica que los objetos tengan icono real.
func _verify_presets() -> void:
for path: String in _scene_paths("res://world") + _scene_paths("res://pickups/variants"):
var packed: PackedScene = load(path) as PackedScene
_check(packed != null, "No se pudo cargar " + path)
if packed == null:
continue
var instance: Node = packed.instantiate()
root.add_child(instance)
await process_frame
if instance is Pickup:
_check((instance as Pickup).pickup_data != null, "Objeto sin datos: " + path)
_check((instance.get_node("Sprite2D") as Sprite2D).texture != null, "Objeto sin icono: " + path)
instance.queue_free()
await process_frame
## F6 debe funcionar sin un menu o singleton que inicialice antes el escenario.
func _verify_levels() -> void:
for path: String in [
"res://levels/templates/level_template.tscn",
"res://levels/examples/scenery_catalog.tscn",
"res://levels/level_01.tscn",
"res://levels/level_02.tscn",
]:
var packed: PackedScene = load(path) as PackedScene
_check(packed != null, "No se pudo cargar el nivel " + path)
if packed == null:
continue
var level: LevelRoot = packed.instantiate() as LevelRoot
root.add_child(level)
current_scene = level
await physics_frame
await physics_frame
var camera: Camera2D = level.get_node("Player/Camera2D") as Camera2D
_check(camera.limit_right == ceili(level.camera_bounds.end.x), "La camara debe respetar Camera Bounds en " + path)
if path.ends_with("level_template.tscn"):
var player: CharacterBody2D = level.get_node("Player") as CharacterBody2D
for _frame: int in range(6):
await physics_frame
_check(player.is_on_floor(), "El jugador de la plantilla debe comenzar apoyado en el suelo")
current_scene = null
level.queue_free()
await process_frame
func _scene_paths(folder: String) -> Array[String]:
var result: Array[String] = []
for file_name: String in DirAccess.get_files_at(folder):
if file_name.ends_with(".tscn"):
result.append(folder.path_join(file_name))
for directory: String in DirAccess.get_directories_at(folder):
result.append_array(_scene_paths(folder.path_join(directory)))
return result
func _check(condition: bool, message: String) -> void:
if not condition:
_failures += 1
push_error("Level Kit: " + message)
+4 -5
View File
@@ -1,9 +1,8 @@
"""Validate Godot pickup resources before exporting Android. """Valida recursos de objetos antes de exportar a Android.
Godot's serialized .tres files only accept Color(r, g, b, a) with numeric Los archivos .tres utilizan Color(r, g, b, a) con argumentos numericos.
arguments. The GDScript syntax Color("#hex") is *not* valid here and caused La forma de GDScript Color("#hex") no se utiliza en estos datos serializados;
all item data to fail to load (white squares named "Item"). la regresion original impedia cargar los objetos y mostraba cuadros blancos."""
"""
from pathlib import Path from pathlib import Path
import re import re
+12 -12
View File
@@ -2,8 +2,8 @@ extends SceneTree
const PICKUP_SCENE: PackedScene = preload("res://pickups/pickup.tscn") const PICKUP_SCENE: PackedScene = preload("res://pickups/pickup.tscn")
## Full Godot integration test. Requires the real engine and imported SVGs. ## Prueba de integracion en Godot. Requiere el motor real y los SVG importados.
## Run: godot --headless --path . --script res://tests/test_pickup_runtime.gd ## Ejecutar: godot --headless --path . --script res://tests/test_pickup_runtime.gd
func _initialize() -> void: func _initialize() -> void:
@@ -26,7 +26,7 @@ func _run() -> void:
_fail("No se esta ejecutando level_01.gd") _fail("No se esta ejecutando level_01.gd")
return return
# The pre-placed control pickup must work even without any enemy death. # El objeto de control colocado en la escena debe funcionar sin muertes enemigas.
var control: Pickup = level.get_node("ControlPickup") as Pickup var control: Pickup = level.get_node("ControlPickup") as Pickup
if control == null or control.pickup_data == null or control.pickup_data.id != &"lab_control": if control == null or control.pickup_data == null or control.pickup_data.id != &"lab_control":
_fail("El pickup de control no se instancio") _fail("El pickup de control no se instancio")
@@ -41,8 +41,8 @@ func _run() -> void:
_fail("Un objeto fijo debe ser recogible desde el primer instante") _fail("Un objeto fijo debe ser recogible desde el primer instante")
return return
# Test a real collision, not a direct call to collect_pickup(). This used # Probar una colision real, no una llamada directa a collect_pickup(). Antes
# to fail when monitoring was disabled while the player ran past the item. # fallaba al pasar corriendo junto al objeto con la deteccion desactivada.
var player: CharacterBody2D = level.get_node("Player") as CharacterBody2D var player: CharacterBody2D = level.get_node("Player") as CharacterBody2D
player.global_position = control.global_position player.global_position = control.global_position
await physics_frame await physics_frame
@@ -58,8 +58,8 @@ func _run() -> void:
_fail("El objeto de control no debe contar entre los 17 drops") _fail("El objeto de control no debe contar entre los 17 drops")
return return
# Touch a dropped speed item while the 0.75-second collection delay is # Tocar un objeto de velocidad durante los 0,75 segundos de espera para
# running, then move away as if running through it. It must not be lost. # recogerlo y alejarse como al pasar corriendo. No debe perderse la recogida.
var base_speed: float = float(player.call("get_move_speed")) var base_speed: float = float(player.call("get_move_speed"))
var speed_drop: Pickup = PICKUP_SCENE.instantiate() as Pickup var speed_drop: Pickup = PICKUP_SCENE.instantiate() as Pickup
speed_drop.pickup_data = load("res://pickups/data/coffee.tres") as PickupData speed_drop.pickup_data = load("res://pickups/data/coffee.tres") as PickupData
@@ -79,7 +79,7 @@ func _run() -> void:
_fail("El Tostado del Averno no ha aumentado la velocidad un 25%%") _fail("El Tostado del Averno no ha aumentado la velocidad un 25%%")
return return
# The multiplier must affect actual horizontal movement, not just a label. # El multiplicador debe afectar al movimiento real, no solo a una etiqueta.
Input.action_press("move_right") Input.action_press("move_right")
await create_timer(0.3).timeout await create_timer(0.3).timeout
Input.action_release("move_right") Input.action_release("move_right")
@@ -90,8 +90,8 @@ func _run() -> void:
player.global_position = Vector2(170, 557) player.global_position = Vector2(170, 557)
await create_timer(0.15).timeout await create_timer(0.15).timeout
# A full-health heal should stay on the floor, then get collected without # Una cura con la vida llena debe seguir en el suelo y recogerse al perder
# requiring a second body_entered signal when HP decreases in place. # vida sin exigir una segunda senal body_entered ni salir del solapamiento.
var heal_pickup: Pickup = PICKUP_SCENE.instantiate() as Pickup var heal_pickup: Pickup = PICKUP_SCENE.instantiate() as Pickup
heal_pickup.pickup_data = load("res://pickups/data/beer.tres") as PickupData heal_pickup.pickup_data = load("res://pickups/data/beer.tres") as PickupData
heal_pickup.position = player.position heal_pickup.position = player.position
@@ -122,8 +122,8 @@ func _run() -> void:
return return
expected_ids[data.id] = true expected_ids[data.id] = true
# Simulate a missed signal for station 01. The polling of is_dead must # Simular la perdida de una senal de la estacion 01. Consultar is_dead debe
# still register its KO and create the guaranteed drop. # permitir registrar la derrota y crear la recompensa garantizada.
var lab_callback: Callable = Callable(level, "_on_station_enemy_died") var lab_callback: Callable = Callable(level, "_on_station_enemy_died")
enemies[0].disconnect(&"died", lab_callback) enemies[0].disconnect(&"died", lab_callback)
for enemy in enemies: for enemy in enemies:
+3 -3
View File
@@ -1,4 +1,4 @@
"""Engine-independent checks. Run: python -m unittest discover -s tests -v.""" """Pruebas sin motor: python -m unittest discover -s tests -v."""
from pathlib import Path from pathlib import Path
import math import math
import re import re
@@ -45,8 +45,8 @@ class PixelCombatResourceTests(unittest.TestCase):
self.assertTrue((ROOT / path).is_file(), path) self.assertTrue((ROOT / path).is_file(), path)
def test_pulse_rounding_preserves_the_damage_budget(self): def test_pulse_rounding_preserves_the_damage_budget(self):
# Mathematical invariant used by the GDScript cumulative damage formula. # Invariante matematica de la formula de dano acumulado de GDScript.
# Runtime behaviour is covered separately by test_pixel_combat_runtime.gd. # test_pixel_combat_runtime.gd comprueba por separado el comportamiento real.
for total in range(1, 101): for total in range(1, 101):
for count in range(1, 9): for count in range(1, 9):
dealt = 0 dealt = 0
+6 -6
View File
@@ -1,8 +1,8 @@
extends SceneTree extends SceneTree
## Run after importing assets: ## Ejecutar despues de importar los recursos:
## godot --headless --path . --script res://tests/test_pixel_combat_runtime.gd ## godot --headless --path . --script res://tests/test_pixel_combat_runtime.gd
## Tests actual scene instantiation, pulse damage, death lifecycle and respawn. ## Comprueba instanciacion real, dano por pulsos, ciclo de muerte y reaparicion.
var _failures: int = 0 var _failures: int = 0
var _death_signals: int = 0 var _death_signals: int = 0
@@ -38,7 +38,7 @@ func _run() -> void:
_check(sprite.sprite_frames.get_frame_texture(animation, index) != null, _check(sprite.sprite_frames.get_frame_texture(animation, index) != null,
"Missing texture in " + str(animation)) "Missing texture in " + str(animation))
# Keep positions fixed, so pulse falloff and screen clipping are deterministic. # Mantener posiciones fijas para que la atenuacion y el recorte sean deterministas.
player.set_physics_process(false) player.set_physics_process(false)
for node: Node in get_nodes_in_group("enemy"): for node: Node in get_nodes_in_group("enemy"):
node.set_physics_process(false) node.set_physics_process(false)
@@ -90,7 +90,7 @@ func _run() -> void:
_check(_death_signals == 1, "Death signal must fire once") _check(_death_signals == 1, "Death signal must fire once")
enemy.call("take_damage", 1000, player.global_position) enemy.call("take_damage", 1000, player.global_position)
_check(_death_signals == 1, "Repeated hits must not produce another death") _check(_death_signals == 1, "Repeated hits must not produce another death")
_check(int(player.get("special_charge")) == mini(100, charge_before_death + 25), _check(int(player.get("special_charge")) == mini(int(player.get("special_max_charge")), charge_before_death + int(player.get("special_charge_per_kill"))),
"Death must grant special charge exactly once") "Death must grant special charge exactly once")
enemy.call("_update_death_animation", 0.20) enemy.call("_update_death_animation", 0.20)
var enemy_visual: Sprite2D = enemy.get_node("Visual") as Sprite2D var enemy_visual: Sprite2D = enemy.get_node("Visual") as Sprite2D
@@ -104,7 +104,7 @@ func _run() -> void:
_check(is_zero_approx(enemy_visual.rotation) and is_equal_approx(enemy_visual.self_modulate.a, 1.0), _check(is_zero_approx(enemy_visual.rotation) and is_equal_approx(enemy_visual.self_modulate.a, 1.0),
"Respawn must restore the sprite transform and opacity") "Respawn must restore the sprite transform and opacity")
# Shape query uses the new landing position, with combat shapes restored. # La consulta de forma usa la posicion de aterrizaje y las colisiones restauradas.
enemy.global_position = player.global_position + Vector2(30, 0) enemy.global_position = player.global_position + Vector2(30, 0)
enemy.set("max_health", 50) enemy.set("max_health", 50)
enemy.set("current_health", 50) enemy.set("current_health", 50)
@@ -115,7 +115,7 @@ func _run() -> void:
player.call("_ground_pound_impact") player.call("_ground_pound_impact")
_check(int(enemy.get("current_health")) == 38, "High ground pound must deal exactly 12 damage") _check(int(enemy.get("current_health")) == 38, "High ground pound must deal exactly 12 damage")
# Exercise effect processing/cleanup, not just resource loading. # Probar el procesamiento y la limpieza de efectos, no solo la carga de recursos.
await create_timer(0.8).timeout await create_timer(0.8).timeout
if _failures == 0: if _failures == 0:
print("OK PIXEL COMBAT: animations, solo pulses, recoil, death, rewards, respawn and ground pound") print("OK PIXEL COMBAT: animations, solo pulses, recoil, death, rewards, respawn and ground pound")
+88
View File
@@ -0,0 +1,88 @@
"""Contratos estaticos del HUD y su parche; no sustituyen la ejecucion en Godot."""
from pathlib import Path
import math
import re
import unittest
import xml.etree.ElementTree as ET
ROOT = Path(__file__).resolve().parents[1]
SCENES = ("ui/hud/player_health_hud.tscn", "ui/hud/special_charge_hud.tscn")
class ThrashHUDResourceTests(unittest.TestCase):
def test_shared_resources_exist_and_load_steps_match(self):
for relative in (*SCENES, "ui/hud/thrash_hud_theme.tres"):
with self.subTest(resource=relative):
text = (ROOT / relative).read_text(encoding="utf-8")
for path in re.findall(r'path="res://([^"]+)"', text):
self.assertTrue((ROOT / path).is_file(), path)
steps = int(re.search(r"load_steps=(\d+)", text).group(1))
self.assertEqual(steps, 1 + len(re.findall(r"^\[(?:ext|sub)_resource ", text, re.M)))
def test_hud_controls_do_not_capture_mouse_or_touch(self):
for relative in SCENES:
for block in re.split(r"(?=^\[node )", (ROOT / relative).read_text(), flags=re.M):
if re.match(r'\[node .*type="(?:Control|Label|TextureRect|ProgressBar)"', block):
self.assertIn("mouse_filter = 2", block, (relative, block.splitlines()[0]))
def test_visual_only_script_is_the_shared_meter(self):
script = (ROOT / "ui/hud/thrash_meter.gd").read_text()
self.assertTrue(script.startswith("@tool\nclass_name ThrashMeter\nextends ProgressBar\n"))
self.assertIn("Engine.is_editor_hint()", script)
self.assertIn("@export var animations_enabled: bool = true", script)
self.assertNotIn("take_damage(", script)
self.assertNotIn("Input.", script)
for relative in SCENES:
scene = (ROOT / relative).read_text()
self.assertIn('path="res://ui/hud/thrash_meter.gd"', scene)
self.assertIn('path="res://ui/hud/thrash_hud_theme.tres"', scene)
def test_svg_art_is_self_contained_and_has_no_embedded_fonts(self):
for asset in (ROOT / "assets/ui/hud").glob("*.svg"):
with self.subTest(asset=asset.name):
root = ET.parse(asset).getroot()
self.assertGreater(int(root.attrib["width"]), 0)
self.assertGreater(int(root.attrib["height"]), 0)
for node in root.iter():
self.assertNotIn(node.tag.rsplit("}", 1)[-1], {"image", "text", "script", "foreignObject"})
for key in node.attrib:
self.assertFalse(key.endswith("href"))
def test_bar_and_readout_paths_are_preserved(self):
for relative, name in zip(SCENES, ("Health", "Special")):
text = (ROOT / relative).read_text()
self.assertIn(f'[node name="{name}Bar" type="ProgressBar" parent="HUD"]', text)
self.assertIn(f'[node name="{name}Label" type="Label" parent="HUD/{name}Bar"]', text)
theme = (ROOT / "ui/hud/thrash_hud_theme.tres").read_text()
self.assertIn('path="res://assets/fonts/PixelOperator8.ttf"', theme)
self.assertIn('ProgressBar/styles/background = SubResource("EmptyBar")', theme)
self.assertIn('ProgressBar/styles/fill = SubResource("EmptyBar")', theme)
def test_charge_defaults_and_economy(self):
script = (ROOT / "player/player.gd").read_text()
values = {}
for key in ("special_max_charge", "special_min_use_charge", "special_charge_per_kill"):
values[key] = int(re.search(rf"var {key}: int = (\d+)", script).group(1))
self.assertEqual(values, {"special_max_charge": 100, "special_min_use_charge": 25, "special_charge_per_kill": 10})
self.assertEqual(math.ceil(values["special_max_charge"] / values["special_charge_per_kill"]), 10)
self.assertEqual(math.ceil(values["special_min_use_charge"] / values["special_charge_per_kill"]), 3)
self.assertIn("@export var special_kills_grant_charge: bool = false", script)
def test_special_reward_context_does_not_gate_all_deaths_during_solo(self):
script = (ROOT / "player/player.gd").read_text()
damage_call = '\t\t_applying_special_damage = true\n\t\tenemy.call("take_damage", damage, global_position)\n\t\t_applying_special_damage = false'
self.assertIn(damage_call, script)
callback = script.split("func _on_enemy_died(", 1)[1].split("\nfunc ", 1)[0]
self.assertIn("_applying_special_damage and not special_kills_grant_charge", callback)
self.assertNotIn("_special_active", callback)
def test_meter_protects_zero_capacity_and_special_has_no_damage_trail(self):
meter = (ROOT / "ui/hud/thrash_meter.gd").read_text()
special = (ROOT / "ui/hud/special_charge_hud.gd").read_text()
self.assertIn("max_value = maxf(capacity, 1.0)", meter)
self.assertIn("float(amount) / float(maxi(capacity, 1))", special)
self.assertIn('show_damage_trail = false', (ROOT / SCENES[1]).read_text())
if __name__ == "__main__":
unittest.main()
+140
View File
@@ -0,0 +1,140 @@
extends SceneTree
## Ejecutar despues de importar el proyecto:
## godot --headless --path . --script res://tests/test_thrash_hud_runtime.gd
## Verifica valores reales, animacion, umbrales y bajas causadas por el especial.
## La composicion visual y el editor requieren ademas una revision interactiva.
var _failures: int = 0
func _initialize() -> void:
call_deferred("_run")
func _run() -> void:
root.size = Vector2i(1152, 648)
var arena := Node2D.new()
var player: CharacterBody2D = load("res://player/player.tscn").instantiate() as CharacterBody2D
var enemy: CharacterBody2D = load("res://enemies/walker/walker.tscn").instantiate() as CharacterBody2D
player.position = Vector2(200, 200)
enemy.position = Vector2(250, 200)
enemy.set("drops_handled_by_level", true)
enemy.set("respawn_delay", 0.0)
# El enemigo entra primero: Player conecta los miembros actuales de su grupo en _ready.
arena.add_child(enemy)
arena.add_child(player)
root.add_child(arena)
current_scene = arena
player.set_physics_process(false)
enemy.set_physics_process(false)
var camera: Camera2D = player.get_node("Camera2D") as Camera2D
camera.force_update_scroll()
await process_frame
var health_hud: CanvasLayer = player.get_node("PlayerHealthHUD") as CanvasLayer
var special_hud: CanvasLayer = player.get_node("SpecialChargeHUD") as CanvasLayer
var health_bar: ThrashMeter = health_hud.get_node("HUD/HealthBar") as ThrashMeter
var special_bar: ThrashMeter = special_hud.get_node("HUD/SpecialBar") as ThrashMeter
var health_label: Label = health_bar.get_node("HealthLabel") as Label
var special_label: Label = special_bar.get_node("SpecialLabel") as Label
var warning_label: Label = health_hud.get_node("HUD/WarningLabel") as Label
var status_label: Label = special_hud.get_node("HUD/StatusLabel") as Label
_check(health_hud.visible and special_hud.visible, "Los dos HUD deben verse al jugar")
_check(health_label.text == "50 / 50", "La primera lectura de vida debe llegar sin animacion")
_check(is_equal_approx(health_bar.value, 50.0), "Vida inicial incorrecta")
_check(special_label.text == "0%", "El especial debe empezar vacio")
player.emit_signal("health_changed", 10, 50)
_check(health_label.text == "10 / 50", "El numero debe cambiar en el mismo evento")
_check(health_bar.highlighted and warning_label.visible, "Falta el aviso de poca vida")
_check(is_equal_approx(float(health_bar.get("_display_ratio")), 0.2), "La perdida de vida no debe retrasarse")
_check(is_equal_approx(float(health_bar.get("_trail_ratio")), 1.0), "La estela debe recordar la vida perdida")
health_bar.call("_process", 1.0)
_check(is_equal_approx(float(health_bar.get("_trail_ratio")), 0.2), "La estela debe desaparecer")
player.emit_signal("health_changed", 40, 50)
_check(not warning_label.visible and not health_bar.highlighted, "Curarse debe quitar el aviso")
health_bar.animations_enabled = false
player.emit_signal("health_changed", 25, 50)
_check(not health_bar.is_processing(), "Sin animacion no debe haber procesamiento visual continuo")
_check(is_equal_approx(float(health_bar.get("_display_ratio")), 0.5), "El modo estatico debe actualizarse al instante")
player.emit_signal("health_changed", 0, 0)
_check(health_label.text == "0 / 0" and is_zero_approx(health_bar.value), "Capacidad nula de vida")
player.emit_signal("health_changed", 50, 50)
# Diez notificaciones de baja ordinaria; el test de combate ya verifica died una sola vez por muerte.
for kills: int in range(1, 12):
player.call("_on_enemy_died", enemy)
_check(int(player.get("special_charge")) == mini(kills * 10, 100), "Carga o saturacion incorrecta")
if kills == 1:
_check(is_zero_approx(float(special_bar.get("_display_ratio"))), "La ganancia debe iniciar una subida, no saltar")
special_bar.call("_process", 0.1)
_check(is_equal_approx(float(special_bar.get("_display_ratio")), 0.05), "10 puntos deben interpolarse en 0.2 segundos")
if kills == 2:
_check(status_label.text == "CARGANDO" and not special_bar.highlighted, "20 puntos no bastan")
player.call("_start_special_attack")
_check(not bool(player.get("_special_active")), "No debe iniciarse el solo con 20 puntos")
_check(int(player.get("special_charge")) == 20, "Un intento invalido no consume carga")
if kills == 3:
_check(status_label.text == "LISTO" and special_bar.highlighted, "30 puntos deben permitir el solo")
_check(status_label.text == "AL 11" and special_label.text == "100%", "Falta el estado de carga completa")
player.call("_start_special_attack")
_check(bool(player.get("_special_active")), "La carga completa debe activar el solo")
_check(int(player.get("special_charge")) == 0 and special_label.text == "0%", "El solo debe consumir la carga")
_check(is_zero_approx(float(special_bar.get("_display_ratio"))), "La barra debe vaciarse sin retraso")
# Una baja ajena al dano del solo sigue concediendo carga aunque la animacion este activa.
player.call("_on_enemy_died", enemy)
_check(int(player.get("special_charge")) == 10, "No se deben filtrar otras bajas durante el solo")
enemy.set("current_health", 1)
player.call("_apply_special_attack", 100, 0)
_check(bool(enemy.get("is_dead")), "El pulso de prueba debe matar al enemigo visible")
_check(int(player.get("special_charge")) == 10, "El solo no debe recargarse con su propia baja")
_check(not bool(player.get("_applying_special_damage")), "El contexto de dano debe restaurarse")
# Enemigo nuevo para comprobar la opcion de restaurar la regla anterior.
var second_enemy: CharacterBody2D = load("res://enemies/walker/walker.tscn").instantiate() as CharacterBody2D
second_enemy.position = player.position + Vector2(50, 0)
second_enemy.set("drops_handled_by_level", true)
second_enemy.set("respawn_delay", 0.0)
arena.add_child(second_enemy)
second_enemy.set_physics_process(false)
second_enemy.set("current_health", 1)
second_enemy.connect(&"died", Callable(player, "_on_enemy_died").bind(second_enemy))
player.set("special_kills_grant_charge", true)
player.call("_apply_special_attack", 100, 0)
_check(bool(second_enemy.get("is_dead")), "El segundo pulso de prueba debe acertar")
_check(int(player.get("special_charge")) == 20, "La opcion de recarga propia debe funcionar")
_check(not bool(player.get("_applying_special_damage")), "El contexto no debe quedar activado")
# La UI respeta capacidad y minimo configurados, en vez de asumir siempre 100 y 25.
player.set("special_max_charge", 50)
player.set("special_min_use_charge", 25)
player.emit_signal("special_charge_changed", 25, 50)
_check(special_label.text == "50%", "25 de 50 debe indicar 50%")
_check(is_equal_approx(special_bar.activation_ratio, 0.5), "La marca debe seguir el umbral real")
player.set("special_min_use_charge", 60)
player.emit_signal("special_charge_changed", 50, 50)
_check(status_label.text == "DESACTIVADO" and not special_bar.highlighted, "Un umbral imposible no debe aparecer listo")
player.emit_signal("special_charge_changed", 0, 0)
_check(special_label.text == "0%" and is_zero_approx(special_bar.value), "Capacidad cero de especial")
# Los objetos conservan su potencia; el cambio de balance solo afecta a las bajas.
player.set("special_max_charge", 100)
player.set("special_min_use_charge", 25)
player.set("special_charge", 0)
var tape: PickupData = load("res://pickups/data/casete_demo.tres") as PickupData
_check(bool(player.call("collect_pickup", tape)), "El casete debe seguir recargando")
_check(int(player.get("special_charge")) == 25, "No debe alterarse la recompensa del casete")
arena.queue_free()
await process_frame
if _failures == 0:
print("OK THRASH HUD: vida, estela, estados, umbrales, capacidad cero y economia del solo")
quit(0 if _failures == 0 else 1)
func _check(condition: bool, message: String) -> void:
if not condition:
_failures += 1
push_error(message)
+19 -20
View File
@@ -1,9 +1,8 @@
"""Regenerate Level 02's original pixel-art PNGs with Pillow. """Regenera los PNG originales de Level02 con Pillow.
Usage: python tools/generate_city_art.py Uso: python tools/generate_city_art.py
Only development-time Pillow is required. Godot uses the exported PNGs directly. Pillow solo se necesita para regenerar arte; Godot utiliza los PNG exportados.
Everything is drawn on a low-resolution pixel grid, then resized with NEAREST. Se dibuja sobre una cuadricula de baja resolucion y se amplia con NEAREST."""
"""
from __future__ import annotations from __future__ import annotations
@@ -14,7 +13,7 @@ from PIL import Image, ImageDraw, ImageFont
ROOT = Path(__file__).resolve().parents[1] / 'assets' / 'city' ROOT = Path(__file__).resolve().parents[1] / 'assets' / 'city'
ROOT.mkdir(parents=True, exist_ok=True) ROOT.mkdir(parents=True, exist_ok=True)
SCALE = 2 SCALE = 2
W, H = 512, 640 # 1024x1280 world units after nearest-neighbour enlargement. W, H = 512, 640 # 1024x1280 unidades tras ampliar sin suavizado.
INK = '#171d31' INK = '#171d31'
SKY = ['#181e38', '#242844', '#32334f', '#4d4159', '#67505d'] SKY = ['#181e38', '#242844', '#32334f', '#4d4159', '#67505d']
FAR = ['#2b3048', '#30354e', '#353a53', '#3c3c54'] FAR = ['#2b3048', '#30354e', '#353a53', '#3c3c54']
@@ -55,7 +54,7 @@ def windows(d, x0, top, x1, bottom, rng, lit_probability, tiny=False):
d.rectangle((xx - 1, yy + wh + 1, xx + ww + 1, yy + wh + 2), fill='#35384c') d.rectangle((xx - 1, yy + wh + 1, xx + ww + 1, yy + wh + 2), fill='#35384c')
# The base is fully opaque. No transparent gaps appear while jumping high. # El fondo es totalmente opaco para evitar huecos transparentes al saltar alto.
sky = Image.new('RGB', (W, H), SKY[-1]); d = ImageDraw.Draw(sky) sky = Image.new('RGB', (W, H), SKY[-1]); d = ImageDraw.Draw(sky)
for yy in range(H): for yy in range(H):
s = yy / H s = yy / H
@@ -72,13 +71,13 @@ for i in range(110):
x,y = rng.randrange(W), rng.randrange(0,275) x,y = rng.randrange(W), rng.randrange(0,275)
color = rng.choice(('#aaafc8','#888fad','#797f9d')) color = rng.choice(('#aaafc8','#888fad','#797f9d'))
d.rectangle((x,y,x+(i%19==0),y+(i%23==0)),fill=color) d.rectangle((x,y,x+(i%19==0),y+(i%23==0)),fill=color)
# Offset glow and a pale disk: deliberately subdued so it never steals focus. # Resplandor desplazado y disco palido: tenues para no distraer del juego.
for rad, col in [(55,'#524b69'), (42,'#655a74'),(30,'#847588'),(22,'#c2a39e')]: for rad, col in [(55,'#524b69'), (42,'#655a74'),(30,'#847588'),(22,'#c2a39e')]:
d.ellipse((410-rad,178-rad,410+rad,178+rad), fill=col) d.ellipse((410-rad,178-rad,410+rad,178+rad), fill=col)
save(sky,'sky.png') save(sky,'sky.png')
# Cloud silhouettes: one independent, slowly drifting parallax layer. # Siluetas de nubes: capa de parallax independiente con desplazamiento lento.
clouds = image(); d=ImageDraw.Draw(clouds); rng=random.Random(97) clouds = image(); d=ImageDraw.Draw(clouds); rng=random.Random(97)
for cx,cy,rw,rh in [(90,218,65,18),(300,340,82,19),(482,280,55,17),(196,419,67,17)]: for cx,cy,rw,rh in [(90,218,65,18),(300,340,82,19),(482,280,55,17),(196,419,67,17)]:
for k in range(9): for k in range(9):
@@ -94,7 +93,7 @@ for cx,cy,rw,rh in [(90,218,65,18),(300,340,82,19),(482,280,55,17),(196,419,67,1
save(clouds,'clouds.png') save(clouds,'clouds.png')
# Silhouette skyline: repeatable at the 1024-unit horizontal seam. # Siluetas de edificios repetibles en la union horizontal de 1024 unidades.
far=image(); d=ImageDraw.Draw(far); rng=random.Random(190) far=image(); d=ImageDraw.Draw(far); rng=random.Random(190)
x=0 x=0
while x<W: while x<W:
@@ -109,7 +108,7 @@ while x<W:
save(far,'skyline_far.png') save(far,'skyline_far.png')
# Mid-range neighbourhood: roofs, gutters, some illuminated windows. # Barrio intermedio: tejados, canalones y algunas ventanas iluminadas.
mid=image(); d=ImageDraw.Draw(mid); rng=random.Random(317) mid=image(); d=ImageDraw.Draw(mid); rng=random.Random(317)
x=0 x=0
while x<W: while x<W:
@@ -119,7 +118,7 @@ while x<W:
d.rectangle((x-2,y-7,xx+3,y),fill='#252b42') d.rectangle((x-2,y-7,xx+3,y),fill='#252b42')
d.rectangle((x+5,y-12,x+17,y-8),fill='#363b50') d.rectangle((x+5,y-12,x+17,y-8),fill='#363b50')
windows(d,x,y,xx,H,rng,.34) windows(d,x,y,xx,H,rng,.34)
# Awnings and air-conditioning boxes establish a recognisable city profile. # Toldos y aparatos de aire acondicionado dan una silueta urbana reconocible.
if ww>85: if ww>85:
d.rectangle((x+ww//2-15,y-17,x+ww//2+23,y-8),fill='#36394e') d.rectangle((x+ww//2-15,y-17,x+ww//2+23,y-8),fill='#36394e')
d.rectangle((x+ww//2-12,y-24,x+ww//2+20,y-18),fill='#5f6074') d.rectangle((x+ww//2-12,y-24,x+ww//2+20,y-18),fill='#5f6074')
@@ -127,8 +126,8 @@ while x<W:
save(mid,'skyline_mid.png') save(mid,'skyline_mid.png')
# Facades are separate reusable transparent PNGs. They can be moved individually # Las fachadas son PNG transparentes reutilizables. Se colocan individualmente
# in the level editor without needing to regenerate a single huge background. # en el editor sin regenerar una imagen enorme de todo el fondo.
font=ImageFont.truetype(str(FONT_PATH), 11) if FONT_PATH.exists() else ImageFont.load_default() font=ImageFont.truetype(str(FONT_PATH), 11) if FONT_PATH.exists() else ImageFont.load_default()
styles=[ styles=[
('SALA RUIDO', 108, 245, '#565369', '#8f596a'), ('SALA RUIDO', 108, 245, '#565369', '#8f596a'),
@@ -140,7 +139,7 @@ styles=[
] ]
for idx,(sign,bw,bh,main,accent) in enumerate(styles): for idx,(sign,bw,bh,main,accent) in enumerate(styles):
rng=random.Random(900+idx); img=Image.new('RGBA',(bw,bh),(0,0,0,0)); dd=ImageDraw.Draw(img) rng=random.Random(900+idx); img=Image.new('RGBA',(bw,bh),(0,0,0,0)); dd=ImageDraw.Draw(img)
# Main mass and pixel masonry. # Volumen principal y ladrillos pixelados.
dd.rectangle((3,11,bw-3,bh-1),fill=main) dd.rectangle((3,11,bw-3,bh-1),fill=main)
dd.rectangle((0,7,bw-1,13),fill='#30364b') dd.rectangle((0,7,bw-1,13),fill='#30364b')
dd.rectangle((4,14,bw-6,17),fill='#787388') dd.rectangle((4,14,bw-6,17),fill='#787388')
@@ -148,7 +147,7 @@ for idx,(sign,bw,bh,main,accent) in enumerate(styles):
for xx in range(7+(yy//12%2)*5,bw-7,19): for xx in range(7+(yy//12%2)*5,bw-7,19):
dd.line((xx, yy,xx+11,yy),fill='#6a657a',width=1) dd.line((xx, yy,xx+11,yy),fill='#6a657a',width=1)
windows(dd,2,15,bw-3,bh,rng,.45) windows(dd,2,15,bw-3,bh,rng,.45)
# Shop front, rolling shutters, and a neon venue sign. # Escaparate, persianas enrollables y cartel de neon.
dd.rectangle((8,bh-49,bw-9,bh-2),fill='#30344b') dd.rectangle((8,bh-49,bw-9,bh-2),fill='#30344b')
dd.rectangle((bw//2-15,bh-45,bw//2+14,bh-3),fill='#515064') dd.rectangle((bw//2-15,bh-45,bw//2+14,bh-3),fill='#515064')
dd.rectangle((bw//2-12,bh-43,bw//2+11,bh-6),fill='#242a40') dd.rectangle((bw//2-12,bh-43,bw//2+11,bh-6),fill='#242a40')
@@ -160,9 +159,9 @@ for idx,(sign,bw,bh,main,accent) in enumerate(styles):
if signw>20: if signw>20:
bbox=dd.textbbox((0,0),sign,font=font) bbox=dd.textbbox((0,0),sign,font=font)
tw=bbox[2]-bbox[0] tw=bbox[2]-bbox[0]
# Pixel text is clipped intentionally if a deliberately long sign occurs. # Los textos demasiado largos se recortan deliberadamente.
dd.text(((bw-tw)//2,32),sign,font=font,fill='#f7ca85') dd.text(((bw-tw)//2,32),sign,font=font,fill='#f7ca85')
# Vent pipe, satellite/radio antenna, fire exit. # Ventilacion, antena y salida de incendios.
dd.rectangle((bw-20,1,bw-16,11),fill='#31384d') dd.rectangle((bw-20,1,bw-16,11),fill='#31384d')
dd.rectangle((bw-26,1,bw-9,3),fill='#747082') dd.rectangle((bw-26,1,bw-9,3),fill='#747082')
dd.rectangle((bw-10,bh//2,bw-4,bh//2+41),fill='#3a4056') dd.rectangle((bw-10,bh//2,bw-4,bh//2+41),fill='#3a4056')
@@ -171,7 +170,7 @@ for idx,(sign,bw,bh,main,accent) in enumerate(styles):
save(img,f'facade_{idx+1:02d}.png') save(img,f'facade_{idx+1:02d}.png')
# Game terrain tiles, also authored pixel-by-pixel. Each is seamless in X/Y. # Texturas de terreno dibujadas pixel a pixel y repetibles en X/Y.
road=Image.new('RGBA',(64,64),'#292f40');d=ImageDraw.Draw(road);rng=random.Random(87) road=Image.new('RGBA',(64,64),'#292f40');d=ImageDraw.Draw(road);rng=random.Random(87)
for gy in range(0,64,16): for gy in range(0,64,16):
for gx in range(0,64,32): for gx in range(0,64,32):
@@ -203,7 +202,7 @@ for y in (13,34,55):
d.rectangle((0,77,23,79),fill='#202838') d.rectangle((0,77,23,79),fill='#202838')
save(barrier,'barrier.png') save(barrier,'barrier.png')
# A compact pavement prop, reused sparingly in the actual scene. # Decoracion compacta de acera, repetida con moderacion en la escena.
lamp=Image.new('RGBA',(48,176),(0,0,0,0));d=ImageDraw.Draw(lamp) lamp=Image.new('RGBA',(48,176),(0,0,0,0));d=ImageDraw.Draw(lamp)
d.rectangle((25,27,28,175),fill='#373e56') d.rectangle((25,27,28,175),fill='#373e56')
d.rectangle((17,24,34,31),fill='#4f5267') d.rectangle((17,24,34,31),fill='#4f5267')
+71
View File
@@ -0,0 +1,71 @@
"""Ejecuta las pruebas estaticas y, si esta disponible, la suite real de Godot.
Uso:
python tools/run_checks.py --static-only
python tools/run_checks.py --godot /ruta/al/ejecutable/godot
No considera las pruebas estaticas equivalentes a haber ejecutado el motor.
"""
from __future__ import annotations
import argparse
from pathlib import Path
import shutil
import subprocess
import sys
ROOT = Path(__file__).resolve().parents[1]
def run_step(command: list[str], *, timeout: int = 180) -> bool:
"""Conserva el diagnostico y detecta errores de script aunque el motor devuelva cero."""
print("\n> " + subprocess.list2cmdline(command), flush=True)
try:
result = subprocess.run(
command,
cwd=ROOT,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=timeout,
check=False,
)
except (OSError, subprocess.TimeoutExpired) as exc:
print(f"No se pudo completar la comprobacion: {exc}", file=sys.stderr)
return False
output = result.stdout + result.stderr
print(output, end="" if output.endswith("\n") else "\n")
return result.returncode == 0 and "SCRIPT ERROR:" not in output and "ERROR:" not in output
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--godot", help="Ejecutable de Godot 4.7.x, con ruta completa si no esta en PATH")
parser.add_argument("--static-only", action="store_true", help="Ejecutar solo los contratos de recursos")
args = parser.parse_args()
if not run_step([sys.executable, "-m", "unittest", "discover", "-s", "tests", "-v"]):
return 1
if args.static_only:
print("OK: pruebas estaticas. No se ha ejecutado Godot ni validado su fisica.")
return 0
executable = args.godot or shutil.which("godot") or shutil.which("godot4")
if not executable:
print("Pruebas estaticas OK. Falta Godot: indica --godot o utiliza --static-only.", file=sys.stderr)
return 2
if not run_step([executable, "--version"], timeout=20):
return 1
# --import espera a la importacion de recursos y termina el editor.
if not run_step([executable, "--headless", "--editor", "--path", str(ROOT), "--import"], timeout=300):
return 1
for script in sorted((ROOT / "tests").glob("test_*_runtime.gd")):
relative = "res://" + script.relative_to(ROOT).as_posix()
if not run_step([executable, "--headless", "--path", str(ROOT), "--script", relative]):
return 1
print("OK: importacion y todas las suites de Godot completadas.")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+55
View File
@@ -0,0 +1,55 @@
@tool
extends Node
## Se coloca como hijo directo de un CanvasLayer de interfaz.
## Oculta esa capa al editar escenarios o personajes, pero la muestra al abrir
## su propia escena. No ejecuta la logica de vida, combate ni controles en el editor.
## Al jugar restaura la capa una vez y deja de procesar; las reglas del juego
## pueden seguir ocultando la interfaz o sus paneles cuando lo necesiten.
## Permite ver esta interfaz tambien dentro de un nivel mientras se edita.
## No afecta a la partida. Normalmente conviene editar la escena de UI por separado.
@export var preview_in_editor: bool = false:
set(value):
preview_in_editor = value
if Engine.is_editor_hint():
_update_visibility()
## _enter_tree tambien se ejecuta al volver a una pestana del editor.
func _enter_tree() -> void:
_update_visibility()
## Godot habilita _process antes de _ready si existe ese callback.
## Se desactiva aqui, no en _enter_tree, para no interferir durante la partida.
func _ready() -> void:
set_process(Engine.is_editor_hint())
## Solo se procesa en el editor: la raiz editada puede establecerse despues
## de _enter_tree o cambiar al abrir otra pestana. No recorre el arbol de nodos.
func _process(_delta: float) -> void:
if Engine.is_editor_hint():
_update_visibility()
## Al arrancar el juego muestra la capa aunque se guardase oculta en el editor.
## No cambia la visibilidad individual de sus hijos (efectos, mensajes, etc.).
func _update_visibility() -> void:
if not is_inside_tree():
return
var canvas_layer := get_parent() as CanvasLayer
if canvas_layer == null:
return
var should_be_visible: bool = true
if Engine.is_editor_hint():
should_be_visible = preview_in_editor or get_tree().edited_scene_root == canvas_layer
if canvas_layer.visible != should_be_visible:
canvas_layer.visible = should_be_visible
func _get_configuration_warnings() -> PackedStringArray:
if not get_parent() is CanvasLayer:
return PackedStringArray(["EditorVisibility debe ser hijo directo de un CanvasLayer de interfaz."])
return PackedStringArray()
+39 -17
View File
@@ -1,36 +1,51 @@
extends CanvasLayer extends CanvasLayer
## Minimal player HUD. ## Conecta el estado de Player con el HUD. La estetica y la animacion viven en ThrashMeter.
## ## CanvasLayer mantiene la interfaz fija en pantalla aunque avance la camara.
## This is a CanvasLayer on purpose: its coordinates belong to the camera
## viewport, not to the level. Therefore (18, 18) always means "18 pixels from
## the top-left corner currently visible by the camera", even while the player
## and Camera2D move through the world.
@onready var health_bar: ProgressBar = $HUD/HealthBar ## Umbral de aviso visual; no cambia la vida ni la dificultad del combate.
@export_range(0.05, 0.5, 0.05) var low_health_ratio: float = 0.25
@onready var health_bar: ThrashMeter = $HUD/HealthBar
@onready var health_label: Label = $HUD/HealthBar/HealthLabel @onready var health_label: Label = $HUD/HealthBar/HealthLabel
@onready var effects_label: Label = $HUD/EffectsLabel @onready var effects_label: Label = $HUD/EffectsLabel
@onready var warning_label: Label = $HUD/WarningLabel
var player_ref: Node var player_ref: Node
var _received_health: bool = false
var _effects_refresh_timer: float = 0.0
## Valida el contrato del jugador y conecta la senal de vida.
func _ready() -> void: func _ready() -> void:
player_ref = get_parent() player_ref = get_parent()
if not player_ref.has_signal(&"health_changed"): if player_ref == null or not player_ref.has_signal(&"health_changed"):
push_error("PlayerHealthHUD must be a child of a Player.") # Abrir esta escena sola permite revisar su diseno sin crear un jugador de mentira.
player_ref = null
set_process(false)
return return
# Children enter _ready before Player. Its initial signal arrives afterward. # Los hijos ejecutan _ready antes que Player; su senal inicial llegara despues de esta conexion.
player_ref.connect(&"health_changed", _on_health_changed) player_ref.connect(&"health_changed", _on_health_changed)
effects_label.visible = false effects_label.visible = false
# Tambien funciona si el HUD se instancia despues de _ready del jugador.
if player_ref.is_node_ready():
var data: Resource = player_ref.get("character_data") as Resource
if data != null:
_on_health_changed(int(player_ref.get("current_health")), int(data.get("max_health")))
func _process(_delta: float) -> void: ## Actualiza los tiempos restantes de las mejoras temporales.
if player_ref == null: func _process(delta: float) -> void:
if not is_instance_valid(player_ref):
return return
# Los contadores muestran segundos: refrescarlos a 10 Hz evita reconstruir texto cada frame.
_effects_refresh_timer -= delta
if _effects_refresh_timer > 0.0:
return
_effects_refresh_timer = 0.1
# Display each active effect individually: essential when validating all # Muestra cada mejora por separado. Los nombres de propiedades corresponden al estado temporal de Player.
# eight pickup families on a phone. Property names match Player's timers.
var active: Array[String] = [] var active: Array[String] = []
var speed_seconds: float = float(player_ref.get("_speed_boost_timer")) var speed_seconds: float = float(player_ref.get("_speed_boost_timer"))
if speed_seconds > 0.0: if speed_seconds > 0.0:
@@ -56,7 +71,14 @@ func _process(_delta: float) -> void:
effects_label.text = "\n".join(active) effects_label.text = "\n".join(active)
## Sincroniza barra y texto a partir del mismo par de valores.
func _on_health_changed(current_health: int, max_health: int) -> void: func _on_health_changed(current_health: int, max_health: int) -> void:
health_bar.max_value = float(max_health) var capacity: int = maxi(max_health, 0)
health_bar.value = float(current_health) var amount: int = clampi(current_health, 0, capacity)
health_label.text = "HP %d / %d" % [current_health, max_health] health_bar.set_amount(amount, capacity, not _received_health)
_received_health = true
health_label.text = "%d / %d" % [amount, capacity]
var low_health: bool = capacity > 0 and float(amount) / float(capacity) <= low_health_ratio
health_bar.highlighted = low_health and amount > 0
warning_label.visible = low_health or amount == 0
warning_label.text = "SIN VIDA" if amount == 0 else "PELIGRO"
+79 -50
View File
@@ -1,30 +1,19 @@
[gd_scene load_steps=4 format=3] [gd_scene load_steps=7 format=3]
[ext_resource type="Script" path="res://ui/hud/player_health_hud.gd" id="1_hud"] [ext_resource type="Script" path="res://ui/hud/player_health_hud.gd" id="1_hud"]
[ext_resource type="Script" path="res://ui/editor_ui_visibility.gd" id="editor_ui_visibility"]
[sub_resource type="StyleBoxFlat" id="HealthBackground"] [ext_resource type="Script" path="res://ui/hud/thrash_meter.gd" id="meter"]
bg_color = Color(0.08, 0.08, 0.09, 0.82) [ext_resource type="Theme" path="res://ui/hud/thrash_hud_theme.tres" id="theme"]
border_width_left = 2 [ext_resource type="Texture2D" path="res://assets/ui/hud/thrash_plate.svg" id="plate"]
border_width_top = 2 [ext_resource type="Texture2D" path="res://assets/ui/hud/thrash_skull.svg" id="skull"]
border_width_right = 2
border_width_bottom = 2
border_color = Color(0.95, 0.95, 0.95, 0.75)
corner_radius_top_left = 7
corner_radius_top_right = 7
corner_radius_bottom_right = 7
corner_radius_bottom_left = 7
[sub_resource type="StyleBoxFlat" id="HealthFill"]
bg_color = Color(0.72, 0.06, 0.06, 0.92)
corner_radius_top_left = 5
corner_radius_top_right = 5
corner_radius_bottom_right = 5
corner_radius_bottom_left = 5
[node name="PlayerHealthHUD" type="CanvasLayer"] [node name="PlayerHealthHUD" type="CanvasLayer"]
layer = 90 layer = 90
script = ExtResource("1_hud") script = ExtResource("1_hud")
[node name="EditorVisibility" type="Node" parent="."]
script = ExtResource("editor_ui_visibility")
[node name="HUD" type="Control" parent="."] [node name="HUD" type="Control" parent="."]
layout_mode = 3 layout_mode = 3
anchors_preset = 15 anchors_preset = 15
@@ -33,47 +22,87 @@ anchor_bottom = 1.0
grow_horizontal = 2 grow_horizontal = 2
grow_vertical = 2 grow_vertical = 2
mouse_filter = 2 mouse_filter = 2
theme = ExtResource("theme")
[node name="HealthBar" type="ProgressBar" parent="HUD"] [node name="Frame" type="TextureRect" parent="HUD"]
layout_mode = 0 layout_mode = 0
offset_left = 18.0 offset_left = 18.0
offset_top = 18.0 offset_top = 18.0
offset_right = 278.0 offset_right = 362.0
offset_bottom = 58.0 offset_bottom = 82.0
mouse_filter = 2 mouse_filter = 2
theme_override_styles/background = SubResource("HealthBackground") texture = ExtResource("plate")
theme_override_styles/fill = SubResource("HealthFill") expand_mode = 1
max_value = 5.0
value = 5.0
show_percentage = false
[node name="HealthLabel" type="Label" parent="HUD/HealthBar"] [node name="Emblem" type="TextureRect" parent="HUD"]
layout_mode = 1 layout_mode = 0
anchors_preset = 15 offset_left = 29.0
anchor_right = 1.0 offset_top = 26.0
anchor_bottom = 1.0 offset_right = 69.0
grow_horizontal = 2 offset_bottom = 66.0
grow_vertical = 2
mouse_filter = 2 mouse_filter = 2
theme_override_colors/font_color = Color(1, 1, 1, 1) texture = ExtResource("skull")
theme_override_colors/font_shadow_color = Color(0, 0, 0, 0.9) expand_mode = 1
theme_override_constants/shadow_offset_x = 1
theme_override_constants/shadow_offset_y = 1 [node name="Title" type="Label" parent="HUD"]
theme_override_font_sizes/font_size = 18 layout_mode = 0
text = "HP 5 / 5" offset_left = 84.0
offset_top = 25.0
offset_right = 152.0
offset_bottom = 45.0
mouse_filter = 2
text = "VIDA"
vertical_alignment = 1
[node name="WarningLabel" type="Label" parent="HUD"]
visible = false
layout_mode = 0
offset_left = 154.0
offset_top = 25.0
offset_right = 212.0
offset_bottom = 45.0
mouse_filter = 2
theme_override_colors/font_color = Color(1, 0.52, 0.42, 1)
theme_override_font_sizes/font_size = 8
text = "PELIGRO"
horizontal_alignment = 1 horizontal_alignment = 1
vertical_alignment = 1 vertical_alignment = 1
[node name="EffectsLabel" type="Label" parent="HUD"] [node name="HealthBar" type="ProgressBar" parent="HUD"]
layout_mode = 0 layout_mode = 0
offset_left = 18.0 offset_left = 84.0
offset_top = 106.0 offset_top = 48.0
offset_right = 298.0 offset_right = 346.0
offset_bottom = 255.0 offset_bottom = 68.0
theme_override_colors/font_color = Color(1, 0.8, 0.2, 1) mouse_filter = 2
theme_override_colors/font_shadow_color = Color(0, 0, 0, 0.9) max_value = 50.0
value = 50.0
show_percentage = false
script = ExtResource("meter")
fill_color = Color(0.84, 0.18, 0.25, 1)
segment_count = 12
[node name="HealthLabel" type="Label" parent="HUD/HealthBar"]
layout_mode = 0
offset_left = 132.0
offset_top = -23.0
offset_right = 262.0
offset_bottom = -3.0
mouse_filter = 2
text = "50 / 50"
horizontal_alignment = 2
vertical_alignment = 1
[node name="EffectsLabel" type="Label" parent="HUD"]
visible = false
layout_mode = 0
offset_left = 22.0
offset_top = 160.0
offset_right = 362.0
offset_bottom = 300.0
mouse_filter = 2
theme_override_colors/font_color = Color(0.85, 0.9, 0.64, 1)
theme_override_font_sizes/font_size = 16 theme_override_font_sizes/font_size = 16
text = "VELOCIDAD: 0s" text = ""
horizontal_alignment = 0 horizontal_alignment = 0
vertical_alignment = 0 vertical_alignment = 0
visible = false
+40 -17
View File
@@ -1,28 +1,51 @@
extends CanvasLayer extends CanvasLayer
## Presenta la carga y su umbral real de uso; no altera costes ni ejecuta ataques.
## Los valores proceden del jugador, no de otra configuracion duplicada en el HUD.
## Minimal HUD showing the player's special attack charge. @onready var special_bar: ThrashMeter = $HUD/SpecialBar
##
## Expects to be a child of a Player that exposes a `special_charge_changed`
## signal, just like PlayerHealthHUD expects `health_changed`.
@onready var special_bar: ProgressBar = $HUD/SpecialBar
@onready var special_label: Label = $HUD/SpecialBar/SpecialLabel @onready var special_label: Label = $HUD/SpecialBar/SpecialLabel
@onready var status_label: Label = $HUD/StatusLabel
@onready var threshold_label: Label = $HUD/ThresholdLabel
var player_ref: Node
var _received_charge: bool = false
func _ready() -> void: func _ready() -> void:
var player: Node = get_parent() player_ref = get_parent()
if player == null or not player.has_signal(&"special_charge_changed"): if player_ref == null or not player_ref.has_signal(&"special_charge_changed"):
push_error("SpecialChargeHUD must be a child of a Player with special_charge_changed signal.") # Conserva la maqueta al ejecutar solo esta escena de interfaz.
player_ref = null
return return
player_ref.connect(&"special_charge_changed", _on_special_charge_changed)
# Child _ready() runs before Player._ready(). We connect here first and the if player_ref.is_node_ready():
# Player will emit its initial charge a moment later during its _ready(). _on_special_charge_changed(int(player_ref.get("special_charge")), int(player_ref.get("special_max_charge")))
player.connect(&"special_charge_changed", _on_special_charge_changed)
## El porcentaje se calcula respecto a la capacidad: 25 de 50 es 50%, no 25%.
## LISTO indica carga suficiente; los bloqueos temporales de combate siguen siendo de Player.
func _on_special_charge_changed(current_charge: int, max_charge: int) -> void: func _on_special_charge_changed(current_charge: int, max_charge: int) -> void:
special_bar.max_value = float(max_charge) var capacity: int = maxi(max_charge, 0)
special_bar.value = float(current_charge) var amount: int = clampi(current_charge, 0, capacity)
special_label.text = "SPECIAL %d%%" % [current_charge] var minimum: int = maxi(int(player_ref.get("special_min_use_charge")), 1)
var available: bool = capacity > 0 and minimum <= capacity
var charged: bool = available and amount >= minimum
var percent: int = roundi(100.0 * float(amount) / float(maxi(capacity, 1)))
special_bar.set_amount(amount, capacity, not _received_charge)
_received_charge = true
special_bar.activation_ratio = float(minimum) / float(capacity) if available else -1.0
special_bar.highlighted = charged
special_label.text = "%d%%" % percent
# La leyenda usa puntos, porque la capacidad es configurable y no siempre vale 100.
threshold_label.text = "MIN %d PT" % minimum if available else "NO DISPONIBLE"
if not available:
status_label.text = "DESACTIVADO"
elif amount == capacity:
status_label.text = "AL 11"
elif charged:
status_label.text = "LISTO"
else:
status_label.text = "CARGANDO"
status_label.add_theme_color_override("font_color", Color("e4f39a") if charged else Color("93a3a0"))
+85 -16
View File
@@ -1,37 +1,106 @@
[gd_scene load_steps=2 format=3] [gd_scene load_steps=7 format=3]
[ext_resource type="Script" path="res://ui/hud/special_charge_hud.gd" id="1_hud"] [ext_resource type="Script" path="res://ui/hud/special_charge_hud.gd" id="1_hud"]
[ext_resource type="Script" path="res://ui/editor_ui_visibility.gd" id="editor_ui_visibility"]
[ext_resource type="Script" path="res://ui/hud/thrash_meter.gd" id="meter"]
[ext_resource type="Theme" path="res://ui/hud/thrash_hud_theme.tres" id="theme"]
[ext_resource type="Texture2D" path="res://assets/ui/hud/thrash_plate.svg" id="plate"]
[ext_resource type="Texture2D" path="res://assets/ui/hud/thrash_bolt.svg" id="bolt"]
[node name="SpecialChargeHUD" type="CanvasLayer"] [node name="SpecialChargeHUD" type="CanvasLayer"]
layer = 95 layer = 95
script = ExtResource("1_hud") script = ExtResource("1_hud")
[node name="EditorVisibility" type="Node" parent="."]
script = ExtResource("editor_ui_visibility")
[node name="HUD" type="Control" parent="."] [node name="HUD" type="Control" parent="."]
layout_mode = 3 layout_mode = 3
anchors_preset = 15 anchors_preset = 15
anchor_right = 1.0 anchor_right = 1.0
anchor_bottom = 1.0 anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
mouse_filter = 2 mouse_filter = 2
theme = ExtResource("theme")
[node name="Frame" type="TextureRect" parent="HUD"]
layout_mode = 0
offset_left = 18.0
offset_top = 86.0
offset_right = 362.0
offset_bottom = 150.0
mouse_filter = 2
texture = ExtResource("plate")
expand_mode = 1
[node name="Emblem" type="TextureRect" parent="HUD"]
layout_mode = 0
offset_left = 29.0
offset_top = 94.0
offset_right = 69.0
offset_bottom = 134.0
mouse_filter = 2
texture = ExtResource("bolt")
expand_mode = 1
[node name="Title" type="Label" parent="HUD"]
layout_mode = 0
offset_left = 84.0
offset_top = 93.0
offset_right = 155.0
offset_bottom = 113.0
mouse_filter = 2
text = "SOLO"
vertical_alignment = 1
[node name="StatusLabel" type="Label" parent="HUD"]
layout_mode = 0
offset_left = 158.0
offset_top = 93.0
offset_right = 270.0
offset_bottom = 113.0
mouse_filter = 2
theme_override_colors/font_color = Color(0.57, 0.64, 0.63, 1)
theme_override_font_sizes/font_size = 8
text = "CARGANDO"
horizontal_alignment = 1
vertical_alignment = 1
[node name="SpecialBar" type="ProgressBar" parent="HUD"] [node name="SpecialBar" type="ProgressBar" parent="HUD"]
offset_left = 18.0 layout_mode = 0
offset_top = 74.0 offset_left = 84.0
offset_right = 278.0 offset_top = 116.0
offset_bottom = 94.0 offset_right = 346.0
offset_bottom = 134.0
mouse_filter = 2
max_value = 100.0 max_value = 100.0
value = 0.0 value = 0.0
show_percentage = false show_percentage = false
script = ExtResource("meter")
fill_color = Color(0.74, 0.89, 0.27, 1)
segment_count = 16
activation_ratio = 0.25
show_damage_trail = false
[node name="SpecialLabel" type="Label" parent="HUD/SpecialBar"] [node name="SpecialLabel" type="Label" parent="HUD/SpecialBar"]
layout_mode = 1 layout_mode = 0
anchors_preset = 15 offset_left = 192.0
offset_left = 4.0 offset_top = -23.0
offset_top = 2.0 offset_right = 262.0
text = "SPECIAL" offset_bottom = -3.0
theme_override_colors/font_color = Color(1, 1, 1, 1) mouse_filter = 2
theme_override_colors/font_shadow_color = Color(0, 0, 0, 0.9) text = "0%"
theme_override_constants/shadow_offset_x = 1 horizontal_alignment = 2
theme_override_constants/shadow_offset_y = 1
theme_override_font_sizes/font_size = 14
horizontal_alignment = 1
vertical_alignment = 1 vertical_alignment = 1
[node name="ThresholdLabel" type="Label" parent="HUD"]
layout_mode = 0
offset_left = 84.0
offset_top = 136.0
offset_right = 244.0
offset_bottom = 146.0
mouse_filter = 2
theme_override_colors/font_color = Color(0.66, 0.71, 0.64, 1)
theme_override_font_sizes/font_size = 8
text = "MIN 25 PT"
+15
View File
@@ -0,0 +1,15 @@
[gd_resource type="Theme" load_steps=3 format=3]
[ext_resource type="FontFile" path="res://assets/fonts/PixelOperator8.ttf" id="pixel_font"]
[sub_resource type="StyleBoxEmpty" id="EmptyBar"]
[resource]
default_font = ExtResource("pixel_font")
default_font_size = 16
Label/colors/font_color = Color(0.91, 0.91, 0.82, 1)
Label/colors/font_shadow_color = Color(0.02, 0.03, 0.04, 1)
Label/constants/shadow_offset_x = 1
Label/constants/shadow_offset_y = 1
ProgressBar/styles/background = SubResource("EmptyBar")
ProgressBar/styles/fill = SubResource("EmptyBar")
+193
View File
@@ -0,0 +1,193 @@
@tool
class_name ThrashMeter
extends ProgressBar
## Medidor visual compartido por vida y especial; no conoce al jugador ni modifica el combate.
## Conserva el contrato de ProgressBar (value/max_value) y dibuja segmentos de amplificador.
## Solo este componente visual se ejecuta en el editor; los controladores del HUD no son @tool.
@export_group("Thrash Appearance")
## Color de los segmentos llenos. La escena de vida usa rojo y la de especial, verde acido.
@export var fill_color: Color = Color("d73949"):
set(new_value):
fill_color = new_value
queue_redraw()
@export_range(4, 32, 1) var segment_count: int = 12:
set(new_value):
segment_count = new_value
queue_redraw()
## Fraccion de la capacidad donde dibujar la marca de activacion. -1 la oculta.
@export_range(-1.0, 1.0, 0.01) var activation_ratio: float = -1.0:
set(new_value):
activation_ratio = new_value
queue_redraw()
@export_group("Thrash Feedback")
## Desactivar para obtener un HUD estatico: sin pulsos, destellos ni interpolacion.
@export var animations_enabled: bool = true:
set(new_value):
animations_enabled = new_value
if not new_value:
_snap_to_value()
_update_processing()
## Conserva brevemente la vida perdida en color hueso. El especial no necesita esta estela.
@export var show_damage_trail: bool = true
@export_range(0.0, 1.0, 0.05) var damage_trail_delay: float = 0.35
## Duracion de cada subida, incluso cuando solo se ganan 10 puntos.
@export_range(0.05, 1.0, 0.05) var fill_transition_seconds: float = 0.2
## El controlador decide cuando destacar la barra: poca vida o carga suficiente.
var highlighted: bool = false:
set(new_value):
highlighted = new_value
queue_redraw()
_update_processing()
var _display_ratio: float = 0.0
var _target_ratio: float = 0.0
var _fill_speed: float = 0.0
var _trail_ratio: float = 0.0
var _trail_wait: float = 0.0
var _damage_flash: float = 0.0
var _pulse_phase: float = 0.0
var _updating_range: bool = false
func _ready() -> void:
mouse_filter = Control.MOUSE_FILTER_IGNORE
value_changed.connect(_on_value_changed)
changed.connect(_on_range_changed)
resized.connect(queue_redraw)
_snap_to_value()
_update_processing()
## Actualiza valor y capacidad como una sola operacion; la primera lectura no se anima.
## Una capacidad cero se representa vacia y nunca provoca una division por cero.
func set_amount(current: float, capacity: float, immediate: bool = false) -> void:
# Cambiar la escala del medidor no es recibir dano: reinicia la representacion visual.
var capacity_changed: bool = not is_equal_approx(max_value, maxf(capacity, 1.0))
_updating_range = true
max_value = maxf(capacity, 1.0)
value = clampf(current, 0.0, maxf(capacity, 0.0))
_updating_range = false
if immediate or capacity_changed or Engine.is_editor_hint() or not animations_enabled:
_snap_to_value()
else:
_change_target()
_update_processing()
func _on_value_changed(_new_value: float) -> void:
if not _updating_range:
if Engine.is_editor_hint() or not animations_enabled:
_snap_to_value()
else:
_change_target()
_update_processing()
func _on_range_changed() -> void:
# Range.changed notifica tambien los cambios de capacidad desde el Inspector.
_on_value_changed(value)
func _snap_to_value() -> void:
_target_ratio = clampf(value / maxf(max_value, 1.0), 0.0, 1.0)
_display_ratio = _target_ratio
_fill_speed = 0.0
_trail_ratio = _target_ratio
_trail_wait = 0.0
_damage_flash = 0.0
queue_redraw()
func _change_target() -> void:
var next_ratio: float = clampf(value / maxf(max_value, 1.0), 0.0, 1.0)
if next_ratio < _target_ratio:
# Perder vida o consumir el solo se muestra al instante; no se finge energia disponible.
_display_ratio = next_ratio
if show_damage_trail:
_trail_ratio = maxf(_trail_ratio, _target_ratio)
_trail_wait = damage_trail_delay
_damage_flash = 0.18
_target_ratio = next_ratio
_fill_speed = absf(_target_ratio - _display_ratio) / maxf(fill_transition_seconds, 0.05)
if not show_damage_trail:
_trail_ratio = next_ratio
queue_redraw()
func _update_processing() -> void:
# Una barra estable no redibuja cada frame. El editor solo cambia al tocar sus propiedades.
if not is_inside_tree():
return
var moving: bool = not is_equal_approx(_display_ratio, _target_ratio)
var trailing: bool = show_damage_trail and not is_equal_approx(_trail_ratio, _target_ratio)
set_process(not Engine.is_editor_hint() and animations_enabled and
(highlighted or moving or trailing or _damage_flash > 0.0))
func _process(delta: float) -> void:
_display_ratio = move_toward(_display_ratio, _target_ratio, delta * _fill_speed)
_trail_wait = maxf(0.0, _trail_wait - delta)
if _trail_wait <= 0.0:
_trail_ratio = move_toward(_trail_ratio, _target_ratio, delta / 0.45)
_damage_flash = maxf(0.0, _damage_flash - delta)
# Pulso lento y localizado; no parpadea toda la pantalla ni mueve los controles.
_pulse_phase = fmod(_pulse_phase + delta * TAU * 0.75, TAU)
if is_visible_in_tree():
queue_redraw()
_update_processing()
func _draw() -> void:
if size.x < 8.0 or size.y < 6.0:
return
var shown: float = clampf(value / maxf(max_value, 1.0), 0.0, 1.0) if Engine.is_editor_hint() else _display_ratio
var inner := Rect2(Vector2(2, 2), size - Vector2(4, 4))
var count: int = maxi(segment_count, 1)
var step_width: float = inner.size.x / float(count)
var cell_width: float = maxf(step_width - 2.0, 1.0)
draw_rect(Rect2(Vector2.ZERO, size), Color("05090b"))
draw_rect(Rect2(Vector2.ZERO, size), Color("3b464b"), false, 1.0)
for index: int in range(count):
var cell := Rect2(inner.position + Vector2(float(index) * step_width, 0), Vector2(cell_width, inner.size.y))
_draw_segment(cell, 1.0, Color("202b30"))
if show_damage_trail and not Engine.is_editor_hint():
_draw_segment(cell, clampf(_trail_ratio * count - index, 0.0, 1.0), Color("a99774"))
var fraction: float = clampf(shown * count - index, 0.0, 1.0)
_draw_segment(cell, fraction, fill_color)
if fraction > 0.0:
# Bisel iluminado y una linea de sombra dentro de cada segmento.
var bevel: float = minf(3.0, cell.size.x * 0.25)
var length: float = (cell.size.x - bevel) * fraction
draw_line(cell.position + Vector2(bevel, 1), cell.position + Vector2(bevel + length, 1), fill_color.lightened(0.45), 1.0)
draw_line(cell.position + Vector2(0, cell.size.y - 1), cell.position + Vector2(length, cell.size.y - 1), fill_color.darkened(0.4), 1.0)
if activation_ratio >= 0.0:
var marker_x: float = inner.position.x + inner.size.x * clampf(activation_ratio, 0.0, 1.0)
draw_line(Vector2(marker_x, 1), Vector2(marker_x, size.y - 1), Color(0.94, 0.94, 0.79, 0.65), 1.0)
draw_colored_polygon(PackedVector2Array([
Vector2(marker_x, size.y), Vector2(marker_x - 3, size.y + 4), Vector2(marker_x + 3, size.y + 4)
]), Color("e7e7ca"))
if highlighted:
var strength: float = 0.7
if animations_enabled and not Engine.is_editor_hint():
strength = 0.65 + sin(_pulse_phase) * 0.2
draw_rect(Rect2(Vector2(-1, -1), size + Vector2(2, 2)), Color(fill_color, strength), false, 1.0)
if _damage_flash > 0.0 and animations_enabled and not Engine.is_editor_hint():
draw_rect(Rect2(Vector2.ZERO, size), Color(1.0, 0.87, 0.76, _damage_flash * 1.5))
## Recorta cada segmento en diagonal sin texturas adicionales ni shaders.
func _draw_segment(rect: Rect2, fraction: float, color: Color) -> void:
if fraction <= 0.0:
return
var bevel: float = minf(3.0, rect.size.x * 0.25)
var length: float = (rect.size.x - bevel) * fraction
var origin: Vector2 = rect.position
draw_colored_polygon(PackedVector2Array([
origin + Vector2(bevel, 0), origin + Vector2(bevel + length, 0),
origin + Vector2(length, rect.size.y), origin + Vector2(0, rect.size.y)
]), color)
+10 -1
View File
@@ -12,7 +12,7 @@ extends CanvasLayer
## Player ## Player
## ##
## Cuando llegue el arte definitivo, esta escena puede cambiar por completo sin ## Cuando llegue el arte definitivo, esta escena puede cambiar por completo sin
## tocar player.gd mientras conserve estas cuatro acciones. ## tocar player.gd mientras conserve estas seis acciones.
@onready var move_left_button: Button = $Controls/MoveLeft @onready var move_left_button: Button = $Controls/MoveLeft
@onready var move_right_button: Button = $Controls/MoveRight @onready var move_right_button: Button = $Controls/MoveRight
@@ -24,6 +24,7 @@ extends CanvasLayer
var direction_touch_index: int = -1 var direction_touch_index: int = -1
## Asocia botones con las mismas acciones utilizadas por el teclado.
func _ready() -> void: func _ready() -> void:
_bind_button(jump_button, &"jump") _bind_button(jump_button, &"jump")
_bind_button(attack_button, &"attack") _bind_button(attack_button, &"attack")
@@ -31,6 +32,7 @@ func _ready() -> void:
_bind_button(special_attack_button, &"special_attack") _bind_button(special_attack_button, &"special_attack")
## Mantiene un unico dedo para direccion y permite deslizarlo entre ambos lados.
func _input(event: InputEvent) -> void: func _input(event: InputEvent) -> void:
if event is InputEventScreenTouch: if event is InputEventScreenTouch:
var touch := event as InputEventScreenTouch var touch := event as InputEventScreenTouch
@@ -49,6 +51,7 @@ func _input(event: InputEvent) -> void:
_press_direction(action) _press_direction(action)
## Libera acciones al cambiar de escena para no dejar botones virtuales pulsados.
func _exit_tree() -> void: func _exit_tree() -> void:
# Si la escena cambia mientras un dedo sigue apoyado, Godot puede no llegar # Si la escena cambia mientras un dedo sigue apoyado, Godot puede no llegar
# a emitir button_up. Liberamos las acciones para no dejar una tecla virtual # a emitir button_up. Liberamos las acciones para no dejar una tecla virtual
@@ -61,6 +64,7 @@ func _exit_tree() -> void:
Input.action_release(&"special_attack") Input.action_release(&"special_attack")
## Determina que control horizontal contiene la posicion tactil.
func _direction_at(position: Vector2) -> StringName: func _direction_at(position: Vector2) -> StringName:
if move_left_button.get_global_rect().has_point(position): if move_left_button.get_global_rect().has_point(position):
return &"move_left" return &"move_left"
@@ -69,26 +73,31 @@ func _direction_at(position: Vector2) -> StringName:
return &"" return &""
## Activa una direccion y desactiva la opuesta.
func _press_direction(action: StringName) -> void: func _press_direction(action: StringName) -> void:
var other_action: StringName = &"move_right" if action == &"move_left" else &"move_left" var other_action: StringName = &"move_right" if action == &"move_left" else &"move_left"
Input.action_release(other_action) Input.action_release(other_action)
Input.action_press(action) Input.action_press(action)
## Suelta ambas direcciones y libera el dedo reservado.
func _release_direction() -> void: func _release_direction() -> void:
Input.action_release(&"move_left") Input.action_release(&"move_left")
Input.action_release(&"move_right") Input.action_release(&"move_right")
direction_touch_index = -1 direction_touch_index = -1
## Conecta pulsacion y liberacion con la accion indicada.
func _bind_button(button: Button, action: StringName) -> void: func _bind_button(button: Button, action: StringName) -> void:
button.button_down.connect(_press_action.bind(action)) button.button_down.connect(_press_action.bind(action))
button.button_up.connect(_release_action.bind(action)) button.button_up.connect(_release_action.bind(action))
## Envia una pulsacion al InputMap compartido.
func _press_action(action: StringName) -> void: func _press_action(action: StringName) -> void:
Input.action_press(action) Input.action_press(action)
## Libera la accion tactil en el InputMap compartido.
func _release_action(action: StringName) -> void: func _release_action(action: StringName) -> void:
Input.action_release(action) Input.action_release(action)
+5
View File
@@ -1,5 +1,7 @@
[gd_scene format=3 uid="uid://g7h185yageqr"] [gd_scene format=3 uid="uid://g7h185yageqr"]
[ext_resource type="Script" path="res://ui/editor_ui_visibility.gd" id="editor_ui_visibility"]
[ext_resource type="Script" uid="uid://2kbajcohyem7" path="res://ui/mobile_controls/mobile_controls.gd" id="1_controls"] [ext_resource type="Script" uid="uid://2kbajcohyem7" path="res://ui/mobile_controls/mobile_controls.gd" id="1_controls"]
[ext_resource type="Texture2D" uid="uid://cj6wl2l43nao2" path="res://assets/ui/mobile_controls/left-arrow.png" id="2_left"] [ext_resource type="Texture2D" uid="uid://cj6wl2l43nao2" path="res://assets/ui/mobile_controls/left-arrow.png" id="2_left"]
[ext_resource type="Texture2D" uid="uid://y0tsuhk4moj3" path="res://assets/ui/mobile_controls/right-arrow.png" id="3_right"] [ext_resource type="Texture2D" uid="uid://y0tsuhk4moj3" path="res://assets/ui/mobile_controls/right-arrow.png" id="3_right"]
@@ -34,6 +36,9 @@ corner_radius_bottom_left = 14
layer = 100 layer = 100
script = ExtResource("1_controls") script = ExtResource("1_controls")
[node name="EditorVisibility" type="Node" parent="."]
script = ExtResource("editor_ui_visibility")
[node name="Controls" type="Control" parent="." unique_id=1754744981] [node name="Controls" type="Control" parent="." unique_id=1754744981]
layout_mode = 3 layout_mode = 3
anchors_preset = 15 anchors_preset = 15
+19
View File
@@ -0,0 +1,19 @@
# Biblioteca de escenario
Arrastra **escenas .tscn**, no scripts. Guia completa: `docs/level_design.md`.
- `terrain/`: suelo, plataforma atravesable, pared y bloque de color.
- `props/`: barril, caja, farola, banco, cono, papelera, roca y seis fachadas.
- `signs/`: cartel con poste y texto suelto.
- `backgrounds/`: fondo urbano reutilizable con cuatro capas.
`terrain_piece.tscn` y `scenery_prop.tscn` son bases tecnicas. Los demas archivos
son presets listos para colocar. Para enemigos usa `enemies/variants/`; para
objetos de recogida usa `pickups/variants/`.
Escena inicial: `levels/templates/level_template.tscn`.
Catalogo jugable: `levels/examples/scenery_catalog.tscn`.
Las superficies se colocan por su centro. Decoracion y carteles con poste se
colocan por sus pies. El tamano de terreno se cambia con Dimensions; no mediante
escalado del nodo.
+52
View File
@@ -0,0 +1,52 @@
[gd_scene load_steps=5 format=3]
[ext_resource type="Texture2D" path="res://assets/city/sky.png" id="art_sky"]
[ext_resource type="Texture2D" path="res://assets/city/clouds.png" id="art_clouds"]
[ext_resource type="Texture2D" path="res://assets/city/skyline_far.png" id="art_skyline_far"]
[ext_resource type="Texture2D" path="res://assets/city/skyline_mid.png" id="art_skyline_mid"]
[node name="CityBackground" type="Node2D"]
[node name="Sky" type="Parallax2D" parent="."]
z_index = -18
scroll_scale = Vector2(0, 1)
repeat_size = Vector2(1024, 0)
repeat_times = 2
[node name="Strip" type="Sprite2D" parent="Sky"]
centered = false
texture_filter = 1
texture = ExtResource("art_sky")
[node name="HighClouds" type="Parallax2D" parent="."]
z_index = -17
scroll_scale = Vector2(0.12, 1)
repeat_size = Vector2(1024, 0)
repeat_times = 2
autoscroll = Vector2(3, 0)
[node name="Strip" type="Sprite2D" parent="HighClouds"]
centered = false
texture_filter = 1
texture = ExtResource("art_clouds")
[node name="FarBuildings" type="Parallax2D" parent="."]
z_index = -16
scroll_scale = Vector2(0.23, 1)
repeat_size = Vector2(1024, 0)
repeat_times = 2
[node name="Strip" type="Sprite2D" parent="FarBuildings"]
centered = false
texture_filter = 1
texture = ExtResource("art_skyline_far")
[node name="NearBuildings" type="Parallax2D" parent="."]
z_index = -15
scroll_scale = Vector2(0.46, 1)
repeat_size = Vector2(1024, 0)
repeat_times = 2
[node name="Strip" type="Sprite2D" parent="NearBuildings"]
centered = false
texture_filter = 1
texture = ExtResource("art_skyline_mid")
+10
View File
@@ -0,0 +1,10 @@
[gd_scene load_steps=3 format=3]
[ext_resource type="PackedScene" path="res://world/props/scenery_prop.tscn" id="base"]
[ext_resource type="Texture2D" path="res://assets/props/barrel.svg" id="texture"]
[node name="Barrel" instance=ExtResource("base")]
texture = ExtResource("texture")
display_size = Vector2(64, 80)
draw_layer = -2
collision_enabled = true
collision_dimensions = Vector2(54, 76)
collision_offset = Vector2(0, -38)
+10
View File
@@ -0,0 +1,10 @@
[gd_scene load_steps=3 format=3]
[ext_resource type="PackedScene" path="res://world/props/scenery_prop.tscn" id="base"]
[ext_resource type="Texture2D" path="res://assets/props/bench.svg" id="texture"]
[node name="Bench" instance=ExtResource("base")]
texture = ExtResource("texture")
display_size = Vector2(160, 84)
draw_layer = -2
collision_enabled = false
collision_dimensions = Vector2(152, 60)
collision_offset = Vector2(0, -30)
+10
View File
@@ -0,0 +1,10 @@
[gd_scene load_steps=3 format=3]
[ext_resource type="PackedScene" path="res://world/props/scenery_prop.tscn" id="base"]
[ext_resource type="Texture2D" path="res://assets/props/crate.svg" id="texture"]
[node name="Crate" instance=ExtResource("base")]
texture = ExtResource("texture")
display_size = Vector2(64, 64)
draw_layer = -2
collision_enabled = true
collision_dimensions = Vector2(60, 60)
collision_offset = Vector2(0, -30)
+10
View File
@@ -0,0 +1,10 @@
[gd_scene load_steps=3 format=3]
[ext_resource type="PackedScene" path="res://world/props/scenery_prop.tscn" id="base"]
[ext_resource type="Texture2D" path="res://assets/city/facade_01.png" id="texture"]
[node name="Facade01" instance=ExtResource("base")]
texture = ExtResource("texture")
display_size = Vector2(216, 490)
draw_layer = -8
collision_enabled = false
collision_dimensions = Vector2(216, 490)
collision_offset = Vector2(0, -245.0)
+10
View File
@@ -0,0 +1,10 @@
[gd_scene load_steps=3 format=3]
[ext_resource type="PackedScene" path="res://world/props/scenery_prop.tscn" id="base"]
[ext_resource type="Texture2D" path="res://assets/city/facade_02.png" id="texture"]
[node name="Facade02" instance=ExtResource("base")]
texture = ExtResource("texture")
display_size = Vector2(188, 414)
draw_layer = -8
collision_enabled = false
collision_dimensions = Vector2(188, 414)
collision_offset = Vector2(0, -207.0)
+10
View File
@@ -0,0 +1,10 @@
[gd_scene load_steps=3 format=3]
[ext_resource type="PackedScene" path="res://world/props/scenery_prop.tscn" id="base"]
[ext_resource type="Texture2D" path="res://assets/city/facade_03.png" id="texture"]
[node name="Facade03" instance=ExtResource("base")]
texture = ExtResource("texture")
display_size = Vector2(264, 544)
draw_layer = -8
collision_enabled = false
collision_dimensions = Vector2(264, 544)
collision_offset = Vector2(0, -272.0)
+10
View File
@@ -0,0 +1,10 @@
[gd_scene load_steps=3 format=3]
[ext_resource type="PackedScene" path="res://world/props/scenery_prop.tscn" id="base"]
[ext_resource type="Texture2D" path="res://assets/city/facade_04.png" id="texture"]
[node name="Facade04" instance=ExtResource("base")]
texture = ExtResource("texture")
display_size = Vector2(224, 446)
draw_layer = -8
collision_enabled = false
collision_dimensions = Vector2(224, 446)
collision_offset = Vector2(0, -223.0)
+10
View File
@@ -0,0 +1,10 @@
[gd_scene load_steps=3 format=3]
[ext_resource type="PackedScene" path="res://world/props/scenery_prop.tscn" id="base"]
[ext_resource type="Texture2D" path="res://assets/city/facade_05.png" id="texture"]
[node name="Facade05" instance=ExtResource("base")]
texture = ExtResource("texture")
display_size = Vector2(278, 590)
draw_layer = -8
collision_enabled = false
collision_dimensions = Vector2(278, 590)
collision_offset = Vector2(0, -295.0)
+10
View File
@@ -0,0 +1,10 @@
[gd_scene load_steps=3 format=3]
[ext_resource type="PackedScene" path="res://world/props/scenery_prop.tscn" id="base"]
[ext_resource type="Texture2D" path="res://assets/city/facade_06.png" id="texture"]
[node name="Facade06" instance=ExtResource("base")]
texture = ExtResource("texture")
display_size = Vector2(240, 514)
draw_layer = -8
collision_enabled = false
collision_dimensions = Vector2(240, 514)
collision_offset = Vector2(0, -257.0)
Loaded 100 of 115 files, more files were not shown because too many files have changed in this diff. Show more