init
This commit is contained in:
commit
276d43613d
1687 changed files with 109059 additions and 0 deletions
151
game/LAYOUT.md
Normal file
151
game/LAYOUT.md
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
# Harvest Season — farm layout
|
||||
|
||||
The playable farm built in Step 2 of `first-game-plan.md`. All numbers here are measured by
|
||||
`game/tests/test_farm_layout.gd`, which fails if the layout drifts from these rules.
|
||||
|
||||
## The map
|
||||
|
||||
- **Playable area: 60 × 60 m**, x −13…47 and z −45…15 (`FarmZones.playable`). The rest of the
|
||||
old farm is out-of-bounds scenery.
|
||||
- **Perimeter:** a wooden fence (`fence_005`, 101 segments) with **6 gaps**. Ground enemies enter
|
||||
and escape through the gaps. Crows (Step 9) fly over the fence.
|
||||
- **Scarecrow bounds:** invisible walls on the fence lines (`Zones/Perimeter/PlayerBounds`, physics
|
||||
layer 3 `player_bounds`). Only the scarecrow collides with them (its mask is 1 + 3), so the
|
||||
scarecrow can step into a gap but not leave the farm. Enemy navigation ignores them.
|
||||
- **Scarecrow start:** (3, −13), between the barn apron and the animal pen.
|
||||
|
||||
Top-down picture with zone outlines:
|
||||
|
||||
```sh
|
||||
godot --path . --script res://game/tools/render_overview.gd -- --out=/tmp/farm.png --center=17,-15 --size=66 --zones
|
||||
```
|
||||
|
||||
## Zones
|
||||
|
||||
Every zone is a `FarmZone` node under `Zones/` in `farm.tscn`: an axis-aligned rectangle with a
|
||||
kind, a display name, and a tint. Its props are its children. In the editor each zone draws a
|
||||
translucent box, so it can be moved and resized there. The HUD banner (`ZoneBanner`) shows the
|
||||
name when the scarecrow walks in.
|
||||
|
||||
| Zone | Rectangle (x, z) | What's there | Purpose |
|
||||
|---|---|---|---|
|
||||
| Crop Field | 14…46, −18.6…11.4 | The sunflower field: 6 plots, 30 crop units, two 2 m walkways between the plot bands | Exposed asset; crows' target |
|
||||
| Supply Shed | −6…8, −24…−14 | The red barn's south doors and the apron in front of them, with stock piles: crates and sacks (west of the doors), logs, hay, and barrels (east of the doors) | Stored materials; ground thieves' target (Step 8) |
|
||||
| Work Area | 8…14, −24…−15 | Tool table, workbench, chair, bucket, between the barn and the house | Crafting, repairs, and upgrades |
|
||||
| Animal Pen | −10…4, −11…−1 | Brown paddock fence, gate opening on the east side (panel swung open), henhouse, 4 chickens, 2 pigs, 2 sheep | Livestock (Step 8). Enemies can only reach the inside through the gate |
|
||||
| Woodlot | 37.5…46.5, −35…−21 | The fir tree line, dead trees and branches, log piles | Wood |
|
||||
| Scrap Heap | 25.5…36.5, −44…−33 | Old pickup, wagon, wheelbarrow, lawn mower, barrels, crate, on the farmyard dirt | Scrap |
|
||||
| Haystacks | 14…22, −44…−35 | The old hay stack (moved in from beyond the north fence) and 3 round bales | Straw |
|
||||
|
||||
The middle and south-west of the map (x −13…14, z −1…15) are deliberately open ground for
|
||||
building defenses.
|
||||
|
||||
### Crop units
|
||||
|
||||
The field is 10 rows, 3 m apart. A column split (rows 1–5 and 6–10) and two walkways (z −8.5…−6.5
|
||||
and 0.4…2.4) divide it into 6 plots. Each **unit is one row segment of a plot**, 9–13 plants:
|
||||
`Zones/CropField/PlotN/UnitMM` (`CropUnit`, `unit_id` 1–30). `GameConfig.start_crops` is 30 to
|
||||
match. The plan estimated about 40, but one row segment per unit keeps every theft clearly
|
||||
visible.
|
||||
|
||||
| | West rows (x 17–29) | East rows (x 32–44) |
|
||||
|---|---|---|
|
||||
| North band (z −15.4…−8.5) | Plot 1: units 1–5 | Plot 2: units 6–10 |
|
||||
| Middle band (z −6.5…0.4) | Plot 3: units 11–15 | Plot 4: units 16–20 |
|
||||
| South band (z 2.4…9.4) | Plot 5: units 21–25 | Plot 6: units 26–30 |
|
||||
|
||||
## Perimeter gaps and approach directions
|
||||
|
||||
Each gap is 3 m wide (the driveway is 4 m) and marked inside by a signpost. A `FarmMarker` (kind
|
||||
GAP) sits 3 m outside each gap, where ground enemies spawn and escape.
|
||||
|
||||
| Gap | Fence side, position | Leads to |
|
||||
|---|---|---|
|
||||
| GapNorth | north, x 10.5…13.5 | Haystacks, work area, barn apron |
|
||||
| GapDriveway | east, z −41.5…−37.5 (the farm road) | Scrap heap and farmyard. The farmers' truck uses it in the ending (Step 11) |
|
||||
| GapEast | east, z −20…−17 | Woodlot and the crop field's north-east corner |
|
||||
| GapSouthEast | south, x 29.5…32.5 | Crop field, south side |
|
||||
| GapSouthWest | south, x −5.5…−2.5 | Open south-west ground, pen (south side) |
|
||||
| GapWest | west, z −7.5…−4.5 | Pen's west fence: enemies must go round it to the gate |
|
||||
|
||||
Crow approach markers (kind CROW, about 8 m outside the fence): CrowNorth (17, −53),
|
||||
CrowEast (55, −5), CrowSouth (17, 23), CrowWest (−21, −15).
|
||||
|
||||
## Travel times
|
||||
|
||||
Scarecrow at run speed (5 m/s). Path lengths come from the navigation grid with the scarecrow's
|
||||
radius (0.4 m), from zone center to zone center. The Animal Pen's center is inside the pen, so
|
||||
routes to it go through the gate.
|
||||
|
||||
| From \ to | Crop Field | Supply Shed | Work Area | Animal Pen | Woodlot | Scrap Heap | Haystacks |
|
||||
|---|---|---|---|---|---|---|---|
|
||||
| **Crop Field** | — | 7.2 s | 5.4 s | 6.8 s | 5.9 s | 7.3 s | 8.0 s |
|
||||
| **Supply Shed** | 7.2 s | — | 2.8 s | 4.7 s | 9.7 s | 9.1 s | 8.3 s |
|
||||
| **Work Area** | 5.4 s | 2.8 s | — | 4.8 s | 7.1 s | 6.6 s | 5.7 s |
|
||||
| **Animal Pen** | 6.8 s | 4.7 s | 4.8 s | — | 10.8 s | 11.0 s | 10.4 s |
|
||||
| **Woodlot** | 5.9 s | 9.7 s | 7.1 s | 10.8 s | — | 3.5 s | 5.3 s |
|
||||
| **Scrap Heap** | 7.3 s | 9.1 s | 6.6 s | 11.0 s | 3.5 s | — | 2.3 s |
|
||||
| **Haystacks** | 8.0 s | 8.3 s | 5.7 s | 10.4 s | 5.3 s | 2.3 s | — |
|
||||
|
||||
The longest trip is 11.0 s (Animal Pen ↔ Scrap Heap). The rule is no key area more than 12 s from
|
||||
another. The two defended fronts sit 6–7 s apart: the crop field in the south-east, and the pen
|
||||
and shed in the west. Holding one leaves the other exposed. The gathering spots are in the north,
|
||||
so a day of gathering pulls the scarecrow away from both fronts.
|
||||
|
||||
Ground-enemy path from each gap to the nearest edge of each zone, in meters (enemy radius 0.35 m):
|
||||
|
||||
| Zone | North | Driveway | East | South-east | South-west | West |
|
||||
|---|---|---|---|---|---|---|
|
||||
| Crop Field | 30 | 23 | 4 | 7 | 24 | 34 |
|
||||
| Supply Shed | 26 | 49 | 43 | 42 | 36 | 16 |
|
||||
| Work Area | 24 | 46 | 37 | 40 | 38 | 30 |
|
||||
| Animal Pen (inside) | 46 | 63 | 51 | 39 | 28 | 32 |
|
||||
| Woodlot | 39 | 10 | 7 | 42 | 60 | 62 |
|
||||
| Scrap Heap | 26 | 14 | 24 | 52 | 63 | 56 |
|
||||
| Haystacks | 6 | 32 | 35 | 57 | 62 | 49 |
|
||||
|
||||
## Navigation
|
||||
|
||||
`FarmNavigation` (`game/scripts/farm_navigation.gd`) rasterizes the farm's own collision into a
|
||||
0.5 m occupancy grid:
|
||||
- Every StaticBody3D shape on layer 1 counts, except walkable trimesh terrain and anything below
|
||||
0.35 m.
|
||||
- Obstacles are inflated by the mover's radius.
|
||||
- Distance fields use octile Dijkstra with no corner cutting.
|
||||
|
||||
For enemies: the playable area plus a 5 m margin is 20,164 cells. 423 shapes are rasterized, and
|
||||
the grid builds in about 25 ms (headless, editor binary). Because the grid comes from the same
|
||||
collision the player walks against, physics and navigation can't drift apart. Step 3 adds flow
|
||||
fields toward the crop plots and the gaps on top of it.
|
||||
|
||||
## What changed from the old farm
|
||||
|
||||
- **Removed:**
|
||||
- 1,122 plants in the three fields outside the map (their bare soil stays as scenery)
|
||||
- 60 plants where the walkways run
|
||||
- the north-west field's soil tile
|
||||
- 29 segments of the old inner east fence that would have doubled the new perimeter
|
||||
- **Moved:** the hay stack from beyond the north fence into the farmyard (Haystacks).
|
||||
- **Collision:**
|
||||
- `build_prop_collision.gd` generated collision for the newly placed prop types.
|
||||
- Animals get none (they become moving entities in Step 8).
|
||||
- The open gate (`fence_018`) has a hand-made thin box along its panel, so the pen opening stays
|
||||
clear.
|
||||
- **Rendering cost:**
|
||||
|
||||
| View | Draw calls before | Draw calls after |
|
||||
|---|---|---|
|
||||
| Game camera at the start | 1,270 | 304 |
|
||||
| Whole farm, top-down | 3,621 | 1,504 |
|
||||
| Over the crop field | — | 649 |
|
||||
|
||||
The plants are cheap enough as ordinary nodes, so the crop field stays as instanced prefabs
|
||||
rather than a MultiMesh.
|
||||
|
||||
## Editing the layout
|
||||
|
||||
- Move or resize zones and props in the editor. After placing a **new prefab type**, re-run
|
||||
`game/tools/build_prop_collision.gd` with the editor closed.
|
||||
- Run `godot --headless --path . --script res://game/tests/run_tests.gd -- --suite=test_farm_layout`
|
||||
to check the result: zones, fence integrity, reachability, and travel times. It prints the
|
||||
tables above.
|
||||
97
game/RULES.md
Normal file
97
game/RULES.md
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
# Harvest Season — rules of the vacation
|
||||
|
||||
The rule set every other system follows. Decision numbers (D1–D10) refer to
|
||||
`first-game-plan.md`, section 2. Every number is a starting value in
|
||||
`res://game/resources/game_config.tres` (`GameConfig`) and gets tuned during balancing.
|
||||
|
||||
Enforced in code: phases, timers, outcomes, loss records, and the retry snapshot
|
||||
(`CampaignController`, `FarmState`). Theft, combat, and building rules are written here first,
|
||||
and later steps implement them as shown in the last column of each table.
|
||||
|
||||
## The vacation
|
||||
|
||||
- The farmers are away for **five nights**. The scarecrow protects the farm until they return.
|
||||
- Each night is one cycle: **Morning → Day → Dusk → Night → Dawn**. After the fifth dawn the
|
||||
farmers return, which ends the game, and the farm is assessed on what remains.
|
||||
- Losses carry over. Stolen crops don't regrow, lost animals don't come back, and stolen supplies
|
||||
are gone. Damaged structures stay damaged until repaired.
|
||||
|
||||
## Phases
|
||||
|
||||
| Phase | Length | What happens | Enforced |
|
||||
|---|---|---|---|
|
||||
| Morning | Untimed | Review last night's losses and damage. The day starts when the player dismisses the review. | Now |
|
||||
| Day | 180 s | Safe. Gather, build, repair, upgrade. | Now (timer) |
|
||||
| Dusk | 30 s | Still safe. Warning of the coming attack; last chance to prepare. | Now (timer) |
|
||||
| Night | 150 s | Enemies attack to steal farm assets or damage defenses. | Now (timer), enemies in Step 3 |
|
||||
| Dawn | 20 s | Sunrise: no more enemies arrive and all of them retreat (D4). Carriers can still be stopped. Then remaining enemies leave and the night's losses are recorded. | Now (timer and record), retreat in Step 7 |
|
||||
|
||||
**Starting the night early (D1).** The player can skip the rest of the day or dusk straight to
|
||||
the night, but only when `allow_early_night` is on. It is **off by default**.
|
||||
|
||||
**What's allowed when (D8).**
|
||||
|
||||
| Action | Day / Dusk | Night / Dawn | Enforced |
|
||||
|---|---|---|---|
|
||||
| Gather materials | Yes | No | Step 5 |
|
||||
| Build new structures | Yes | No | Step 6 |
|
||||
| Repair, dismantle, patch the scarecrow | Yes | Yes | Steps 4, 6 |
|
||||
|
||||
## Farm assets
|
||||
|
||||
Three kinds of asset can be stolen: **crops**, **animals**, and **supplies** (stored
|
||||
construction materials in the shed). A kind is "in play" once the farm has any of it; until
|
||||
Step 8 only crops are in play.
|
||||
|
||||
### Theft lifecycle
|
||||
|
||||
| State | Meaning | Feedback |
|
||||
|---|---|---|
|
||||
| Targeted | An enemy is heading for the asset | Marker over it; arrow at the screen edge if off screen |
|
||||
| Being stolen | The enemy is taking it, which takes visible time (crops: 2.5 s). Damage resets the timer. | Progress ring |
|
||||
| Carried | The enemy is heading for the nearest escape point, slower than usual | The asset shown on the enemy |
|
||||
| Dropped | The carrier was stopped | The asset lies on the ground, glowing |
|
||||
| Recovered | The scarecrow got it back | It returns home |
|
||||
| Lost | The carrier escaped off the farm | Permanently gone |
|
||||
|
||||
- **Stopping a carrier (D5).** Killing a carrier drops its loot. Fear also makes carriers drop
|
||||
their loot (`fear_drops_loot`).
|
||||
- **Recovering (D6).** Crops and supplies: touch the dropped item and it goes straight home.
|
||||
Animals: touch one and it follows the scarecrow (at most 3 at once) until it's back inside
|
||||
the pen.
|
||||
- Another thief can pick up a dropped item.
|
||||
- Anything still on the ground when the dawn grace ends returns home automatically
|
||||
(`loot_returns_at_dawn`).
|
||||
- Animals can also escape through a breach in the pen. An animal that leaves the farm is lost.
|
||||
|
||||
Implemented in Steps 3 (crops), 4 (fear), and 8 (animals and supplies).
|
||||
|
||||
## The scarecrow
|
||||
|
||||
- Starts with **10 HP**. HP **carries over between nights** (D7).
|
||||
- **Patching** restores HP. It costs straw, takes a 2 s channel, can be done in any phase, and
|
||||
damage interrupts it (Steps 4–5).
|
||||
- **0 HP is an immediate Game Over.**
|
||||
|
||||
## How the vacation ends
|
||||
|
||||
| Outcome | Condition | Result |
|
||||
|---|---|---|
|
||||
| Scarecrow destroyed | Scarecrow HP reaches 0, in any phase | Game Over |
|
||||
| Farm stripped (D2) | **Every** kind of asset in play is gone: crops, animals, and stored supplies all at zero. Losing one kind isn't enough. | Game Over |
|
||||
| Vacation complete | The fifth night's dawn ends | The farmers return; final assessment |
|
||||
|
||||
- **Order of checks.** The outcome is checked every tick, after gameplay and before any phase
|
||||
change. A destroyed scarecrow is checked first, then a stripped farm, then completion. If a
|
||||
failure and the end of the final dawn happen on the same tick, the result is a **loss**.
|
||||
- **Retry (D9).** After a Game Over, Retry restarts the failed night from its morning, with
|
||||
everything as it was then: earlier losses, damage, and scarecrow HP. New Vacation starts the
|
||||
whole campaign over.
|
||||
|
||||
## Night record
|
||||
|
||||
When a night's dawn ends, the losses of that night (night and dawn together) are recorded per
|
||||
asset kind. The morning review (Step 7) and nightly results (Step 11) read from this record.
|
||||
|
||||
Open item for Step 8: supplies spent on building also reduce stored supplies. Decide then
|
||||
whether a farm whose supplies were *spent* rather than stolen counts as stripped.
|
||||
19
game/resources/game_config.tres
Normal file
19
game/resources/game_config.tres
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
[gd_resource type="Resource" script_class="GameConfig" format=3]
|
||||
|
||||
[ext_resource type="Script" path="res://game/scripts/game_config.gd" id="1_cfg"]
|
||||
|
||||
[resource]
|
||||
script = ExtResource("1_cfg")
|
||||
campaign_nights = 5
|
||||
day_length = 180.0
|
||||
dusk_length = 30.0
|
||||
night_length = 150.0
|
||||
dawn_grace = 20.0
|
||||
allow_early_night = false
|
||||
scarecrow_max_hp = 10
|
||||
start_crops = 30
|
||||
start_animals = 0
|
||||
start_supplies = 0
|
||||
fear_drops_loot = true
|
||||
loot_returns_at_dawn = true
|
||||
max_following_animals = 3
|
||||
BIN
game/resources/player_animations.res
Normal file
BIN
game/resources/player_animations.res
Normal file
Binary file not shown.
2928
game/scenes/farm.tscn
Normal file
2928
game/scenes/farm.tscn
Normal file
File diff suppressed because it is too large
Load diff
30
game/scenes/player.tscn
Normal file
30
game/scenes/player.tscn
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
[gd_scene format=3]
|
||||
|
||||
[ext_resource type="Script" path="res://game/scripts/player_character.gd" id="1_script"]
|
||||
[ext_resource type="PackedScene" path="res://assets/kaykit_characters/characters/Mannequin_Medium.glb" id="2_mannequin"]
|
||||
[ext_resource type="AnimationLibrary" path="res://game/resources/player_animations.res" id="3_anims"]
|
||||
|
||||
[sub_resource type="CapsuleShape3D" id="CapsuleShape3D_body"]
|
||||
radius = 0.4
|
||||
height = 2.0
|
||||
|
||||
[node name="Player" type="CharacterBody3D"]
|
||||
collision_layer = 2
|
||||
collision_mask = 5
|
||||
script = ExtResource("1_script")
|
||||
|
||||
[node name="CollisionShape3D" type="CollisionShape3D" parent="."]
|
||||
position = Vector3(0, 1, 0)
|
||||
shape = SubResource("CapsuleShape3D_body")
|
||||
|
||||
[node name="Model" type="Node3D" parent="."]
|
||||
|
||||
[node name="Mannequin" parent="Model" instance=ExtResource("2_mannequin")]
|
||||
rotation = Vector3(0, 3.14159, 0)
|
||||
|
||||
[node name="AnimationPlayer" type="AnimationPlayer" parent="Model"]
|
||||
root_node = NodePath("../Mannequin")
|
||||
libraries = {
|
||||
&"": ExtResource("3_anims")
|
||||
}
|
||||
autoplay = &"Idle_A"
|
||||
156
game/scripts/campaign_controller.gd
Normal file
156
game/scripts/campaign_controller.gd
Normal file
|
|
@ -0,0 +1,156 @@
|
|||
class_name CampaignController
|
||||
extends Node
|
||||
## Owns the five-night vacation: the phase state machine, phase timers, the outcome rules, and
|
||||
## the morning snapshot used to retry a failed night (rules: game/RULES.md).
|
||||
##
|
||||
## MORNING -> DAY -> DUSK -> NIGHT -> DAWN -> MORNING of the next night; after the final dawn,
|
||||
## FARMERS_RETURN. GAME_OVER can follow any phase. Both are terminal. The morning review is
|
||||
## untimed and ends through begin_day(); the other phases run on game-time timers, so
|
||||
## Engine.time_scale speeds the whole cycle up.
|
||||
##
|
||||
## Gameplay systems (later steps) run before tick() in each physics tick. tick() advances the
|
||||
## phase timer, then evaluates the outcome before applying any transition. Failures are checked
|
||||
## before completion, so a scarecrow destroyed on the tick the final dawn ends is a Game Over.
|
||||
|
||||
enum Phase { MORNING, DAY, DUSK, NIGHT, DAWN, FARMERS_RETURN, GAME_OVER }
|
||||
enum Outcome { CONTINUE, GAME_OVER_SCARECROW, GAME_OVER_STRIPPED, VACATION_COMPLETE }
|
||||
|
||||
signal phase_changed(phase: Phase, previous: Phase)
|
||||
signal campaign_ended(outcome: Outcome)
|
||||
|
||||
@export var config: GameConfig
|
||||
|
||||
var state: FarmState
|
||||
var outcome: Outcome = Outcome.CONTINUE
|
||||
|
||||
var _morning_snapshot: Dictionary = {}
|
||||
var _night_start := PackedInt32Array()
|
||||
|
||||
|
||||
func _ready() -> void:
|
||||
if config == null:
|
||||
config = load("res://game/resources/game_config.tres") as GameConfig
|
||||
config = config.duplicate() as GameConfig # runtime overrides never touch the asset
|
||||
new_campaign()
|
||||
|
||||
|
||||
func _physics_process(delta: float) -> void:
|
||||
tick(delta)
|
||||
|
||||
|
||||
## Starts a fresh vacation: full farm, full scarecrow, the morning of night 1.
|
||||
func new_campaign() -> void:
|
||||
state = FarmState.create(config)
|
||||
outcome = Outcome.CONTINUE
|
||||
_enter(Phase.MORNING)
|
||||
|
||||
|
||||
func tick(delta: float) -> void:
|
||||
if is_over():
|
||||
return
|
||||
var finished := false
|
||||
if is_timed(state.phase):
|
||||
state.phase_time_left = maxf(state.phase_time_left - delta, 0.0)
|
||||
finished = state.phase_time_left <= 0.0
|
||||
_resolve(finished)
|
||||
|
||||
|
||||
## Ends the morning review, the only way out of the untimed morning.
|
||||
func begin_day() -> bool:
|
||||
if state.phase != Phase.MORNING:
|
||||
return false
|
||||
_resolve(true)
|
||||
return true
|
||||
|
||||
|
||||
## D1: skips the rest of the day or dusk straight to the night, when the option is enabled.
|
||||
func start_night_early() -> bool:
|
||||
if not can_start_night_early():
|
||||
return false
|
||||
_enter(Phase.NIGHT)
|
||||
return true
|
||||
|
||||
|
||||
func can_start_night_early() -> bool:
|
||||
return config.allow_early_night and (state.phase == Phase.DAY or state.phase == Phase.DUSK)
|
||||
|
||||
|
||||
## Debug: ends the current phase now, through the normal transition and outcome path.
|
||||
func advance_phase() -> void:
|
||||
if not is_over():
|
||||
_resolve(true)
|
||||
|
||||
|
||||
## D9: restarts the current night from its morning (the autosave point once saving exists).
|
||||
func retry_night() -> bool:
|
||||
var restored := FarmState.from_dict(_morning_snapshot)
|
||||
if restored == null:
|
||||
return false
|
||||
state = restored
|
||||
outcome = Outcome.CONTINUE
|
||||
_enter(Phase.MORNING)
|
||||
return true
|
||||
|
||||
|
||||
func is_over() -> bool:
|
||||
return state.phase == Phase.GAME_OVER or state.phase == Phase.FARMERS_RETURN
|
||||
|
||||
|
||||
func is_timed(phase: Phase) -> bool:
|
||||
return is_finite(config.phase_length(phase))
|
||||
|
||||
|
||||
## The outcome rules as a pure function of the farm state. Scarecrow destruction is checked
|
||||
## first, then a stripped farm, and only then completing the vacation.
|
||||
static func check_outcome(s: FarmState, campaign_nights: int) -> Outcome:
|
||||
if s.scarecrow_hp <= 0:
|
||||
return Outcome.GAME_OVER_SCARECROW
|
||||
if s.is_stripped():
|
||||
return Outcome.GAME_OVER_STRIPPED
|
||||
if s.nights_survived >= campaign_nights:
|
||||
return Outcome.VACATION_COMPLETE
|
||||
return Outcome.CONTINUE
|
||||
|
||||
|
||||
func _resolve(phase_finished: bool) -> void:
|
||||
var finished_phase := state.phase
|
||||
if phase_finished and finished_phase == Phase.DAWN:
|
||||
state.nights_survived = state.night
|
||||
state.log_night(_night_start)
|
||||
var result := check_outcome(state, config.campaign_nights)
|
||||
if result != Outcome.CONTINUE:
|
||||
outcome = result
|
||||
_enter(Phase.FARMERS_RETURN if result == Outcome.VACATION_COMPLETE else Phase.GAME_OVER)
|
||||
campaign_ended.emit(result)
|
||||
return
|
||||
if not phase_finished:
|
||||
return
|
||||
if finished_phase == Phase.DAWN:
|
||||
state.night += 1
|
||||
_enter(_next_phase(finished_phase))
|
||||
|
||||
|
||||
func _enter(phase: Phase) -> void:
|
||||
var previous := state.phase
|
||||
state.phase = phase
|
||||
var length := config.phase_length(phase)
|
||||
state.phase_time_left = length if is_finite(length) else 0.0
|
||||
match phase:
|
||||
Phase.MORNING:
|
||||
_morning_snapshot = state.to_dict()
|
||||
Phase.NIGHT:
|
||||
_night_start = state.asset_counts()
|
||||
phase_changed.emit(phase, previous)
|
||||
|
||||
|
||||
static func _next_phase(phase: Phase) -> Phase:
|
||||
match phase:
|
||||
Phase.MORNING:
|
||||
return Phase.DAY
|
||||
Phase.DAY:
|
||||
return Phase.DUSK
|
||||
Phase.DUSK:
|
||||
return Phase.NIGHT
|
||||
Phase.NIGHT:
|
||||
return Phase.DAWN
|
||||
return Phase.MORNING
|
||||
1
game/scripts/campaign_controller.gd.uid
Normal file
1
game/scripts/campaign_controller.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://dh1gl5p44sjb1
|
||||
97
game/scripts/campaign_debug.gd
Normal file
97
game/scripts/campaign_debug.gd
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
class_name CampaignDebug
|
||||
extends CanvasLayer
|
||||
## Temporary campaign readout and debug keys, until the phase HUD (Step 7) and menus (Step 11)
|
||||
## replace it.
|
||||
## Enter / Space / A begin the day (ends the untimed morning review)
|
||||
## N start the night early (only when GameConfig.allow_early_night is on)
|
||||
## R / Start after Game Over: retry the night; after the farmers return: new vacation
|
||||
## F6 end the current phase now
|
||||
## F7 cycle game speed 1x / 5x / 20x
|
||||
## F9 debug: scarecrow to 0 HP
|
||||
## F10 debug: strip every farm asset
|
||||
|
||||
const SPEEDS: Array[float] = [1.0, 5.0, 20.0]
|
||||
const ENDINGS := {
|
||||
CampaignController.Outcome.GAME_OVER_SCARECROW: "GAME OVER: the scarecrow was destroyed",
|
||||
CampaignController.Outcome.GAME_OVER_STRIPPED: "GAME OVER: the farm was stripped bare",
|
||||
CampaignController.Outcome.VACATION_COMPLETE: "THE FARMERS ARE BACK: vacation complete",
|
||||
}
|
||||
|
||||
@export var campaign: CampaignController
|
||||
|
||||
var _label: Label
|
||||
var _speed_index: int = 0
|
||||
|
||||
|
||||
func _ready() -> void:
|
||||
_label = Label.new()
|
||||
_label.position = Vector2(24.0, 20.0)
|
||||
_label.add_theme_font_size_override("font_size", 22)
|
||||
_label.add_theme_color_override("font_outline_color", Color.BLACK)
|
||||
_label.add_theme_constant_override("outline_size", 6)
|
||||
add_child(_label)
|
||||
|
||||
|
||||
func _exit_tree() -> void:
|
||||
Engine.time_scale = 1.0
|
||||
|
||||
|
||||
func _process(_delta: float) -> void:
|
||||
_label.text = _describe()
|
||||
|
||||
|
||||
func _unhandled_input(event: InputEvent) -> void:
|
||||
var s := campaign.state
|
||||
if event.is_action_pressed("ui_accept") and s.phase == CampaignController.Phase.MORNING:
|
||||
campaign.begin_day()
|
||||
elif event.is_action_pressed("restart"):
|
||||
if s.phase == CampaignController.Phase.GAME_OVER:
|
||||
campaign.retry_night()
|
||||
elif s.phase == CampaignController.Phase.FARMERS_RETURN:
|
||||
campaign.new_campaign()
|
||||
var key := event as InputEventKey
|
||||
if key == null or not key.pressed or key.echo:
|
||||
return
|
||||
match key.physical_keycode:
|
||||
KEY_N:
|
||||
campaign.start_night_early()
|
||||
KEY_F6:
|
||||
campaign.advance_phase()
|
||||
KEY_F7:
|
||||
_speed_index = (_speed_index + 1) % SPEEDS.size()
|
||||
Engine.time_scale = SPEEDS[_speed_index]
|
||||
KEY_F9:
|
||||
s.scarecrow_hp = 0
|
||||
KEY_F10:
|
||||
s.crops = 0
|
||||
s.animals = 0
|
||||
s.supplies = 0
|
||||
|
||||
|
||||
func _describe() -> String:
|
||||
var s := campaign.state
|
||||
var lines: Array[String] = []
|
||||
var phase_name: String = CampaignController.Phase.keys()[s.phase]
|
||||
var head := "Night %d/%d · %s" % [s.night, campaign.config.campaign_nights, phase_name.replace("_", " ")]
|
||||
if campaign.is_timed(s.phase):
|
||||
var t := ceili(s.phase_time_left)
|
||||
head += " · %d:%02d left" % [floori(t / 60.0), t % 60]
|
||||
lines.append(head + " · speed %dx" % int(SPEEDS[_speed_index]))
|
||||
var farm := "Scarecrow %d/%d · Crops %d/%d" % [s.scarecrow_hp, s.scarecrow_max_hp, s.crops, s.crops_total]
|
||||
if s.animals_total > 0:
|
||||
farm += " · Animals %d/%d" % [s.animals, s.animals_total]
|
||||
if s.supplies_total > 0:
|
||||
farm += " · Supplies %d" % s.supplies
|
||||
lines.append(farm)
|
||||
match s.phase:
|
||||
CampaignController.Phase.MORNING:
|
||||
lines.append("[Enter] begin the day")
|
||||
CampaignController.Phase.GAME_OVER:
|
||||
lines.append(ENDINGS[campaign.outcome] + " · [R] retry the night")
|
||||
CampaignController.Phase.FARMERS_RETURN:
|
||||
lines.append(ENDINGS[campaign.outcome] + " · [R] new vacation")
|
||||
_:
|
||||
if campaign.can_start_night_early():
|
||||
lines.append("[N] start the night early")
|
||||
lines.append("F6 next phase · F7 speed · F9 scarecrow to 0 HP · F10 strip farm")
|
||||
return "\n".join(lines)
|
||||
1
game/scripts/campaign_debug.gd.uid
Normal file
1
game/scripts/campaign_debug.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://bvvdfx5idf2u5
|
||||
7
game/scripts/crop_unit.gd
Normal file
7
game/scripts/crop_unit.gd
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
class_name CropUnit
|
||||
extends Node3D
|
||||
## One stealable crop unit: a cluster of plants (this node's children) with one ID in FarmState.
|
||||
## The crop field holds 6 plots of 5 units; each unit is one row segment of its plot.
|
||||
|
||||
@export var unit_id: int = 0
|
||||
@export var plot: int = 0
|
||||
1
game/scripts/crop_unit.gd.uid
Normal file
1
game/scripts/crop_unit.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://d0bha7ghc1lfc
|
||||
10
game/scripts/farm_marker.gd
Normal file
10
game/scripts/farm_marker.gd
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
@tool
|
||||
class_name FarmMarker
|
||||
extends Marker3D
|
||||
## A point on the farm perimeter. A GAP marker sits just outside a gap in the perimeter fence:
|
||||
## ground enemies arrive and escape there. A CROW marker is a direction that flyers arrive from
|
||||
## and leave toward.
|
||||
|
||||
enum Kind { GAP, CROW }
|
||||
|
||||
@export var kind: Kind = Kind.GAP
|
||||
1
game/scripts/farm_marker.gd.uid
Normal file
1
game/scripts/farm_marker.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://dewrnp06jkx2y
|
||||
238
game/scripts/farm_navigation.gd
Normal file
238
game/scripts/farm_navigation.gd
Normal file
|
|
@ -0,0 +1,238 @@
|
|||
class_name FarmNavigation
|
||||
extends RefCounted
|
||||
## Navigation grid for ground movement on the farm.
|
||||
##
|
||||
## * Occupancy is rasterized from the farm's own collision: every CollisionShape3D under a
|
||||
## StaticBody3D on the given layers, so physics and navigation can't drift apart. Walkable
|
||||
## terrain is skipped (trimesh ground and road tiles, and anything that stays below BAND_LOW,
|
||||
## like the flat concrete pads). Every other shape that reaches into BAND_LOW..BAND_HIGH blocks
|
||||
## the cells its XZ outline covers, inflated by the mover's radius. Bodies on other layers
|
||||
## (the scarecrow-only PlayerBounds) are ignored. The grid has a 1-cell blocked border.
|
||||
## * Distance fields toward a set of goal cells: Dijkstra over 8 neighbors with octile integer
|
||||
## costs (orthogonal 5, diagonal 7 ~ 5 * sqrt(2)) and a circular bucket queue with lazy
|
||||
## deletion, the scheme of the prototype's ArenaNavigation. Diagonal steps never cut a blocked
|
||||
## corner. Unreachable cells keep UNREACHABLE.
|
||||
|
||||
const UNREACHABLE := 1 << 29
|
||||
const COST_ORTH := 5
|
||||
const COST_DIAG := 7
|
||||
const BUCKETS := 8 # > max edge cost, so each pending distance maps to a unique bucket
|
||||
## Height band (meters above the farm floor at y = 0) in which a shape obstructs ground movement.
|
||||
const BAND_LOW := 0.35
|
||||
const BAND_HIGH := 2.0
|
||||
|
||||
var cell_size: float
|
||||
var inv_cell: float
|
||||
var origin_x: float # world position of cell (0, 0)'s min corner
|
||||
var origin_z: float
|
||||
var width: int
|
||||
var height: int
|
||||
var blocked: PackedByteArray
|
||||
var shapes_rasterized: int = 0
|
||||
var build_usec: int = 0
|
||||
|
||||
var _offsets := PackedInt32Array()
|
||||
var _side_a := PackedInt32Array()
|
||||
var _side_b := PackedInt32Array()
|
||||
var _bucket_buf := PackedInt32Array() # BUCKETS stacks of capacity cell_count()
|
||||
var _bucket_cnt := PackedInt32Array()
|
||||
|
||||
|
||||
func build(world: Node, bounds: Rect2, p_cell_size: float, inflate: float, layer_mask: int = 1) -> void:
|
||||
var t0 := Time.get_ticks_usec()
|
||||
cell_size = p_cell_size
|
||||
inv_cell = 1.0 / cell_size
|
||||
width = ceili(bounds.size.x * inv_cell) + 2
|
||||
height = ceili(bounds.size.y * inv_cell) + 2
|
||||
origin_x = bounds.position.x - cell_size
|
||||
origin_z = bounds.position.y - cell_size
|
||||
var n := width * height
|
||||
blocked = PackedByteArray()
|
||||
blocked.resize(n)
|
||||
for cx in width:
|
||||
blocked[cx] = 1
|
||||
blocked[(height - 1) * width + cx] = 1
|
||||
for cz in height:
|
||||
blocked[cz * width] = 1
|
||||
blocked[cz * width + width - 1] = 1
|
||||
shapes_rasterized = 0
|
||||
for node in world.find_children("*", "CollisionShape3D", true, false):
|
||||
var cs := node as CollisionShape3D
|
||||
var body := cs.get_parent() as StaticBody3D
|
||||
if body == null or cs.disabled or cs.shape == null or (body.collision_layer & layer_mask) == 0:
|
||||
continue
|
||||
if cs.shape is ConcavePolygonShape3D or cs.shape is WorldBoundaryShape3D:
|
||||
continue
|
||||
var outline := _outline(cs)
|
||||
if outline.size() > 0:
|
||||
_rasterize(outline, inflate)
|
||||
shapes_rasterized += 1
|
||||
var w := width
|
||||
# Orthogonal first (indices 0..3), then diagonals (4..7) with their two side cells.
|
||||
_offsets = PackedInt32Array([1, -1, w, -w, w + 1, w - 1, -w + 1, -w - 1])
|
||||
_side_a = PackedInt32Array([0, 0, 0, 0, 1, -1, 1, -1])
|
||||
_side_b = PackedInt32Array([0, 0, 0, 0, w, w, -w, -w])
|
||||
_bucket_buf = PackedInt32Array()
|
||||
_bucket_buf.resize(n * BUCKETS)
|
||||
_bucket_cnt = PackedInt32Array()
|
||||
_bucket_cnt.resize(BUCKETS)
|
||||
build_usec = Time.get_ticks_usec() - t0
|
||||
|
||||
|
||||
func cell_count() -> int:
|
||||
return width * height
|
||||
|
||||
|
||||
func cell_of(x: float, z: float) -> int:
|
||||
var cx := clampi(int((x - origin_x) * inv_cell), 0, width - 1)
|
||||
var cz := clampi(int((z - origin_z) * inv_cell), 0, height - 1)
|
||||
return cz * width + cx
|
||||
|
||||
|
||||
func cell_center(i: int) -> Vector2:
|
||||
@warning_ignore("integer_division")
|
||||
var cz := i / width
|
||||
var cx := i - cz * width
|
||||
return Vector2(origin_x + (cx + 0.5) * cell_size, origin_z + (cz + 0.5) * cell_size)
|
||||
|
||||
|
||||
func is_free(i: int) -> bool:
|
||||
return blocked[i] == 0
|
||||
|
||||
|
||||
## Nearest free cell to i (breadth-first over 4-neighbors), or -1 if none within max_cells.
|
||||
func nearest_free(i: int, max_cells: int = 4096) -> int:
|
||||
if blocked[i] == 0:
|
||||
return i
|
||||
var seen := {i: true}
|
||||
var queue: Array[int] = [i]
|
||||
var head := 0
|
||||
while head < queue.size() and head < max_cells:
|
||||
var c := queue[head]
|
||||
head += 1
|
||||
for k in 4:
|
||||
var nb := c + _offsets[k]
|
||||
if nb < 0 or nb >= blocked.size() or seen.has(nb):
|
||||
continue
|
||||
if blocked[nb] == 0:
|
||||
return nb
|
||||
seen[nb] = true
|
||||
queue.append(nb)
|
||||
return -1
|
||||
|
||||
|
||||
## Free cells whose centers lie inside a world rectangle on the XZ plane.
|
||||
func free_cells_in(rect: Rect2) -> PackedInt32Array:
|
||||
var out := PackedInt32Array()
|
||||
var c0 := cell_of(rect.position.x, rect.position.y)
|
||||
var c1 := cell_of(rect.end.x, rect.end.y)
|
||||
@warning_ignore("integer_division")
|
||||
for cz in range(c0 / width, c1 / width + 1):
|
||||
for cx in range(c0 % width, c1 % width + 1):
|
||||
var i := cz * width + cx
|
||||
if blocked[i] == 0 and rect.has_point(cell_center(i)):
|
||||
out.append(i)
|
||||
return out
|
||||
|
||||
|
||||
## Path cost from distance_field() in meters.
|
||||
func meters(cost: int) -> float:
|
||||
return cost * cell_size / COST_ORTH
|
||||
|
||||
|
||||
## Octile path cost from every cell to the nearest goal cell (blocked goals are ignored).
|
||||
func distance_field(goals: PackedInt32Array) -> PackedInt32Array:
|
||||
var n := cell_count()
|
||||
var dist := PackedInt32Array()
|
||||
dist.resize(n)
|
||||
dist.fill(UNREACHABLE)
|
||||
var buf := _bucket_buf
|
||||
var cnt := _bucket_cnt
|
||||
cnt.fill(0)
|
||||
var pending := 0
|
||||
for g in goals:
|
||||
if blocked[g] == 1 or dist[g] == 0:
|
||||
continue
|
||||
dist[g] = 0
|
||||
buf[cnt[0]] = g
|
||||
cnt[0] += 1
|
||||
pending += 1
|
||||
var cur := 0
|
||||
while pending > 0:
|
||||
var b := cur % BUCKETS
|
||||
var base := b * n
|
||||
while cnt[b] > 0:
|
||||
cnt[b] -= 1
|
||||
var c := buf[base + cnt[b]]
|
||||
pending -= 1
|
||||
if dist[c] != cur:
|
||||
continue # superseded by a shorter path (lazy deletion)
|
||||
for k in 8:
|
||||
var nb := c + _offsets[k]
|
||||
if blocked[nb] == 1:
|
||||
continue
|
||||
var cost := COST_ORTH
|
||||
if k >= 4:
|
||||
if blocked[c + _side_a[k]] == 1 or blocked[c + _side_b[k]] == 1:
|
||||
continue
|
||||
cost = COST_DIAG
|
||||
var nd := cur + cost
|
||||
if nd < dist[nb]:
|
||||
dist[nb] = nd
|
||||
var nk := nd % BUCKETS
|
||||
buf[nk * n + cnt[nk]] = nb
|
||||
cnt[nk] += 1
|
||||
pending += 1
|
||||
cur += 1
|
||||
return dist
|
||||
|
||||
|
||||
## XZ convex outline of a shape (from its debug mesh in world space), or empty when the shape
|
||||
## stays out of the obstruction band.
|
||||
func _outline(cs: CollisionShape3D) -> PackedVector2Array:
|
||||
var mesh := cs.shape.get_debug_mesh()
|
||||
var xf := cs.global_transform
|
||||
var points := PackedVector2Array()
|
||||
var lo := INF
|
||||
var hi := -INF
|
||||
for s in mesh.get_surface_count():
|
||||
var verts: PackedVector3Array = mesh.surface_get_arrays(s)[Mesh.ARRAY_VERTEX]
|
||||
for v in verts:
|
||||
var p := xf * v
|
||||
lo = minf(lo, p.y)
|
||||
hi = maxf(hi, p.y)
|
||||
points.append(Vector2(p.x, p.z))
|
||||
if points.is_empty() or hi < BAND_LOW or lo > BAND_HIGH:
|
||||
return PackedVector2Array()
|
||||
return Geometry2D.convex_hull(points)
|
||||
|
||||
|
||||
func _rasterize(hull: PackedVector2Array, inflate: float) -> void:
|
||||
var lo := hull[0]
|
||||
var hi := hull[0]
|
||||
for p in hull:
|
||||
lo = lo.min(p)
|
||||
hi = hi.max(p)
|
||||
var c0 := cell_of(lo.x - inflate, lo.y - inflate)
|
||||
var c1 := cell_of(hi.x + inflate, hi.y + inflate)
|
||||
var r2 := inflate * inflate
|
||||
var solid := hull.size() >= 4 # closed hull of at least a triangle
|
||||
@warning_ignore("integer_division")
|
||||
for cz in range(c0 / width, c1 / width + 1):
|
||||
for cx in range(c0 % width, c1 % width + 1):
|
||||
var i := cz * width + cx
|
||||
if blocked[i] == 1:
|
||||
continue
|
||||
var p := cell_center(i)
|
||||
if (solid and Geometry2D.is_point_in_polygon(p, hull)) or _dist2_to_outline(p, hull) <= r2:
|
||||
blocked[i] = 1
|
||||
|
||||
|
||||
static func _dist2_to_outline(p: Vector2, hull: PackedVector2Array) -> float:
|
||||
var best := INF
|
||||
for k in hull.size() - 1:
|
||||
var q := Geometry2D.get_closest_point_to_segment(p, hull[k], hull[k + 1])
|
||||
best = minf(best, p.distance_squared_to(q))
|
||||
if hull.size() == 1:
|
||||
best = p.distance_squared_to(hull[0])
|
||||
return best
|
||||
1
game/scripts/farm_navigation.gd.uid
Normal file
1
game/scripts/farm_navigation.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://c7u02hu43p42n
|
||||
146
game/scripts/farm_state.gd
Normal file
146
game/scripts/farm_state.gd
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
class_name FarmState
|
||||
extends RefCounted
|
||||
## The single source of truth for everything that persists through the vacation: farm assets,
|
||||
## scarecrow health, campaign progress, and the nightly loss records. Scene nodes only display
|
||||
## it. to_dict() / from_dict() round-trip every field, also through JSON (the morning retry
|
||||
## snapshot now, save games later). Plain asset counts become per-unit records in Step 3.
|
||||
|
||||
const VERSION := 1
|
||||
const KEYS: Array[String] = [
|
||||
"night", "nights_survived", "phase", "phase_time_left", "scarecrow_max_hp", "scarecrow_hp",
|
||||
"crops_total", "crops", "animals_total", "animals", "supplies_total", "supplies", "night_log",
|
||||
]
|
||||
const LOG_KEYS: Array[String] = ["night", "crops_lost", "animals_lost", "supplies_lost"]
|
||||
|
||||
## Current night (1-based). The morning, day, dusk, night, and dawn of a cycle all belong to it.
|
||||
var night: int = 1
|
||||
var nights_survived: int = 0
|
||||
var phase: CampaignController.Phase = CampaignController.Phase.MORNING
|
||||
## Game seconds left in a timed phase (0 in the untimed morning and terminal phases).
|
||||
var phase_time_left: float = 0.0
|
||||
|
||||
var scarecrow_max_hp: int = 10
|
||||
var scarecrow_hp: int = 10
|
||||
|
||||
## Per category: the starting count (0 = not in play yet) and what remains on the farm.
|
||||
var crops_total: int = 0
|
||||
var crops: int = 0
|
||||
var animals_total: int = 0
|
||||
var animals: int = 0
|
||||
var supplies_total: int = 0
|
||||
var supplies: int = 0
|
||||
|
||||
## One entry per completed night, closed when its dawn ends:
|
||||
## {"night", "crops_lost", "animals_lost", "supplies_lost"}.
|
||||
var night_log: Array[Dictionary] = []
|
||||
|
||||
|
||||
static func create(cfg: GameConfig) -> FarmState:
|
||||
var s := FarmState.new()
|
||||
s.scarecrow_max_hp = cfg.scarecrow_max_hp
|
||||
s.scarecrow_hp = cfg.scarecrow_max_hp
|
||||
s.crops_total = cfg.start_crops
|
||||
s.crops = cfg.start_crops
|
||||
s.animals_total = cfg.start_animals
|
||||
s.animals = cfg.start_animals
|
||||
s.supplies_total = cfg.start_supplies
|
||||
s.supplies = cfg.start_supplies
|
||||
return s
|
||||
|
||||
|
||||
## D2: every category in play is gone. Categories not in play (starting count 0) are ignored.
|
||||
func is_stripped() -> bool:
|
||||
var in_play := false
|
||||
for pair: Vector2i in [Vector2i(crops_total, crops), Vector2i(animals_total, animals),
|
||||
Vector2i(supplies_total, supplies)]:
|
||||
if pair.x > 0:
|
||||
in_play = true
|
||||
if pair.y > 0:
|
||||
return false
|
||||
return in_play
|
||||
|
||||
|
||||
func asset_counts() -> PackedInt32Array:
|
||||
return PackedInt32Array([crops, animals, supplies])
|
||||
|
||||
|
||||
## Records the night that just ended, given the asset counts when it started.
|
||||
func log_night(start: PackedInt32Array) -> void:
|
||||
var now := asset_counts()
|
||||
if start.size() != now.size():
|
||||
start = now
|
||||
night_log.append({
|
||||
"night": night,
|
||||
"crops_lost": maxi(start[0] - now[0], 0),
|
||||
"animals_lost": maxi(start[1] - now[1], 0),
|
||||
"supplies_lost": maxi(start[2] - now[2], 0),
|
||||
})
|
||||
|
||||
|
||||
func to_dict() -> Dictionary:
|
||||
var entries: Array = []
|
||||
for entry in night_log:
|
||||
entries.append(entry.duplicate())
|
||||
return {
|
||||
"version": VERSION,
|
||||
"night": night,
|
||||
"nights_survived": nights_survived,
|
||||
"phase": int(phase),
|
||||
"phase_time_left": phase_time_left,
|
||||
"scarecrow_max_hp": scarecrow_max_hp,
|
||||
"scarecrow_hp": scarecrow_hp,
|
||||
"crops_total": crops_total,
|
||||
"crops": crops,
|
||||
"animals_total": animals_total,
|
||||
"animals": animals,
|
||||
"supplies_total": supplies_total,
|
||||
"supplies": supplies,
|
||||
"night_log": entries,
|
||||
}
|
||||
|
||||
|
||||
## Rebuilds a state from to_dict() output (numbers may arrive as floats after JSON). Returns
|
||||
## null for another version, missing keys, or values that break the state's invariants.
|
||||
static func from_dict(d: Dictionary) -> FarmState:
|
||||
if int(d.get("version", -1)) != VERSION:
|
||||
return null
|
||||
for key in KEYS:
|
||||
if not d.has(key):
|
||||
return null
|
||||
var phase_value := int(d["phase"])
|
||||
if not CampaignController.Phase.values().has(phase_value):
|
||||
return null
|
||||
if not d["night_log"] is Array:
|
||||
return null
|
||||
var s := FarmState.new()
|
||||
s.night = int(d["night"])
|
||||
s.nights_survived = int(d["nights_survived"])
|
||||
s.phase = phase_value as CampaignController.Phase
|
||||
s.phase_time_left = float(d["phase_time_left"])
|
||||
s.scarecrow_max_hp = int(d["scarecrow_max_hp"])
|
||||
s.scarecrow_hp = int(d["scarecrow_hp"])
|
||||
s.crops_total = int(d["crops_total"])
|
||||
s.crops = int(d["crops"])
|
||||
s.animals_total = int(d["animals_total"])
|
||||
s.animals = int(d["animals"])
|
||||
s.supplies_total = int(d["supplies_total"])
|
||||
s.supplies = int(d["supplies"])
|
||||
for raw in d["night_log"]:
|
||||
if not raw is Dictionary:
|
||||
return null
|
||||
var entry := {}
|
||||
for key in LOG_KEYS:
|
||||
if not (raw as Dictionary).has(key):
|
||||
return null
|
||||
entry[key] = int(raw[key])
|
||||
s.night_log.append(entry)
|
||||
return s if s.is_valid() else null
|
||||
|
||||
|
||||
func is_valid() -> bool:
|
||||
return night >= 1 and nights_survived >= 0 and nights_survived <= night \
|
||||
and phase_time_left >= 0.0 \
|
||||
and scarecrow_max_hp >= 1 and scarecrow_hp >= 0 and scarecrow_hp <= scarecrow_max_hp \
|
||||
and crops >= 0 and crops <= crops_total \
|
||||
and animals >= 0 and animals <= animals_total \
|
||||
and supplies >= 0 and supplies <= supplies_total
|
||||
1
game/scripts/farm_state.gd.uid
Normal file
1
game/scripts/farm_state.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://drlyw88ovhrfd
|
||||
53
game/scripts/farm_zone.gd
Normal file
53
game/scripts/farm_zone.gd
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
@tool
|
||||
class_name FarmZone
|
||||
extends Node3D
|
||||
## One purposeful area of the farm: an axis-aligned rectangle on the ground, centered on this
|
||||
## node (rotation is ignored). Zones live under Zones/ in farm.tscn, and FarmZones looks them
|
||||
## up by position. In the editor each zone draws a translucent box so the layout is visible.
|
||||
|
||||
enum Kind { CROP_FIELD, ANIMAL_PEN, SUPPLY_SHED, WORK_AREA, WOOD, SCRAP, STRAW }
|
||||
|
||||
@export var kind: Kind = Kind.CROP_FIELD
|
||||
## Name shown on the HUD when the scarecrow walks in.
|
||||
@export var display_name: String = ""
|
||||
## Footprint in meters along X and Z.
|
||||
@export var size: Vector2 = Vector2(10.0, 10.0):
|
||||
set(value):
|
||||
size = value
|
||||
_update_preview()
|
||||
@export var tint: Color = Color(1.0, 1.0, 1.0):
|
||||
set(value):
|
||||
tint = value
|
||||
_update_preview()
|
||||
|
||||
var _preview: MeshInstance3D
|
||||
|
||||
|
||||
func _ready() -> void:
|
||||
if Engine.is_editor_hint():
|
||||
_preview = MeshInstance3D.new()
|
||||
add_child(_preview)
|
||||
_update_preview()
|
||||
|
||||
|
||||
func rect() -> Rect2:
|
||||
var p := global_position
|
||||
return Rect2(Vector2(p.x, p.z) - size * 0.5, size)
|
||||
|
||||
|
||||
func contains(point: Vector3) -> bool:
|
||||
return rect().has_point(Vector2(point.x, point.z))
|
||||
|
||||
|
||||
func _update_preview() -> void:
|
||||
if _preview == null:
|
||||
return
|
||||
var box := BoxMesh.new()
|
||||
box.size = Vector3(size.x, 0.1, size.y)
|
||||
var mat := StandardMaterial3D.new()
|
||||
mat.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED
|
||||
mat.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA
|
||||
mat.albedo_color = Color(tint, 0.25)
|
||||
box.material = mat
|
||||
_preview.mesh = box
|
||||
_preview.position = Vector3(0.0, 0.05, 0.0)
|
||||
1
game/scripts/farm_zone.gd.uid
Normal file
1
game/scripts/farm_zone.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://celghhlevq85l
|
||||
49
game/scripts/farm_zones.gd
Normal file
49
game/scripts/farm_zones.gd
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
class_name FarmZones
|
||||
extends Node3D
|
||||
## The Zones/ node of farm.tscn: every FarmZone (with the props that belong to it), the
|
||||
## perimeter and its markers, and the crop units, plus lookups by position. The playable map is
|
||||
## the rectangle inside the perimeter fence; the rest of the farm is out-of-bounds scenery.
|
||||
|
||||
@export var playable := Rect2(-13.0, -45.0, 60.0, 60.0)
|
||||
|
||||
|
||||
func zones() -> Array[FarmZone]:
|
||||
var out: Array[FarmZone] = []
|
||||
for child in get_children():
|
||||
if child is FarmZone:
|
||||
out.append(child)
|
||||
return out
|
||||
|
||||
|
||||
## The zone containing a world position (zones don't overlap), or null between zones.
|
||||
func zone_at(point: Vector3) -> FarmZone:
|
||||
for zone in zones():
|
||||
if zone.contains(point):
|
||||
return zone
|
||||
return null
|
||||
|
||||
|
||||
func zone(kind: FarmZone.Kind) -> FarmZone:
|
||||
for z in zones():
|
||||
if z.kind == kind:
|
||||
return z
|
||||
return null
|
||||
|
||||
|
||||
func markers(kind: FarmMarker.Kind) -> Array[FarmMarker]:
|
||||
var out: Array[FarmMarker] = []
|
||||
for node in find_children("*", "Marker3D", true, false):
|
||||
if node is FarmMarker and (node as FarmMarker).kind == kind:
|
||||
out.append(node)
|
||||
return out
|
||||
|
||||
|
||||
func crop_units() -> Array[CropUnit]:
|
||||
var out: Array[CropUnit] = []
|
||||
var field := zone(FarmZone.Kind.CROP_FIELD)
|
||||
if field == null:
|
||||
return out
|
||||
for node in field.find_children("*", "Node3D", true, false):
|
||||
if node is CropUnit:
|
||||
out.append(node)
|
||||
return out
|
||||
1
game/scripts/farm_zones.gd.uid
Normal file
1
game/scripts/farm_zones.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://bpl66stkcn1rr
|
||||
59
game/scripts/follow_camera.gd
Normal file
59
game/scripts/follow_camera.gd
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
@tool
|
||||
class_name FollowCamera
|
||||
extends Camera3D
|
||||
## Angled top-down camera that trails a target. The framing comes entirely from pitch / yaw /
|
||||
## distance (the transform is overwritten every frame, also in the editor so the framing can be
|
||||
## previewed). PlayerCharacter moves relative to this camera's yaw. Mouse wheel zooms.
|
||||
|
||||
@export var target: Node3D
|
||||
@export_range(5.0, 89.0) var pitch_deg := 50.0
|
||||
@export_range(-180.0, 180.0) var yaw_deg := 45.0
|
||||
@export var distance := 16.0
|
||||
@export var min_distance := 6.0
|
||||
@export var max_distance := 40.0
|
||||
@export var zoom_step := 1.5
|
||||
## Height above the target's origin that the camera looks at.
|
||||
@export var look_height := 1.0
|
||||
## How quickly the camera catches up with the target (higher = tighter, 0 = locked on).
|
||||
@export var follow_speed := 6.0
|
||||
|
||||
var _focus := Vector3.ZERO
|
||||
|
||||
|
||||
func _ready() -> void:
|
||||
physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
|
||||
snap_to_target()
|
||||
|
||||
|
||||
## Jumps straight to the target (use after teleporting it).
|
||||
func snap_to_target() -> void:
|
||||
if target != null:
|
||||
_focus = target.global_position + Vector3.UP * look_height
|
||||
_apply()
|
||||
|
||||
|
||||
func _process(delta: float) -> void:
|
||||
if target != null:
|
||||
var origin := target.global_position if Engine.is_editor_hint() \
|
||||
else target.get_global_transform_interpolated().origin
|
||||
var goal := origin + Vector3.UP * look_height
|
||||
if follow_speed <= 0.0 or Engine.is_editor_hint():
|
||||
_focus = goal
|
||||
else:
|
||||
_focus = _focus.lerp(goal, 1.0 - exp(-follow_speed * delta))
|
||||
_apply()
|
||||
|
||||
|
||||
func _unhandled_input(event: InputEvent) -> void:
|
||||
var mb := event as InputEventMouseButton
|
||||
if mb == null or not mb.pressed:
|
||||
return
|
||||
if mb.button_index == MOUSE_BUTTON_WHEEL_UP:
|
||||
distance = maxf(distance - zoom_step, min_distance)
|
||||
elif mb.button_index == MOUSE_BUTTON_WHEEL_DOWN:
|
||||
distance = minf(distance + zoom_step, max_distance)
|
||||
|
||||
|
||||
func _apply() -> void:
|
||||
var b := Basis.from_euler(Vector3(deg_to_rad(-pitch_deg), deg_to_rad(yaw_deg), 0.0))
|
||||
global_transform = Transform3D(b, _focus + b.z * distance)
|
||||
1
game/scripts/follow_camera.gd.uid
Normal file
1
game/scripts/follow_camera.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://bdlmtj20npler
|
||||
52
game/scripts/game_config.gd
Normal file
52
game/scripts/game_config.gd
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
class_name GameConfig
|
||||
extends Resource
|
||||
## Every tunable campaign setting, kept in one resource (see game/RULES.md for the rules these
|
||||
## values feed). The defaults live in res://game/resources/game_config.tres; every number is a
|
||||
## starting value to tune during balancing.
|
||||
|
||||
@export_group("Campaign")
|
||||
## Nights the scarecrow must survive before the farmers return.
|
||||
@export_range(1, 20) var campaign_nights: int = 5
|
||||
|
||||
@export_group("Phases")
|
||||
## Seconds of game time per phase. The morning review is untimed: it waits for the player.
|
||||
@export var day_length: float = 180.0
|
||||
@export var dusk_length: float = 30.0
|
||||
@export var night_length: float = 150.0
|
||||
## After sunrise: enemies retreat and carriers can still be intercepted for this long.
|
||||
@export var dawn_grace: float = 20.0
|
||||
## D1: lets the player skip the rest of the day/dusk and start the night (off by default).
|
||||
@export var allow_early_night: bool = false
|
||||
|
||||
@export_group("Scarecrow")
|
||||
## HP carries over between nights (D7); 0 HP is an immediate Game Over.
|
||||
@export_range(1, 100) var scarecrow_max_hp: int = 10
|
||||
|
||||
@export_group("Farm assets")
|
||||
## Starting count per target category. A category with a count of 0 is not in play and is
|
||||
## ignored by the "farm stripped" check (D2). Animals and supplies arrive in Step 8.
|
||||
@export_range(0, 500) var start_crops: int = 30
|
||||
@export_range(0, 100) var start_animals: int = 0
|
||||
@export_range(0, 5000) var start_supplies: int = 0
|
||||
|
||||
@export_group("Theft rules")
|
||||
## D5: fear makes carriers drop their loot, not only killing them.
|
||||
@export var fear_drops_loot: bool = true
|
||||
## D6: dropped loot still on the ground when the dawn grace ends returns home automatically.
|
||||
@export var loot_returns_at_dawn: bool = true
|
||||
## D6: animals that can follow the scarecrow back to the pen at once.
|
||||
@export_range(1, 10) var max_following_animals: int = 3
|
||||
|
||||
|
||||
## Length of a phase in seconds, or INF for the untimed morning review and terminal phases.
|
||||
func phase_length(phase: CampaignController.Phase) -> float:
|
||||
match phase:
|
||||
CampaignController.Phase.DAY:
|
||||
return day_length
|
||||
CampaignController.Phase.DUSK:
|
||||
return dusk_length
|
||||
CampaignController.Phase.NIGHT:
|
||||
return night_length
|
||||
CampaignController.Phase.DAWN:
|
||||
return dawn_grace
|
||||
return INF
|
||||
1
game/scripts/game_config.gd.uid
Normal file
1
game/scripts/game_config.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://bow5a4dimtdto
|
||||
54
game/scripts/player_character.gd
Normal file
54
game/scripts/player_character.gd
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
class_name PlayerCharacter
|
||||
extends CharacterBody3D
|
||||
## The farmer: camera-relative movement on the move_* actions (WASD / arrows / left stick) with
|
||||
## gravity. The model turns toward the direction of travel and crossfades idle / walk / run.
|
||||
## The walk clip plays for partial stick deflection; full keyboard input runs.
|
||||
|
||||
@export var run_speed := 5.0
|
||||
@export var acceleration := 30.0
|
||||
## How quickly the model turns to face the movement direction (higher = snappier).
|
||||
@export var turn_speed := 12.0
|
||||
## Input strength (0..1) above which the run clip plays instead of the walk clip.
|
||||
@export_range(0.0, 1.0) var run_threshold := 0.6
|
||||
|
||||
@export_group("Animation")
|
||||
@export var idle_animation: StringName = &"Idle_A"
|
||||
@export var walk_animation: StringName = &"Walking_A"
|
||||
@export var run_animation: StringName = &"Running_A"
|
||||
@export var blend_time := 0.2
|
||||
|
||||
@onready var model: Node3D = $Model
|
||||
@onready var animation_player: AnimationPlayer = $Model/AnimationPlayer
|
||||
|
||||
|
||||
func _physics_process(delta: float) -> void:
|
||||
var move := _move_direction()
|
||||
var horizontal := Vector3(velocity.x, 0.0, velocity.z).move_toward(move * run_speed, acceleration * delta)
|
||||
velocity.x = horizontal.x
|
||||
velocity.z = horizontal.z
|
||||
if not is_on_floor():
|
||||
velocity += get_gravity() * delta
|
||||
move_and_slide()
|
||||
|
||||
if move.length_squared() > 1e-4:
|
||||
var yaw := atan2(-move.x, -move.z)
|
||||
model.rotation.y = lerp_angle(model.rotation.y, yaw, 1.0 - exp(-turn_speed * delta))
|
||||
_update_animation(move.length())
|
||||
|
||||
|
||||
## Input rotated by the active camera's yaw, so "forward" is always up the screen.
|
||||
func _move_direction() -> Vector3:
|
||||
var input := Input.get_vector("move_left", "move_right", "move_forward", "move_back")
|
||||
var camera := get_viewport().get_camera_3d()
|
||||
var yaw := camera.global_rotation.y if camera != null else 0.0
|
||||
return Vector3(input.x, 0.0, input.y).rotated(Vector3.UP, yaw)
|
||||
|
||||
|
||||
func _update_animation(strength: float) -> void:
|
||||
var clip := idle_animation
|
||||
if strength > run_threshold:
|
||||
clip = run_animation
|
||||
elif strength > 0.0:
|
||||
clip = walk_animation
|
||||
if animation_player.current_animation != clip:
|
||||
animation_player.play(clip, blend_time)
|
||||
1
game/scripts/player_character.gd.uid
Normal file
1
game/scripts/player_character.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://0alr34qa8lbd
|
||||
37
game/scripts/zone_banner.gd
Normal file
37
game/scripts/zone_banner.gd
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
class_name ZoneBanner
|
||||
extends CanvasLayer
|
||||
## Shows a zone's name at the top of the screen when the tracked node walks into it, then fades.
|
||||
|
||||
@export var zones: FarmZones
|
||||
@export var target: Node3D
|
||||
@export var hold_time: float = 1.6
|
||||
@export var fade_time: float = 0.6
|
||||
|
||||
var current: FarmZone
|
||||
var _label: Label
|
||||
var _left: float = 0.0
|
||||
|
||||
|
||||
func _ready() -> void:
|
||||
_label = Label.new()
|
||||
_label.set_anchors_preset(Control.PRESET_TOP_WIDE)
|
||||
_label.offset_top = 64.0
|
||||
_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
|
||||
_label.add_theme_font_size_override("font_size", 36)
|
||||
_label.add_theme_color_override("font_outline_color", Color.BLACK)
|
||||
_label.add_theme_constant_override("outline_size", 8)
|
||||
_label.modulate.a = 0.0
|
||||
add_child(_label)
|
||||
|
||||
|
||||
func _process(delta: float) -> void:
|
||||
if zones == null or target == null:
|
||||
return
|
||||
var zone := zones.zone_at(target.global_position)
|
||||
if zone != current:
|
||||
current = zone
|
||||
if zone != null:
|
||||
_label.text = zone.display_name
|
||||
_left = hold_time + fade_time
|
||||
_left = maxf(_left - delta, 0.0)
|
||||
_label.modulate.a = clampf(_left / fade_time, 0.0, 1.0)
|
||||
1
game/scripts/zone_banner.gd.uid
Normal file
1
game/scripts/zone_banner.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://dbfcgsdrh5v60
|
||||
85
game/tests/run_tests.gd
Normal file
85
game/tests/run_tests.gd
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
class_name GameTestRunner
|
||||
extends SceneTree
|
||||
## Headless test runner for the game (same pattern as prototype/tests/run_tests.gd). Run:
|
||||
## godot --headless --path . --script res://game/tests/run_tests.gd
|
||||
## Optional: -- --suite=test_campaign (run one suite)
|
||||
## Exit code = number of failures.
|
||||
|
||||
const SUITES := [
|
||||
"res://game/tests/test_farm_state.gd",
|
||||
"res://game/tests/test_outcome.gd",
|
||||
"res://game/tests/test_campaign.gd",
|
||||
"res://game/tests/test_farm_layout.gd",
|
||||
]
|
||||
const TICK := 1.0 / 60.0
|
||||
|
||||
var passes: int = 0
|
||||
var failures: int = 0
|
||||
var current: String = ""
|
||||
|
||||
|
||||
func _initialize() -> void:
|
||||
_main.call_deferred()
|
||||
|
||||
|
||||
func _main() -> void:
|
||||
await process_frame
|
||||
var only := ""
|
||||
for a in OS.get_cmdline_user_args():
|
||||
if String(a).begins_with("--suite="):
|
||||
only = String(a).trim_prefix("--suite=")
|
||||
var t0 := Time.get_ticks_msec()
|
||||
for path: String in SUITES:
|
||||
if only != "" and path.get_file().get_basename() != only:
|
||||
continue
|
||||
current = path.get_file().get_basename()
|
||||
print("== ", current)
|
||||
var suite: Object = (load(path) as GDScript).new()
|
||||
await suite.call("run", self)
|
||||
print("TESTS: %d checks passed, %d failed (%.1f s)" % [passes, failures, (Time.get_ticks_msec() - t0) / 1000.0])
|
||||
quit(mini(failures, 125))
|
||||
|
||||
|
||||
func check(cond: bool, message: String) -> void:
|
||||
if cond:
|
||||
passes += 1
|
||||
else:
|
||||
failures += 1
|
||||
printerr(" FAIL [%s] %s" % [current, message])
|
||||
|
||||
|
||||
func info(message: String) -> void:
|
||||
print(" ", message)
|
||||
|
||||
|
||||
## A campaign in the tree (so it is freed at exit) driven only by explicit tick() calls.
|
||||
func make_campaign(cfg: GameConfig = null) -> CampaignController:
|
||||
var c := CampaignController.new()
|
||||
c.config = cfg
|
||||
root.add_child(c)
|
||||
c.set_physics_process(false)
|
||||
return c
|
||||
|
||||
|
||||
## Ticks at 60 Hz until the phase changes; returns the game seconds that took (INF if it
|
||||
## never changed within max_seconds).
|
||||
static func run_phase(c: CampaignController, max_seconds: float = 1000.0) -> float:
|
||||
var start := c.state.phase
|
||||
var ticks := 0
|
||||
while c.state.phase == start:
|
||||
if ticks * TICK > max_seconds:
|
||||
return INF
|
||||
c.tick(TICK)
|
||||
ticks += 1
|
||||
return ticks * TICK
|
||||
|
||||
|
||||
## Ticks at 60 Hz until the given phase is reached (or the campaign ends).
|
||||
static func run_until(c: CampaignController, phase: CampaignController.Phase) -> void:
|
||||
var guard := 0
|
||||
while c.state.phase != phase and not c.is_over() and guard < 1000000:
|
||||
if c.state.phase == CampaignController.Phase.MORNING:
|
||||
c.begin_day()
|
||||
else:
|
||||
c.tick(TICK)
|
||||
guard += 1
|
||||
1
game/tests/run_tests.gd.uid
Normal file
1
game/tests/run_tests.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://bke1ak3n6vb4x
|
||||
130
game/tests/test_campaign.gd
Normal file
130
game/tests/test_campaign.gd
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
extends RefCounted
|
||||
## Phase state machine: the untimed morning, phase order and lengths, five-night completion,
|
||||
## the early-night option, night loss records, and retrying a failed night from its morning.
|
||||
|
||||
const O := CampaignController.Outcome
|
||||
const P := CampaignController.Phase
|
||||
|
||||
|
||||
func run(r: GameTestRunner) -> void:
|
||||
_order_and_timers(r)
|
||||
_five_nights(r)
|
||||
_early_night(r)
|
||||
_night_log(r)
|
||||
_retry(r)
|
||||
|
||||
|
||||
func _order_and_timers(r: GameTestRunner) -> void:
|
||||
var c := r.make_campaign()
|
||||
var seen: Array[CampaignController.Phase] = []
|
||||
c.phase_changed.connect(func(p: CampaignController.Phase, _prev: CampaignController.Phase) -> void: seen.append(p))
|
||||
r.check(c.state.phase == P.MORNING and c.state.night == 1, "a new vacation starts on the morning of night 1")
|
||||
c.tick(1000.0)
|
||||
r.check(c.state.phase == P.MORNING, "the morning review is untimed (waits for the player)")
|
||||
r.check(c.begin_day(), "begin_day ends the morning review")
|
||||
r.check(not c.begin_day(), "begin_day only works in the morning")
|
||||
|
||||
var cfg := c.config
|
||||
var expected := {P.DAY: cfg.day_length, P.DUSK: cfg.dusk_length, P.NIGHT: cfg.night_length, P.DAWN: cfg.dawn_grace}
|
||||
for phase: CampaignController.Phase in [P.DAY, P.DUSK, P.NIGHT, P.DAWN]:
|
||||
r.check(c.state.phase == phase and is_equal_approx(c.state.phase_time_left, expected[phase]),
|
||||
"%s starts with %.0f s on the clock" % [P.keys()[phase], expected[phase]])
|
||||
var took := GameTestRunner.run_phase(c)
|
||||
r.check(absf(took - expected[phase]) <= GameTestRunner.TICK + 1e-4,
|
||||
"%s lasts %.0f s of game time (took %.3f s)" % [P.keys()[phase], expected[phase], took])
|
||||
r.check(seen == [P.DAY, P.DUSK, P.NIGHT, P.DAWN, P.MORNING], "phases run MORNING -> DAY -> DUSK -> NIGHT -> DAWN -> MORNING")
|
||||
r.check(c.state.night == 2 and c.state.nights_survived == 1, "after the first dawn it is the morning of night 2")
|
||||
|
||||
# advance_phase (debug) goes through the same transitions.
|
||||
c.advance_phase()
|
||||
r.check(c.state.phase == P.DAY, "advance_phase ends the morning")
|
||||
c.advance_phase()
|
||||
c.advance_phase()
|
||||
c.advance_phase()
|
||||
c.advance_phase()
|
||||
r.check(c.state.phase == P.MORNING and c.state.night == 3, "advance_phase walks a whole cycle")
|
||||
|
||||
|
||||
func _five_nights(r: GameTestRunner) -> void:
|
||||
var c := r.make_campaign()
|
||||
var ended: Array[CampaignController.Outcome] = []
|
||||
var mornings: Array[int] = []
|
||||
c.campaign_ended.connect(func(o: CampaignController.Outcome) -> void: ended.append(o))
|
||||
c.phase_changed.connect(func(p: CampaignController.Phase, _prev: CampaignController.Phase) -> void:
|
||||
if p == P.MORNING:
|
||||
mornings.append(c.state.night))
|
||||
GameTestRunner.run_until(c, P.FARMERS_RETURN)
|
||||
r.check(c.state.phase == P.FARMERS_RETURN and c.outcome == O.VACATION_COMPLETE, "surviving every night brings the farmers back")
|
||||
r.check(c.state.nights_survived == 5 and c.state.night == 5, "the vacation is exactly five nights (night %d, survived %d)" % [c.state.night, c.state.nights_survived])
|
||||
r.check(mornings == [2, 3, 4, 5], "a morning follows each night except the last (got %s)" % [mornings])
|
||||
r.check(ended == [O.VACATION_COMPLETE], "campaign_ended fires once")
|
||||
r.check(c.state.night_log.size() == 5, "every night is recorded")
|
||||
c.tick(1000.0)
|
||||
c.advance_phase()
|
||||
r.check(c.state.phase == P.FARMERS_RETURN and ended.size() == 1, "the farmers' return is terminal")
|
||||
|
||||
c.new_campaign()
|
||||
r.check(c.state.phase == P.MORNING and c.state.night == 1 and c.outcome == O.CONTINUE and c.state.night_log.is_empty(),
|
||||
"new_campaign starts a fresh vacation")
|
||||
|
||||
|
||||
func _early_night(r: GameTestRunner) -> void:
|
||||
var c := r.make_campaign()
|
||||
r.check(not c.config.allow_early_night, "starting the night early is off by default")
|
||||
c.begin_day()
|
||||
r.check(not c.can_start_night_early() and not c.start_night_early() and c.state.phase == P.DAY,
|
||||
"with the option off, the day can't be cut short")
|
||||
GameTestRunner.run_until(c, P.DUSK)
|
||||
r.check(not c.start_night_early() and c.state.phase == P.DUSK, "with the option off, dusk can't be cut short")
|
||||
|
||||
var cfg := c.config.duplicate() as GameConfig
|
||||
cfg.allow_early_night = true
|
||||
c = r.make_campaign(cfg)
|
||||
r.check(not c.start_night_early(), "the night can't start early from the morning review")
|
||||
c.begin_day()
|
||||
c.tick(10.0)
|
||||
r.check(c.start_night_early() and c.state.phase == P.NIGHT and is_equal_approx(c.state.phase_time_left, cfg.night_length),
|
||||
"with the option on, the day can skip straight to a full night")
|
||||
r.check(not c.start_night_early(), "the night can't be started early again")
|
||||
c = r.make_campaign(cfg)
|
||||
GameTestRunner.run_until(c, P.DUSK)
|
||||
r.check(c.start_night_early() and c.state.phase == P.NIGHT, "with the option on, dusk can skip to the night")
|
||||
|
||||
|
||||
func _night_log(r: GameTestRunner) -> void:
|
||||
var c := r.make_campaign()
|
||||
GameTestRunner.run_until(c, P.NIGHT)
|
||||
c.state.crops -= 3
|
||||
GameTestRunner.run_until(c, P.DAWN)
|
||||
c.state.crops -= 1 # loot escaping during the dawn grace still counts for that night
|
||||
GameTestRunner.run_until(c, P.MORNING)
|
||||
var e: Dictionary = c.state.night_log[0]
|
||||
r.check(e["night"] == 1 and e["crops_lost"] == 4, "night 1 records 4 crops lost, dawn included (got %s)" % [e])
|
||||
r.check(c.state.crops == c.config.start_crops - 4, "losses persist into the next day")
|
||||
c.state.crops -= 2 # lost during the day don't count against the next night
|
||||
c.begin_day()
|
||||
GameTestRunner.run_until(c, P.MORNING)
|
||||
r.check(c.state.night_log[1]["crops_lost"] == 0, "night 2 only counts losses after it started")
|
||||
|
||||
|
||||
func _retry(r: GameTestRunner) -> void:
|
||||
var c := r.make_campaign()
|
||||
GameTestRunner.run_until(c, P.NIGHT)
|
||||
c.state.crops -= 3
|
||||
c.state.scarecrow_hp -= 4
|
||||
GameTestRunner.run_until(c, P.MORNING)
|
||||
var morning := c.state.to_dict()
|
||||
|
||||
c.begin_day()
|
||||
GameTestRunner.run_until(c, P.NIGHT)
|
||||
c.state.crops -= 5
|
||||
c.state.scarecrow_hp = 0
|
||||
c.tick(GameTestRunner.TICK)
|
||||
r.check(c.state.phase == P.GAME_OVER, "the scarecrow falls on night 2")
|
||||
r.check(c.retry_night(), "retry_night is available after Game Over")
|
||||
r.check(c.state.to_dict() == morning, "retry restores the morning of the failed night exactly")
|
||||
r.check(c.state.night == 2 and c.state.scarecrow_hp == c.config.scarecrow_max_hp - 4 and c.outcome == O.CONTINUE,
|
||||
"night 1's losses and damage are kept; night 2 is replayed")
|
||||
c.begin_day()
|
||||
GameTestRunner.run_until(c, P.MORNING)
|
||||
r.check(c.state.night == 3 and c.state.night_log.size() == 2, "the retried night plays through normally")
|
||||
1
game/tests/test_campaign.gd.uid
Normal file
1
game/tests/test_campaign.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://c2vk5glcqxcxr
|
||||
187
game/tests/test_farm_layout.gd
Normal file
187
game/tests/test_farm_layout.gd
Normal file
|
|
@ -0,0 +1,187 @@
|
|||
extends RefCounted
|
||||
## The playable farm: every zone exists once inside the 60 x 60 m map without overlapping,
|
||||
## lookups by position, the crop units, the perimeter markers, a perimeter fence without holes
|
||||
## except its gaps, ground navigation from every gap to every zone, scarecrow-only bounds,
|
||||
## zone-to-zone travel times (printed as the table kept in game/LAYOUT.md), and the zone banner.
|
||||
|
||||
const RUN_SPEED := 5.0 # PlayerCharacter.run_speed
|
||||
const MAX_TRAVEL := 12.0
|
||||
const ENEMY_RADIUS := 0.35
|
||||
const SCARECROW_RADIUS := 0.4
|
||||
const CELL := 0.5
|
||||
|
||||
|
||||
func run(r: GameTestRunner) -> void:
|
||||
var farm := (load("res://game/scenes/farm.tscn") as PackedScene).instantiate() as Node3D
|
||||
r.root.add_child(farm)
|
||||
await r.process_frame
|
||||
await r.physics_frame
|
||||
var zones := farm.get_node("Zones") as FarmZones
|
||||
r.check(zones != null, "farm.tscn has a FarmZones node")
|
||||
if zones == null:
|
||||
return
|
||||
var map := zones.playable
|
||||
r.check(is_equal_approx(map.size.x, 60.0) and is_equal_approx(map.size.y, 60.0), "the playable map is 60 x 60 m")
|
||||
|
||||
_zones(r, zones)
|
||||
_crops(r, zones)
|
||||
_markers(r, zones)
|
||||
var nav := FarmNavigation.new()
|
||||
nav.build(farm, map.grow(5.0), CELL, ENEMY_RADIUS)
|
||||
r.info("enemy nav: %d cells, %d shapes rasterized, built in %.1f ms" % [nav.cell_count(), nav.shapes_rasterized, nav.build_usec / 1000.0])
|
||||
_fence(r, zones, nav)
|
||||
_enemy_routes(r, zones, nav)
|
||||
_scarecrow(r, farm, zones)
|
||||
_travel_times(r, farm, zones)
|
||||
await _banner(r, farm, zones)
|
||||
farm.queue_free()
|
||||
await r.process_frame
|
||||
|
||||
|
||||
func _zones(r: GameTestRunner, zones: FarmZones) -> void:
|
||||
var all := zones.zones()
|
||||
r.check(all.size() == FarmZone.Kind.size(), "one zone per kind (%d zones)" % all.size())
|
||||
for kind: FarmZone.Kind in FarmZone.Kind.values():
|
||||
var z := zones.zone(kind)
|
||||
r.check(z != null and z.display_name != "", "zone %s exists and has a name" % FarmZone.Kind.keys()[kind])
|
||||
for i in all.size():
|
||||
var a := all[i]
|
||||
r.check(zones.playable.encloses(a.rect()), "%s lies inside the playable map" % a.display_name)
|
||||
r.check(zones.zone_at(a.global_position) == a, "zone_at(center of %s) finds it" % a.display_name)
|
||||
for j in range(i + 1, all.size()):
|
||||
r.check(not a.rect().intersects(all[j].rect()), "%s and %s don't overlap" % [a.display_name, all[j].display_name])
|
||||
r.check(zones.zone_at(Vector3(8.0, 0.0, -10.0)) == null, "open ground between zones belongs to no zone")
|
||||
|
||||
|
||||
func _crops(r: GameTestRunner, zones: FarmZones) -> void:
|
||||
var cfg := load("res://game/resources/game_config.tres") as GameConfig
|
||||
var units := zones.crop_units()
|
||||
var field := zones.zone(FarmZone.Kind.CROP_FIELD)
|
||||
r.check(units.size() == cfg.start_crops, "%d crop units, matching GameConfig.start_crops (%d)" % [units.size(), cfg.start_crops])
|
||||
var ids := {}
|
||||
var per_plot := {}
|
||||
var fewest := 1 << 30
|
||||
for u in units:
|
||||
ids[u.unit_id] = true
|
||||
per_plot[u.plot] = int(per_plot.get(u.plot, 0)) + 1
|
||||
fewest = mini(fewest, u.get_child_count())
|
||||
r.check(field.contains(u.global_position), "crop unit %d lies in the crop field" % u.unit_id)
|
||||
r.check(ids.size() == units.size() and ids.has(1) and ids.has(units.size()), "crop unit ids are unique, 1..%d" % units.size())
|
||||
r.check(per_plot.size() == 6 and per_plot.values().all(func(n: int) -> bool: return n == 5), "6 plots of 5 units (%s)" % [per_plot])
|
||||
r.check(fewest >= 8, "every unit is a visible cluster (fewest plants: %d)" % fewest)
|
||||
|
||||
|
||||
func _markers(r: GameTestRunner, zones: FarmZones) -> void:
|
||||
var map := zones.playable
|
||||
var gaps := zones.markers(FarmMarker.Kind.GAP)
|
||||
r.check(gaps.size() == 6, "6 perimeter gaps (got %d)" % gaps.size())
|
||||
for m in gaps:
|
||||
var p := Vector2(m.global_position.x, m.global_position.z)
|
||||
r.check(not map.has_point(p) and map.grow(4.0).has_point(p), "%s sits just outside the perimeter" % m.name)
|
||||
var crows := zones.markers(FarmMarker.Kind.CROW)
|
||||
r.check(crows.size() == 4, "4 crow approach directions (got %d)" % crows.size())
|
||||
for m in crows:
|
||||
r.check(not map.grow(4.0).has_point(Vector2(m.global_position.x, m.global_position.z)), "%s is well outside the fence" % m.name)
|
||||
|
||||
|
||||
## Every free cell on the fence line is part of a gap (near a gap marker), and every gap is open.
|
||||
func _fence(r: GameTestRunner, zones: FarmZones, nav: FarmNavigation) -> void:
|
||||
var map := zones.playable
|
||||
var gaps := zones.markers(FarmMarker.Kind.GAP)
|
||||
var corners := [map.position, Vector2(map.end.x, map.position.y), map.end, Vector2(map.position.x, map.end.y)]
|
||||
var holes: Array[Vector2] = []
|
||||
for side in 4:
|
||||
var a: Vector2 = corners[side]
|
||||
var b: Vector2 = corners[(side + 1) % 4]
|
||||
var steps := ceili(a.distance_to(b) / (CELL * 0.5))
|
||||
for k in steps + 1:
|
||||
var p := a.lerp(b, k / float(steps))
|
||||
if nav.is_free(nav.cell_of(p.x, p.y)) and not gaps.any(func(m: FarmMarker) -> bool:
|
||||
return Vector2(m.global_position.x, m.global_position.z).distance_to(p) < 4.5):
|
||||
holes.append(p)
|
||||
r.check(holes.is_empty(), "the perimeter fence has no holes outside its gaps %s" % [holes.slice(0, 5)])
|
||||
for m in gaps:
|
||||
var g := Vector2(m.global_position.x, m.global_position.z)
|
||||
var edge := Vector2(clampf(g.x, map.position.x, map.end.x), clampf(g.y, map.position.y, map.end.y))
|
||||
r.check(nav.is_free(nav.cell_of(edge.x, edge.y)), "%s is open for ground enemies" % m.name)
|
||||
|
||||
|
||||
func _enemy_routes(r: GameTestRunner, zones: FarmZones, nav: FarmNavigation) -> void:
|
||||
var gaps := zones.markers(FarmMarker.Kind.GAP)
|
||||
for zone in zones.zones():
|
||||
var goal := nav.free_cells_in(zone.rect())
|
||||
r.check(goal.size() > 0, "%s has walkable ground (%d cells)" % [zone.display_name, goal.size()])
|
||||
var field := nav.distance_field(goal)
|
||||
var lengths: Array[String] = []
|
||||
for m in gaps:
|
||||
var c := nav.nearest_free(nav.cell_of(m.global_position.x, m.global_position.z))
|
||||
var reachable := c >= 0 and field[c] < FarmNavigation.UNREACHABLE
|
||||
r.check(reachable, "ground enemies can walk from %s to the %s and back" % [m.name, zone.display_name])
|
||||
lengths.append("%.0f" % nav.meters(field[c]) if reachable else "-")
|
||||
r.info("%-12s from gaps (m): %s" % [zone.display_name, ", ".join(lengths)])
|
||||
|
||||
|
||||
func _scarecrow(r: GameTestRunner, farm: Node3D, zones: FarmZones) -> void:
|
||||
var player := farm.get_node("Player") as CharacterBody3D
|
||||
var bounds := farm.get_node("Zones/Perimeter/PlayerBounds") as StaticBody3D
|
||||
r.check(zones.playable.has_point(Vector2(player.global_position.x, player.global_position.z)), "the scarecrow starts inside the map")
|
||||
r.check(bounds.collision_layer == 4 and (player.collision_mask & 4) != 0 and (player.collision_mask & 1) != 0,
|
||||
"PlayerBounds is on the player_bounds layer, which only the scarecrow collides with")
|
||||
# Stand in each gap and try to walk out: the invisible wall stops the scarecrow.
|
||||
var start := player.global_transform
|
||||
for m in zones.markers(FarmMarker.Kind.GAP):
|
||||
var g := Vector2(m.global_position.x, m.global_position.z)
|
||||
var map := zones.playable
|
||||
var edge := Vector2(clampf(g.x, map.position.x, map.end.x), clampf(g.y, map.position.y, map.end.y))
|
||||
var out := (g - edge).normalized()
|
||||
player.global_position = Vector3(edge.x - out.x * 1.0, 0.3, edge.y - out.y * 1.0)
|
||||
var hit := player.move_and_collide(Vector3(out.x, 0.0, out.y) * 3.0, true)
|
||||
r.check(hit != null, "the scarecrow can't walk out through %s" % m.name)
|
||||
player.global_transform = start
|
||||
|
||||
|
||||
func _travel_times(r: GameTestRunner, farm: Node3D, zones: FarmZones) -> void:
|
||||
var nav := FarmNavigation.new()
|
||||
nav.build(farm, zones.playable, CELL, SCARECROW_RADIUS, 1 | 4)
|
||||
var all := zones.zones()
|
||||
var anchors := PackedInt32Array()
|
||||
for z in all:
|
||||
anchors.append(nav.nearest_free(nav.cell_of(z.global_position.x, z.global_position.z)))
|
||||
var header := "| From \\ to |"
|
||||
var rule := "|---|"
|
||||
for z in all:
|
||||
header += " %s |" % z.display_name
|
||||
rule += "---|"
|
||||
r.info(header)
|
||||
r.info(rule)
|
||||
var worst := 0.0
|
||||
var worst_pair := ""
|
||||
for i in all.size():
|
||||
var field := nav.distance_field(PackedInt32Array([anchors[i]]))
|
||||
var row := "| **%s** |" % all[i].display_name
|
||||
for j in all.size():
|
||||
var cost := field[anchors[j]]
|
||||
r.check(cost < FarmNavigation.UNREACHABLE, "the scarecrow can walk from %s to %s" % [all[i].display_name, all[j].display_name])
|
||||
var seconds := nav.meters(cost) / RUN_SPEED
|
||||
row += " — |" if i == j else " %.1f s |" % seconds
|
||||
if seconds > worst:
|
||||
worst = seconds
|
||||
worst_pair = "%s -> %s" % [all[i].display_name, all[j].display_name]
|
||||
r.info(row)
|
||||
r.check(worst <= MAX_TRAVEL, "no key area is more than %.0f s from another (worst %.1f s: %s)" % [MAX_TRAVEL, worst, worst_pair])
|
||||
|
||||
|
||||
func _banner(r: GameTestRunner, farm: Node3D, zones: FarmZones) -> void:
|
||||
var banner := farm.get_node("ZoneBanner") as ZoneBanner
|
||||
var player := farm.get_node("Player") as Node3D
|
||||
var start := player.global_transform
|
||||
for zone in zones.zones():
|
||||
player.global_position = zone.global_position + Vector3(0.0, 0.5, 0.0)
|
||||
await r.process_frame # emitted before _process, so wait for the next one too
|
||||
await r.process_frame
|
||||
r.check(banner.current == zone, "walking into the %s shows its name" % zone.display_name)
|
||||
player.global_position = Vector3(8.0, 0.5, -10.0)
|
||||
await r.process_frame
|
||||
await r.process_frame
|
||||
r.check(banner.current == null, "walking out of every zone clears the banner")
|
||||
player.global_transform = start
|
||||
1
game/tests/test_farm_layout.gd.uid
Normal file
1
game/tests/test_farm_layout.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://bak4w33e4nqeq
|
||||
71
game/tests/test_farm_state.gd
Normal file
71
game/tests/test_farm_state.gd
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
extends RefCounted
|
||||
## FarmState: creation from config, exact to_dict/from_dict round trips (also through JSON),
|
||||
## rejection of invalid data, snapshot independence, and night loss records.
|
||||
|
||||
|
||||
func run(r: GameTestRunner) -> void:
|
||||
var cfg := (load("res://game/resources/game_config.tres") as GameConfig).duplicate() as GameConfig
|
||||
var s := FarmState.create(cfg)
|
||||
r.check(s.night == 1 and s.nights_survived == 0, "a new farm starts before night 1")
|
||||
r.check(s.phase == CampaignController.Phase.MORNING, "a new farm starts in the morning")
|
||||
r.check(s.scarecrow_hp == cfg.scarecrow_max_hp and s.scarecrow_max_hp == cfg.scarecrow_max_hp, "scarecrow starts at full HP")
|
||||
r.check(s.crops == cfg.start_crops and s.crops_total == cfg.start_crops, "crops start at the configured count")
|
||||
r.check(s.animals_total == 0 and s.supplies_total == 0, "animals and supplies are not in play until Step 8")
|
||||
r.check(s.is_valid(), "a new farm is valid")
|
||||
|
||||
# A state with every field away from its default.
|
||||
s.night = 3
|
||||
s.nights_survived = 2
|
||||
s.phase = CampaignController.Phase.DUSK
|
||||
s.phase_time_left = 12.5
|
||||
s.scarecrow_hp = 6
|
||||
s.crops_total = 40
|
||||
s.crops = 31
|
||||
s.animals_total = 8
|
||||
s.animals = 5
|
||||
s.supplies_total = 120
|
||||
s.supplies = 77
|
||||
s.night_log.append({"night": 1, "crops_lost": 4, "animals_lost": 0, "supplies_lost": 0})
|
||||
s.night_log.append({"night": 2, "crops_lost": 5, "animals_lost": 3, "supplies_lost": 43})
|
||||
var d := s.to_dict()
|
||||
|
||||
var copy := FarmState.from_dict(d)
|
||||
r.check(copy != null and copy.to_dict() == d, "to_dict -> from_dict round trip is exact")
|
||||
var parsed: Variant = JSON.parse_string(JSON.stringify(d))
|
||||
var from_json := FarmState.from_dict(parsed as Dictionary)
|
||||
r.check(from_json != null and from_json.to_dict() == d, "round trip through JSON is exact (numbers coerced back to ints)")
|
||||
r.check(from_json != null and typeof(from_json.night_log[1]["supplies_lost"]) == TYPE_INT, "night log values are ints after JSON")
|
||||
|
||||
d["night_log"][0]["crops_lost"] = 99
|
||||
r.check(s.night_log[0]["crops_lost"] == 4, "a snapshot is independent of the live state")
|
||||
|
||||
_rejects(r, s.to_dict())
|
||||
_night_records(r, cfg)
|
||||
|
||||
|
||||
func _rejects(r: GameTestRunner, good: Dictionary) -> void:
|
||||
var cases := {
|
||||
"another version": func(d: Dictionary) -> void: d["version"] = FarmState.VERSION + 1,
|
||||
"a missing key": func(d: Dictionary) -> void: d.erase("crops"),
|
||||
"an unknown phase": func(d: Dictionary) -> void: d["phase"] = 42,
|
||||
"more crops than the total": func(d: Dictionary) -> void: d["crops"] = d["crops_total"] + 1,
|
||||
"negative animals": func(d: Dictionary) -> void: d["animals"] = -1,
|
||||
"HP above max": func(d: Dictionary) -> void: d["scarecrow_hp"] = d["scarecrow_max_hp"] + 1,
|
||||
"night 0": func(d: Dictionary) -> void: d["night"] = 0,
|
||||
"more nights survived than played": func(d: Dictionary) -> void: d["nights_survived"] = d["night"] + 1,
|
||||
"a malformed night log": func(d: Dictionary) -> void: d["night_log"] = [{"night": 1}],
|
||||
}
|
||||
for name: String in cases:
|
||||
var d := good.duplicate(true)
|
||||
(cases[name] as Callable).call(d)
|
||||
r.check(FarmState.from_dict(d) == null, "from_dict rejects %s" % name)
|
||||
|
||||
|
||||
func _night_records(r: GameTestRunner, cfg: GameConfig) -> void:
|
||||
var s := FarmState.create(cfg)
|
||||
var start := s.asset_counts()
|
||||
s.crops -= 7
|
||||
s.log_night(start)
|
||||
var e: Dictionary = s.night_log[0]
|
||||
r.check(s.night_log.size() == 1 and e["night"] == 1 and e["crops_lost"] == 7 and e["animals_lost"] == 0,
|
||||
"log_night records the losses since the night started")
|
||||
1
game/tests/test_farm_state.gd.uid
Normal file
1
game/tests/test_farm_state.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://dll6k5miikrur
|
||||
111
game/tests/test_outcome.gd
Normal file
111
game/tests/test_outcome.gd
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
extends RefCounted
|
||||
## Outcome rules: scarecrow destruction, a stripped farm (only categories in play count),
|
||||
## completing the vacation, the failure-before-completion tie policy, failure in every phase,
|
||||
## and terminal phases staying terminal.
|
||||
|
||||
const O := CampaignController.Outcome
|
||||
const P := CampaignController.Phase
|
||||
|
||||
|
||||
func run(r: GameTestRunner) -> void:
|
||||
var cfg := (load("res://game/resources/game_config.tres") as GameConfig).duplicate() as GameConfig
|
||||
var n := cfg.campaign_nights
|
||||
var fresh := FarmState.create(cfg)
|
||||
r.check(CampaignController.check_outcome(fresh, n) == O.CONTINUE, "a fresh farm continues")
|
||||
|
||||
var s := FarmState.create(cfg)
|
||||
s.scarecrow_hp = 0
|
||||
r.check(CampaignController.check_outcome(s, n) == O.GAME_OVER_SCARECROW, "0 HP is a Game Over")
|
||||
|
||||
s = FarmState.create(cfg)
|
||||
s.crops = 0
|
||||
r.check(CampaignController.check_outcome(s, n) == O.GAME_OVER_STRIPPED, "with only crops in play, no crops left is a stripped farm")
|
||||
|
||||
s = _all_categories(cfg)
|
||||
s.crops = 0
|
||||
r.check(CampaignController.check_outcome(s, n) == O.CONTINUE, "losing every crop alone does not end the game")
|
||||
s.animals = 0
|
||||
r.check(CampaignController.check_outcome(s, n) == O.CONTINUE, "losing crops and animals with supplies left does not end the game")
|
||||
s.supplies = 0
|
||||
r.check(CampaignController.check_outcome(s, n) == O.GAME_OVER_STRIPPED, "losing every category ends the game")
|
||||
|
||||
s = FarmState.create(cfg)
|
||||
s.crops_total = 0
|
||||
s.crops = 0
|
||||
r.check(not s.is_stripped(), "a farm with nothing in play is not 'stripped'")
|
||||
|
||||
s = FarmState.create(cfg)
|
||||
s.nights_survived = n - 1
|
||||
r.check(CampaignController.check_outcome(s, n) == O.CONTINUE, "%d nights survived continues" % (n - 1))
|
||||
s.nights_survived = n
|
||||
r.check(CampaignController.check_outcome(s, n) == O.VACATION_COMPLETE, "%d nights survived completes the vacation" % n)
|
||||
|
||||
# Tie policy: any failure beats completion; scarecrow destruction is reported first.
|
||||
s.scarecrow_hp = 0
|
||||
r.check(CampaignController.check_outcome(s, n) == O.GAME_OVER_SCARECROW, "tie: scarecrow destroyed on the final night loses")
|
||||
s.scarecrow_hp = 1
|
||||
s.crops = 0
|
||||
r.check(CampaignController.check_outcome(s, n) == O.GAME_OVER_STRIPPED, "tie: farm stripped on the final night loses")
|
||||
s.scarecrow_hp = 0
|
||||
r.check(CampaignController.check_outcome(s, n) == O.GAME_OVER_SCARECROW, "scarecrow destruction is reported before a stripped farm")
|
||||
|
||||
_failure_in_every_phase(r)
|
||||
_final_dawn_tie(r)
|
||||
_terminal(r)
|
||||
|
||||
|
||||
func _all_categories(cfg: GameConfig) -> FarmState:
|
||||
var s := FarmState.create(cfg)
|
||||
s.animals_total = 8
|
||||
s.animals = 8
|
||||
s.supplies_total = 50
|
||||
s.supplies = 50
|
||||
return s
|
||||
|
||||
|
||||
func _failure_in_every_phase(r: GameTestRunner) -> void:
|
||||
for phase: CampaignController.Phase in [P.MORNING, P.DAY, P.DUSK, P.NIGHT, P.DAWN]:
|
||||
var c := r.make_campaign()
|
||||
var ended: Array[CampaignController.Outcome] = []
|
||||
c.campaign_ended.connect(func(o: CampaignController.Outcome) -> void: ended.append(o))
|
||||
GameTestRunner.run_until(c, phase)
|
||||
c.state.scarecrow_hp = 0
|
||||
c.tick(GameTestRunner.TICK)
|
||||
r.check(c.state.phase == P.GAME_OVER and c.outcome == O.GAME_OVER_SCARECROW and ended == [O.GAME_OVER_SCARECROW],
|
||||
"scarecrow destroyed during %s ends the game once" % P.keys()[phase])
|
||||
c = r.make_campaign()
|
||||
GameTestRunner.run_until(c, phase)
|
||||
c.state.crops = 0
|
||||
c.tick(GameTestRunner.TICK)
|
||||
r.check(c.state.phase == P.GAME_OVER and c.outcome == O.GAME_OVER_STRIPPED,
|
||||
"farm stripped during %s ends the game" % P.keys()[phase])
|
||||
|
||||
|
||||
## The scarecrow is destroyed on the very tick the final dawn ends: a loss, not a victory.
|
||||
func _final_dawn_tie(r: GameTestRunner) -> void:
|
||||
var c := r.make_campaign()
|
||||
for i in c.config.campaign_nights - 1:
|
||||
GameTestRunner.run_until(c, P.DAWN)
|
||||
GameTestRunner.run_until(c, P.MORNING)
|
||||
GameTestRunner.run_until(c, P.DAWN)
|
||||
r.check(c.state.night == c.config.campaign_nights, "reached the final dawn")
|
||||
c.state.phase_time_left = GameTestRunner.TICK * 0.5
|
||||
c.state.scarecrow_hp = 0
|
||||
c.tick(GameTestRunner.TICK)
|
||||
r.check(c.state.phase == P.GAME_OVER and c.outcome == O.GAME_OVER_SCARECROW,
|
||||
"tie on the final dawn tick resolves as a loss (got %s)" % P.keys()[c.state.phase])
|
||||
|
||||
|
||||
func _terminal(r: GameTestRunner) -> void:
|
||||
var c := r.make_campaign()
|
||||
GameTestRunner.run_until(c, P.NIGHT)
|
||||
c.state.scarecrow_hp = 0
|
||||
c.tick(GameTestRunner.TICK)
|
||||
var before := c.state.to_dict()
|
||||
c.tick(1000.0)
|
||||
c.advance_phase()
|
||||
r.check(not c.begin_day(), "begin_day does nothing after Game Over")
|
||||
c.state.scarecrow_hp = 5
|
||||
c.tick(GameTestRunner.TICK)
|
||||
before["scarecrow_hp"] = 5
|
||||
r.check(c.state.to_dict() == before and c.state.phase == P.GAME_OVER, "Game Over is terminal: ticks and phase skips change nothing")
|
||||
1
game/tests/test_outcome.gd.uid
Normal file
1
game/tests/test_outcome.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://ylvc3hivyh53
|
||||
95
game/tools/build_player_animations.gd
Normal file
95
game/tools/build_player_animations.gd
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
extends SceneTree
|
||||
## Builds res://game/resources/player_animations.res: the KayKit Rig_Medium clips the farmer
|
||||
## uses, copied out of the shared animation files into one AnimationLibrary so the player
|
||||
## scene's AnimationPlayer can reference (and the editor can preview) them.
|
||||
## Tracks for bones the mannequin lacks (handslot.l/.r) are dropped; loop flags are set here
|
||||
## because every source clip is imported as non-looping. Source assets are not modified.
|
||||
## Re-run after editing CLIPS (editor closed):
|
||||
## godot --headless --path . --script res://game/tools/build_player_animations.gd
|
||||
|
||||
const MANNEQUIN := "res://assets/kaykit_characters/characters/Mannequin_Medium.glb"
|
||||
const ANIM_DIR := "res://assets/kaykit_characters/animations/Rig_Medium/"
|
||||
const OUTPUT := "res://game/resources/player_animations.res"
|
||||
const SKELETON_PATH := "Rig_Medium/Skeleton3D"
|
||||
|
||||
## Clip name (kept as in KayKit) -> [source file, loops].
|
||||
const CLIPS := {
|
||||
"Idle_A": ["Rig_Medium_General.glb", true],
|
||||
"Idle_B": ["Rig_Medium_General.glb", true],
|
||||
"Interact": ["Rig_Medium_General.glb", false],
|
||||
"PickUp": ["Rig_Medium_General.glb", false],
|
||||
"Use_Item": ["Rig_Medium_General.glb", false],
|
||||
"Walking_A": ["Rig_Medium_MovementBasic.glb", true],
|
||||
"Running_A": ["Rig_Medium_MovementBasic.glb", true],
|
||||
"Digging": ["Rig_Medium_Tools.glb", true],
|
||||
"Chopping": ["Rig_Medium_Tools.glb", true],
|
||||
"Hammering": ["Rig_Medium_Tools.glb", true],
|
||||
"Waving": ["Rig_Medium_Simulation.glb", false],
|
||||
}
|
||||
|
||||
|
||||
func _initialize() -> void:
|
||||
var ok := _build()
|
||||
quit(0 if ok else 1)
|
||||
|
||||
|
||||
func _build() -> bool:
|
||||
var bones := _mannequin_bones()
|
||||
if bones.is_empty():
|
||||
return false
|
||||
var library := AnimationLibrary.new()
|
||||
var sources := {} # file -> instantiated scene root (freed at the end)
|
||||
var dropped := 0
|
||||
var ok := true
|
||||
for clip: String in CLIPS:
|
||||
var file: String = CLIPS[clip][0]
|
||||
if not sources.has(file):
|
||||
var scene := load(ANIM_DIR + file) as PackedScene
|
||||
if scene == null:
|
||||
push_error("missing animation file " + file)
|
||||
ok = false
|
||||
continue
|
||||
sources[file] = scene.instantiate()
|
||||
var player := (sources[file] as Node).get_node_or_null("AnimationPlayer") as AnimationPlayer
|
||||
if player == null or not player.has_animation(clip):
|
||||
push_error("clip %s not found in %s" % [clip, file])
|
||||
ok = false
|
||||
continue
|
||||
var anim := player.get_animation(clip).duplicate(true) as Animation
|
||||
for t in range(anim.get_track_count() - 1, -1, -1):
|
||||
var path := anim.track_get_path(t)
|
||||
var keep := String(path.get_concatenated_names()) == SKELETON_PATH \
|
||||
and path.get_subname_count() == 1 and bones.has(String(path.get_subname(0)))
|
||||
if not keep:
|
||||
anim.remove_track(t)
|
||||
dropped += 1
|
||||
anim.loop_mode = Animation.LOOP_LINEAR if CLIPS[clip][1] else Animation.LOOP_NONE
|
||||
library.add_animation(clip, anim)
|
||||
for file: String in sources:
|
||||
(sources[file] as Node).free()
|
||||
if not ok:
|
||||
return false
|
||||
DirAccess.make_dir_recursive_absolute(ProjectSettings.globalize_path(OUTPUT.get_base_dir()))
|
||||
var err := ResourceSaver.save(library, OUTPUT)
|
||||
if err != OK:
|
||||
push_error("could not save %s (error %d)" % [OUTPUT, err])
|
||||
return false
|
||||
print("saved %s: %d clips, %d foreign tracks dropped" % [OUTPUT, library.get_animation_list().size(), dropped])
|
||||
return true
|
||||
|
||||
|
||||
func _mannequin_bones() -> Dictionary:
|
||||
var scene := load(MANNEQUIN) as PackedScene
|
||||
if scene == null:
|
||||
push_error("missing mannequin " + MANNEQUIN)
|
||||
return {}
|
||||
var root := scene.instantiate()
|
||||
var skel := root.get_node_or_null(SKELETON_PATH) as Skeleton3D
|
||||
var bones := {}
|
||||
if skel == null:
|
||||
push_error("mannequin skeleton not found at " + SKELETON_PATH)
|
||||
else:
|
||||
for b in skel.get_bone_count():
|
||||
bones[skel.get_bone_name(b)] = true
|
||||
root.free()
|
||||
return bones
|
||||
1
game/tools/build_player_animations.gd.uid
Normal file
1
game/tools/build_player_animations.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://dxwma3n3eecow
|
||||
268
game/tools/build_prop_collision.gd
Normal file
268
game/tools/build_prop_collision.gd
Normal file
|
|
@ -0,0 +1,268 @@
|
|||
extends SceneTree
|
||||
## Gives the ithappy farm prefabs that farm.tscn places their collision, so every instance (and
|
||||
## every later placement of the same prefab) collides. Each processed prefab gets a "Collision"
|
||||
## StaticBody3D (layer 1, world) holding one CollisionShape3D fitted to its mesh:
|
||||
## * ground/, road/ (terrain folders): trimesh of the mesh, so the player walks on the visible
|
||||
## surface instead of the flat floor under it (tile and curb edges are ramps).
|
||||
## * plant/, animal/: none. Crops are walk-through; animals become moving entities (Step 8).
|
||||
## * prop/fence_018 (the open gate) carries a hand-made thin box along its panel, so it is
|
||||
## skipped like any prefab that already has collision.
|
||||
## * tree/ trees: cylinder around the trunk, widened to half the reach of foliage hanging below
|
||||
## 1.5 m; tree/ bushes: cylinder at 80 % of the bush's mean half-width; barrels: cylinder.
|
||||
## * box_*: the pack's unit cube, placed scaled flat as concrete pads, so its top is inset 5 %
|
||||
## per side; on a pad that turns the 0.2 m edge into a ramp (a plain box edge blocks the
|
||||
## capsule), on a cube-shaped crate the sides stay near vertical.
|
||||
## * everything else: box around the geometry in the first 2 m above its base (the footprint,
|
||||
## ignoring roof overhangs), spanning the full mesh height.
|
||||
## Prefabs that already contain a CollisionShape3D are left alone, so hand-tuned shapes survive;
|
||||
## --force regenerates the "Collision" bodies this tool made (other collision is still kept).
|
||||
## Re-run after placing new prefab types (editor closed):
|
||||
## godot --headless --path . --script res://game/tools/build_prop_collision.gd [-- --force]
|
||||
|
||||
const SCENE := "res://game/scenes/farm.tscn"
|
||||
const PREFAB_DIR := "res://assets/farm/ithappy/farm/prefabs/assets/"
|
||||
const BODY_NAME := "Collision"
|
||||
## Folders whose prefabs are walked on rather than around.
|
||||
const WALKABLE := ["ground", "road", "field", "landscape", "mountain"]
|
||||
const NO_COLLISION := ["plant", "animal"]
|
||||
## Band above the prefab's base that counts as its footprint (about the player's height).
|
||||
const FOOTPRINT_HEIGHT := 2.0
|
||||
const TRUNK_HEIGHT := 0.5
|
||||
const LOW_FOLIAGE_HEIGHT := 1.5
|
||||
const LOW_FOLIAGE_SHARE := 0.5
|
||||
const TRUNK_MARGIN := 0.05
|
||||
const BUSH_SHARE := 0.8
|
||||
const SLAB_TOP_INSET := 0.05
|
||||
|
||||
|
||||
func _initialize() -> void:
|
||||
var ok := _build("--force" in OS.get_cmdline_user_args())
|
||||
quit(0 if ok else 1)
|
||||
|
||||
|
||||
func _build(force: bool) -> bool:
|
||||
var farm := load(SCENE) as PackedScene
|
||||
if farm == null:
|
||||
push_error("missing " + SCENE)
|
||||
return false
|
||||
var state := farm.get_state()
|
||||
var placed := {}
|
||||
for i in state.get_node_count():
|
||||
var instance := state.get_node_instance(i)
|
||||
if instance != null and instance.resource_path.begins_with(PREFAB_DIR):
|
||||
placed[instance.resource_path] = true
|
||||
var paths: Array = placed.keys()
|
||||
paths.sort()
|
||||
var ok := true
|
||||
var added := 0
|
||||
for path: String in paths:
|
||||
var result := _process_prefab(path, force)
|
||||
if result.begins_with("error"):
|
||||
push_error("%s: %s" % [path, result])
|
||||
ok = false
|
||||
elif result.begins_with("added"):
|
||||
added += 1
|
||||
print("%-44s %s" % [path.trim_prefix(PREFAB_DIR), result])
|
||||
print("%d placed prefabs, collision added to %d" % [paths.size(), added])
|
||||
return ok
|
||||
|
||||
|
||||
func _process_prefab(path: String, force: bool) -> String:
|
||||
var scene := load(path) as PackedScene
|
||||
if scene == null:
|
||||
return "error: not a scene"
|
||||
var root := scene.instantiate(PackedScene.GEN_EDIT_STATE_MAIN) as Node3D
|
||||
if root == null:
|
||||
return "error: root is not a Node3D"
|
||||
var previous := root.get_node_or_null(BODY_NAME)
|
||||
if force and previous is StaticBody3D:
|
||||
root.remove_child(previous)
|
||||
previous.free()
|
||||
if not root.find_children("*", "CollisionShape3D", true, false).is_empty():
|
||||
root.free()
|
||||
return "kept existing collision"
|
||||
var kind := _kind(path)
|
||||
if kind == "none":
|
||||
root.free()
|
||||
return "no collision (walk-through)"
|
||||
var faces := _faces(root)
|
||||
if faces.is_empty():
|
||||
root.free()
|
||||
return "error: no mesh faces"
|
||||
var shape := _fit(kind, faces)
|
||||
var description := _describe(shape)
|
||||
var body := StaticBody3D.new()
|
||||
body.name = BODY_NAME
|
||||
root.add_child(body)
|
||||
body.owner = root
|
||||
body.add_child(shape)
|
||||
shape.owner = root
|
||||
root.scene_file_path = ""
|
||||
var uid := ResourceLoader.get_resource_uid(path)
|
||||
var packed := PackedScene.new()
|
||||
var err := packed.pack(root)
|
||||
root.free()
|
||||
if err == OK:
|
||||
err = ResourceSaver.save(packed, path)
|
||||
if err == OK:
|
||||
err = _restore_uids(path, uid)
|
||||
if err != OK:
|
||||
return "error %d while saving" % err
|
||||
return "added " + description
|
||||
|
||||
|
||||
func _kind(path: String) -> String:
|
||||
var folder := path.get_base_dir().get_file()
|
||||
var file := path.get_file().get_basename()
|
||||
if folder in NO_COLLISION:
|
||||
return "none"
|
||||
if folder in WALKABLE:
|
||||
return "trimesh"
|
||||
if file.begins_with("box_"):
|
||||
return "slab"
|
||||
if folder == "tree":
|
||||
return "bush" if file.begins_with("bush") else "trunk"
|
||||
if file.begins_with("barrel"):
|
||||
return "cylinder"
|
||||
return "box"
|
||||
|
||||
|
||||
func _fit(kind: String, faces: PackedVector3Array) -> CollisionShape3D:
|
||||
var node := CollisionShape3D.new()
|
||||
node.name = "CollisionShape3D"
|
||||
var aabb := AABB(faces[0], Vector3.ZERO)
|
||||
for v in faces:
|
||||
aabb = aabb.expand(v)
|
||||
var base := maxf(aabb.position.y, 0.0)
|
||||
var mid_y := aabb.get_center().y
|
||||
match kind:
|
||||
"trimesh":
|
||||
var mesh_shape := ConcavePolygonShape3D.new()
|
||||
mesh_shape.set_faces(faces)
|
||||
node.shape = mesh_shape
|
||||
"slab":
|
||||
var hull := ConvexPolygonShape3D.new()
|
||||
var inset := aabb.size * SLAB_TOP_INSET
|
||||
var lo := aabb.position
|
||||
var hi := aabb.end
|
||||
hull.points = PackedVector3Array([
|
||||
Vector3(lo.x, lo.y, lo.z), Vector3(hi.x, lo.y, lo.z),
|
||||
Vector3(hi.x, lo.y, hi.z), Vector3(lo.x, lo.y, hi.z),
|
||||
Vector3(lo.x + inset.x, hi.y, lo.z + inset.z), Vector3(hi.x - inset.x, hi.y, lo.z + inset.z),
|
||||
Vector3(hi.x - inset.x, hi.y, hi.z - inset.z), Vector3(lo.x + inset.x, hi.y, hi.z - inset.z),
|
||||
])
|
||||
node.shape = hull
|
||||
"trunk":
|
||||
var trunk := _band_points(faces, base, base + TRUNK_HEIGHT)
|
||||
var center := _rect(trunk).get_center()
|
||||
var foliage := _band_points(faces, base, base + LOW_FOLIAGE_HEIGHT)
|
||||
var radius := maxf(_reach(trunk, center) + TRUNK_MARGIN, _reach(foliage, center) * LOW_FOLIAGE_SHARE)
|
||||
node.shape = _cylinder(radius, aabb.size.y)
|
||||
node.position = Vector3(center.x, mid_y, center.y)
|
||||
"bush", "cylinder":
|
||||
var rect := _rect(_band_points(faces, base, base + FOOTPRINT_HEIGHT))
|
||||
var radius := maxf(rect.size.x, rect.size.y) * 0.5
|
||||
if kind == "bush":
|
||||
radius = (rect.size.x + rect.size.y) * 0.25 * BUSH_SHARE
|
||||
node.shape = _cylinder(radius, aabb.size.y)
|
||||
node.position = Vector3(rect.get_center().x, mid_y, rect.get_center().y)
|
||||
_:
|
||||
var rect := _rect(_band_points(faces, base, base + FOOTPRINT_HEIGHT))
|
||||
var box := BoxShape3D.new()
|
||||
box.size = Vector3(rect.size.x, aabb.size.y, rect.size.y)
|
||||
node.shape = box
|
||||
node.position = Vector3(rect.get_center().x, mid_y, rect.get_center().y)
|
||||
return node
|
||||
|
||||
|
||||
## Every mesh triangle of the prefab, in the prefab root's space.
|
||||
func _faces(root: Node3D) -> PackedVector3Array:
|
||||
var faces := PackedVector3Array()
|
||||
for mesh_instance: MeshInstance3D in root.find_children("*", "MeshInstance3D", true, false):
|
||||
if mesh_instance.mesh == null:
|
||||
continue
|
||||
var to_root := mesh_instance.transform
|
||||
var parent := mesh_instance.get_parent()
|
||||
while parent != root:
|
||||
if parent is Node3D:
|
||||
to_root = (parent as Node3D).transform * to_root
|
||||
parent = parent.get_parent()
|
||||
for v in mesh_instance.mesh.get_faces():
|
||||
faces.append(to_root * v)
|
||||
return faces
|
||||
|
||||
|
||||
## XZ corners of the faces clipped to heights lo..hi: triangle corners inside the band plus the
|
||||
## points where triangle edges cross its two planes.
|
||||
func _band_points(faces: PackedVector3Array, lo: float, hi: float) -> PackedVector2Array:
|
||||
var points := PackedVector2Array()
|
||||
for t in range(0, faces.size(), 3):
|
||||
for i in 3:
|
||||
var p := faces[t + i]
|
||||
var q := faces[t + (i + 1) % 3]
|
||||
if p.y >= lo and p.y <= hi:
|
||||
points.append(Vector2(p.x, p.z))
|
||||
for h: float in [lo, hi]:
|
||||
if (p.y - h) * (q.y - h) < 0.0:
|
||||
var cross := p.lerp(q, (h - p.y) / (q.y - p.y))
|
||||
points.append(Vector2(cross.x, cross.z))
|
||||
return points
|
||||
|
||||
|
||||
func _rect(points: PackedVector2Array) -> Rect2:
|
||||
var rect := Rect2(points[0], Vector2.ZERO)
|
||||
for p in points:
|
||||
rect = rect.expand(p)
|
||||
return rect
|
||||
|
||||
|
||||
func _reach(points: PackedVector2Array, center: Vector2) -> float:
|
||||
var reach := 0.0
|
||||
for p in points:
|
||||
reach = maxf(reach, p.distance_to(center))
|
||||
return reach
|
||||
|
||||
|
||||
func _cylinder(radius: float, height: float) -> CylinderShape3D:
|
||||
var cylinder := CylinderShape3D.new()
|
||||
cylinder.radius = radius
|
||||
cylinder.height = height
|
||||
return cylinder
|
||||
|
||||
|
||||
## ResourceSaver only writes UIDs when the editor supplies them, so this headless save drops the
|
||||
## scene's own uid and its ext_resource uids. Put them back, or references by uid (farm.tscn's)
|
||||
## would fall back to paths and the editor would hand the prefab a new uid.
|
||||
func _restore_uids(path: String, uid: int) -> Error:
|
||||
var text := FileAccess.get_file_as_string(path)
|
||||
if text.is_empty():
|
||||
return FileAccess.get_open_error()
|
||||
var lines := text.split("\n")
|
||||
for i in lines.size():
|
||||
var line := lines[i]
|
||||
if line.contains(" uid="):
|
||||
continue
|
||||
if line.begins_with("[gd_scene") and uid != ResourceUID.INVALID_ID:
|
||||
lines[i] = line.trim_suffix("]") + ' uid="%s"]' % ResourceUID.id_to_text(uid)
|
||||
elif line.begins_with("[ext_resource"):
|
||||
var ext_uid := ResourceLoader.get_resource_uid(line.get_slice(' path="', 1).get_slice('"', 0))
|
||||
if ext_uid != ResourceUID.INVALID_ID:
|
||||
lines[i] = line.replace(' path="', ' uid="%s" path="' % ResourceUID.id_to_text(ext_uid))
|
||||
var file := FileAccess.open(path, FileAccess.WRITE)
|
||||
if file == null:
|
||||
return FileAccess.get_open_error()
|
||||
file.store_string("\n".join(lines))
|
||||
return OK
|
||||
|
||||
|
||||
func _describe(node: CollisionShape3D) -> String:
|
||||
var shape := node.shape
|
||||
if shape is BoxShape3D:
|
||||
var s := (shape as BoxShape3D).size
|
||||
return "box %.2f x %.2f x %.2f" % [s.x, s.y, s.z]
|
||||
if shape is CylinderShape3D:
|
||||
var c := shape as CylinderShape3D
|
||||
return "cylinder r %.2f h %.2f" % [c.radius, c.height]
|
||||
if shape is ConvexPolygonShape3D:
|
||||
return "ramped slab"
|
||||
return "trimesh %d triangles" % ((shape as ConcavePolygonShape3D).get_faces().size() / 3)
|
||||
1
game/tools/build_prop_collision.gd.uid
Normal file
1
game/tools/build_prop_collision.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://7ry6bn00e5pk
|
||||
143
game/tools/render_overview.gd
Normal file
143
game/tools/render_overview.gd
Normal file
|
|
@ -0,0 +1,143 @@
|
|||
extends SceneTree
|
||||
## Renders a top-down orthographic picture of the farm (needs a window, not --headless):
|
||||
## godot --path . --script res://game/tools/render_overview.gd -- --out=/tmp/farm.png
|
||||
## Options: --scene=res://... (default the farm), --center=x,z (default 0,0), --size=meters
|
||||
## (default 70), --res=pixels (default 1400), --grid=meters (0 = off, default 10),
|
||||
## --zones (draw the Zones/ areas and markers on top), --pitch=deg / --yaw=deg (angled
|
||||
## orthographic view instead of straight down; e.g. --pitch=50 --yaw=45 is the game camera).
|
||||
|
||||
var _out := "/tmp/farm_overview.png"
|
||||
var _scene := "res://game/scenes/farm.tscn"
|
||||
var _center := Vector2.ZERO
|
||||
var _size := 70.0
|
||||
var _res := 1400
|
||||
var _grid := 10.0
|
||||
var _zones := false
|
||||
var _pitch := 90.0
|
||||
var _yaw := 0.0
|
||||
|
||||
|
||||
func _initialize() -> void:
|
||||
for a in OS.get_cmdline_user_args():
|
||||
var arg := String(a)
|
||||
if arg.begins_with("--out="):
|
||||
_out = arg.trim_prefix("--out=")
|
||||
elif arg.begins_with("--scene="):
|
||||
_scene = arg.trim_prefix("--scene=")
|
||||
elif arg.begins_with("--center="):
|
||||
var p := arg.trim_prefix("--center=").split(",")
|
||||
_center = Vector2(float(p[0]), float(p[1]))
|
||||
elif arg.begins_with("--size="):
|
||||
_size = float(arg.trim_prefix("--size="))
|
||||
elif arg.begins_with("--res="):
|
||||
_res = int(arg.trim_prefix("--res="))
|
||||
elif arg.begins_with("--grid="):
|
||||
_grid = float(arg.trim_prefix("--grid="))
|
||||
elif arg == "--zones":
|
||||
_zones = true
|
||||
elif arg.begins_with("--pitch="):
|
||||
_pitch = float(arg.trim_prefix("--pitch="))
|
||||
elif arg.begins_with("--yaw="):
|
||||
_yaw = float(arg.trim_prefix("--yaw="))
|
||||
_render.call_deferred()
|
||||
|
||||
|
||||
func _render() -> void:
|
||||
root.size = Vector2i(_res, _res)
|
||||
var farm := (load(_scene) as PackedScene).instantiate()
|
||||
root.add_child(farm)
|
||||
for node in farm.find_children("*", "CanvasLayer", true, false):
|
||||
(node as CanvasLayer).visible = false
|
||||
var cam := Camera3D.new()
|
||||
cam.projection = Camera3D.PROJECTION_ORTHOGONAL
|
||||
cam.size = _size
|
||||
cam.far = 400.0
|
||||
root.add_child(cam)
|
||||
var basis := Basis.from_euler(Vector3(deg_to_rad(-_pitch), deg_to_rad(_yaw), 0.0))
|
||||
cam.global_transform = Transform3D(basis, Vector3(_center.x, 0.0, _center.y) + basis.z * 150.0)
|
||||
cam.make_current()
|
||||
if _grid > 0.0:
|
||||
_draw_grid()
|
||||
if _zones:
|
||||
_draw_zones(farm)
|
||||
for i in 8:
|
||||
await process_frame
|
||||
await RenderingServer.frame_post_draw
|
||||
var err := root.get_texture().get_image().save_png(_out)
|
||||
print("overview %s: %s" % [_out, error_string(err)])
|
||||
quit()
|
||||
|
||||
|
||||
func _draw_grid() -> void:
|
||||
var mesh := ImmediateMesh.new()
|
||||
mesh.surface_begin(Mesh.PRIMITIVE_LINES)
|
||||
var half := _size * 0.5
|
||||
var lo := Vector2(_center.x - half, _center.y - half)
|
||||
var hi := Vector2(_center.x + half, _center.y + half)
|
||||
var x := ceilf(lo.x / _grid) * _grid
|
||||
while x <= hi.x:
|
||||
mesh.surface_add_vertex(Vector3(x, 8.0, lo.y))
|
||||
mesh.surface_add_vertex(Vector3(x, 8.0, hi.y))
|
||||
_label(Vector3(x + 0.4, 8.1, lo.y + 1.2), "x%d" % int(x))
|
||||
x += _grid
|
||||
var z := ceilf(lo.y / _grid) * _grid
|
||||
while z <= hi.y:
|
||||
mesh.surface_add_vertex(Vector3(lo.x, 8.0, z))
|
||||
mesh.surface_add_vertex(Vector3(hi.x, 8.0, z))
|
||||
_label(Vector3(lo.x + 0.6, 8.1, z - 0.4), "z%d" % int(z))
|
||||
z += _grid
|
||||
mesh.surface_end()
|
||||
_add_lines(mesh, Color(1, 1, 1, 0.6))
|
||||
|
||||
|
||||
func _draw_zones(farm: Node) -> void:
|
||||
var zones := farm.get_node_or_null("Zones")
|
||||
if zones == null:
|
||||
return
|
||||
for node in zones.find_children("*", "Node3D", true, false):
|
||||
var n := node as Node3D
|
||||
if n is FarmZone:
|
||||
var zone := n as FarmZone
|
||||
var rect := zone.rect()
|
||||
var mesh := ImmediateMesh.new()
|
||||
mesh.surface_begin(Mesh.PRIMITIVE_LINES)
|
||||
var c := [Vector2(rect.position.x, rect.position.y), Vector2(rect.end.x, rect.position.y),
|
||||
Vector2(rect.end.x, rect.end.y), Vector2(rect.position.x, rect.end.y)]
|
||||
for i in 4:
|
||||
var a: Vector2 = c[i]
|
||||
var b: Vector2 = c[(i + 1) % 4]
|
||||
mesh.surface_add_vertex(Vector3(a.x, 9.0, a.y))
|
||||
mesh.surface_add_vertex(Vector3(b.x, 9.0, b.y))
|
||||
mesh.surface_end()
|
||||
_add_lines(mesh, zone.tint)
|
||||
_label(Vector3(rect.position.x + 0.5, 9.1, rect.position.y + 1.5), zone.display_name, zone.tint)
|
||||
elif n is Marker3D:
|
||||
_label(n.global_position + Vector3(0, 9.0, 0), "◆ " + n.name, Color(1, 0.3, 0.2))
|
||||
|
||||
|
||||
func _add_lines(mesh: ImmediateMesh, color: Color) -> void:
|
||||
var mat := StandardMaterial3D.new()
|
||||
mat.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED
|
||||
mat.albedo_color = color
|
||||
mat.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA
|
||||
var mi := MeshInstance3D.new()
|
||||
mi.mesh = mesh
|
||||
mi.material_override = mat
|
||||
mi.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
|
||||
root.add_child(mi)
|
||||
|
||||
|
||||
func _label(pos: Vector3, text: String, color: Color = Color.WHITE) -> void:
|
||||
var l := Label3D.new()
|
||||
l.text = text
|
||||
l.modulate = color
|
||||
l.outline_modulate = Color.BLACK
|
||||
l.outline_size = 8
|
||||
l.font_size = 48
|
||||
l.pixel_size = _size / float(_res) * 0.5
|
||||
l.horizontal_alignment = HORIZONTAL_ALIGNMENT_LEFT
|
||||
l.rotation = Vector3(-PI / 2.0, 0.0, 0.0)
|
||||
l.no_depth_test = true
|
||||
l.shaded = false
|
||||
root.add_child(l)
|
||||
l.global_position = pos
|
||||
1
game/tools/render_overview.gd.uid
Normal file
1
game/tools/render_overview.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://dkayyvaspu2g
|
||||
Loading…
Add table
Add a link
Reference in a new issue