War council: guards march to other towns, one fight, then home; main assault

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rope 2026-11-04 16:56:24 +00:00
parent 2b04db3b31
commit a78274803b
5 changed files with 470 additions and 18 deletions

231
game.py
View file

@ -1684,7 +1684,7 @@ RAID_TRAITS = ["lightly armoured, heavy on archers", "mounted and fast, few bows
# --- world ---------------------------------------------------------------
WORLD_VERSION = 40
WORLD_VERSION = 41
HOME_CITY = "guildhall"
CITY_KEYS = ("events", "next_event_at", "next_minor_at", "next_hardship_at", "next_fortune_at", "caravan", "orders")
TRAVEL_TIME = 12 * 60 # game seconds on the road between two towns
@ -1701,6 +1701,10 @@ REGIONS = {
REGION_YIELD = [1.0, 0.75, 0.5, 0.3, 0.2, 0.1] # more per trip at each material tier, for a full city
TOWN_SCALE = [0.5, 0.7, 0.85, 1.0] # how much of that a hamlet, village, town and city get
MAX_CITIES = 1 + len(REGIONS)
MARCH_TIME = 20 * HOUR # guards on the road, as a unit, between any two towns (a road comes with each founding)
VOTE_TIME = HOUR # how long the war council has before the votes cast decide
MAIN_ASSAULT = (1.5, 0.75) # how the bandits weigh their main target against the rest, kingdom total unchanged
MAIN_TIER = 2 # a town has to be this big to draw it, and it takes two such towns
FOUNDING = {"settlers": 20, "gold": 5000, "provisions": 200} # what a new town takes from the one it leaves
FOUNDING_GRACE = 24 # game hours a new town gets before its first threat lands
@ -1791,6 +1795,7 @@ def new_world(now: float, speed: float = 1.0) -> World:
"players": {},
"cities": {HOME_CITY: _new_city(now, speed, "Guildhall")},
"charter": None,
"marches": [], "council": [], "next_march_id": 1,
"next_event_id": 1,
"ledger": [],
"board": [],
@ -2057,6 +2062,10 @@ def migrate(world: dict, now: float | None = None) -> World:
raid = upcoming_raid(world)
world["bank_risk_after"] = raid.get("slot", 0) if raid else 0
world["version"] = 40
if world["version"] < 41:
# The war council, and guards on the march.
world.doc.update(marches=[], council=[], next_march_id=1)
world["version"] = 41
return world
@ -4671,19 +4680,114 @@ def cancel_charter(world: World, player: dict) -> str | None:
return None
def propose_march(world: World, player: dict, source: str, target: str, guards, now: float) -> str | None:
"""Put a march before the war council. Your vote counts for it."""
cities = world.doc["cities"]
if source not in cities or target not in cities or source == target:
return "Pick two towns"
if not isinstance(guards, int) or guards < 1:
return "Send at least one guard"
if any(p["status"] == "open" and p["from"] == source for p in world["council"]):
return f"{cities[source]['name']} already has a march before the council"
ready = guards_on_duty(world.at(source))
if guards > ready:
return f"{cities[source]['name']} has {ready:,} guards paid and at their posts"
proposal = {"id": world["next_march_id"], "by": player["id"], "from": source, "to": target, "guards": guards,
"at": now, "ends": now + VOTE_TIME / speed(world), "yes": [player["id"]], "no": [], "status": "open"}
world["next_march_id"] += 1
world["council"].append(proposal)
del world["council"][:-20]
log(world, now, "raid", f"{player['name']} asked the war council to send {guards} guards from "
f"{cities[source]['name']} to {cities[target]['name']}", player["id"])
_count_votes(world, proposal, now)
return None
def vote_march(world: World, player: dict, proposal_id, yes: bool, now: float) -> str | None:
proposal = next((p for p in world["council"] if p["id"] == proposal_id), None)
if not proposal or proposal["status"] != "open":
return "That vote is over"
for side in ("yes", "no"):
if player["id"] in proposal[side]:
proposal[side].remove(player["id"])
proposal["yes" if yes else "no"].append(player["id"])
_count_votes(world, proposal, now)
return None
def _count_votes(world: World, proposal: dict, now: float) -> None:
"""A majority of everyone active settles it at once. Otherwise the votes cast decide when the hour is up:
not voting never blocks a march."""
active = sum(1 for p in world["players"].values() if p["last_active"] > now - 2 * DAY / speed(world))
if 2 * len(proposal["yes"]) > active:
_close_vote(world, proposal, True, now)
elif 2 * len(proposal["no"]) > active:
_close_vote(world, proposal, False, now)
def _close_vote(world: World, proposal: dict, passed: bool, now: float) -> None:
proposal["closed"] = now
proposal["status"] = "rejected"
if passed:
proposal["status"] = "sent" if _send_guards(world, proposal, now) else "failed"
cities = world.doc["cities"]
if proposal["status"] == "failed":
log(world, now, "raid", f"The war council's march from {cities[proposal['from']]['name']} found no guards at their posts")
elif proposal["status"] == "rejected":
log(world, now, "raid", f"The war council kept the guards in {cities[proposal['from']]['name']}")
def _send_guards(world: World, proposal: dict, now: float) -> bool:
"""The guards leave with their kit and this threat's wage, for one fight. Returns False if none could go."""
home, target = world.at(proposal["from"]), world.at(proposal["to"])
guards = min(proposal["guards"], guards_on_duty(home))
if guards < 1:
return False
stock = home["city"]["stockpile"]
kit = {}
for slot in KIT_DEFENCE:
for item, qty in issued_kit(home, slot, guards):
take_stock_qty(stock, item, qty)
kit[item] = qty
militia = round(_militia(home) * guards / max(1, guard_posts(home)), 1)
home["city"]["wages"] = home["city"].get("wages", 0) - guards * GUARD_WAGE
threat = upcoming_raid(target)
world["marches"].append({"id": proposal["id"], "from": proposal["from"], "to": proposal["to"], "guards": guards,
"kit": kit, "militia": militia, "left": now, "arrive": now + MARCH_TIME / speed(world),
"status": "marching", "for": threat.get("slot") if threat else None})
log(world, now, "raid", f"{guards} guards marched from {home['city']['name']} for {target['city']['name']}")
return True
def _threat_glance(world: World, now: float) -> dict | None:
"""What this town's scouts know of its coming threat, for the war table."""
threat = upcoming_raid(world)
if not threat:
return None
view = event_view(world, threat, now)
return {key: view[key] for key in ("id", "kind", "intel", "at_gates", "earliest", "latest", "exact", "size", "range", "strength", "main") if key in view}
def kingdom_view(world: World, now: float) -> dict:
"""Every town at a glance, and what's on the road."""
cities = []
for key, city in world.doc["cities"].items():
people = [p for p in world["players"].values() if p["at"] == key and not p["travel"]]
town = world.at(key)
guard = defence(town)
cities.append({"id": key, "name": city["name"], "region": city.get("region"), "town_scale": TOWN_SCALE[city["tier"]],
"population": int(city["population"]),
"tier": TIERS[city["tier"]]["name"], "repelled": city["repelled"],
"people": [p["id"] for p in people], "founded": city["founded"]})
"people": [p["id"] for p in people], "founded": city["founded"],
"defence": guard["total"], "guards": guard["guards"], "posts": guard["posts"], "away": guard["away"],
"garrison": [entry["id"] for entry in guard["garrison"]], "threat": _threat_glance(town, now)})
charter = world["charter"]
return {"cities": cities, "charter": charter, "pouch": {"slots": POUCH_SLOTS, "stack": POUCH_STACK},
"founding": FOUNDING, "max": MAX_CITIES, "short": _founding_short(world),
"regions": REGIONS, "region_yield": REGION_YIELD,
"council": [p for p in world["council"] if p["status"] == "open" or now - p.get("closed", now) < 6 * HOUR / speed(world)],
"marches": [{key: march[key] for key in ("id", "from", "to", "guards", "arrive", "status")} | {"power": march_power(march)}
for march in world["marches"]],
"road": [{"id": p["id"], **{k: p["travel"][k] for k in ("from", "to", "arrive")}}
for p in world["players"].values() if p["travel"]]}
@ -5096,9 +5200,32 @@ def guard_posts(world: dict) -> int:
return min(GUARD_POSTS_BASE + GUARD_POSTS * building_level(world, "barracks"), int(world["city"]["population"] // 2))
def guards_away(world: World) -> int:
"""This town's guards out on the road or standing in another town. Their posts wait for them."""
return sum(march["guards"] for march in world["marches"] if march["from"] == world.here)
def guards_on_duty(world: dict) -> int:
"""Guards whose wage for the coming threat is in the chest."""
return min(guard_posts(world), int(world["city"].get("wages", 0) // GUARD_WAGE))
return min(max(0, guard_posts(world) - guards_away(world)), int(world["city"].get("wages", 0) // GUARD_WAGE))
def _militia(world: World) -> float:
"""What every post in the barracks is worth together, before kit."""
city = world["city"]
return (0.3 * building_level(world, "barracks") * city["population"] * (1.5 if fitted(world, "weapon_racks") else 1)
* mood(world)["militia"])
def marched_here(world: World) -> list[dict]:
"""Guards from other towns standing here now."""
return [march for march in world["marches"] if march["to"] == world.here and march["status"] == "there"]
def march_power(march: dict) -> float:
"""What a marching company adds to a defence: its drill and the kit it carries."""
kit = sum(kit_defence(march["kit"], slot, march["guards"]) for slot in KIT_DEFENCE if slot != "salve")
return round(march["militia"] + kit + min(SALVE_CAP, kit_defence(march["kit"], "salve", march["guards"])), 1)
def defence(world: dict, guards: int | None = None) -> dict:
@ -5108,8 +5235,7 @@ def defence(world: dict, guards: int | None = None) -> dict:
stock = city["stockpile"]
posts = guard_posts(world)
armed = guards_on_duty(world) if guards is None else min(guards, posts)
militia = (0.3 * building_level(world, "barracks") * pop * (1.5 if fitted(world, "weapon_racks") else 1)
* mood(world)["militia"])
militia = _militia(world)
parts = {
"townsfolk": 10,
"walls": 20 * building_level(world, "walls") + 25 * fitted(world, "hoardings"),
@ -5127,6 +5253,9 @@ def defence(world: dict, guards: int | None = None) -> dict:
}
if guards is not None:
return {"total": round(sum(parts.values()), 1), "parts": parts}
helping = marched_here(world)
if helping:
parts["reinforcements"] = round(sum(march_power(march) for march in helping), 1)
garrison = []
for player in world["players"].values():
if player["garrison"] and player["at"] == world.here:
@ -5137,8 +5266,9 @@ def defence(world: dict, guards: int | None = None) -> dict:
if city["starving"]:
total *= 0.8
return {"parts": parts, "garrison": garrison, "total": round(total, 1), "starving": city["starving"],
"guards": armed, "posts": posts, "wages": int(city.get("wages", 0)), "wage": GUARD_WAGE,
"kit": {slot: issued_kit(world, slot, posts) for slot in KIT_DEFENCE}}
"guards": armed, "posts": posts, "away": guards_away(world), "wages": int(city.get("wages", 0)), "wage": GUARD_WAGE,
"helping": [{"from": march["from"], "guards": march["guards"], "power": march_power(march)} for march in helping],
"kit": {slot: issued_kit(world, slot, max(0, posts - guards_away(world))) for slot in KIT_DEFENCE}}
def standing_defence(world: dict) -> float:
@ -5150,7 +5280,7 @@ def standing_defence(world: dict) -> float:
def pay_wages(world: dict, player: dict, qty, source: str, now: float) -> str | None:
"""Put gold in the barracks' wage chest, from your purse (earns favour) or the treasury."""
city = world["city"]
room = guard_posts(world) * GUARD_WAGE - int(city.get("wages", 0))
room = (guard_posts(world) - guards_away(world)) * GUARD_WAGE - int(city.get("wages", 0))
if room <= 0:
return "Every post is paid for"
have = player["gold"] if source == "bank" else int(city["treasury"]) if source == "city" else None
@ -5180,10 +5310,43 @@ def _pay_guards(world: dict, report: dict) -> None:
city["wages"] = city.get("wages", 0) - report["guards"] * GUARD_WAGE
def _muster_tick(world: World, now: float) -> bool:
"""Close the votes whose hour is up and move the companies on the road."""
changed = False
for proposal in world["council"]:
if proposal["status"] == "open" and now >= proposal["ends"]:
_close_vote(world, proposal, len(proposal["yes"]) > len(proposal["no"]), now)
changed = True
for march in list(world["marches"]):
if march["status"] != "there" and now >= march["arrive"]:
_march_on(world, march, now)
changed = True
return changed
def _march_on(world: World, march: dict, now: float) -> None:
"""A company has reached the end of its road: the town it was sent to, or home."""
target, home = world.at(march["to"]), world.at(march["from"])
if march["status"] == "marching":
too_late = any(event.get("slot") == march["for"] and event["status"] == "done" for event in target["events"])
if too_late:
march.update(status="returning", arrive=now + MARCH_TIME / speed(world))
log(target, now, "raid", f"{march['guards']} guards from {home['city']['name']} came too late and turned for home")
else:
march["status"] = "there"
log(target, now, "raid", f"{march['guards']} guards from {home['city']['name']} marched in")
return
stock = home["city"]["stockpile"]
for item, qty in march["kit"].items():
stock[item] = stock.get(item, 0) + qty
log(home, now, "raid", f"{march['guards']} guards came home from {target['city']['name']}")
world["marches"].remove(march)
def tick(world: World, now: float, rng: random.Random | None = None) -> bool:
"""Advance every town and its events to `now`. Returns True if anything changed."""
rng = rng or random.Random()
changed = False
changed = _muster_tick(world, now)
for key in list(world.doc["cities"]):
changed = _tick_city(world.at(key), now, rng) or changed
return changed
@ -5320,6 +5483,19 @@ def threat_base(world: World, now: float) -> float:
return (15 + 5 * city_age(world, now) + 1.5 * city["population"] + 1.6 * math.sqrt(wealth)) * (1 + 0.08 * city["repelled"])
def _assault_shift(world: World, event: dict, base: float, now: float) -> float:
"""The bandits pick one big town a slot for their main assault, drawing strength from the other big
towns, so the kingdom's total stays the same. Every town picks the same one: the slot seeds the choice."""
big = sorted(key for key, city in world.doc["cities"].items() if city["tier"] >= MAIN_TIER)
if world.here not in big or len(big) < 2:
return 0.0
main = random.Random(f"main-{event['slot']}").choice(big)
event["main"] = main == world.here
bases = {key: threat_base(world.at(key), now) for key in big}
weighted = {key: value * MAIN_ASSAULT[0 if key == main else 1] for key, value in bases.items()}
return sum(bases.values()) * weighted[world.here] / sum(weighted.values()) - base
def _threats_elsewhere(world: World) -> list[dict]:
"""The threats coming for the other towns."""
return [event for key, city in world.doc["cities"].items() if key != world.here
@ -5366,6 +5542,7 @@ def _announce(world: dict, now: float, rng: random.Random) -> None:
fighters = sum(combat_power(p) for p in world["players"].values() if p["last_active"] > now - 2 * DAY / speed(world))
base = threat_base(world, now)
strength = base + 0.5 * fighters * (base / sum(threat_base(world.at(key), now) for key in world.doc["cities"]))
strength += _assault_shift(world, event, base, now)
# How big it looks is measured against what the city holds without preparing.
event["standing"] = round(max(1.0, standing_defence(world)), 1)
if kind == "dragon":
@ -5462,6 +5639,8 @@ def event_view(world: dict, event: dict, now: float) -> dict:
"recon": int(min(event["recon"], costs[-1])), "recon_full": costs[-1],
"recon_next": max(0, round(costs[level] - event["recon"])) if level < 3 else 0,
}
if level >= 3 and event.get("main"):
view["main"] = True
if event["kind"] == "dragon":
strength = event["strength"]
view["headline"] = "Herders whisper of scorched pastures in the hills."
@ -5590,6 +5769,35 @@ def _loot_banks(world: World, event: dict, share: float, now: float) -> bool:
return looted
def _reinforcements_fought(world: World, share: float, severity: float, now: float, rng: random.Random) -> list[str]:
"""Guards from elsewhere have stood their fight: kit wears as it does for the town's own,
salves are used up, a lost fight kills some, and they march for home."""
lines = []
for march in marched_here(world):
kit = march["kit"]
for slot in ("weapon", "shield", "jerkin"):
stat = KIT_DEFENCE[slot][0]
items = sorted((item for item in kit if kit_slot(item) == slot), key=lambda item: ITEMS[item].get(stat, 0))
breaks = int(sum(kit[item] for item in items) * share + rng.random())
for item in items:
lost = min(breaks, kit[item])
if lost:
take_stock_qty(kit, item, lost)
breaks -= lost
for item in [item for item in kit if kit_slot(item) == "salve"]:
del kit[item]
home = world.at(march["from"])
fallen = int(march["guards"] * (0.1 + 0.3 * severity)) if severity else 0
lines.append(f"{march['guards']} guards from {home['city']['name']} stood with us"
+ (f". {fallen} fell." if fallen else "."))
if fallen:
march["militia"] = round(march["militia"] * (march["guards"] - fallen) / march["guards"], 1)
march["guards"] -= fallen
home["city"]["population"] = max(5.0, home["city"]["population"] - fallen)
march.update(status="returning", arrive=now + MARCH_TIME / speed(world))
return lines
def _resolve_raid(world: dict, event: dict, now: float, rng: random.Random) -> None:
city = world["city"]
stock = city["stockpile"]
@ -5663,6 +5871,7 @@ def _resolve_raid(world: dict, event: dict, now: float, rng: random.Random) -> N
gain_xp(world, world["players"][entry["id"]], "combat", round(attack), now)
log(world, now, "raid", f"{upper_first(event["group"])} broke into the city")
shock_mood(world, now, "raid_lost")
lines.extend(_reinforcements_fought(world, wear_share(ratio), 0 if ratio >= 1 else min(1.0, 1 - ratio), now, rng))
report["lines"] = lines
event["report"] = report
_pay_guards(world, report)
@ -5727,6 +5936,8 @@ def _resolve_dragon(world: dict, event: dict, now: float, rng: random.Random) ->
gain_xp(world, world["players"][entry["id"]], "combat", round(attack), now)
log(world, now, "raid", report["title"])
shock_mood(world, now, "dragon_lost")
held = guard["total"] / attack if attack else 9
lines.extend(_reinforcements_fought(world, wear_share(held), 0 if held >= 1 else min(1.0, 1 - held), now, rng))
report["lines"] = lines
event["report"] = report
_pay_guards(world, report)
@ -7377,7 +7588,7 @@ def content() -> dict:
"city_uses": {item: city_uses(item) for item in ITEMS},
"prayers": [{**prayer, "text": describe_prayer(prayer)} for prayer in PRAYERS], "max_prayers": MAX_PRAYERS,
"potion_charges": POTION_CHARGES, "kit_defence": KIT_DEFENCE, "salve_cap": SALVE_CAP, "order_recipes": ORDER_RECIPES, "order_raw": ORDER_RAW,
"make_max": MAKE_MAX, "travel_time": TRAVEL_TIME, "input_share": INPUT_SHARE, "problems": PROBLEMS, "fittings": list(FITTING_BY_ID.values()),
"make_max": MAKE_MAX, "travel_time": TRAVEL_TIME, "march_time": MARCH_TIME, "vote_time": VOTE_TIME, "input_share": INPUT_SHARE, "problems": PROBLEMS, "fittings": list(FITTING_BY_ID.values()),
"equip_slots": EQUIP_SLOTS, "class_speed": CLASS_SPEED, "rest_rate": REST_RATE, "bite": BITE, "eat_below": EAT_BELOW, "eat_choices": EAT_CHOICES,
"abilities": combat.ABILITIES, "enemy_abilities": combat.ENEMY_ABILITIES, "unlock": combat.UNLOCK, "auto_cd": combat.AUTO_CD, "watch": combat.WATCH, "gcd": combat.GCD,
"weapon_kits": combat.WEAPON_KITS, "group_size": GROUP_SIZE, "dungeon_size": DUNGEON_SIZE, "dungeon_wipes": DUNGEON_WIPES, "trade_ability": combat.TRADE_ABILITY, "potion_below": combat.POTION_BELOW,