harvest/game/tools/make_nights.gd
Forrest eac2cb65fe Room for 40 robots; fewer robots and more UFOs in the late nights
The #28 soak's recommendation 2, which the user chose:
- character_pool 48 thieves / 20 breakers -> 32 / 40 (thieves never
  passed 15 at once; breakers filled 20 from night 11).
- make_nights.gd MIX_TO breakers 0.20 -> 0.12 (flat), UFOs 0.15 -> 0.23;
  nights 6-29 regenerated with --force (titles, hints, uids unchanged).
- Night 30: breakers 13 -> 8 base (91 -> 56 played), the 5 moved to its
  UFO groups (70 -> 105), so it stays the biggest night at 511.
RULES.md's nights table and limits follow; the soak report records the
decisions. Full suite: same 24 FAIL lines; nights 5 and 10 now arrive in
full in the scarecrow-less back-to-back test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 18:06:28 -04:00

379 lines
16 KiB
GDScript

extends SceneTree
## Writes the vacation's middle nights (docs/plan.md #27) as ordinary NightPlan files,
## game/resources/nights/night_<n>.tres, so each stays editable in the inspector. Nights 1-5 and
## 30 are hand-authored; this makes 6-29 (and refuses any range beyond them) by a fixed recipe and
## a seeded RNG (the same seed writes the same nights):
## base total 24 x (1 + 0.065 x (n - 5)), rounded; every fifth night (n % 5 == 0) is a siege,
## x 1.3 at the normal length
## mix crows 0.45 -> 0.30, thieves 0.35, breakers 0.12 (flat), UFOs 0.08 -> 0.23, from
## night 6 to 29; at least one group of each
## targets crows the crops, breakers and UFOs any, thieves animals -> supplies -> any in turn
## waves 3 below night 12, 4 to 21, then 5; evenly spaced from 5 s to length - 30 s, each
## 2-4 groups of different types arriving within 6 s of each other (a type with more
## groups than there are waves doubles up in the emptiest)
## groups 1-5 enemies (base), every 1.5-3.0 s (base), shortened so the last arrives by
## length - 5 s as played
## scales enemy_speed_scale 1 + 0.01 x (n - 5), enemy_hp_scale 1 + 0.025 x (n - 5)
## title, hint placeholder drafts from the lists below, for the user to rewrite; sieges are
## "Siege: ..."
## Counts are the plans' (base); played, each group is GameConfig.wave_count_scale times its size,
## wave_spacing_scale times its spacing. The text is written directly in the hand-made files'
## layout (a headless ResourceSaver drops uid lines), each new file with a fresh uid. Existing
## files are kept unless --force (which keeps their uid). Every night in the range, written or
## kept, is then loaded and checked with NightPlan.problems() at the played scales; any problem
## exits non-zero. Run (editor closed), then --import so the uid cache knows new files:
## godot --headless --path . --script res://game/tools/make_nights.gd [-- --from=6 --to=29 --seed=30 --force]
const DIR := "res://game/resources/nights/"
const CONFIG := "res://game/resources/game_config.tres"
const PLAN_SCRIPT := "res://game/scripts/night_plan.gd"
const FIRST := 6
const LAST := 29
const SEED := 30
## Night 5's base total, the start of the ramp, and its growth per night after it.
const BASE := 24.0
const GROWTH := 0.065
const SIEGE_EVERY := 5
const SIEGE_SCALE := 1.3
## Shares of the base total by type, at night FIRST and night LAST (linear between).
const TYPES: Array[String] = ["crow", "thief", "breaker", "ufo"]
const MIX_FROM := {"crow": 0.45, "thief": 0.35, "breaker": 0.12, "ufo": 0.08}
const MIX_TO := {"crow": 0.30, "thief": 0.35, "breaker": 0.12, "ufo": 0.23}
const THIEF_TARGETS: Array[String] = ["animals", "supplies", "any"]
const FIRST_WAVE := 5.0
## The last wave starts this long before sunrise, and its stream ends at least END_MARGIN before.
const LAST_WAVE_BEFORE_END := 30.0
const END_MARGIN := 5.0
const WAVE_SPREAD := 6
const MAX_GROUPS_PER_WAVE := 4
const MIN_GROUPS_PER_WAVE := 2
const MAX_COUNT := 5
const EVERY: Array[float] = [1.5, 2.0, 2.5, 3.0]
const SPEED_PER_NIGHT := 0.01
const HP_PER_NIGHT := 0.025
## Drafts: no lore beyond what nights 1-5 and 30 say (crows, aliens, alien robots, lights in the
## sky, the farmers coming back).
const TITLES: Array[String] = [
"Back for more", "Crows over the field", "Aliens at the pen", "Robots at the gate",
"The shed again", "Lights over the house", "Every side at once", "No quiet nights",
"Thin fences", "Busy skies", "One more night", "The long dark", "Hold the pen",
"Mind the shed", "Under the lights", "Crows and robots", "Short on sleep",
"They know the way in", "Keep the lantern lit", "Still standing",
]
const HINTS: Array[String] = [
"More of them tonight..... keep the fences up.",
"The crows are back. They always come back.",
"Something's moving out past the fence.....",
"Lights in the sky again..... here they come.",
"Watch the pen tonight. And the shed. And the crops.....",
"They came from every side last night. Tonight too.",
"The robots go for the fences first..... fix what you can.",
"It's quiet. Too quiet.....",
"Count the crops in the morning. Hopefully all of them.",
"Another night, another crowd at the fence.....",
"Is that the UFOs again?! ..... yep.",
"The crows don't sleep, and neither do you.",
"Keep the lantern lit and the fences standing.",
"The farmers would be proud..... if they were here.",
"Hold on. The farmers will be back.",
"Here they come again.....",
"Crows. Aliens. Robots. UFOs. You know the drill.",
"They're getting faster..... aren't they?",
"Tougher than last night..... or is it just you?",
"Patch up, stock up, and keep watch.....",
]
const SIEGE_TITLES: Array[String] = ["Siege: the fences", "Siege: the pen", "Siege: the shed", "Siege: the whole farm"]
const SIEGE_HINTS: Array[String] = [
"Every fence, every gate..... they want it all tonight.",
"They're all coming at once tonight.....",
"That's a lot of lights out there..... it's a siege.",
"The biggest crowd yet..... hold the farm.",
]
func _initialize() -> void:
var from := FIRST
var to := LAST
var seed_value := SEED
var force := false
for a in OS.get_cmdline_user_args():
var arg := String(a)
if arg.begins_with("--from="):
from = int(arg.trim_prefix("--from="))
elif arg.begins_with("--to="):
to = int(arg.trim_prefix("--to="))
elif arg.begins_with("--seed="):
seed_value = int(arg.trim_prefix("--seed="))
elif arg == "--force":
force = true
quit(0 if _make(from, to, seed_value, force) else 1)
static func is_siege(n: int) -> bool:
return n % SIEGE_EVERY == 0
## Night n's planned enemies (before the played count scale).
static func base_total(n: int) -> int:
var base := roundi(BASE * (1.0 + GROWTH * (n - 5)))
return roundi(base * SIEGE_SCALE) if is_siege(n) else base
static func wave_count(n: int) -> int:
return 3 if n < 12 else (4 if n < 22 else 5)
func _make(from: int, to: int, seed_value: int, force: bool) -> bool:
var cfg := load(CONFIG) as GameConfig
if cfg == null or from < FIRST or to > LAST or to < from:
push_error("make_nights: bad config, or a range %d..%d outside %d..%d (the other nights are hand-made)" % [from, to, FIRST, LAST])
return false
var names := _drafts(seed_value)
var ok := true
for n in range(from, to + 1):
var path := DIR + "night_%d.tres" % n
var exists := FileAccess.file_exists(path)
var what := "kept"
if not exists or force:
var rng := RandomNumberGenerator.new()
rng.seed = seed_value * 1000 + n
var length := cfg.night_length
var groups := _groups(n, rng, length, cfg.wave_count_scale, cfg.wave_spacing_scale)
var draft: Array = names.get(n, ["Night %d" % n, "Here they come again....."])
var text := _text(n, draft[0], draft[1], groups, _uid_of(path) if exists else "")
var f := FileAccess.open(path, FileAccess.WRITE)
if f == null:
push_error("make_nights: can't write %s" % path)
ok = false
continue
f.store_string(text)
f.close()
what = "rewritten" if exists else "written"
ok = _check(n, path, cfg, what) and ok
return ok
## Night n's groups: the base total split by the mix into groups of 1-5, laid out in waves.
func _groups(n: int, rng: RandomNumberGenerator, length: float, count_scale: float, spacing_scale: float) -> Array[Dictionary]:
var waves := wave_count(n)
var counts := _type_counts(n)
# How many groups each type comes in: enough that none tops MAX_COUNT, at most one per wave
# unless that's not enough; then 2-4 groups per wave in all.
var parts := {}
var lowest := {}
for t in TYPES:
var c: int = counts[t]
lowest[t] = ceili(c / float(MAX_COUNT))
parts[t] = rng.randi_range(lowest[t], maxi(lowest[t], mini(c, waves)))
while _sum(parts) < MIN_GROUPS_PER_WAVE * waves:
var can := TYPES.filter(func(t: String) -> bool: return parts[t] < counts[t])
parts[can[rng.randi_range(0, can.size() - 1)]] += 1
while _sum(parts) > MAX_GROUPS_PER_WAVE * waves:
var can := TYPES.filter(func(t: String) -> bool: return parts[t] > lowest[t])
parts[can[rng.randi_range(0, can.size() - 1)]] -= 1
# Each type's groups to the emptiest waves that don't have that type yet (any emptiest one
# when every wave has it), the type with the most groups first: the waves stay within one
# group of each other.
var order := TYPES.duplicate()
order.sort_custom(func(a: String, b: String) -> bool: return parts[a] > parts[b] or (parts[a] == parts[b] and TYPES.find(a) < TYPES.find(b)))
var in_wave: Array = []
for w in waves:
in_wave.append([])
for t in order:
var sizes := _split(counts[t], parts[t], rng)
for size in sizes:
var w := _emptiest(in_wave, t, rng)
in_wave[w].append({"type": t, "count": size})
var out: Array[Dictionary] = []
var span := length - LAST_WAVE_BEFORE_END - FIRST_WAVE
for w in waves:
var start := roundi(FIRST_WAVE + span * w / float(waves - 1))
var wave: Array = in_wave[w]
_shuffle(wave, rng)
for k in wave.size():
var g: Dictionary = wave[k]
var time := float(start + (0 if k == 0 else rng.randi_range(0, WAVE_SPREAD)))
var every := EVERY[rng.randi_range(0, EVERY.size() - 1)]
var played := NightPlan.scaled_count(g, count_scale) - 1
# The last arrival by length - END_MARGIN, as played: closer together, else earlier.
while every > EVERY[0] and time + played * every * spacing_scale > length - END_MARGIN:
every -= 0.5
time = minf(time, floorf(length - END_MARGIN - played * every * spacing_scale))
out.append({"count": g["count"], "every": every, "target": "", "time": time, "type": g["type"]})
out.sort_custom(func(a: Dictionary, b: Dictionary) -> bool:
return a["time"] < b["time"] or (a["time"] == b["time"] and TYPES.find(a["type"]) < TYPES.find(b["type"])))
var thieves := 0
for g in out:
match String(g["type"]):
"crow":
g["target"] = "crops"
"thief":
g["target"] = THIEF_TARGETS[thieves % THIEF_TARGETS.size()]
thieves += 1
_:
g["target"] = "any"
return out
## The base total by type: the night's mix, rounded by largest remainder, at least one of each.
static func _type_counts(n: int) -> Dictionary:
var total := base_total(n)
var at := clampf((n - FIRST) / float(LAST - FIRST), 0.0, 1.0)
var raw := {}
var out := {}
for t in TYPES:
raw[t] = total * lerpf(MIX_FROM[t], MIX_TO[t], at)
out[t] = maxi(floori(raw[t]), 1)
while _sum(out) < total:
var best := ""
for t in TYPES:
if best == "" or raw[t] - out[t] > raw[best] - out[best]:
best = t
out[best] += 1
while _sum(out) > total:
var worst := ""
for t in TYPES:
if out[t] > 1 and (worst == "" or raw[t] - out[t] < raw[worst] - out[worst]):
worst = t
out[worst] -= 1
return out
## count split into parts groups of 1..MAX_COUNT.
static func _split(count: int, parts: int, rng: RandomNumberGenerator) -> Array[int]:
var sizes: Array[int] = []
for k in parts:
sizes.append(1)
for k in count - parts:
var room: Array[int] = []
for i in parts:
if sizes[i] < MAX_COUNT:
room.append(i)
sizes[room[rng.randi_range(0, room.size() - 1)]] += 1
return sizes
## The emptiest wave without a group of type (the emptiest of all when they all have one).
static func _emptiest(in_wave: Array, type: String, rng: RandomNumberGenerator) -> int:
var free: Array[int] = []
for w in in_wave.size():
if not (in_wave[w] as Array).any(func(g: Dictionary) -> bool: return g["type"] == type):
free.append(w)
if free.is_empty():
for w in in_wave.size():
free.append(w)
var least := 1 << 30
for w in free:
least = mini(least, (in_wave[w] as Array).size())
var best: Array[int] = []
for w in free:
if (in_wave[w] as Array).size() == least:
best.append(w)
return best[rng.randi_range(0, best.size() - 1)]
static func _shuffle(a: Array, rng: RandomNumberGenerator) -> void:
for i in range(a.size() - 1, 0, -1):
var j := rng.randi_range(0, i)
var keep: Variant = a[i]
a[i] = a[j]
a[j] = keep
static func _sum(d: Dictionary) -> int:
var n := 0
for k in d:
n += int(d[k])
return n
## Night -> [title, hint] for every night FIRST..LAST, from the draft lists in an order fixed by
## the seed (so one night's draft doesn't depend on which others are written).
static func _drafts(seed_value: int) -> Dictionary:
var rng := RandomNumberGenerator.new()
rng.seed = seed_value
var titles := TITLES.duplicate()
var hints := HINTS.duplicate()
_shuffle(titles, rng)
_shuffle(hints, rng)
var out := {}
var k := 0
var sieges := 0
for n in range(FIRST, LAST + 1):
if is_siege(n):
out[n] = [SIEGE_TITLES[sieges % SIEGE_TITLES.size()], SIEGE_HINTS[sieges % SIEGE_HINTS.size()]]
sieges += 1
else:
out[n] = [titles[k % titles.size()], hints[k % hints.size()]]
k += 1
return out
## The .tres text, laid out as the hand-made night files are.
func _text(n: int, title: String, hint: String, groups: Array[Dictionary], uid: String) -> String:
if uid == "":
uid = ResourceUID.id_to_text(ResourceUID.create_id())
var script_uid := ResourceLoader.get_resource_uid(PLAN_SCRIPT)
var lines := PackedStringArray()
lines.append('[gd_resource type="Resource" script_class="NightPlan" format=3 uid="%s"]' % uid)
lines.append("")
if script_uid != ResourceUID.INVALID_ID:
lines.append('[ext_resource type="Script" uid="%s" path="%s" id="1_plan"]' % [ResourceUID.id_to_text(script_uid), PLAN_SCRIPT])
else:
lines.append('[ext_resource type="Script" path="%s" id="1_plan"]' % PLAN_SCRIPT)
lines.append("")
lines.append("[resource]")
lines.append('script = ExtResource("1_plan")')
lines.append("title = %s" % var_to_str(title))
lines.append("dusk_hint = %s" % var_to_str(hint))
lines.append("enemy_speed_scale = %s" % _num(1.0 + SPEED_PER_NIGHT * (n - 5)))
lines.append("enemy_hp_scale = %s" % _num(1.0 + HP_PER_NIGHT * (n - 5)))
var entries := PackedStringArray()
for g in groups:
var keys := ["count", "every", "target", "time", "type"]
var fields := PackedStringArray()
for key in keys:
fields.append('"%s": %s' % [key, var_to_str(g[key])])
entries.append("{\n" + ",\n".join(fields) + "\n}")
lines.append("groups = Array[Dictionary]([" + ", ".join(entries) + "])")
return "\n".join(lines) + "\n"
## A scale as the file shows it: 1.025, not 1.0250000000000001.
static func _num(x: float) -> String:
var text := String.num(x, 4)
return text if text.contains(".") else text + ".0"
## The uid in an existing file's header ("" if none).
static func _uid_of(path: String) -> String:
var f := FileAccess.open(path, FileAccess.READ)
if f == null:
return ""
var head := f.get_line()
var at := head.find('uid="')
if at < 0:
return ""
return head.substr(at + 5, head.find('"', at + 5) - at - 5)
## Loads night n back from disk and checks it at the played scales; prints a line about it.
func _check(n: int, path: String, cfg: GameConfig, what: String) -> bool:
var plan := ResourceLoader.load(path, "", ResourceLoader.CACHE_MODE_IGNORE) as NightPlan
if plan == null:
printerr("night %d: %s doesn't load as a NightPlan" % [n, path])
return false
var length := plan.night_length if plan.night_length > 0.0 else cfg.night_length
var count_scale := plan.count_scale_in(cfg)
var bad := plan.problems(length, count_scale, plan.spacing_scale_in(cfg))
if plan.title == "" or plan.dusk_hint.length() <= 20:
bad.append("needs a title and a dusk hint")
var types := plan.type_counts(count_scale)
var mix := PackedStringArray()
for t in TYPES:
mix.append("%s %d" % [t, int(types.get(EnemySystem.TYPE_NAMES.find(t), 0))])
print("night %d %s: '%s', %.0f s, %d base, %d played (%s), %d groups, speed %s, HP %s%s" % [n, what, plan.title,
length, plan.total(), plan.total(count_scale), ", ".join(mix), plan.groups.size(), plan.enemy_speed_scale,
plan.enemy_hp_scale, "" if bad.is_empty() else " PROBLEMS: %s" % [bad]])
return bad.is_empty()