diff --git a/docs/booth-runbook.md b/docs/booth-runbook.md index 0a548ae7..0b70eaa7 100644 --- a/docs/booth-runbook.md +++ b/docs/booth-runbook.md @@ -45,7 +45,7 @@ Booth mode itself runs fullscreen and ignores the menu's **Quit Game**. A game n | The game freezes | The watchdog restarts it within about a minute. | | Someone presses Cmd+Q | The game closes, and the watchdog opens it again. | | The player's controller disconnects | The game pauses and asks for the controller. Plug it back in, or press Start on another controller. | -| You want to clear the Endless Runner scores | Start the Endless Runner tile, pause (Esc or Start) and choose **Leaderboard → Reset scores**, then **Reset** to confirm. | +| You want to clear a game's scores | Start that game's tile, pause (Esc or Start) and choose **Leaderboard → Reset scores**, then **Reset** to confirm. Each game has its own board. | ## Stop the game for maintenance diff --git a/docs/enchanted-repo.md b/docs/enchanted-repo.md index 602ebc0c..04debf42 100644 --- a/docs/enchanted-repo.md +++ b/docs/enchanted-repo.md @@ -16,7 +16,7 @@ The 5,300-pixel route has three gaps (160–170 px), six solid raised root platf Branches support Hoppy until 0.7 seconds after landing, then remove collision, show breaking/falling art, and regrow after a 0.25-second break plus 3.5-second absence. Regrowth waits if Hoppy occupies the future platform shape. Pause freezes all timers. Branches over gaps provide stepping stones; falling into a pit still kills Hoppy through the normal retry flow. -Comment traps and Spaghetti Code Vines use 2.0 seconds dormant, 0.9 seconds amber warning, 0.45 seconds active, and 1.55 seconds recovery. Only active intervals damage. Comment traps mark a 64×130 vertical region. Vines mark a 155×48 low horizontal region on their fixed attack side; jump over it or wait. Rectangular cues show actual damage extents. Vines are environmental hazards in v1, not destructible enemies. +Comment traps and Spaghetti Code Vines use 2.0 seconds dormant, 0.9 seconds amber warning, 0.45 seconds active, and 1.55 seconds recovery. Only active intervals damage. Comment traps damage a 64×130 vertical region. A vine stands on its root and lashes out 120 px to its fixed attack side (a 140×48 low band that the `vine_whip` frame covers, anchored by its root rocks so the tentacle reaches over the band instead of the sprite jumping sideways); jump over it or wait. The warning and whip frames are the only cues; no rectangle is drawn over the art. Vines are environmental hazards in v1, not destructible enemies. Nitpick Gnomes have 1 HP, a short patrol, a 0.6-second jab tell and 0.65-second recovery. Bloat Trolls have 2 HP, slower patrols, a 0.95-second club tell and 1.0-second recovery. Both attacks stay committed to the warned side, have a 0.22-second active interval, and disable contact damage during recovery. Ordinary kills award 100 points and tokens award 25. Auto-Fix defeats nearby ordinary enemies but excludes the boss. Shared shields, 1.2-second post-hit invulnerability, player movement, jump buffering, coyote time, pause, and results are unchanged. @@ -32,7 +32,7 @@ The Monolith has **3 outer-armor hits + 3 inner-armor hits + 6 core hits**. Ordi | Dependency Sweep | 0.9s committed direction tell, 0.25s low sweep reaching 215px, 1.4s recovery | | Regression Stomp | 1.0s raised-foot tell, 0.2s local impact within 95px, one 260px/s ground shockwave, 1.6s recovery | -Slow tracking intervals separate attacks. The boss stays between x=4350 and 4810, and stops advancing within 160px of Hoppy. Jumping clears the low attacks. Damage remains one heart; reach, commitment and knockback provide the heavy impact. The wave uses Orbital's terrain/player collision and swept movement ray, expires after four seconds, and respects shields/i-frames. The independently generated armor sheets use adjusted offsets/scales to keep feet and approximate body height consistent. +Slow tracking intervals separate attacks. The boss stays between x=4350 and 4810, and stops advancing within 160px of Hoppy; while it advances it plays its `walk` cycle (four frames per sheet, added by `tools/build_monolith_walk.py` from the idle poses: a lean to each side about the feet with a lift between them) and stands on `idle` once close. Attack telegraphs are the warning poses themselves; no outline is drawn over the art. Jumping clears the low attacks. Damage remains one heart; reach, commitment and knockback provide the heavy impact. The wave uses Orbital's terrain/player collision and swept movement ray, expires after four seconds, and respects shields/i-frames. The independently generated armor sheets use adjusted offsets/scales to keep feet and approximate body height consistent. Defeat awards 1,000 points once, leaves the final rubble pose, clears projectiles, opens the gates, restores the following camera, resumes traversal music, and unlocks MERGE. HP, armor and timers are per-instance; SpriteFrames resources are never mutated. diff --git a/docs/main-menu.md b/docs/main-menu.md index 314d7076..6fce6df6 100644 --- a/docs/main-menu.md +++ b/docs/main-menu.md @@ -66,12 +66,12 @@ The first time a visitor enters a game, `AppRouter.go()` opens that game's how-t All six games share one pause menu, `app/pause_menu.gd`, built in code in the hub's style (`menu_style.gd`, the how-to-play card's panel colours, outlined text). Esc, P or Start opens and closes it; a game pauses itself (the tree, or its own state machine) and calls `open()` / `close()`, so each game keeps its pause rules, its focus-loss pause and ControllerService's pad-disconnect pause, which synthesizes the same `pause` action. -- **Buttons.** **Resume**, **Restart**, **How to Play**, **Main Menu**; the Endless Runner adds **Leaderboard** before Main Menu. Up and down wrap (arrows, D-pad, stick), Enter or the pad's bottom button confirms, mouse hover focuses and a click presses. The menu binds neither `pause` nor `ui_cancel` itself: Esc is both actions and the game owns the toggle, so the pad's B does nothing on the menu and Start or Esc resumes. The first press of Restart or Main Menu locks every button until the router's fade has carried the player away. +- **Buttons.** **Resume**, **Restart**, **How to Play**, **Leaderboard**, **Main Menu**, the same in every game. Up and down wrap (arrows, D-pad, stick), Enter or the pad's bottom button confirms, mouse hover focuses and a click presses. The menu binds neither `pause` nor `ui_cancel` itself: Esc is both actions and the game owns the toggle, so the pad's B does nothing on the menu and Start or Esc resumes. The first press of Restart or Main Menu locks every button until the router's fade has carried the player away. - **Restart** reloads the game's own route (a fresh scene; the how-to-play card doesn't reappear because the visitor has seen it). **Main Menu** runs the game's leave path (stop its music, cancel its sequences) and ends in `AppRouter.go("hub")`. The platformer stays paused under the router's fade and the router unpauses the tree once the hub is in; the brawlers and the runner unpause first, as before. - **Results stay the games' own.** The platformer's MERGE SUCCESSFUL / BUILD FAILED overlay offers **Retry ** and **Main Menu**; the brawlers' REVIEW FAILED and victory screens and the runner's CAUGHT BY THE BACKLOG screen offer their retries and **Main Menu**. The Code City opening story's bar has **Main Menu** too. -- **Runner leaderboard.** **Leaderboard** opens `scenes/runner/ui/leaderboard_panel.gd` over the paused run: the local top ten with medals, **Reset scores** (a confirmation asks first; a failed reset reloads the rows from disk and says so) and **Close**. Esc, B or Start inside the panel closes the confirmation first, then the panel, and never reaches the run's pause toggle; focus returns to the Leaderboard button. The game-over screen keeps showing the top ten. +- **Leaderboards.** Every game keeps a local top ten. `app/leaderboards.gd` maps a route to its board (`user://leaderboards/.cfg`; the runner keeps `user://leaderboard.cfg`) on the runner's leaderboard engine (`scenes/runner/systems/runner_leaderboard.gd`: validated rows, atomic writes with a `.bak`, a schema version). A finished run is recorded where the game ends it: the platformers' results overlay, the brawlers' REVIEW FAILED and victory screens, and the runner's game over as before; a placing shows there as **LEADERBOARD #n**. A booth has no keyboard within reach, so those five games name a run `Hoppy hh:mm` after the time it finished; only the runner has name entry. **Leaderboard** on the pause menu opens `app/leaderboard_panel.gd` over the paused game: the game's top ten with medals, **Reset scores** (a confirmation asks first; a failed reset reloads the rows from disk and says so) and **Close**. Esc, B or Start inside the panel closes the confirmation first, then the panel, and never reaches the game's pause toggle; focus returns to the Leaderboard button. The runner's game-over screen keeps showing its top ten. A headless suite (anything run with `--script`) records to a scratch folder of its own (`user://test_leaderboards_/`, emptied the first time the run uses it and removed by `Leaderboards.clear_scratch()`) unless it sets `Leaderboards.override_dir`; the runner's default `leaderboard_path` comes from the same mapping, so a suite run by hand never touches a player's boards in any game. `tools/tests/run_tests.py` isolates `user://` entirely anyway. - **Audio.** The menu plays the hub's UI blips (`AudioService.sfx` processes while the tree is paused) and touches nothing else: pausable music stops with the tree as before. -- **Tests.** `tests/pause_menu.gd` opens the menu in all six games through the `pause` action and checks the buttons, focus wrap, Resume, Restart, Main Menu (hub, unpaused, hub music), the How to Play card and, for the runner, the leaderboard panel. `tests/menu_return_layout.gd` returns from Bay Area Blitz through the pause menu and the results; `tests/runner_visual_smoke.gd` drives the runner's leaderboard and Reset scores flow. +- **Tests.** `tests/pause_menu.gd` opens the menu in all six games through the `pause` action and checks the buttons, focus wrap, Resume, Restart, Main Menu (hub, unpaused, hub music), the How to Play card and, for the runner, the leaderboard panel; `tests/leaderboards.gd` covers the per-game boards and the shared panel. `tests/menu_return_layout.gd` returns from Bay Area Blitz through the pause menu and the results; `tests/runner_visual_smoke.gd` drives the runner's leaderboard and Reset scores flow. ![Runner leaderboard panel over a paused run](previews/pause-menu-runner-leaderboard.png) diff --git a/hoppys-adventure-arcade/Assets/enchanted-repo-assets-only/PROMPTS.md b/hoppys-adventure-arcade/Assets/enchanted-repo-assets-only/PROMPTS.md index de726ad1..2868df5a 100644 --- a/hoppys-adventure-arcade/Assets/enchanted-repo-assets-only/PROMPTS.md +++ b/hoppys-adventure-arcade/Assets/enchanted-repo-assets-only/PROMPTS.md @@ -41,3 +41,7 @@ Use case: precise-object-edit. Fix sprite sheet packing ONLY. Preserve every one ## monolith_armor correction Use case: precise-object-edit. Reformat this sheet into a SQUARE image, exact 4 by 4 grid. Keep these EXACT 16 poses and their order, same stone golem identity, pixel-art style, armor stages and colors. Each square cell must have HUGE empty transparent margins: character and effects occupy ONLY THE CENTRAL 60% of each cell's width AND height. Uniform small character size. Rows separated by large completely transparent horizontal bands. Columns separated by large completely transparent vertical bands. This is a game sprite atlas, NOT a full-bleed illustration. No character part or debris may enter another cell. Background truly transparent. Do not add text, gridlines or labels. + +## legacy_monolith and monolith_armor walk rows + +Not generated: `tools/build_monolith_walk.py` (November 2026) appends one `walk` row of four frames to `legacy_monolith.png` and `cracked_walk` / `bare_walk` rows to `monolith_armor.png`, each frame the matching idle pose leaned 3° about the pivot (left, up, right, up) with a 5 px lift on the off-steps, nearest-neighbour and re-thresholded so the pixels stay crisp. The manifest and both `.tres` files list them; the script is deterministic and leaves a sheet that already has its rows alone. diff --git a/hoppys-adventure-arcade/Assets/enchanted-repo-assets-only/enchanted_repo/legacy_monolith.png b/hoppys-adventure-arcade/Assets/enchanted-repo-assets-only/enchanted_repo/legacy_monolith.png index 10f20177..4ea7ba19 100644 Binary files a/hoppys-adventure-arcade/Assets/enchanted-repo-assets-only/enchanted_repo/legacy_monolith.png and b/hoppys-adventure-arcade/Assets/enchanted-repo-assets-only/enchanted_repo/legacy_monolith.png differ diff --git a/hoppys-adventure-arcade/Assets/enchanted-repo-assets-only/enchanted_repo/legacy_monolith.tres b/hoppys-adventure-arcade/Assets/enchanted-repo-assets-only/enchanted_repo/legacy_monolith.tres index 68782bbc..32cbdfad 100644 --- a/hoppys-adventure-arcade/Assets/enchanted-repo-assets-only/enchanted_repo/legacy_monolith.tres +++ b/hoppys-adventure-arcade/Assets/enchanted-repo-assets-only/enchanted_repo/legacy_monolith.tres @@ -1,4 +1,4 @@ -[gd_resource type="SpriteFrames" load_steps=26 format=3] +[gd_resource type="SpriteFrames" load_steps=30 format=3] [ext_resource type="Texture2D" path="legacy_monolith.png" id="1"] @@ -122,6 +122,26 @@ atlas = ExtResource("1") region = Rect2(576, 960, 192, 192) filter_clip = true +[sub_resource type="AtlasTexture" id="F24"] +atlas = ExtResource("1") +region = Rect2(0, 1152, 192, 192) +filter_clip = true + +[sub_resource type="AtlasTexture" id="F25"] +atlas = ExtResource("1") +region = Rect2(192, 1152, 192, 192) +filter_clip = true + +[sub_resource type="AtlasTexture" id="F26"] +atlas = ExtResource("1") +region = Rect2(384, 1152, 192, 192) +filter_clip = true + +[sub_resource type="AtlasTexture" id="F27"] +atlas = ExtResource("1") +region = Rect2(576, 1152, 192, 192) +filter_clip = true + [resource] animations = [ {"frames": [{"duration": 1.0, "texture": SubResource("F0")}, {"duration": 1.0, "texture": SubResource("F1")}, {"duration": 1.0, "texture": SubResource("F2")}, {"duration": 1.0, "texture": SubResource("F3")}], "loop": true, "name": &"idle", "speed": 4.0}, @@ -139,5 +159,6 @@ animations = [ {"frames": [{"duration": 1.0, "texture": SubResource("F18")}], "loop": false, "name": &"armor_break", "speed": 5.0}, {"frames": [{"duration": 1.0, "texture": SubResource("F19")}], "loop": true, "name": &"exposed", "speed": 4.0}, {"frames": [{"duration": 1.0, "texture": SubResource("F20")}], "loop": false, "name": &"core_hurt", "speed": 8.0}, -{"frames": [{"duration": 1.0, "texture": SubResource("F21")}, {"duration": 1.0, "texture": SubResource("F22")}, {"duration": 1.0, "texture": SubResource("F23")}], "loop": false, "name": &"defeat", "speed": 4.0} +{"frames": [{"duration": 1.0, "texture": SubResource("F21")}, {"duration": 1.0, "texture": SubResource("F22")}, {"duration": 1.0, "texture": SubResource("F23")}], "loop": false, "name": &"defeat", "speed": 4.0}, +{"frames": [{"duration": 1.0, "texture": SubResource("F24")}, {"duration": 1.0, "texture": SubResource("F25")}, {"duration": 1.0, "texture": SubResource("F26")}, {"duration": 1.0, "texture": SubResource("F27")}], "loop": true, "name": &"walk", "speed": 6.0} ] diff --git a/hoppys-adventure-arcade/Assets/enchanted-repo-assets-only/enchanted_repo/manifest.json b/hoppys-adventure-arcade/Assets/enchanted-repo-assets-only/enchanted_repo/manifest.json index 5bbf1e38..1e3eacda 100644 --- a/hoppys-adventure-arcade/Assets/enchanted-repo-assets-only/enchanted_repo/manifest.json +++ b/hoppys-adventure-arcade/Assets/enchanted-repo-assets-only/enchanted_repo/manifest.json @@ -12,7 +12,7 @@ ], "grid": [ 4, - 6 + 7 ], "pivot": [ 96, @@ -379,6 +379,66 @@ 167, 173 ] + }, + { + "index": 24, + "rect": [ + 0, + 1152, + 192, + 192 + ], + "visible_bounds": [ + 38, + 33, + 158, + 175 + ] + }, + { + "index": 25, + "rect": [ + 192, + 1152, + 192, + 192 + ], + "visible_bounds": [ + 36, + 27, + 155, + 168 + ] + }, + { + "index": 26, + "rect": [ + 384, + 1152, + 192, + 192 + ], + "visible_bounds": [ + 34, + 31, + 152, + 175 + ] + }, + { + "index": 27, + "rect": [ + 576, + 1152, + 192, + 192 + ], + "visible_bounds": [ + 36, + 27, + 155, + 168 + ] } ], "clips": [ @@ -517,6 +577,17 @@ ], "fps": 4, "loop": false + }, + { + "name": "walk", + "frames": [ + 24, + 25, + 26, + 27 + ], + "fps": 6, + "loop": true } ], "source_rects_ltrb": [ @@ -663,6 +734,30 @@ 1378, 1013, 1516 + ], + [ + 30, + 12, + 229, + 247 + ], + [ + 285, + 12, + 485, + 247 + ], + [ + 542, + 12, + 741, + 247 + ], + [ + 798, + 12, + 997, + 247 ] ], "source_scale": 0.6166423357664234, @@ -2507,7 +2602,7 @@ ], "grid": [ 4, - 4 + 6 ], "pivot": [ 128, @@ -2754,6 +2849,126 @@ 215, 230 ] + }, + { + "index": 16, + "rect": [ + 0, + 1024, + 256, + 256 + ], + "visible_bounds": [ + 65, + 97, + 195, + 233 + ] + }, + { + "index": 17, + "rect": [ + 256, + 1024, + 256, + 256 + ], + "visible_bounds": [ + 63, + 91, + 192, + 225 + ] + }, + { + "index": 18, + "rect": [ + 512, + 1024, + 256, + 256 + ], + "visible_bounds": [ + 61, + 95, + 189, + 233 + ] + }, + { + "index": 19, + "rect": [ + 768, + 1024, + 256, + 256 + ], + "visible_bounds": [ + 63, + 91, + 192, + 225 + ] + }, + { + "index": 20, + "rect": [ + 0, + 1280, + 256, + 256 + ], + "visible_bounds": [ + 62, + 102, + 198, + 234 + ] + }, + { + "index": 21, + "rect": [ + 256, + 1280, + 256, + 256 + ], + "visible_bounds": [ + 61, + 97, + 195, + 226 + ] + }, + { + "index": 22, + "rect": [ + 512, + 1280, + 256, + 256 + ], + "visible_bounds": [ + 59, + 102, + 192, + 234 + ] + }, + { + "index": 23, + "rect": [ + 768, + 1280, + 256, + 256 + ], + "visible_bounds": [ + 61, + 97, + 195, + 226 + ] } ], "clips": [ @@ -2884,6 +3099,28 @@ ], "fps": 4, "loop": true + }, + { + "name": "cracked_walk", + "frames": [ + 16, + 17, + 18, + 19 + ], + "fps": 6, + "loop": true + }, + { + "name": "bare_walk", + "frames": [ + 20, + 21, + 22, + 23 + ], + "fps": 6, + "loop": true } ], "source_rects_ltrb": [ @@ -2982,6 +3219,54 @@ 1010, 1232, 1183 + ], + [ + 62, + 84, + 265, + 296 + ], + [ + 62, + 84, + 265, + 296 + ], + [ + 62, + 84, + 265, + 296 + ], + [ + 62, + 84, + 265, + 296 + ], + [ + 63, + 693, + 275, + 896 + ], + [ + 63, + 693, + 275, + 896 + ], + [ + 63, + 693, + 275, + 896 + ], + [ + 63, + 693, + 275, + 896 ] ], "source_scale": 0.6625882352941177, diff --git a/hoppys-adventure-arcade/Assets/enchanted-repo-assets-only/enchanted_repo/monolith_armor.png b/hoppys-adventure-arcade/Assets/enchanted-repo-assets-only/enchanted_repo/monolith_armor.png index b7f11790..2b99de40 100644 Binary files a/hoppys-adventure-arcade/Assets/enchanted-repo-assets-only/enchanted_repo/monolith_armor.png and b/hoppys-adventure-arcade/Assets/enchanted-repo-assets-only/enchanted_repo/monolith_armor.png differ diff --git a/hoppys-adventure-arcade/Assets/enchanted-repo-assets-only/enchanted_repo/monolith_armor.tres b/hoppys-adventure-arcade/Assets/enchanted-repo-assets-only/enchanted_repo/monolith_armor.tres index 43b3a044..eee469c3 100644 --- a/hoppys-adventure-arcade/Assets/enchanted-repo-assets-only/enchanted_repo/monolith_armor.tres +++ b/hoppys-adventure-arcade/Assets/enchanted-repo-assets-only/enchanted_repo/monolith_armor.tres @@ -1,4 +1,4 @@ -[gd_resource type="SpriteFrames" load_steps=18 format=3] +[gd_resource type="SpriteFrames" load_steps=26 format=3] [ext_resource type="Texture2D" path="monolith_armor.png" id="1"] @@ -82,6 +82,46 @@ atlas = ExtResource("1") region = Rect2(768, 768, 256, 256) filter_clip = true +[sub_resource type="AtlasTexture" id="F16"] +atlas = ExtResource("1") +region = Rect2(0, 1024, 256, 256) +filter_clip = true + +[sub_resource type="AtlasTexture" id="F17"] +atlas = ExtResource("1") +region = Rect2(256, 1024, 256, 256) +filter_clip = true + +[sub_resource type="AtlasTexture" id="F18"] +atlas = ExtResource("1") +region = Rect2(512, 1024, 256, 256) +filter_clip = true + +[sub_resource type="AtlasTexture" id="F19"] +atlas = ExtResource("1") +region = Rect2(768, 1024, 256, 256) +filter_clip = true + +[sub_resource type="AtlasTexture" id="F20"] +atlas = ExtResource("1") +region = Rect2(0, 1280, 256, 256) +filter_clip = true + +[sub_resource type="AtlasTexture" id="F21"] +atlas = ExtResource("1") +region = Rect2(256, 1280, 256, 256) +filter_clip = true + +[sub_resource type="AtlasTexture" id="F22"] +atlas = ExtResource("1") +region = Rect2(512, 1280, 256, 256) +filter_clip = true + +[sub_resource type="AtlasTexture" id="F23"] +atlas = ExtResource("1") +region = Rect2(768, 1280, 256, 256) +filter_clip = true + [resource] animations = [ {"frames": [{"duration": 1.0, "texture": SubResource("F0")}], "loop": true, "name": &"cracked_idle", "speed": 4.0}, @@ -99,5 +139,7 @@ animations = [ {"frames": [{"duration": 1.0, "texture": SubResource("F12")}], "loop": false, "name": &"bare_sweep", "speed": 4.0}, {"frames": [{"duration": 1.0, "texture": SubResource("F13")}], "loop": false, "name": &"bare_stomp_warning", "speed": 4.0}, {"frames": [{"duration": 1.0, "texture": SubResource("F14")}], "loop": false, "name": &"bare_stomp", "speed": 4.0}, -{"frames": [{"duration": 1.0, "texture": SubResource("F15")}], "loop": true, "name": &"bare_exposed", "speed": 4.0} +{"frames": [{"duration": 1.0, "texture": SubResource("F15")}], "loop": true, "name": &"bare_exposed", "speed": 4.0}, +{"frames": [{"duration": 1.0, "texture": SubResource("F16")}, {"duration": 1.0, "texture": SubResource("F17")}, {"duration": 1.0, "texture": SubResource("F18")}, {"duration": 1.0, "texture": SubResource("F19")}], "loop": true, "name": &"cracked_walk", "speed": 6.0}, +{"frames": [{"duration": 1.0, "texture": SubResource("F20")}, {"duration": 1.0, "texture": SubResource("F21")}, {"duration": 1.0, "texture": SubResource("F22")}, {"duration": 1.0, "texture": SubResource("F23")}], "loop": true, "name": &"bare_walk", "speed": 6.0} ] diff --git a/hoppys-adventure-arcade/app/leaderboard_panel.gd b/hoppys-adventure-arcade/app/leaderboard_panel.gd new file mode 100644 index 00000000..15ac5d30 --- /dev/null +++ b/hoppys-adventure-arcade/app/leaderboard_panel.gd @@ -0,0 +1,229 @@ +extends Control +## A game's local top ten with its Reset scores flow, opened from the pause menu. It processes +## while the game is paused (its parent is the always-processing pause menu). `ui_cancel` or +## `pause` closes the confirmation first, then the panel, and never reaches the game. Reset asks +## twice; a failed reset reloads the rows from disk and reports it. `leaderboard_path` picks the +## board (app/leaderboards.gd maps a route to one) and `title` names it. + +signal closed + +const Style = preload("res://scenes/runner/ui/hud_style.gd") +const Palette = preload("res://scenes/runner/environment/runner_palette.gd") +const Leaderboard = preload("res://scenes/runner/systems/runner_leaderboard.gd") + +var leaderboard_path := Leaderboard.DEFAULT_PATH +var title := "LOCAL LEADERBOARD" +## The path the open board read, so Reset clears what the player is looking at. +var leaderboard_path_at_open := Leaderboard.DEFAULT_PATH +var board: VBoxContainer +var reset_btn: Button +var close_btn: Button +var reset_confirm: Control +var confirm_status: Label +@onready var audio_service: Node = get_node("/root/AudioService") +@onready var router: Node = get_node("/root/AppRouter") + +func _init() -> void: + name = "Leaderboard" + set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT) + mouse_filter = Control.MOUSE_FILTER_STOP + +func _ready() -> void: + theme = Style.theme() + var dim := ColorRect.new() + dim.color = Color(0.01, 0.02, 0.04, 0.9) + dim.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT) + dim.mouse_filter = Control.MOUSE_FILTER_IGNORE + add_child(dim) + var center := CenterContainer.new() + center.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT) + center.mouse_filter = Control.MOUSE_FILTER_IGNORE + add_child(center) + var panel := PanelContainer.new() + panel.custom_minimum_size = Vector2(720, 0) + panel.add_theme_stylebox_override("panel", _panel_style()) + Style.polish(panel, true) + center.add_child(panel) + var column := VBoxContainer.new() + column.add_theme_constant_override("separation", 14) + panel.add_child(column) + column.add_child(Style.label(title, 28)) + column.add_child(Style.label("RANK NAME SCORE TIME", 18, Style.MINT)) + board = VBoxContainer.new() + board.add_theme_constant_override("separation", 8) + column.add_child(board) + leaderboard_path_at_open = leaderboard_path + var entries := Leaderboard.load_entries(leaderboard_path_at_open) + _build_board_rows(entries) + var button_row := HBoxContainer.new() + button_row.add_theme_constant_override("separation", 12) + column.add_child(button_row) + reset_btn = Style.button("Reset scores", 46) + reset_btn.name = "ResetScoresButton" + reset_btn.disabled = entries.is_empty() + reset_btn.focus_entered.connect(_focus_sound) + reset_btn.mouse_entered.connect(_focus_sound) + reset_btn.pressed.connect(_open_reset_confirm) + button_row.add_child(reset_btn) + close_btn = Style.button("Close", 46) + close_btn.name = "CloseButton" + close_btn.focus_entered.connect(_focus_sound) + close_btn.mouse_entered.connect(_focus_sound) + close_btn.pressed.connect(close) + button_row.add_child(close_btn) + _wrap_pair(reset_btn, close_btn) + close_btn.grab_focus() + +func _panel_style() -> StyleBoxFlat: + var box := Style.panel(Style.MINT, 0.96) + box.content_margin_left = 24 + box.content_margin_right = 24 + box.content_margin_top = 20 + box.content_margin_bottom = 20 + return box + +## Focus wraps between two buttons in every direction. +static func _wrap_pair(a: Button, b: Button) -> void: + for pair in [[a, b], [b, a]]: + var from: Button = pair[0] + var to: NodePath = from.get_path_to(pair[1]) + from.focus_neighbor_left = to + from.focus_neighbor_right = to + from.focus_neighbor_top = to + from.focus_neighbor_bottom = to + from.focus_next = to + from.focus_previous = to + +func _focus_sound() -> void: + if not router.busy: + audio_service.play_ui(0) + +func _build_board_rows(entries: Array[Dictionary]) -> void: + for child in board.get_children(): + child.queue_free() + for i in 10: + var text := "%02d --- --- ---" % (i + 1) + if i < entries.size(): + var entry: Dictionary = entries[i] + var seconds := maxi(0, int(entry.duration)) + text = "%02d %-16s %8d %02d:%02d" % [i + 1, entry.name, entry.score, seconds / 60, seconds % 60] + var row := HBoxContainer.new() + row.add_child(rank_marker(i, i < entries.size())) + row.add_child(Style.label(text, 18)) + board.add_child(row) + +func close() -> void: + if router.busy: + return + audio_service.play_ui(1) + closed.emit() + queue_free() + +func _open_reset_confirm() -> void: + if reset_confirm or router.busy: + return + audio_service.play_ui(1) + reset_btn.disabled = true + close_btn.disabled = true + reset_confirm = Control.new() + reset_confirm.name = "ResetConfirm" + reset_confirm.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT) + add_child(reset_confirm) + var dim := ColorRect.new() + dim.color = Color(0.01, 0.02, 0.04, 0.9) + dim.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT) + reset_confirm.add_child(dim) + var center := CenterContainer.new() + center.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT) + center.mouse_filter = Control.MOUSE_FILTER_IGNORE + reset_confirm.add_child(center) + var panel := PanelContainer.new() + panel.custom_minimum_size = Vector2(620, 0) + panel.add_theme_stylebox_override("panel", _panel_style()) + Style.polish(panel, true) + center.add_child(panel) + var column := VBoxContainer.new() + column.add_theme_constant_override("separation", 16) + panel.add_child(column) + column.add_child(Style.label("RESET ALL SCORES?", 28)) + column.add_child(Style.label("This deletes the top ten and cannot be undone.", 18)) + var keep := Style.button("Keep scores", 46) + keep.name = "KeepScoresButton" + keep.focus_entered.connect(_focus_sound) + keep.mouse_entered.connect(_focus_sound) + keep.pressed.connect(_close_reset_confirm) + column.add_child(keep) + var do_reset := Style.button("Reset", 46) + do_reset.name = "ResetConfirmButton" + do_reset.focus_entered.connect(_focus_sound) + do_reset.mouse_entered.connect(_focus_sound) + do_reset.pressed.connect(_confirm_reset) + column.add_child(do_reset) + confirm_status = Style.label("", 16, Color("ff7185")) + confirm_status.name = "StatusLabel" + confirm_status.visible = false + column.add_child(confirm_status) + _wrap_pair(keep, do_reset) + keep.grab_focus() + +func _close_reset_confirm() -> void: + if not reset_confirm: + return + reset_confirm.queue_free() + reset_confirm = null + confirm_status = null + if is_instance_valid(reset_btn): + reset_btn.disabled = false + reset_btn.grab_focus() + if is_instance_valid(close_btn): + close_btn.disabled = false + audio_service.play_ui(1) + +func _confirm_reset() -> void: + if router.busy: + return + var error := Leaderboard.clear(leaderboard_path_at_open) + if error == OK: + reset_confirm.queue_free() + reset_confirm = null + confirm_status = null + _build_board_rows(Leaderboard.load_entries(leaderboard_path_at_open)) + if is_instance_valid(reset_btn): + reset_btn.disabled = true + if is_instance_valid(close_btn): + close_btn.disabled = false + close_btn.grab_focus() + audio_service.play_ui(1) + else: + # clear() may have written an empty primary before the .bak/.tmp removal failed: reload + # the rows so the board matches what is on disk. + var entries_after := Leaderboard.load_entries(leaderboard_path_at_open) + _build_board_rows(entries_after) + if is_instance_valid(reset_btn): + reset_btn.disabled = entries_after.is_empty() + if confirm_status != null: + confirm_status.text = "Could not reset scores." + confirm_status.visible = true + var keep_btn := reset_confirm.find_child("KeepScoresButton", true, false) as Button + if keep_btn != null: + keep_btn.grab_focus() + +## Back (Esc, B) or Start closes the confirmation first, then the board. Handled in _input so the +## press never also reaches the runner's pause toggle. +func _input(event: InputEvent) -> void: + if not visible or router.busy: + return + if event.is_action_pressed("ui_cancel") or event.is_action_pressed("pause"): + if reset_confirm: + _close_reset_confirm() + else: + close() + get_viewport().set_input_as_handled() + +static func rank_marker(index: int, occupied: bool) -> Control: + if occupied and index < 3: + return Style.icon(&"medal", [Palette.CREAM.lerp(Palette.ORANGE, 0.35), Palette.SLATE.lerp(Palette.CREAM, 0.65), Palette.ORANGE.lerp(Palette.NAVY_2, 0.3)][index], Vector2(24, 24)) + var spacer := Control.new() + spacer.custom_minimum_size = Vector2(24, 24) + spacer.mouse_filter = Control.MOUSE_FILTER_IGNORE + return spacer diff --git a/hoppys-adventure-arcade/app/leaderboard_panel.gd.uid b/hoppys-adventure-arcade/app/leaderboard_panel.gd.uid new file mode 100644 index 00000000..4d9526a6 --- /dev/null +++ b/hoppys-adventure-arcade/app/leaderboard_panel.gd.uid @@ -0,0 +1 @@ +uid://c3nb0467pn5w6 diff --git a/hoppys-adventure-arcade/app/leaderboards.gd b/hoppys-adventure-arcade/app/leaderboards.gd new file mode 100644 index 00000000..f98e763d --- /dev/null +++ b/hoppys-adventure-arcade/app/leaderboards.gd @@ -0,0 +1,83 @@ +extends RefCounted +## One local top ten per game. The Endless Runner's leaderboard engine +## (scenes/runner/systems/runner_leaderboard.gd: validated entries, atomic writes, a .bak, a +## schema version) stores every board; this maps a game's route to its file and records a finished +## run in one call. The runner keeps its own file and name-entry flow, so its route maps to the +## engine's default path and the other five games write under user://leaderboards/. +## +## A booth has no keyboard within players' reach, so a run is recorded under a name that still +## tells rows apart on the board: "Hoppy" plus the time of day it finished. + +const Board := preload("res://scenes/runner/systems/runner_leaderboard.gd") +const RUNNER_ROUTE := "runner_game" +const DIR := "user://leaderboards/" +const SCRATCH_PREFIX := "user://test_leaderboards_" +## Tests and dev captures point every board somewhere else with this; "" means the real files. +static var override_dir := "" +## A headless suite (run with --script, the convention AppRouter uses) that plays a game to its +## results screen records runs like any player. With no override_dir, those land in a scratch +## folder of this process instead of the player's boards, so a suite run outside +## tools/tests/run_tests.py (which gives each suite a private user://) still leaves them alone. +## The folder is named after the process and emptied the first time this run uses it, so rows +## a crashed run with the same id left behind never rank against this run's; other runs' folders +## are never touched, since two suites may share user:// at once. clear_scratch() removes it. +static var redirect_tests := true +static var scratch_dir := "" + +## The folder boards are written to: the override, a test's scratch folder, or the real one. +static func dir() -> String: + if not override_dir.is_empty(): + return override_dir + if redirect_tests and "--script" in OS.get_cmdline_args(): + return _scratch() + return DIR + +static func _scratch() -> String: + if scratch_dir.is_empty(): + scratch_dir = "%s%d/" % [SCRATCH_PREFIX, OS.get_process_id()] + clear_scratch(scratch_dir) + return scratch_dir + +## Removes a test's scratch folder (this process's by default) and the boards in it. +static func clear_scratch(folder := scratch_dir) -> void: + if folder.is_empty() or not DirAccess.dir_exists_absolute(folder): + return + for file in DirAccess.get_files_at(folder): + DirAccess.remove_absolute(folder + file) + DirAccess.remove_absolute(folder) + +## The board file for `route`. +static func path_for(route: String) -> String: + if route == RUNNER_ROUTE and dir() == DIR: + return Board.DEFAULT_PATH + return dir() + route + ".cfg" + +## Records a finished run and returns the engine's {rank, entries, error}: rank is 1-10 when the +## run placed, 0 otherwise. `duration` is the run's length in seconds. +static func record(route: String, score: int, duration: float, player_name := "") -> Dictionary: + var now := int(Time.get_unix_time_from_system()) + return Board.submit({ + "run_id": "%s-%d-%d" % [route, now, Time.get_ticks_usec()], + "name": player_name if not player_name.is_empty() else default_name(), + "score": maxi(0, score), + "duration": maxf(0.0, duration), + "seed": 0, + "submitted_at": now, + }, path_for(route)) + +## The sorted rows of `route`'s board, best first. +static func entries(route: String) -> Array[Dictionary]: + return Board.load_entries(path_for(route)) + +## "Hoppy 14:32": the mascot plus the local time, so a booth's board stays readable without typing. +static func default_name() -> String: + var clock := Time.get_time_dict_from_system() + return "Hoppy %02d:%02d" % [int(clock.hour), int(clock.minute)] + +## The line a results screen shows for a recorded run: a rank, or nothing when it did not place +## or could not be saved. +static func rank_line(result: Dictionary) -> String: + var rank := int(result.get("rank", 0)) + if rank <= 0 or int(result.get("error", OK)) != OK: + return "" + return "LEADERBOARD #%d" % rank diff --git a/hoppys-adventure-arcade/app/leaderboards.gd.uid b/hoppys-adventure-arcade/app/leaderboards.gd.uid new file mode 100644 index 00000000..7cf775ba --- /dev/null +++ b/hoppys-adventure-arcade/app/leaderboards.gd.uid @@ -0,0 +1 @@ +uid://cwnlklaopekpv diff --git a/hoppys-adventure-arcade/app/pause_menu.gd b/hoppys-adventure-arcade/app/pause_menu.gd index 16ed62e4..40388266 100644 --- a/hoppys-adventure-arcade/app/pause_menu.gd +++ b/hoppys-adventure-arcade/app/pause_menu.gd @@ -7,12 +7,16 @@ extends CanvasLayer ## pause on the `pause` action (ControllerService synthesizes that action on a pad disconnect). ## Restart and Main Menu run the game's callables, which end in AppRouter.go(); the menu locks its ## buttons on that press so a second press during the router's fade does nothing. -## A game may add a button of its own before Main Menu (the runner's Leaderboard). +## Every game also gets a Leaderboard button that opens its local top ten (app/leaderboards.gd +## maps the route to the board) over the menu; the runner points it at its own board. A game may +## add further buttons of its own before Main Menu with add_button(). const Style := preload("res://scenes/main_menu/menu_style.gd") const Data := preload("res://app/how_to_play_data.gd") const Prompts := preload("res://app/controller_prompts.gd") const HowToPlay := preload("res://app/how_to_play.gd") +const Leaderboards := preload("res://app/leaderboards.gd") +const LeaderboardPanel := preload("res://app/leaderboard_panel.gd") ## Above every game's HUD, results and story layers (at most 22), below the how-to-play card (89), ## ControllerService's disconnect banner (90) and the router's fade (100). @@ -31,6 +35,12 @@ var resume_button: Button var restart_button: Button var how_to_play_button: Button var menu_button: Button +var leaderboard_button: Button +## The board file the Leaderboard button opens; set after setup() to point at another board +## (the runner's game owns its path, tests use scratch files). +var leaderboard_path := "" +## The open leaderboard panel, or null. +var leaderboard: Control ## Every button in focus order, Main Menu last. var buttons: Array[Button] = [] var locked := false @@ -66,6 +76,9 @@ func setup(game_route: String, on_resume: Callable, on_restart: Callable, on_lea var title: String = Data.game(route).get("title", "") if Data.has_game(route) else "" eyebrow.text = title.to_upper() eyebrow.visible = not title.is_empty() + leaderboard_path = Leaderboards.path_for(route) + if leaderboard_button == null: + leaderboard_button = add_button("Leaderboard", _open_leaderboard) func _build() -> void: ui = Control.new() @@ -174,10 +187,40 @@ func open(detail := "") -> void: resume_button.grab_focus() _opening = false -## Hides the menu. The game unpauses itself; this never touches the tree. +## Hides the menu. The game unpauses itself; this never touches the tree. Closing the menu +## (resume, pad reconnect, a route change) takes an open leaderboard with it. func close() -> void: + if is_instance_valid(leaderboard): + leaderboard.closed.disconnect(_on_leaderboard_closed) + leaderboard.queue_free() + leaderboard = null + _set_menu_enabled(true) visible = false +## Opens the game's top ten over the menu. The board owns the screen while it is up: the menu's +## own buttons can't be reached until it closes. +func _open_leaderboard() -> void: + if leaderboard != null: + return + _set_menu_enabled(false) + leaderboard = LeaderboardPanel.new() + leaderboard.leaderboard_path = leaderboard_path + var title: String = Data.game(route).get("title", "") if Data.has_game(route) else "" + leaderboard.title = (title.to_upper() + " · " if not title.is_empty() else "") + "LOCAL TOP 10" + leaderboard.closed.connect(_on_leaderboard_closed) + ui.add_child(leaderboard) + +func _on_leaderboard_closed() -> void: + leaderboard = null + _set_menu_enabled(true) + if visible: + leaderboard_button.grab_focus() + +func _set_menu_enabled(enabled: bool) -> void: + for button in buttons: + button.disabled = not enabled or locked + button.focus_mode = Control.FOCUS_ALL if enabled else Control.FOCUS_NONE + func is_open() -> bool: return visible diff --git a/hoppys-adventure-arcade/modes/beatem_up/game.gd b/hoppys-adventure-arcade/modes/beatem_up/game.gd index c4129060..753d425b 100644 --- a/hoppys-adventure-arcade/modes/beatem_up/game.gd +++ b/hoppys-adventure-arcade/modes/beatem_up/game.gd @@ -13,6 +13,7 @@ const VictoryScreen = preload("res://modes/beatem_up/victory_screen.gd") const Minimap = preload("res://modes/beatem_up/minimap.gd") const Style = preload("res://scenes/main_menu/menu_style.gd") const PauseMenu = preload("res://app/pause_menu.gd") +const Leaderboards = preload("res://app/leaderboards.gd") ## This game's AppRouter route: Restart reloads it. const ROUTE := "code_city_brawl" const PAUSABLE := ["combat","intro","ending","stage_enter","stage_exit","knockout","boss_victory","celebration"] @@ -608,8 +609,12 @@ func game_over() -> void: playing = false state = "game_over" _update_hud() + # The run goes on this game's local top ten (app/leaderboards.gd) before the booth may move on. + var placing := Leaderboards.rank_line(Leaderboards.record(ROUTE, score, elapsed)) if AppRouter.booth_game_over("SCORE %05d" % score): return # Booth: the next player's turn. - show_overlay("REVIEW FAILED", "Retry %s with 3 HP and fresh equipment." % Catalog.TITLES[stage_index],"Retry current stage",retry_stage) + var detail := "Retry %s with 3 HP and fresh equipment." % Catalog.TITLES[stage_index] + if not placing.is_empty(): detail += "\n" + placing + show_overlay("REVIEW FAILED", detail,"Retry current stage",retry_stage) func boss_defeated() -> void: # A knocked-out Hoppy can't win: the knockout ends in game over. @@ -733,7 +738,9 @@ func show_victory() -> void: overlay.hide() hide_toast() prompt.text = "" - victory.show_result(Catalog.VICTORY.title,Catalog.VICTORY.line,score,elapsed,Catalog.STORY_ACCENT,"Main Menu",leave) + var placing := Leaderboards.rank_line(Leaderboards.record(ROUTE, score, elapsed)) + var line: String = Catalog.VICTORY.line + ("" if placing.is_empty() else " · " + placing) + victory.show_result(Catalog.VICTORY.title,line,score,elapsed,Catalog.STORY_ACCENT,"Main Menu",leave) func toast(message: String, seconds := 2.0) -> void: # Combat opens under the fading stage title; anything said then waits for it (latest wins). diff --git a/hoppys-adventure-arcade/modes/beatem_up/reinvent/game.gd b/hoppys-adventure-arcade/modes/beatem_up/reinvent/game.gd index 4ae5d1eb..ce7052cc 100644 --- a/hoppys-adventure-arcade/modes/beatem_up/reinvent/game.gd +++ b/hoppys-adventure-arcade/modes/beatem_up/reinvent/game.gd @@ -8,6 +8,7 @@ const StageFlow = preload("res://modes/beatem_up/stage_flow.gd") const Knockout = preload("res://modes/beatem_up/knockout.gd") const Style = preload("res://scenes/main_menu/menu_style.gd") const PauseMenu = preload("res://app/pause_menu.gd") +const Leaderboards = preload("res://app/leaderboards.gd") ## This game's AppRouter route: Restart reloads it. const ROUTE := "heroes_vs_villains" const VictoryScreen = preload("res://modes/beatem_up/victory_screen.gd") @@ -581,8 +582,12 @@ func game_over() -> void: playing = false state = "game_over" _update_hud() + # The run goes on this game's local top ten (app/leaderboards.gd) before the booth may move on. + var placing := Leaderboards.rank_line(Leaderboards.record(ROUTE, score, elapsed)) if AppRouter.booth_game_over("SCORE %05d" % score): return # Booth: the next player's turn. - show_overlay("REVIEW FAILED", "Retry %s with 3 HP and fresh equipment." % Catalog.TITLES[stage_index],"Retry current stage",retry_stage) + var detail := "Retry %s with 3 HP and fresh equipment." % Catalog.TITLES[stage_index] + if not placing.is_empty(): detail += "\n" + placing + show_overlay("REVIEW FAILED", detail,"Retry current stage",retry_stage) func boss_defeated() -> void: # A knocked-out Hoppy can't win: the knockout ends in game over. @@ -626,7 +631,9 @@ func win() -> void: _update_hud() overlay.hide();card_host.hide() toast_left=0;held_toast="";toast_label.hide();prompt.text="" - victory.show_result(Catalog.VICTORY.title,Catalog.VICTORY.line,score,elapsed,Catalog.STORY_ACCENT,"Main Menu",leave) + var placing := Leaderboards.rank_line(Leaderboards.record(ROUTE, score, elapsed)) + var line: String = Catalog.VICTORY.line + ("" if placing.is_empty() else " · " + placing) + victory.show_result(Catalog.VICTORY.title,line,score,elapsed,Catalog.STORY_ACCENT,"Main Menu",leave) func toast(message: String, seconds := 2.0) -> void: # Combat opens under the fading stage title; anything said then waits for it (latest wins). diff --git a/hoppys-adventure-arcade/modes/platformer/art.gd b/hoppys-adventure-arcade/modes/platformer/art.gd index 5667777c..7f4ed762 100644 --- a/hoppys-adventure-arcade/modes/platformer/art.gd +++ b/hoppys-adventure-arcade/modes/platformer/art.gd @@ -1,5 +1,9 @@ extends RefCounted const ROOT := "res://Assets/bay-area-blitz-assets-only/bay_area/" +## Decoded atlas pages for Art.run, once each: get_image() is a GPU readback on this renderer. +static var images := {} +## Repeatable interior textures for Art.run, keyed by crop region and trim. +static var strips := {} static func sprite(sheet: String, clip: String, pos := Vector2.ZERO) -> AnimatedSprite2D: var s := AnimatedSprite2D.new() s.sprite_frames = load(ROOT + sheet + ".tres") @@ -14,3 +18,65 @@ static func shape(size: Vector2, pos := Vector2.ZERO) -> CollisionShape2D: c.shape = rect c.position = pos return c + +## Seamless runs of a cropped kit tile. Butting whole crops side by side shows each one's end +## caps (rounded corners, bolts, ragged edges) as a dark gutter between every tile, so a long +## platform reads as a row of boxes. A run keeps one cap at each end and repeats the painted +## interior between them, so it reads as one piece of any length. + +## The crop's interior, `trim.x` texels in from its left edge and `trim.y` from its right, as a +## texture that can repeat. +static func strip(cropped: AtlasTexture, trim: Vector2i) -> ImageTexture: + var key := "%s %s %s" % [cropped.atlas.resource_path, cropped.region, trim] + if not strips.has(key): + if not images.has(cropped.atlas.resource_path): + images[cropped.atlas.resource_path] = cropped.atlas.get_image() + var region := Rect2i(cropped.region) + region.position.x += trim.x + region.size.x -= trim.x + trim.y + var page: Image = images[cropped.atlas.resource_path] + strips[key] = ImageTexture.create_from_image(page.get_region(region)) + return strips[key] + +## `cropped` laid across `size` from `pos`: a cap at each end and the interior repeated between. +## Texels are as wide as one crop's when stretched to `tile.x`, so a run matches the tiles it +## replaces, and the run is exactly `size.y` tall, so a thin platform stays thin whatever the kit +## tile's height. A run too short for both caps is the whole crop stretched to fit. +static func run(cropped: AtlasTexture, pos: Vector2, size: Vector2, tile: Vector2, + trim := Vector2i.ZERO) -> Node2D: + var group := Node2D.new() + group.position = pos + var texels := cropped.region.size + var scale := Vector2(tile.x / texels.x, size.y / texels.y) + var caps := Vector2(trim.x, trim.y) * scale.x + if caps.x + caps.y + scale.x > size.x: + var whole := Sprite2D.new() + whole.texture = cropped + whole.centered = false + whole.scale = size / texels + group.add_child(whole) + return group + var middle := Sprite2D.new() + middle.texture = strip(cropped, trim) + middle.texture_repeat = CanvasItem.TEXTURE_REPEAT_ENABLED + middle.centered = false + middle.position.x = caps.x + middle.scale = scale + middle.region_enabled = true + middle.region_rect = Rect2(0, 0, (size.x - caps.x - caps.y) / scale.x, texels.y) + group.add_child(middle) + for side in 2: + var width := trim.x if side == 0 else trim.y + if width == 0: continue + var cap := Sprite2D.new() + var piece := AtlasTexture.new() + piece.atlas = cropped.atlas + var inset := Vector2(0 if side == 0 else texels.x - width, 0) + piece.region = Rect2(cropped.region.position + inset, Vector2(width, texels.y)) + piece.filter_clip = true + cap.texture = piece + cap.centered = false + cap.position.x = 0.0 if side == 0 else size.x - caps.y + cap.scale = scale + group.add_child(cap) + return group diff --git a/hoppys-adventure-arcade/modes/platformer/enchanted_art.gd b/hoppys-adventure-arcade/modes/platformer/enchanted_art.gd index 2997bc4b..58599066 100644 --- a/hoppys-adventure-arcade/modes/platformer/enchanted_art.gd +++ b/hoppys-adventure-arcade/modes/platformer/enchanted_art.gd @@ -1,6 +1,13 @@ extends RefCounted const ROOT := "res://Assets/enchanted-repo-assets-only/enchanted_repo/" const TREELINE_SHADER = preload("res://modes/platformer/enchanted_treeline.gdshader") +const Art = preload("res://modes/platformer/art.gd") +## End caps of the terrain clips, in texels (left, right): the slabs' rounded ends, the wall's +## ragged right edge and the root's tapering tips. See Art.run. +const TRIMS := { + "ground_slab": Vector2i(2, 2), "arena_slab": Vector2i(7, 7), + "castle_wall": Vector2i(3, 7), "root_platform": Vector2i(9, 8), +} static var crops := {} static var manifest: Dictionary = {} @@ -51,3 +58,7 @@ static func prop(clip: String, pos: Vector2, size: Vector2) -> Sprite2D: result.position = pos result.scale = size / result.texture.get_size() return result + +## `clip` laid seamlessly across `size`, at the texel scale one crop has stretched to `tile`. +static func run(clip: String, pos: Vector2, size: Vector2, tile: Vector2) -> Node2D: + return Art.run(crop("forest_kit", clip), pos, size, tile, TRIMS.get(clip, Vector2i.ZERO)) diff --git a/hoppys-adventure-arcade/modes/platformer/enchanted_hazard.gd b/hoppys-adventure-arcade/modes/platformer/enchanted_hazard.gd index df5969a1..080e3163 100644 --- a/hoppys-adventure-arcade/modes/platformer/enchanted_hazard.gd +++ b/hoppys-adventure-arcade/modes/platformer/enchanted_hazard.gd @@ -1,6 +1,12 @@ extends Node2D const Art = preload("res://modes/platformer/art.gd") const ForestArt = preload("res://modes/platformer/enchanted_art.gd") +## Where each vine frame's root rocks sit (texels from the crop's left edge); the whip frame's root +## is right of centre because the tentacle lashes out to the left. Other frames stand centred. +const VINE_ROOT := {"vine_whip": 76.0} +## The whip's reach: the band the lashing tentacle covers, measured on the anchored vine_whip crop +## at this scale (about 120 px out from the root, 20 px behind it), so nothing is hit off the art. +const VINE_BAND := Rect2(-120, -48, 140, 48) var kind := "comment" var clock := 0.0 var state := "idle" @@ -15,7 +21,12 @@ func _ready() -> void: area = Area2D.new() area.collision_layer = 0 area.collision_mask = 2 - area.add_child(Art.shape(Vector2(64,130) if kind == "comment" else Vector2(155,48), Vector2(0,-65) if kind == "comment" else Vector2(direction*55,-24))) + if kind == "comment": + area.add_child(Art.shape(Vector2(64,130), Vector2(0,-65))) + else: + var band := VINE_BAND + if direction > 0: band.position.x = -band.end.x + area.add_child(Art.shape(band.size, band.get_center())) add_child(area) _show("comment_dormant" if kind == "comment" else "vine_idle") @@ -23,10 +34,14 @@ func _show(clip: String) -> void: if current_clip == clip: return current_clip = clip visual.texture = ForestArt.crop("hazards",clip) - # Stable ground anchor; fit visual feedback to the actual damage band. + # Every frame stands on the ground with its root at the hazard's position (a flipped vine + # mirrors about that root), so the whip reaches out over its damage band instead of jumping. visual.scale = Vector2.ONE * (1.45 if kind == "comment" else 1.6) - visual.position = Vector2(0, -visual.texture.get_height()*visual.scale.y/2) + var width := visual.texture.get_width() + var root: float = VINE_ROOT.get(clip, width/2.0) visual.flip_h = kind == "vine" and direction > 0 + var shift := direction*(root-width/2.0)*visual.scale.x if kind == "vine" else 0.0 + visual.position = Vector2(shift, -visual.texture.get_height()*visual.scale.y/2) func tick(dt: float, player: CharacterBody2D) -> void: clock += dt @@ -38,12 +53,5 @@ func tick(dt: float, player: CharacterBody2D) -> void: else: clip = {"idle":"vine_idle","warning":"vine_warning","active":"vine_whip","recover":"vine_idle"}[state] _show(clip) + # The warning and burst/whip clips are the whole telegraph: no box is drawn over the art. if state == "active" and area.overlaps_body(player): player.damage(position.x) - queue_redraw() - -func _draw() -> void: - if state not in ["warning","active"]: return - var color := Color(1,.75,.25,.75) if state == "warning" else Color(.8,.3,1,.6) - var rect := Rect2(-32,-130,64,130) if kind == "comment" else Rect2(direction*55-77.5,-48,155,48) - draw_rect(rect,color,false,2) - if state == "active": draw_rect(rect,Color(color,.13)) diff --git a/hoppys-adventure-arcade/modes/platformer/legacy_monolith.gd b/hoppys-adventure-arcade/modes/platformer/legacy_monolith.gd index fa0a96dc..2148329c 100644 --- a/hoppys-adventure-arcade/modes/platformer/legacy_monolith.gd +++ b/hoppys-adventure-arcade/modes/platformer/legacy_monolith.gd @@ -59,10 +59,13 @@ func _physics_process(dt: float) -> void: var current := state() var layer_text := "OUTER ARMOR %d/3" % (hp-9) if armor_stage == 0 else ("INNER ARMOR %d/3" % (hp-6) if armor_stage == 1 else "CORE %d/6" % hp) attack_name = layer_text + " · " + ("RECOVERY — ATTACK!" if vulnerable() else {"tracking":"KEEP YOUR DISTANCE", "slam_warning":"DEBT SLAM — JUMP!", "sweep_warning":"LOW SWEEP — JUMP!", "stomp_warning":"STOMP — WATCH THE WAVE"}.get(current,current.replace("_"," ").to_upper())) - _pose("idle" if current == "tracking" else current) + if current != "tracking": _pose(current) if current == "tracking": + # Lumber toward Hoppy on the walk cycle (tools/build_monolith_walk.py); stand once close. var dx := player.position.x-position.x + var before := position.x if absf(dx)>160: position.x=clampf(position.x+signf(dx)*65*dt,4350,4810) + _pose("walk" if not is_equal_approx(position.x,before) else "idle") sprite.flip_h=dx>0 elif current in ["slam","stomp"]: var reach := 175.0 if current == "slam" else 95.0 @@ -124,13 +127,7 @@ func _draw() -> void: if break_time>0: draw_arc(Vector2(0,-95),75,0,TAU,32,Color(.4,1,.85,break_time),4) return - var current := state() - if current in ["slam_warning","slam","stomp_warning","stomp","sweep_warning","sweep"]: - var warning := current.ends_with("warning") - var reach := 175.0 if current.begins_with("slam") else 95.0 - var rect := Rect2(-reach,-8,reach*2,8) - if current.begins_with("sweep"): rect=Rect2(-30 if direction>0 else -215,-58,245,58) - if warning: draw_rect(rect,Color(1,.75,.25,.55),false,3) - else: draw_rect(rect,Color(.85,.25,1,.7)) - if current=="stomp_warning": - draw_line(Vector2(direction*105,-18),Vector2(direction*310,-18),Color("ffc769"),3) + # The warning poses are the telegraph; no box is drawn over the art. The stomp keeps its amber + # line, which shows where the ground wave will travel. + if state()=="stomp_warning": + draw_line(Vector2(direction*105,-18),Vector2(direction*310,-18),Color("ffc769"),3) diff --git a/hoppys-adventure-arcade/modes/platformer/level.gd b/hoppys-adventure-arcade/modes/platformer/level.gd index aa837969..d3e0f1c8 100644 --- a/hoppys-adventure-arcade/modes/platformer/level.gd +++ b/hoppys-adventure-arcade/modes/platformer/level.gd @@ -1,6 +1,7 @@ extends Node2D ## Shared platformer session. Concrete levels provide layout, actors and presentation. const Art = preload("res://modes/platformer/art.gd") +const Leaderboards = preload("res://app/leaderboards.gd") const Knockout = preload("res://modes/platformer/knockout.gd") const Player = preload("res://modes/platformer/player.gd") const Enemy = preload("res://modes/platformer/enemy.gd") @@ -275,6 +276,10 @@ func _finish(won: bool) -> void: pause_menu.close() overlay_title.text = "MERGE SUCCESSFUL!" if won else "BUILD FAILED" overlay_detail.text = "%06d POINTS / %02d:%02d\n%s" % [score, int(elapsed) / 60, int(elapsed) % 60, level_title + " complete." if won else "Fresh branch. Another try."] + # Every finished run goes on this level's local top ten (app/leaderboards.gd); a placing shows. + var placing := Leaderboards.rank_line(Leaderboards.record(level_route, score, elapsed)) + if not placing.is_empty(): + overlay_detail.text += "\n" + placing if won: stage_clear.play() _reveal_results(0.35) diff --git a/hoppys-adventure-arcade/modes/platformer/orbital_art.gd b/hoppys-adventure-arcade/modes/platformer/orbital_art.gd index 869236ae..6346096b 100644 --- a/hoppys-adventure-arcade/modes/platformer/orbital_art.gd +++ b/hoppys-adventure-arcade/modes/platformer/orbital_art.gd @@ -1,5 +1,13 @@ extends RefCounted const ROOT := "res://Assets/orbital-ops-assets-only/orbital_ops/" +const Art = preload("res://modes/platformer/art.gd") +## End caps of the station-kit terrain clips, in texels (left, right); see Art.run. The one-way +## platform's and the scaffold's interiors are cut to whole repeats of their painted pattern +## (two thruster humps, three lattice bays) so the repeat joins on the pattern. +const TRIMS := { + "floor_slab": Vector2i(4, 4), "hull_panel": Vector2i(2, 3), "wall_block": Vector2i(1, 1), + "one_way_platform": Vector2i(9, 31), "scaffold_horizontal": Vector2i(12, 5), +} static var crops := {} static var manifest: Dictionary = {} @@ -35,3 +43,7 @@ static func prop(clip: String, pos: Vector2, size: Vector2) -> Sprite2D: result.position = pos result.scale = size / result.texture.get_size() return result + +## `clip` laid seamlessly across `size`, at the texel scale one crop has stretched to `tile`. +static func run(clip: String, pos: Vector2, size: Vector2, tile: Vector2) -> Node2D: + return Art.run(crop("station_kit", clip), pos, size, tile, TRIMS.get(clip, Vector2i.ZERO)) diff --git a/hoppys-adventure-arcade/scenes/platformer/bay_area_blitz.gd b/hoppys-adventure-arcade/scenes/platformer/bay_area_blitz.gd index 68eec813..6433200e 100644 --- a/hoppys-adventure-arcade/scenes/platformer/bay_area_blitz.gd +++ b/hoppys-adventure-arcade/scenes/platformer/bay_area_blitz.gd @@ -5,6 +5,11 @@ const LEVEL_MUSIC = preload("res://Assets/Audio/Platformer/Bay Area Blitz/bay_ar const MUSIC = preload("res://Assets/Audio/Platformer/Bay Area Blitz/bay_area_blitz_boss.ogg") ## Copies drawn on each side of a repeating background strip. const REPEATS := 4 +## End caps of the street-kit terrain art, in texels (left, right); see Art.run. The steel +## platform's caps are its rounded, riveted ends, so a long one reads as a single plate. +const TRIMS := { + "sidewalk": Vector2i(3, 4), "brick_block": Vector2i(3, 3), "steel_platform": Vector2i(15, 16), +} var terrain_crops := {} func _init() -> void: @@ -28,8 +33,10 @@ func _ready() -> void: platform(Vector2(5300, 0), Vector2(50, 900), "brick_block") for p in [Vector2(470, 485), Vector2(730, 385), Vector2(1450, 475), Vector2(1770, 370), Vector2(2070, 450), Vector2(2800, 480), Vector2(3070, 380), Vector2(3430, 465)]: platform(p, Vector2(170, 24), "steel_platform") + # The lamp's base is 50 texels below its cell centre: at 1.6x that is 80 px, so a lamp + # centred at y 520 stands on the sidewalk's y 600 surface. for x in [180, 900, 1390, 2620, 3520, 4100, 5020]: - var lamp := Art.sprite("street_kit", "street_lamp", Vector2(x, 513)) + var lamp := Art.sprite("street_kit", "street_lamp", Vector2(x, 520)) lamp.scale = Vector2(1.6, 1.6) add_child(lamp) _car(Vector2(1680, 531), Vector2(420, -55)) @@ -112,19 +119,15 @@ func platform(pos: Vector2, size: Vector2, art: String) -> void: solid.one_way_collision = art == "steel_platform" body.add_child(solid) add_child(body) - var fill := Polygon2D.new() - fill.polygon = PackedVector2Array([Vector2.ZERO, Vector2(size.x, 0), size, Vector2(0, size.y)]) - fill.color = Color("223c48") - body.add_child(fill) - var cropped := _terrain_crop(art) - var bounds := cropped.region - for x in range(0, int(size.x), 96): - var piece := Sprite2D.new() - piece.texture = cropped - piece.centered = false - piece.position.x = x - piece.scale = Vector2(minf(96, size.x - x) / bounds.size.x, minf(size.y, 32) / bounds.size.y) - body.add_child(piece) + # Every platform is one seamless run of its art (Art.run), never butted tiles. Only the + # sidewalks and walls get a backing; a steel platform floats with nothing behind it. + if not solid.one_way_collision: + var fill := Polygon2D.new() + fill.polygon = PackedVector2Array([Vector2.ZERO, Vector2(size.x, 0), size, Vector2(0, size.y)]) + fill.color = Color("223c48") + body.add_child(fill) + var band := Vector2(size.x, minf(size.y, 32)) + body.add_child(Art.run(_terrain_crop(art), Vector2.ZERO, band, Vector2(96, band.y), TRIMS[art])) # get_image() is a GPU readback on this renderer: crop each street-kit texture once. func _terrain_crop(art: String) -> AtlasTexture: if not terrain_crops.has(art): diff --git a/hoppys-adventure-arcade/scenes/platformer/enchanted_repo.gd b/hoppys-adventure-arcade/scenes/platformer/enchanted_repo.gd index 4e32198e..7998c939 100644 --- a/hoppys-adventure-arcade/scenes/platformer/enchanted_repo.gd +++ b/hoppys-adventure-arcade/scenes/platformer/enchanted_repo.gd @@ -7,6 +7,8 @@ const Branch = preload("res://modes/platformer/crumbling_branch.gd") const Wave = preload("res://modes/platformer/enchanted_shockwave.gd") const FOREST_MUSIC = preload("res://Assets/Audio/Platformer/The Enchanted Repo/enchanted_repo_level.ogg") const BOSS_MUSIC = preload("res://Assets/Audio/Platformer/The Enchanted Repo/enchanted_repo_boss.ogg") +## Ground segments as (x, width); the grass line is y 600 and pits lie between them. +const GROUND := [Vector2(0,1100),Vector2(1260,1120),Vector2(2550,950),Vector2(3670,1630)] var forest_hazards: Array[Node2D] = [] var branches: Array[StaticBody2D] = [] @@ -26,7 +28,7 @@ func _ready() -> void: process_physics_priority=-10 texture_filter=CanvasItem.TEXTURE_FILTER_NEAREST _background() - for segment in [Vector2(0,1100),Vector2(1260,1120),Vector2(2550,950),Vector2(3670,1630)]: + for segment in GROUND: platform(Vector2(segment.x,600),Vector2(segment.y,160),false,"arena_slab" if segment.x>=3670 else "ground_slab") platform(Vector2(-50,0),Vector2(50,900),false,"castle_wall") platform(Vector2(5300,0),Vector2(50,900),false,"castle_wall") @@ -104,18 +106,28 @@ func platform(pos: Vector2, size: Vector2, one_way := false, clip := "ground_sla shape.one_way_collision=one_way body.add_child(shape) add_child(body) - # Raised roots keep their painted silhouette and transparent hanging roots. - # Ground and boundary walls still need a solid backing between their tiles. + # Every platform is one seamless run of its clip (Art.run), never butted tiles. Raised roots + # keep their painted silhouette and transparent hanging roots, with nothing behind them. + # Ground and boundary walls get a backing (drawn first, so it sits behind the art) in the + # dirt's own tone, starting under the grass tufts so the sky shows through them instead of a + # dark band. The castle wall below keeps a shadow-dark backing behind its crenellation gaps. + var cap := minf(size.y,68) + var walled := not one_way and size.y>70 and size.x>60 if not one_way: - var fill := Polygon2D.new() - fill.polygon=PackedVector2Array([Vector2.ZERO,Vector2(size.x,0),size,Vector2(0,size.y)]) - fill.color=Color("252f35") - body.add_child(fill) - for x in range(0,int(size.x),128): - body.add_child(ForestArt.prop(clip,Vector2(x,0),Vector2(minf(128,size.x-x),minf(size.y,68)))) - if size.y>70 and size.x>60: - for x in range(0,int(size.x),128): - body.add_child(ForestArt.prop("castle_wall",Vector2(x,68),Vector2(minf(128,size.x-x),size.y-68))) + _backing(body,Rect2(0,10,size.x,cap-10),Color("473638")) + if walled: + _backing(body,Rect2(0,68,size.x,size.y-68),Color("252f35")) + body.add_child(ForestArt.run(clip,Vector2.ZERO,Vector2(size.x,cap),Vector2(128,68))) + if walled: + var wall := Vector2(size.x,size.y-68) + body.add_child(ForestArt.run("castle_wall",Vector2(0,68),wall,Vector2(128,wall.y))) + +func _backing(body: Node2D, rect: Rect2, color: Color) -> void: + var fill := Polygon2D.new() + fill.polygon=PackedVector2Array([rect.position,Vector2(rect.end.x,rect.position.y), + rect.end,Vector2(rect.position.x,rect.end.y)]) + fill.color=color + body.add_child(fill) func _add_hazard(kind: String, pos: Vector2, offset: float, direction := -1.0) -> void: var hazard := Hazard.new() @@ -180,6 +192,12 @@ func _background() -> void: var tree := ForestArt.prop("rune_tree",Vector2(x,190),Vector2(260,410)) tree.modulate=Color(.55,.65,.6,.6) near.add_child(tree) + # Foreground flora stands on the ground, never over a pit: a clump is placed only where its + # whole 180 px footprint lies on one ground segment, with its base on the grass line (y 600). for x in range(200,5200,460): - var flora := ForestArt.prop("foreground_flora",Vector2(x,645),Vector2(180,65)) - add_child(flora) + var grounded := false + for segment in GROUND: + if x>=segment.x and x+180<=segment.x+segment.y: + grounded=true + if grounded: + add_child(ForestArt.prop("foreground_flora",Vector2(x,537),Vector2(180,65))) diff --git a/hoppys-adventure-arcade/scenes/platformer/orbital_ops.gd b/hoppys-adventure-arcade/scenes/platformer/orbital_ops.gd index 779789eb..8c401230 100644 --- a/hoppys-adventure-arcade/scenes/platformer/orbital_ops.gd +++ b/hoppys-adventure-arcade/scenes/platformer/orbital_ops.gd @@ -100,15 +100,17 @@ func platform(pos: Vector2, size: Vector2, one_way := false, clip := "floor_slab shape.one_way_collision=one_way body.add_child(shape) add_child(body) - var fill := Polygon2D.new() - fill.polygon=PackedVector2Array([Vector2.ZERO,Vector2(size.x,0),size,Vector2(0,size.y)]) - fill.color=Color("101d35") - body.add_child(fill) - for x in range(0,int(size.x),128): - body.add_child(OrbitalArt.prop(clip,Vector2(x,0),Vector2(minf(128,size.x-x),minf(size.y,40)))) + # Every platform is one seamless run of its clip (Art.run), never butted tiles. Only solid + # decks and walls get a hull-dark backing; a one-way platform floats with nothing behind it. + if not one_way: + var fill := Polygon2D.new() + fill.polygon=PackedVector2Array([Vector2.ZERO,Vector2(size.x,0),size,Vector2(0,size.y)]) + fill.color=Color("101d35") + body.add_child(fill) + body.add_child(OrbitalArt.run(clip,Vector2.ZERO,Vector2(size.x,minf(size.y,40)),Vector2(128,40))) if size.y>60 and size.x>60: - for x in range(0,int(size.x),128): - body.add_child(OrbitalArt.prop("hull_panel",Vector2(x,40),Vector2(minf(128,size.x-x),size.y-40))) + var hull := Vector2(size.x,size.y-40) + body.add_child(OrbitalArt.run("hull_panel",Vector2(0,40),hull,Vector2(128,hull.y))) func _shuttle(pos: Vector2, travel: Vector2) -> void: var body := AnimatableBody2D.new() diff --git a/hoppys-adventure-arcade/scenes/runner/runner_game.gd b/hoppys-adventure-arcade/scenes/runner/runner_game.gd index 0284e968..94d1384b 100644 --- a/hoppys-adventure-arcade/scenes/runner/runner_game.gd +++ b/hoppys-adventure-arcade/scenes/runner/runner_game.gd @@ -4,6 +4,7 @@ extends Node3D ## sequence and the single leaderboard write. const RunnerLeaderboard = preload("res://scenes/runner/systems/runner_leaderboard.gd") +const Leaderboards = preload("res://app/leaderboards.gd") const RunConfig = preload("res://scenes/runner/data/run_config.gd") ## Only for the phase count of the §11.4 boss block; boss_defs.gd preloads no scene script, so this ## is not the cycle boss_encounter.gd has to avoid. @@ -130,9 +131,10 @@ signal pursuer_distance_changed(normalized: float) @export var config: RunConfig = preload(CONFIG_PATH) ## Tests instantiate the scene with autostart off and call start_run() themselves. @export var autostart := true -## Where this session reads and writes the board. Tests point it at a throwaway file so a headless -## run never touches the player's real leaderboard; the game leaves it at the default. -var leaderboard_path := RunnerLeaderboard.DEFAULT_PATH +## Where this session reads and writes the board: the runner's file for a player, and a test's +## scratch folder under --script (app/leaderboards.gd), so a headless run never touches the +## player's real leaderboard. Tests may still point it at a throwaway file of their own. +var leaderboard_path: String = Leaderboards.path_for(Leaderboards.RUNNER_ROUTE) # Read-only properties (contract §4.2). Treat these as outputs; drive the run through the methods. var state: StringName = &"ready" diff --git a/hoppys-adventure-arcade/scenes/runner/ui/leaderboard_panel.gd b/hoppys-adventure-arcade/scenes/runner/ui/leaderboard_panel.gd index 6640db08..0a858b2d 100644 --- a/hoppys-adventure-arcade/scenes/runner/ui/leaderboard_panel.gd +++ b/hoppys-adventure-arcade/scenes/runner/ui/leaderboard_panel.gd @@ -1,227 +1,3 @@ -extends Control -## The Endless Runner's local top ten with its Reset scores flow, opened from the runner's pause -## menu. It processes while the run is paused (its parent is the always-processing pause menu). -## `ui_cancel` or `pause` closes the confirmation first, then the panel, and never reaches the run. -## Reset asks twice; a failed reset reloads the rows from disk and reports it. - -signal closed - -const Style = preload("res://scenes/runner/ui/hud_style.gd") -const Palette = preload("res://scenes/runner/environment/runner_palette.gd") -const Leaderboard = preload("res://scenes/runner/systems/runner_leaderboard.gd") - -var leaderboard_path := Leaderboard.DEFAULT_PATH -## The path the open board read, so Reset clears what the player is looking at. -var leaderboard_path_at_open := Leaderboard.DEFAULT_PATH -var board: VBoxContainer -var reset_btn: Button -var close_btn: Button -var reset_confirm: Control -var confirm_status: Label -@onready var audio_service: Node = get_node("/root/AudioService") -@onready var router: Node = get_node("/root/AppRouter") - -func _init() -> void: - name = "Leaderboard" - set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT) - mouse_filter = Control.MOUSE_FILTER_STOP - -func _ready() -> void: - theme = Style.theme() - var dim := ColorRect.new() - dim.color = Color(0.01, 0.02, 0.04, 0.9) - dim.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT) - dim.mouse_filter = Control.MOUSE_FILTER_IGNORE - add_child(dim) - var center := CenterContainer.new() - center.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT) - center.mouse_filter = Control.MOUSE_FILTER_IGNORE - add_child(center) - var panel := PanelContainer.new() - panel.custom_minimum_size = Vector2(720, 0) - panel.add_theme_stylebox_override("panel", _panel_style()) - Style.polish(panel, true) - center.add_child(panel) - var column := VBoxContainer.new() - column.add_theme_constant_override("separation", 14) - panel.add_child(column) - column.add_child(Style.label("LOCAL LEADERBOARD", 28)) - column.add_child(Style.label("RANK NAME SCORE TIME", 18, Style.MINT)) - board = VBoxContainer.new() - board.add_theme_constant_override("separation", 8) - column.add_child(board) - leaderboard_path_at_open = leaderboard_path - var entries := Leaderboard.load_entries(leaderboard_path_at_open) - _build_board_rows(entries) - var button_row := HBoxContainer.new() - button_row.add_theme_constant_override("separation", 12) - column.add_child(button_row) - reset_btn = Style.button("Reset scores", 46) - reset_btn.name = "ResetScoresButton" - reset_btn.disabled = entries.is_empty() - reset_btn.focus_entered.connect(_focus_sound) - reset_btn.mouse_entered.connect(_focus_sound) - reset_btn.pressed.connect(_open_reset_confirm) - button_row.add_child(reset_btn) - close_btn = Style.button("Close", 46) - close_btn.name = "CloseButton" - close_btn.focus_entered.connect(_focus_sound) - close_btn.mouse_entered.connect(_focus_sound) - close_btn.pressed.connect(close) - button_row.add_child(close_btn) - _wrap_pair(reset_btn, close_btn) - close_btn.grab_focus() - -func _panel_style() -> StyleBoxFlat: - var box := Style.panel(Style.MINT, 0.96) - box.content_margin_left = 24 - box.content_margin_right = 24 - box.content_margin_top = 20 - box.content_margin_bottom = 20 - return box - -## Focus wraps between two buttons in every direction. -static func _wrap_pair(a: Button, b: Button) -> void: - for pair in [[a, b], [b, a]]: - var from: Button = pair[0] - var to: NodePath = from.get_path_to(pair[1]) - from.focus_neighbor_left = to - from.focus_neighbor_right = to - from.focus_neighbor_top = to - from.focus_neighbor_bottom = to - from.focus_next = to - from.focus_previous = to - -func _focus_sound() -> void: - if not router.busy: - audio_service.play_ui(0) - -func _build_board_rows(entries: Array[Dictionary]) -> void: - for child in board.get_children(): - child.queue_free() - for i in 10: - var text := "%02d --- --- ---" % (i + 1) - if i < entries.size(): - var entry: Dictionary = entries[i] - var seconds := maxi(0, int(entry.duration)) - text = "%02d %-16s %8d %02d:%02d" % [i + 1, entry.name, entry.score, seconds / 60, seconds % 60] - var row := HBoxContainer.new() - row.add_child(rank_marker(i, i < entries.size())) - row.add_child(Style.label(text, 18)) - board.add_child(row) - -func close() -> void: - if router.busy: - return - audio_service.play_ui(1) - closed.emit() - queue_free() - -func _open_reset_confirm() -> void: - if reset_confirm or router.busy: - return - audio_service.play_ui(1) - reset_btn.disabled = true - close_btn.disabled = true - reset_confirm = Control.new() - reset_confirm.name = "ResetConfirm" - reset_confirm.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT) - add_child(reset_confirm) - var dim := ColorRect.new() - dim.color = Color(0.01, 0.02, 0.04, 0.9) - dim.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT) - reset_confirm.add_child(dim) - var center := CenterContainer.new() - center.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT) - center.mouse_filter = Control.MOUSE_FILTER_IGNORE - reset_confirm.add_child(center) - var panel := PanelContainer.new() - panel.custom_minimum_size = Vector2(620, 0) - panel.add_theme_stylebox_override("panel", _panel_style()) - Style.polish(panel, true) - center.add_child(panel) - var column := VBoxContainer.new() - column.add_theme_constant_override("separation", 16) - panel.add_child(column) - column.add_child(Style.label("RESET ALL SCORES?", 28)) - column.add_child(Style.label("This deletes the top ten and cannot be undone.", 18)) - var keep := Style.button("Keep scores", 46) - keep.name = "KeepScoresButton" - keep.focus_entered.connect(_focus_sound) - keep.mouse_entered.connect(_focus_sound) - keep.pressed.connect(_close_reset_confirm) - column.add_child(keep) - var do_reset := Style.button("Reset", 46) - do_reset.name = "ResetConfirmButton" - do_reset.focus_entered.connect(_focus_sound) - do_reset.mouse_entered.connect(_focus_sound) - do_reset.pressed.connect(_confirm_reset) - column.add_child(do_reset) - confirm_status = Style.label("", 16, Color("ff7185")) - confirm_status.name = "StatusLabel" - confirm_status.visible = false - column.add_child(confirm_status) - _wrap_pair(keep, do_reset) - keep.grab_focus() - -func _close_reset_confirm() -> void: - if not reset_confirm: - return - reset_confirm.queue_free() - reset_confirm = null - confirm_status = null - if is_instance_valid(reset_btn): - reset_btn.disabled = false - reset_btn.grab_focus() - if is_instance_valid(close_btn): - close_btn.disabled = false - audio_service.play_ui(1) - -func _confirm_reset() -> void: - if router.busy: - return - var error := Leaderboard.clear(leaderboard_path_at_open) - if error == OK: - reset_confirm.queue_free() - reset_confirm = null - confirm_status = null - _build_board_rows(Leaderboard.load_entries(leaderboard_path_at_open)) - if is_instance_valid(reset_btn): - reset_btn.disabled = true - if is_instance_valid(close_btn): - close_btn.disabled = false - close_btn.grab_focus() - audio_service.play_ui(1) - else: - # clear() may have written an empty primary before the .bak/.tmp removal failed: reload - # the rows so the board matches what is on disk. - var entries_after := Leaderboard.load_entries(leaderboard_path_at_open) - _build_board_rows(entries_after) - if is_instance_valid(reset_btn): - reset_btn.disabled = entries_after.is_empty() - if confirm_status != null: - confirm_status.text = "Could not reset scores." - confirm_status.visible = true - var keep_btn := reset_confirm.find_child("KeepScoresButton", true, false) as Button - if keep_btn != null: - keep_btn.grab_focus() - -## Back (Esc, B) or Start closes the confirmation first, then the board. Handled in _input so the -## press never also reaches the runner's pause toggle. -func _input(event: InputEvent) -> void: - if not visible or router.busy: - return - if event.is_action_pressed("ui_cancel") or event.is_action_pressed("pause"): - if reset_confirm: - _close_reset_confirm() - else: - close() - get_viewport().set_input_as_handled() - -static func rank_marker(index: int, occupied: bool) -> Control: - if occupied and index < 3: - return Style.icon(&"medal", [Palette.CREAM.lerp(Palette.ORANGE, 0.35), Palette.SLATE.lerp(Palette.CREAM, 0.65), Palette.ORANGE.lerp(Palette.NAVY_2, 0.3)][index], Vector2(24, 24)) - var spacer := Control.new() - spacer.custom_minimum_size = Vector2(24, 24) - spacer.mouse_filter = Control.MOUSE_FILTER_IGNORE - return spacer +extends "res://app/leaderboard_panel.gd" +## The Endless Runner's leaderboard panel. The panel itself moved to app/leaderboard_panel.gd when +## every game got a board; this path stays for the runner's dev captures and tests. diff --git a/hoppys-adventure-arcade/scenes/runner/ui/leaderboard_panel.gd.uid b/hoppys-adventure-arcade/scenes/runner/ui/leaderboard_panel.gd.uid index 4d9526a6..bc9ddb1a 100644 --- a/hoppys-adventure-arcade/scenes/runner/ui/leaderboard_panel.gd.uid +++ b/hoppys-adventure-arcade/scenes/runner/ui/leaderboard_panel.gd.uid @@ -1 +1 @@ -uid://c3nb0467pn5w6 +uid://ca3kqckt6otmq diff --git a/hoppys-adventure-arcade/scenes/runner/ui/pause_menu.gd b/hoppys-adventure-arcade/scenes/runner/ui/pause_menu.gd index 9b8c811d..5acc4547 100644 --- a/hoppys-adventure-arcade/scenes/runner/ui/pause_menu.gd +++ b/hoppys-adventure-arcade/scenes/runner/ui/pause_menu.gd @@ -1,14 +1,10 @@ extends "res://app/pause_menu.gd" -## The runner's pause menu: the shared menu (app/pause_menu.gd) plus a Leaderboard button that -## opens the local top ten with its Reset scores flow over the paused run. Display only: the facade -## owns pause state and input, and this menu binds neither `pause` nor `ui_cancel`. - -const LeaderboardPanel := preload("res://scenes/runner/ui/leaderboard_panel.gd") +## The runner's pause menu: the shared menu (app/pause_menu.gd), whose Leaderboard button reads +## the run's own board (`game.leaderboard_path`, which a test or capture can point elsewhere). +## Display only: the facade owns pause state and input, and this menu binds neither `pause` nor +## `ui_cancel`. var game: Node -var leaderboard_button: Button -## The open leaderboard panel, or null. -var leaderboard: Control func bind(runner: Node) -> void: game = runner @@ -16,7 +12,6 @@ func bind(runner: Node) -> void: func() -> void: _call_game(&"resume"), func() -> void: _call_game(&"retry"), func() -> void: _call_game(&"go_to_menu")) - leaderboard_button = add_button("Leaderboard", _open_leaderboard) runner.paused_changed.connect(_on_paused_changed) _on_paused_changed(runner.paused) @@ -26,35 +21,11 @@ func _on_paused_changed(is_paused: bool) -> void: else: close() -## Closing the menu (resume, pad reconnect, a route change) takes the leaderboard with it. -func close() -> void: - if is_instance_valid(leaderboard): - leaderboard.closed.disconnect(_on_leaderboard_closed) - leaderboard.queue_free() - leaderboard = null - _set_menu_enabled(true) - super.close() - +## The board is read when it opens, so a path changed after bind() (tests) is honoured. func _open_leaderboard() -> void: - if leaderboard != null or game == null: - return - _set_menu_enabled(false) - leaderboard = LeaderboardPanel.new() - leaderboard.leaderboard_path = game.leaderboard_path - leaderboard.closed.connect(_on_leaderboard_closed) - ui.add_child(leaderboard) - -func _on_leaderboard_closed() -> void: - leaderboard = null - _set_menu_enabled(true) - if visible: - leaderboard_button.grab_focus() - -## The board owns the screen while it is up: the menu's own buttons can't be reached. -func _set_menu_enabled(enabled: bool) -> void: - for button in buttons: - button.disabled = not enabled or locked - button.focus_mode = Control.FOCUS_ALL if enabled else Control.FOCUS_NONE + if game != null: + leaderboard_path = game.leaderboard_path + super._open_leaderboard() func _call_game(method: StringName) -> void: if game != null and game.has_method(method): diff --git a/hoppys-adventure-arcade/tests/enchanted_assets.gd b/hoppys-adventure-arcade/tests/enchanted_assets.gd index c5035cd7..4a5f0c23 100644 --- a/hoppys-adventure-arcade/tests/enchanted_assets.gd +++ b/hoppys-adventure-arcade/tests/enchanted_assets.gd @@ -47,7 +47,9 @@ func run() -> void: if texture == null: continue check(texture.get_size() == Vector2(960, 540), bg.file) - check(frames == 104 and clips == 78, "Complete frame/state inventory") + # 104 generated frames and 78 clips, plus the 12 walk frames and 3 walk clips that + # tools/build_monolith_walk.py adds to the Legacy Monolith and its armor sheet. + check(frames == 116 and clips == 81, "Complete frame/state inventory") check(manifest.atlases.size() == 6 and manifest.backgrounds.size() == 2, "Complete resource inventory") if failures > 0: printerr(failures, " Enchanted Repo asset checks failed") diff --git a/hoppys-adventure-arcade/tests/leaderboards.gd b/hoppys-adventure-arcade/tests/leaderboards.gd new file mode 100644 index 00000000..3af87434 --- /dev/null +++ b/hoppys-adventure-arcade/tests/leaderboards.gd @@ -0,0 +1,110 @@ +extends SceneTree +## Every game keeps a local top ten (app/leaderboards.gd): a route maps to its own board file, a +## recorded run ranks against that board only, the runner keeps its own file, and the shared pause +## menu's Leaderboard button opens a game's board over the paused game. Run headless with +## --script res://tests/leaderboards.gd. +const Leaderboards = preload("res://app/leaderboards.gd") +const Board = preload("res://scenes/runner/systems/runner_leaderboard.gd") +const PauseMenu = preload("res://app/pause_menu.gd") +var failures := 0 +var scratch := "user://test_leaderboards_%d/" % OS.get_process_id() + +func _initialize() -> void: + call_deferred("run") + +func check(ok: bool, message: String) -> void: + print("PASS: " if ok else "FAIL: ", message) + if not ok: + failures += 1 + +func run() -> void: + await process_frame + # A suite runs with --script, so with no override the boards go to this process's scratch + # folder, never the player's. Rows left there by an earlier run with the same id are cleared + # the first time this run uses the folder; another run's folder is left alone. + var own := "%s%d/" % [Leaderboards.SCRATCH_PREFIX, OS.get_process_id()] + # Another run's folder, named so two copies of this suite sharing user:// never share it. + var neighbour := "%s%d_neighbour/" % [Leaderboards.SCRATCH_PREFIX, OS.get_process_id()] + for folder in [own, neighbour]: + DirAccess.make_dir_recursive_absolute(folder) + FileAccess.open(folder + "leftover.cfg", FileAccess.WRITE).store_string("[board]\n") + var auto := Leaderboards.dir() + check(auto == own and not FileAccess.file_exists(own + "leftover.cfg") + and Leaderboards.path_for("runner_game") == auto + "runner_game.cfg" + and FileAccess.file_exists(neighbour + "leftover.cfg"), + "A test run empties and uses its own scratch folder, the runner included, and no neighbour") + DirAccess.remove_absolute(neighbour + "leftover.cfg") + DirAccess.remove_absolute(neighbour) + check(int(Leaderboards.record("bay_area_blitz", 5, 1.0).rank) == 1 + and FileAccess.file_exists(auto + "bay_area_blitz.cfg"), + "A run recorded under test lands in the scratch folder") + Leaderboards.clear_scratch() + check(not DirAccess.dir_exists_absolute(auto), "clear_scratch removes the folder and its boards") + Leaderboards.redirect_tests = false + check(Leaderboards.path_for("runner_game") == Board.DEFAULT_PATH, + "The runner keeps its own board file") + check(Leaderboards.path_for("bay_area_blitz") == Leaderboards.DIR + "bay_area_blitz.cfg", + "A game's board lives under user://leaderboards/ by route") + Leaderboards.redirect_tests = true + Leaderboards.override_dir = scratch + check(Leaderboards.path_for("runner_game") == scratch + "runner_game.cfg", + "An override directory redirects every board, the runner's too") + + var first := Leaderboards.record("bay_area_blitz", 1200, 61.5) + check(int(first.rank) == 1 and int(first.error) == OK, "The first run on an empty board ranks #1") + var second := Leaderboards.record("bay_area_blitz", 800, 40.0) + check(int(second.rank) == 2, "A lower score ranks below it") + var other := Leaderboards.record("orbital_ops", 50, 5.0) + check(int(other.rank) == 1, "Another game's run ranks on its own board") + var rows := Leaderboards.entries("bay_area_blitz") + check(rows.size() == 2 and int(rows[0].score) == 1200 and rows[0].name.begins_with("Hoppy "), + "Rows are sorted best first and named after the mascot and the time of day") + check(FileAccess.file_exists(scratch + "bay_area_blitz.cfg") and FileAccess.file_exists(scratch + "orbital_ops.cfg"), + "Each board is its own file") + for i in 12: + Leaderboards.record("code_city_brawl", 100 + i, 10.0) + check(Leaderboards.entries("code_city_brawl").size() == Board.MAX_ENTRIES, + "A board keeps its top ten") + check(int(Leaderboards.record("code_city_brawl", 1, 1.0).rank) == 0, "A run below the ten does not place") + check(Leaderboards.rank_line(first) == "LEADERBOARD #1" and Leaderboards.rank_line({"rank": 0, "error": OK}) == "" + and Leaderboards.rank_line({"rank": 1, "error": ERR_FILE_CANT_WRITE}) == "", + "The results line names a placing and stays empty for a miss or a failed save") + + # The shared pause menu opens the game's board over the menu and closes it with the menu. + var host := Node.new() + root.add_child(host) + var menu: Node = PauseMenu.create(host, "orbital_ops", func() -> void: pass, func() -> void: pass, func() -> void: pass) + await process_frame + check(menu.leaderboard_button != null and menu.leaderboard_button.text == "Leaderboard" + and menu.buttons[menu.buttons.size() - 2] == menu.leaderboard_button, + "The menu has a Leaderboard button just before Main Menu") + check(menu.leaderboard_path == scratch + "orbital_ops.cfg", "The button points at the game's board") + menu.open() + menu.leaderboard_button.pressed.emit() + await process_frame + var board: Control = menu.leaderboard + check(board != null and board.title.begins_with("ORBITAL OPS") and board.board.get_child_count() == 10 + and board.close_btn.has_focus() and not board.reset_btn.disabled, + "Leaderboard opens the game's titled top ten with Close focused and Reset offered") + check(menu.resume_button.disabled and menu.resume_button.focus_mode == Control.FOCUS_NONE, + "The menu's own buttons are unreachable while the board is up") + board.close() + await process_frame + check(menu.leaderboard == null and not menu.resume_button.disabled and menu.leaderboard_button.has_focus(), + "Closing the board re-enables the menu and refocuses Leaderboard") + menu.leaderboard_button.pressed.emit() + await process_frame + menu.close() + await process_frame + check(menu.leaderboard == null and not menu.is_open(), "Closing the menu takes an open board with it") + host.queue_free() + + for file in DirAccess.get_files_at(scratch): + DirAccess.remove_absolute(scratch + file) + DirAccess.remove_absolute(scratch) + Leaderboards.override_dir = "" + Leaderboards.clear_scratch() + print("LEADERBOARDS: %s (%d failures)" % ["PASS" if failures == 0 else "FAIL", failures]) + var audio := root.get_node_or_null("AudioService") + if audio: await audio.settle() + quit(1 if failures else 0) diff --git a/hoppys-adventure-arcade/tests/leaderboards.gd.uid b/hoppys-adventure-arcade/tests/leaderboards.gd.uid new file mode 100644 index 00000000..6ddf37a7 --- /dev/null +++ b/hoppys-adventure-arcade/tests/leaderboards.gd.uid @@ -0,0 +1 @@ +uid://ckg1071lmoprd diff --git a/hoppys-adventure-arcade/tests/pause_menu.gd b/hoppys-adventure-arcade/tests/pause_menu.gd index a0ee8b7d..64872440 100644 --- a/hoppys-adventure-arcade/tests/pause_menu.gd +++ b/hoppys-adventure-arcade/tests/pause_menu.gd @@ -162,9 +162,8 @@ func check_route(route: String) -> void: await press_pause() check(paused and menu.is_open() and scene.is_player_paused(), "%s: pause opens the menu and pauses the game" % route) check(menu.resume_button.has_focus(), "%s: Resume takes focus" % route) - var expected: Array[String] = ["Resume", "Restart", "How to Play", "Main Menu"] - if route == "runner_game": - expected.insert(3, "Leaderboard") + # Every game has a local top ten (app/leaderboards.gd), so every menu has the Leaderboard button. + var expected: Array[String] = ["Resume", "Restart", "How to Play", "Leaderboard", "Main Menu"] var texts: Array[String] = [] for button in menu.buttons: texts.append(button.text) diff --git a/tools/build_monolith_walk.py b/tools/build_monolith_walk.py new file mode 100644 index 00000000..0031c193 --- /dev/null +++ b/tools/build_monolith_walk.py @@ -0,0 +1,151 @@ +"""Add a walk cycle to the Legacy Monolith sheets. + +The generated Enchanted Repo pack (tools/build_enchanted_asset_pack.py) gave the boss no walking +frames, so it slid across the arena in its idle pose. This appends one row of four `walk` frames +to `legacy_monolith.png` and, for the two armor states, `cracked_walk` and `bare_walk` rows to +`monolith_armor.png`, then registers them in `manifest.json` and the SpriteFrames `.tres` files. + +Each walk frame is the matching idle frame leaning a few degrees about the pivot (the feet) and +lifted a little on the off-steps, which reads as a heavy stone golem lumbering: lean left, rise, +lean right, rise. Rotation is nearest-neighbour about the pivot and the alpha is re-thresholded, +so the frames stay crisp pixel art. The build is deterministic and idempotent: a sheet that +already has its walk row is left alone. + +Usage, from the repository root: + python3 tools/build_monolith_walk.py +""" + +from __future__ import annotations + +import json +from pathlib import Path + +from PIL import Image + +PACK = Path("hoppys-adventure-arcade/Assets/enchanted-repo-assets-only/enchanted_repo") +LEANS = (-3.0, 0.0, 3.0, 0.0) +LIFTS = (0, -5, 0, -5) +WALK_FPS = 6 + +# sheet -> list of (walk clip, idle clip to derive it from) +WALKS = { + "legacy_monolith": [("walk", "idle")], + "monolith_armor": [("cracked_walk", "cracked_idle"), ("bare_walk", "bare_idle")], +} + + +def clip_frames(atlas: dict, name: str) -> list[int]: + for clip in atlas["clips"]: + if clip["name"] == name: + return list(clip["frames"]) + raise KeyError(name) + + +def walk_frame( + cell: Image.Image, pivot: tuple[int, int], lean: float, lift: int +) -> Image.Image: + """One walk frame: the idle cell leaned `lean` degrees about `pivot` and raised `lift` px.""" + turned = cell.rotate(lean, resample=Image.NEAREST, center=pivot) + frame = Image.new("RGBA", cell.size, (0, 0, 0, 0)) + frame.paste(turned, (0, lift)) + alpha = frame.getchannel("A").point(lambda v: 255 if v > 128 else 0) + frame.putalpha(alpha) + return frame + + +def add_walks(sheet: str, manifest: dict) -> bool: + atlas = manifest["atlases"][sheet] + if all(any(c["name"] == walk for c in atlas["clips"]) for walk, _ in WALKS[sheet]): + print(f"{sheet}: walk rows already present") + return False + cell = atlas["cell"][0] + columns, rows = atlas["grid"] + pivot = tuple(atlas["pivot"]) + png = PACK / atlas["file"] + image = Image.open(png).convert("RGBA") + new_rows = len(WALKS[sheet]) + grown = Image.new( + "RGBA", (image.width, image.height + cell * new_rows), (0, 0, 0, 0) + ) + grown.paste(image, (0, 0)) + for row_offset, (walk, idle) in enumerate(WALKS[sheet]): + idle_frames = clip_frames(atlas, idle) + indices = [] + for i in range(columns): + source = atlas["frames"][idle_frames[i % len(idle_frames)]] + x, y, w, h = source["rect"] + frame = walk_frame( + image.crop((x, y, x + w, y + h)), pivot, LEANS[i], LIFTS[i] + ) + index = len(atlas["frames"]) + fx, fy = i * cell, (rows + row_offset) * cell + grown.paste(frame, (fx, fy)) + left, top, right, bottom = frame.getbbox() + atlas["frames"].append( + { + "index": index, + "rect": [fx, fy, cell, cell], + "visible_bounds": [left, top, right, bottom], + } + ) + atlas["source_rects_ltrb"].append( + list(atlas["source_rects_ltrb"][idle_frames[i % len(idle_frames)]]) + ) + indices.append(index) + atlas["clips"].append( + {"name": walk, "frames": indices, "fps": WALK_FPS, "loop": True} + ) + atlas["grid"] = [columns, rows + new_rows] + grown.save(png, optimize=True) + write_tres(PACK / atlas["resource"], atlas, cell) + print( + f"{sheet}: added {new_rows * columns} walk frames ({image.size} -> {grown.size})" + ) + return True + + +def write_tres(path: Path, atlas: dict, cell: int) -> None: + """Rewrite the SpriteFrames resource from the manifest, in the pack builder's own format.""" + frames = atlas["frames"] + text = [ + f'[gd_resource type="SpriteFrames" load_steps={len(frames) + 2} format=3]', + f'\n[ext_resource type="Texture2D" path="{atlas["file"]}" id="1"]', + ] + for frame in frames: + x, y, _, _ = frame["rect"] + text += [ + f'\n[sub_resource type="AtlasTexture" id="F{frame["index"]}"]', + 'atlas = ExtResource("1")', + f"region = Rect2({x}, {y}, {cell}, {cell})", + "filter_clip = true", + ] + animations = [] + for clip in atlas["clips"]: + refs = ", ".join( + '{"duration": 1.0, "texture": SubResource("F%d")}' % i + for i in clip["frames"] + ) + loop = "true" if clip["loop"] else "false" + animations.append( + '{"frames": [%s], "loop": %s, "name": &"%s", "speed": %.1f}' + % (refs, loop, clip["name"], clip["fps"]) + ) + text += ["\n[resource]", "animations = [\n" + ",\n".join(animations) + "\n]"] + path.write_text("\n".join(text) + "\n") + + +def main() -> None: + manifest_path = PACK / "manifest.json" + manifest = json.loads(manifest_path.read_text()) + changed = False + for sheet in WALKS: + changed = add_walks(sheet, manifest) or changed + if changed: + manifest_path.write_text(json.dumps(manifest, indent=2) + "\n") + total_frames = sum(len(a["frames"]) for a in manifest["atlases"].values()) + total_clips = sum(len(a["clips"]) for a in manifest["atlases"].values()) + print(f"Pack now has {total_frames} frames and {total_clips} named clips.") + + +if __name__ == "__main__": + main()