This commit is contained in:
Forrest 2026-10-03 12:14:28 -04:00
commit 276d43613d
1687 changed files with 109059 additions and 0 deletions

View 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

View file

@ -0,0 +1 @@
uid://dh1gl5p44sjb1

View 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)

View file

@ -0,0 +1 @@
uid://bvvdfx5idf2u5

View 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

View file

@ -0,0 +1 @@
uid://d0bha7ghc1lfc

View 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

View file

@ -0,0 +1 @@
uid://dewrnp06jkx2y

View 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

View file

@ -0,0 +1 @@
uid://c7u02hu43p42n

146
game/scripts/farm_state.gd Normal file
View 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

View file

@ -0,0 +1 @@
uid://drlyw88ovhrfd

53
game/scripts/farm_zone.gd Normal file
View 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)

View file

@ -0,0 +1 @@
uid://celghhlevq85l

View 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

View file

@ -0,0 +1 @@
uid://bpl66stkcn1rr

View 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)

View file

@ -0,0 +1 @@
uid://bdlmtj20npler

View 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

View file

@ -0,0 +1 @@
uid://bow5a4dimtdto

View 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)

View file

@ -0,0 +1 @@
uid://0alr34qa8lbd

View 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)

View file

@ -0,0 +1 @@
uid://dbfcgsdrh5v60