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

6
app.py
View file

@ -229,7 +229,7 @@ def roster(world: dict, now: float) -> list[dict]:
return sorted(people, key=lambda p: -p["donated"]) return sorted(people, key=lambda p: -p["donated"])
ROAD_ROUTES = ("/api/seen", "/api/pin", "/api/track", "/api/board", "/api/board/delete", "/api/charter/sign", "/api/charter/cancel") # what you can still do on the road ROAD_ROUTES = ("/api/council/propose", "/api/council/vote", "/api/seen", "/api/pin", "/api/track", "/api/board", "/api/board/delete", "/api/charter/sign", "/api/charter/cancel") # what you can still do on the road
class Handler(BaseHTTPRequestHandler): class Handler(BaseHTTPRequestHandler):
@ -364,6 +364,10 @@ class Handler(BaseHTTPRequestHandler):
if path == "/api/travel": if path == "/api/travel":
pouch = body.get("pouch") pouch = body.get("pouch")
return game.travel(world, player, str(body.get("to")), pouch if isinstance(pouch, dict) else {}, now) return game.travel(world, player, str(body.get("to")), pouch if isinstance(pouch, dict) else {}, now)
if path == "/api/council/propose":
return game.propose_march(world, player, str(body.get("from")), str(body.get("to")), body.get("guards"), now)
if path == "/api/council/vote":
return game.vote_march(world, player, body.get("id"), bool(body.get("yes")), now)
if path == "/api/charter": if path == "/api/charter":
return game.propose_charter(world, player, body.get("name"), body.get("region"), now) return game.propose_charter(world, player, body.get("name"), body.get("region"), now)
if path == "/api/charter/sign": if path == "/api/charter/sign":

231
game.py
View file

@ -1684,7 +1684,7 @@ RAID_TRAITS = ["lightly armoured, heavy on archers", "mounted and fast, few bows
# --- world --------------------------------------------------------------- # --- world ---------------------------------------------------------------
WORLD_VERSION = 40 WORLD_VERSION = 41
HOME_CITY = "guildhall" HOME_CITY = "guildhall"
CITY_KEYS = ("events", "next_event_at", "next_minor_at", "next_hardship_at", "next_fortune_at", "caravan", "orders") 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 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 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 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) 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 = {"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 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": {}, "players": {},
"cities": {HOME_CITY: _new_city(now, speed, "Guildhall")}, "cities": {HOME_CITY: _new_city(now, speed, "Guildhall")},
"charter": None, "charter": None,
"marches": [], "council": [], "next_march_id": 1,
"next_event_id": 1, "next_event_id": 1,
"ledger": [], "ledger": [],
"board": [], "board": [],
@ -2057,6 +2062,10 @@ def migrate(world: dict, now: float | None = None) -> World:
raid = upcoming_raid(world) raid = upcoming_raid(world)
world["bank_risk_after"] = raid.get("slot", 0) if raid else 0 world["bank_risk_after"] = raid.get("slot", 0) if raid else 0
world["version"] = 40 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 return world
@ -4671,19 +4680,114 @@ def cancel_charter(world: World, player: dict) -> str | None:
return 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: def kingdom_view(world: World, now: float) -> dict:
"""Every town at a glance, and what's on the road.""" """Every town at a glance, and what's on the road."""
cities = [] cities = []
for key, city in world.doc["cities"].items(): for key, city in world.doc["cities"].items():
people = [p for p in world["players"].values() if p["at"] == key and not p["travel"]] 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"]], cities.append({"id": key, "name": city["name"], "region": city.get("region"), "town_scale": TOWN_SCALE[city["tier"]],
"population": int(city["population"]), "population": int(city["population"]),
"tier": TIERS[city["tier"]]["name"], "repelled": city["repelled"], "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"] charter = world["charter"]
return {"cities": cities, "charter": charter, "pouch": {"slots": POUCH_SLOTS, "stack": POUCH_STACK}, return {"cities": cities, "charter": charter, "pouch": {"slots": POUCH_SLOTS, "stack": POUCH_STACK},
"founding": FOUNDING, "max": MAX_CITIES, "short": _founding_short(world), "founding": FOUNDING, "max": MAX_CITIES, "short": _founding_short(world),
"regions": REGIONS, "region_yield": REGION_YIELD, "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")}} "road": [{"id": p["id"], **{k: p["travel"][k] for k in ("from", "to", "arrive")}}
for p in world["players"].values() if p["travel"]]} 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)) 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: def guards_on_duty(world: dict) -> int:
"""Guards whose wage for the coming threat is in the chest.""" """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: 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"] stock = city["stockpile"]
posts = guard_posts(world) posts = guard_posts(world)
armed = guards_on_duty(world) if guards is None else min(guards, posts) 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) militia = _militia(world)
* mood(world)["militia"])
parts = { parts = {
"townsfolk": 10, "townsfolk": 10,
"walls": 20 * building_level(world, "walls") + 25 * fitted(world, "hoardings"), "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: if guards is not None:
return {"total": round(sum(parts.values()), 1), "parts": parts} 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 = [] garrison = []
for player in world["players"].values(): for player in world["players"].values():
if player["garrison"] and player["at"] == world.here: if player["garrison"] and player["at"] == world.here:
@ -5137,8 +5266,9 @@ def defence(world: dict, guards: int | None = None) -> dict:
if city["starving"]: if city["starving"]:
total *= 0.8 total *= 0.8
return {"parts": parts, "garrison": garrison, "total": round(total, 1), "starving": city["starving"], 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, "guards": armed, "posts": posts, "away": guards_away(world), "wages": int(city.get("wages", 0)), "wage": GUARD_WAGE,
"kit": {slot: issued_kit(world, slot, posts) for slot in KIT_DEFENCE}} "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: 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: 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.""" """Put gold in the barracks' wage chest, from your purse (earns favour) or the treasury."""
city = world["city"] 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: if room <= 0:
return "Every post is paid for" return "Every post is paid for"
have = player["gold"] if source == "bank" else int(city["treasury"]) if source == "city" else None 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 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: 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.""" """Advance every town and its events to `now`. Returns True if anything changed."""
rng = rng or random.Random() rng = rng or random.Random()
changed = False changed = _muster_tick(world, now)
for key in list(world.doc["cities"]): for key in list(world.doc["cities"]):
changed = _tick_city(world.at(key), now, rng) or changed changed = _tick_city(world.at(key), now, rng) or changed
return 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"]) 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]: def _threats_elsewhere(world: World) -> list[dict]:
"""The threats coming for the other towns.""" """The threats coming for the other towns."""
return [event for key, city in world.doc["cities"].items() if key != world.here 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)) 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) 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 = 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. # How big it looks is measured against what the city holds without preparing.
event["standing"] = round(max(1.0, standing_defence(world)), 1) event["standing"] = round(max(1.0, standing_defence(world)), 1)
if kind == "dragon": 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": int(min(event["recon"], costs[-1])), "recon_full": costs[-1],
"recon_next": max(0, round(costs[level] - event["recon"])) if level < 3 else 0, "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": if event["kind"] == "dragon":
strength = event["strength"] strength = event["strength"]
view["headline"] = "Herders whisper of scorched pastures in the hills." 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 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: def _resolve_raid(world: dict, event: dict, now: float, rng: random.Random) -> None:
city = world["city"] city = world["city"]
stock = city["stockpile"] 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) gain_xp(world, world["players"][entry["id"]], "combat", round(attack), now)
log(world, now, "raid", f"{upper_first(event["group"])} broke into the city") log(world, now, "raid", f"{upper_first(event["group"])} broke into the city")
shock_mood(world, now, "raid_lost") 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 report["lines"] = lines
event["report"] = report event["report"] = report
_pay_guards(world, 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) gain_xp(world, world["players"][entry["id"]], "combat", round(attack), now)
log(world, now, "raid", report["title"]) log(world, now, "raid", report["title"])
shock_mood(world, now, "dragon_lost") 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 report["lines"] = lines
event["report"] = report event["report"] = report
_pay_guards(world, report) _pay_guards(world, report)
@ -7377,7 +7588,7 @@ def content() -> dict:
"city_uses": {item: city_uses(item) for item in ITEMS}, "city_uses": {item: city_uses(item) for item in ITEMS},
"prayers": [{**prayer, "text": describe_prayer(prayer)} for prayer in PRAYERS], "max_prayers": MAX_PRAYERS, "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, "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, "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, "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, "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,

View file

@ -775,7 +775,7 @@ function sidebar() {
<div class="navhead">City</div> <div class="navhead">City</div>
${nav("town", "🏘️", "Town square", `${S.city.population}`, "", `Population ${S.city.population}`)} ${nav("town", "🏘️", "Town square", `${S.city.population}`, "", `Population ${S.city.population}`)}
${nav("council", "📜", "Council & threats", "", raid ? `<span class="alert"></span>` : "", raid ? "A threat is coming" : "")} ${nav("council", "📜", "Council & threats", "", raid ? `<span class="alert"></span>` : "", raid ? "A threat is coming" : "")}
${nav("kingdom", "🗺️", "Kingdom", `${S.kingdom.cities.length}`, S.kingdom.charter ? `<span class="badge">sign</span>` : "", S.kingdom.charter ? "A charter is waiting to be signed" : "")} ${nav("kingdom", "🗺️", "Kingdom", `${S.kingdom.cities.length}`, S.kingdom.charter ? `<span class="badge">sign</span>` : votesWaiting() ? `<span class="badge">${votesWaiting()}</span>` : "", S.kingdom.charter ? "A charter is waiting to be signed" : votesWaiting() ? "The war council wants your vote" : "")}
${nav("orders", ORDER_ICON(), "Work orders", "", takeable ? `<span class="badge">${takeable}</span>` : "", takeable ? `${takeable} for you` : "")} ${nav("orders", ORDER_ICON(), "Work orders", "", takeable ? `<span class="badge">${takeable}</span>` : "", takeable ? `${takeable} for you` : "")}
${nav("board", "💬", "Town board")} ${nav("board", "💬", "Town board")}
${rosterNav()} ${rosterNav()}
@ -935,6 +935,43 @@ function pageHtml() {
// --- kingdom ---------------------------------------------------------------- // --- kingdom ----------------------------------------------------------------
let pouch = {}; let pouch = {};
function votesWaiting() {
return S.kingdom.council.filter((p) => p.status === "open" && !p.yes.includes(S.uid) && !p.no.includes(S.uid)).length;
}
function threatLine(t) {
if (!t) return `<p class="small muted">No threat rumoured</p>`;
const size = t.strength ? fmt(t.strength) : t.range ? `${fmt(t.range[0])} - ${fmt(t.range[1])}` : t.size || "?";
return `<p class="small">${eventIcon(t.kind)} ${eventWhen(t, true)} · ${esc(String(size))}${t.main ? ` <span class="tag warn" title="The bandits' main assault">Main assault</span>` : ""}</p>`;
}
function warTable() {
const k = S.kingdom, me = S.me;
const proposal = (p) => {
const open = p.status === "open", mine = p.yes.includes(S.uid) ? "yes" : p.no.includes(S.uid) ? "no" : null;
const result = { sent: "🛤️ Sent", rejected: "Kept home", failed: "No guards" }[p.status];
return `<div class="council-row small"><span>💂 ${fmt(p.guards)} · ${esc(townName(p.from))} → ${esc(townName(p.to))} · ${esc(playerName(p.by))}</span>
<span>✅ ${p.yes.length} ❌ ${p.no.length}${open ? ` · ⏳ ${dur(Math.max(0, p.ends - S.now))}` : ` · ${result}`}</span>
${open ? `<span><button class="btn sm ${mine === "yes" ? "primary" : ""}" data-vote="${p.id}" data-yes="1">✅</button> <button class="btn sm ${mine === "no" ? "primary" : ""}" data-vote="${p.id}" data-yes="0">❌</button></span>` : "<span></span>"}</div>`;
};
const march = (m) => {
const target = k.cities.find((c) => c.id === m.to);
const known = target?.threat && (target.threat.exact || target.threat.latest);
const late = m.status === "marching" && known && m.arrive > known;
const text = { marching: `🛤️ ${dur(Math.max(0, m.arrive - S.now))}`, there: `🛡️ +${fmt(m.power)}`, returning: `🏠 ${dur(Math.max(0, m.arrive - S.now))}` }[m.status];
return `<div class="council-row small"><span>💂 ${fmt(m.guards)} · ${esc(townName(m.from))} → ${esc(townName(m.to))}</span><span>${text}${late ? ` <span class="tag warn">Late</span>` : ""}</span><span></span></div>`;
};
const options = (key) => k.cities.map((c) => `<option value="${esc(c.id)}">${esc(c.name)}</option>`).join("");
return `<div class="panel" style="margin-top:14px"><h2>War council</h2>
${k.council.map(proposal).join("")}
${k.marches.map(march).join("")}
<div class="pouch-row"><select data-keep="march-from">${options()}</select> → <select data-keep="march-to">${options()}</select>
<input type="number" min="1" value="10" data-keep="march-guards" style="width:80px" title="Guards">
<button class="btn primary" data-march-propose>📜 Propose</button></div>
<p class="small muted">🛤️ ${dur(C.march_time / S.city_speed)} · vote ${dur(C.vote_time / S.city_speed)} · one fight, then home</p>
</div>`;
}
function regionPerks(region, scale) { function regionPerks(region, scale) {
const y = S.kingdom.region_yield; const y = S.kingdom.region_yield;
return `${region.skills.map((id) => skillOf(id).icon).join("")} +${pct(y[0] * scale)} → +${pct(y.at(-1) * scale)}`; return `${region.skills.map((id) => skillOf(id).icon).join("")} +${pct(y[0] * scale)} → +${pct(y.at(-1) * scale)}`;
@ -952,7 +989,9 @@ function kingdom() {
const region = k.regions[c.region]; const region = k.regions[c.region];
return `<div class="panel"> return `<div class="panel">
<h2>${esc(c.name)} ${here ? `<span class="tag">📍 Here</span>` : ""}</h2> <h2>${esc(c.name)} ${here ? `<span class="tag">📍 Here</span>` : ""}</h2>
<p class="small">${esc(c.tier)} · 👥 ${fmt(c.population)} · 🛡️ ${fmt(c.repelled)}${road ? ` · 🛤️ ${road}` : ""}</p> <p class="small">${esc(c.tier)} · 👥 ${fmt(c.population)} · 🏆 ${fmt(c.repelled)}${road ? ` · 🛤️ ${road}` : ""}</p>
${threatLine(c.threat)}
<p class="small" title="Defence · guards paid and at their posts · away">🛡️ ${fmt(c.defence)} · 💂 ${fmt(c.guards)} / ${fmt(c.posts - c.away)}${c.away ? ` · 🛤️ ${fmt(c.away)}` : ""}${c.garrison.length ? ` · 🏰 ${c.garrison.map((uid) => esc(playerName(uid))).join(", ")}` : ""}</p>
${region ? `<p class="small" title="More per trip, by material tier. Grows with the town.">${region.icon} ${esc(region.name)} · ${regionPerks(region, c.town_scale)}</p>` : ""} ${region ? `<p class="small" title="More per trip, by material tier. Grows with the town.">${region.icon} ${esc(region.name)} · ${regionPerks(region, c.town_scale)}</p>` : ""}
<p class="small">${c.people.length ? c.people.map((uid) => esc(playerName(uid))).join(", ") : `<span class="muted">Nobody here</span>`}</p> <p class="small">${c.people.length ? c.people.map((uid) => esc(playerName(uid))).join(", ") : `<span class="muted">Nobody here</span>`}</p>
${here || me.travel ? "" : `<button class="btn primary" data-travel="${esc(c.id)}">🛤️ Travel (${dur(C.travel_time / S.city_speed)})</button>`} ${here || me.travel ? "" : `<button class="btn primary" data-travel="${esc(c.id)}">🛤️ Travel (${dur(C.travel_time / S.city_speed)})</button>`}
@ -984,7 +1023,8 @@ function kingdom() {
<div class="grid" style="margin-top:14px"> <div class="grid" style="margin-top:14px">
<div class="panel"><h2>${me.travel ? "On the road" : "Travel pouch"}</h2>${pack}</div> <div class="panel"><h2>${me.travel ? "On the road" : "Travel pouch"}</h2>${pack}</div>
<div class="panel"><h2>Found a town</h2>${founding}</div> <div class="panel"><h2>Found a town</h2>${founding}</div>
</div>`; </div>
${k.cities.length > 1 ? warTable() : ""}`;
} }
// Where an item comes from: the recipe that makes it, else what finds it, else the fight that drops it. // Where an item comes from: the recipe that makes it, else what finds it, else the fight that drops it.
@ -2505,7 +2545,7 @@ function foodKinds(r) {
function armoury(d) { function armoury(d) {
const slots = { weapon: "Weapons", shield: "Shields", jerkin: "Body armour", salve: "Salves" }; const slots = { weapon: "Weapons", shield: "Shields", jerkin: "Body armour", salve: "Salves" };
return Object.entries(slots).map(([slot, label]) => { return Object.entries(slots).map(([slot, label]) => {
const issued = d.kit[slot] || [], bare = d.posts - issued.reduce((n, [, q]) => n + q, 0); const issued = d.kit[slot] || [], bare = d.posts - d.away - issued.reduce((n, [, q]) => n + q, 0);
let seat = 0; let seat = 0;
const chips = [...issued, ...(bare > 0 ? [[null, bare]] : [])].flatMap(([id, qty]) => { const chips = [...issued, ...(bare > 0 ? [[null, bare]] : [])].flatMap(([id, qty]) => {
const paid = Math.max(0, Math.min(qty, d.guards - seat)); const paid = Math.max(0, Math.min(qty, d.guards - seat));
@ -2521,14 +2561,14 @@ function armoury(d) {
function raidPrep(ev) { function raidPrep(ev) {
const city = S.city, me = S.me, d = city.defence; const city = S.city, me = S.me, d = city.defence;
const names = { mercenaries: "Hired sellswords", ward: "Divine ward (temple)", rallied: "Rallied militia (favour)", drilled: "Drilled militia", townsfolk: "Townsfolk with pitchforks", walls: "Walls", militia: "Paid guards (barracks)", weapons: "Weapons the guards hold", shields: "Shields the guards hold", jerkins: "Body armour the guards wear", salves: "Salves", arrows: "Arrows", garrison: "Garrison" }; const names = { mercenaries: "Hired sellswords", ward: "Divine ward (temple)", rallied: "Rallied militia (favour)", drilled: "Drilled militia", townsfolk: "Townsfolk with pitchforks", walls: "Walls", militia: "Paid guards (barracks)", weapons: "Weapons the guards hold", shields: "Shields the guards hold", jerkins: "Body armour the guards wear", salves: "Salves", arrows: "Arrows", garrison: "Garrison", reinforcements: "Reinforcements" };
const full = d.posts * d.wage, owed = Math.max(0, full - d.wages); const full = (d.posts - d.away) * d.wage, owed = Math.max(0, full - d.wages);
const reqs = (ev.requests || []).map(reqRow).join(""); const reqs = (ev.requests || []).map(reqRow).join("");
return `<div class="cols"> return `<div class="cols">
<div class="panel"><h2>Raid readiness</h2>${reqs} <div class="panel"><h2>Raid readiness</h2>${reqs}
<p class="small muted">Stockpile gear arms the defenders, best first. Fights use up arrows and break some gear.</p> <p class="small muted">Stockpile gear arms the defenders, best first. Fights use up arrows and break some gear.</p>
<h2 style="margin-top:16px">Armoury</h2>${armoury(d)}</div> <h2 style="margin-top:16px">Armoury</h2>${armoury(d)}</div>
<div class="panel"><h2>Guards · ${d.guards} / ${d.posts} paid</h2> <div class="panel"><h2>Guards · ${d.guards} / ${d.posts - d.away} paid${d.away ? ` · 🛤️ ${d.away} away` : ""}${d.helping.length ? ` · +${d.helping.reduce((n, h) => n + h.guards, 0)} here` : ""}</h2>
<p class="small">Wage chest ${COIN} ${fmt(d.wages)} / ${fmt(full)} · ${d.wage} gold a guard per threat</p> <p class="small">Wage chest ${COIN} ${fmt(d.wages)} / ${fmt(full)} · ${d.wage} gold a guard per threat</p>
<div class="bar"><span style="width:${full ? Math.min(100, d.wages / full * 100) : 0}%"></span></div> <div class="bar"><span style="width:${full ? Math.min(100, d.wages / full * 100) : 0}%"></span></div>
<div class="btns" style="margin-top:8px"> <div class="btns" style="margin-top:8px">
@ -3345,6 +3385,10 @@ document.addEventListener("click", (e) => {
if (d.install) return act("/api/install", { fitting: d.install, source: d.source }); if (d.install) return act("/api/install", { fitting: d.install, source: d.source });
if ("plot" in d) return act("/api/plot", { id: d.plot || null }); if ("plot" in d) return act("/api/plot", { id: d.plot || null });
if (d.garrison) return act("/api/garrison", { join: d.garrison === "1" }); if (d.garrison) return act("/api/garrison", { join: d.garrison === "1" });
if ("marchPropose" in d) {
return act("/api/council/propose", { from: $("[data-keep=march-from]").value, to: $("[data-keep=march-to]").value, guards: Number($("[data-keep=march-guards]").value) });
}
if (d.vote) return act("/api/council/vote", { id: Number(d.vote), yes: d.yes === "1" });
if (d.travel) { if (d.travel) {
if (!confirm(`Travel to ${townName(d.travel)}? Work stops on the road.`)) return; if (!confirm(`Travel to ${townName(d.travel)}? Work stops on the road.`)) return;
const sent = pouch; const sent = pouch;

View file

@ -955,3 +955,5 @@ button.swatch { width: 36px; height: 36px; }
.pouch-row { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; margin-top: 8px; } .pouch-row { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; margin-top: 8px; }
.pouch-row select, .pouch-row input[type=text] { min-width: 0; flex: 1 1 140px; } .pouch-row select, .pouch-row input[type=text] { min-width: 0; flex: 1 1 140px; }
.council-row { display: grid; grid-template-columns: minmax(0, 1fr) auto auto; gap: 10px; align-items: center; padding: 6px 0; border-bottom: 1px solid rgba(255, 255, 255, .06); }
@media (max-width: 520px) { .council-row { grid-template-columns: minmax(0, 1fr) auto; } }

View file

@ -3850,6 +3850,197 @@ class KingdomTest(unittest.TestCase):
game.log(new, T0, "raid", "Trouble") game.log(new, T0, "raid", "Trouble")
self.assertIn("Saltmere", self.world["ledger"][-1]["text"]) self.assertIn("Saltmere", self.world["ledger"][-1]["text"])
def garrisoned_home(self):
"""The capital with a full paid barracks and kit."""
city = self.world["city"]
city["buildings"]["barracks"]["level"] = 5
city["wages"] = game.guard_posts(self.world) * game.GUARD_WAGE
city["stockpile"].update(copper_sword=50)
for player in (self.a, self.b):
player["last_active"] = T0
def send(self, to, guards=30, now=T0):
self.a["last_active"] = self.b["last_active"] = now
self.assertIsNone(game.propose_march(self.world, self.a, game.HOME_CITY, to, guards, now))
return self.world["council"][-1]
def test_a_march_goes_on_a_majority_and_takes_kit_and_wage(self):
new = self.found()
self.garrisoned_home()
posts, wages = game.guards_on_duty(self.world), self.world["city"]["wages"]
proposal = self.send(new.here)
self.assertEqual(proposal["status"], "open")
self.assertIsNone(game.vote_march(self.world, self.b, proposal["id"], True, T0))
self.assertEqual(proposal["status"], "sent")
march = self.world["marches"][0]
self.assertEqual(march["guards"], 30)
self.assertEqual(march["kit"]["copper_sword"], 30)
self.assertEqual(self.world["city"]["stockpile"]["copper_sword"], 20)
self.assertEqual(self.world["city"]["wages"], wages - 30 * game.GUARD_WAGE)
self.assertEqual(game.guards_on_duty(self.world), posts - 30)
def test_the_votes_cast_decide_when_the_hour_is_up(self):
new = self.found()
self.garrisoned_home()
self.world["players"]["c"] = game.new_player("c", "Cy", "miner", T0)
self.world["players"]["d"] = game.new_player("d", "Di", "miner", T0)
proposal = self.send(new.here)
game.tick(self.world, T0 + game.VOTE_TIME - 1, random.Random(1))
self.assertEqual(proposal["status"], "open")
game.tick(self.world, T0 + game.VOTE_TIME, random.Random(1))
self.assertEqual(proposal["status"], "sent")
def test_a_tie_keeps_the_guards_home(self):
new = self.found()
self.garrisoned_home()
self.world["players"]["c"] = game.new_player("c", "Cy", "miner", T0)
self.world["players"]["d"] = game.new_player("d", "Di", "miner", T0)
proposal = self.send(new.here)
game.vote_march(self.world, self.b, proposal["id"], False, T0)
game.tick(self.world, T0 + game.VOTE_TIME, random.Random(1))
self.assertEqual(proposal["status"], "rejected")
self.assertEqual(self.world["marches"], [])
def test_one_march_per_town_before_the_council(self):
new = self.found()
self.garrisoned_home()
self.world["players"]["c"] = game.new_player("c", "Cy", "miner", T0)
self.world["players"]["d"] = game.new_player("d", "Di", "miner", T0)
self.send(new.here)
self.assertIn("already", game.propose_march(self.world, self.b, game.HOME_CITY, new.here, 5, T0))
def test_you_cant_send_more_than_are_paid_and_posted(self):
new = self.found()
self.garrisoned_home()
too_many = game.guards_on_duty(self.world) + 1
self.assertIn("paid", game.propose_march(self.world, self.a, game.HOME_CITY, new.here, too_many, T0))
def march(self, new, guards=30):
self.b["last_active"] = self.a["last_active"] = T0
proposal = self.send(new.here, guards)
game.vote_march(self.world, self.b, proposal["id"], True, T0)
return self.world["marches"][0]
def test_marching_guards_count_only_once_they_arrive(self):
new = self.found()
self.garrisoned_home()
march = self.march(new)
self.assertNotIn("reinforcements", game.defence(new)["parts"])
game._muster_tick(self.world, T0 + game.MARCH_TIME)
self.assertEqual(march["status"], "there")
self.assertEqual(game.defence(new)["parts"]["reinforcements"], game.march_power(march))
self.assertGreater(game.march_power(march), 0)
def test_posts_stay_empty_while_their_guards_are_away(self):
new = self.found()
self.garrisoned_home()
before = game.guards_on_duty(self.world)
self.march(new)
self.world["city"]["wages"] = 10**6
self.assertEqual(game.guards_on_duty(self.world), game.guard_posts(self.world) - 30)
self.assertLess(game.guards_on_duty(self.world), before)
def test_home_defence_falls_by_about_what_arrives(self):
new = self.found()
self.garrisoned_home()
home_before = game.defence(self.world)["total"]
march = self.march(new)
game._muster_tick(self.world, T0 + game.MARCH_TIME)
self.assertAlmostEqual(home_before - game.defence(self.world)["total"], game.march_power(march), delta=1)
def test_a_late_company_turns_back(self):
new = self.found()
self.garrisoned_home()
game.tick(self.world, T0 + 1, random.Random(4))
threat = game.upcoming_raid(new)
march = self.march(new)
march["for"] = threat["slot"]
threat["status"] = "done"
game._muster_tick(self.world, T0 + game.MARCH_TIME)
self.assertEqual(march["status"], "returning")
def test_after_the_fight_they_march_home_with_their_kit(self):
new = self.found()
self.garrisoned_home()
march = self.march(new)
game._muster_tick(self.world, T0 + game.MARCH_TIME)
now = T0 + game.MARCH_TIME + 10
lines = game._reinforcements_fought(new, 0.1, 0, now, random.Random(1))
self.assertIn("stood with us", lines[0])
self.assertEqual(march["status"], "returning")
self.assertLessEqual(march["kit"]["copper_sword"], 30)
left = march["kit"]["copper_sword"]
game._muster_tick(self.world, now + game.MARCH_TIME)
self.assertEqual(self.world["marches"], [])
self.assertEqual(self.world["city"]["stockpile"]["copper_sword"], 20 + left)
self.assertEqual(game.guards_away(self.world), 0)
def test_a_lost_fight_kills_guards_and_home_mourns(self):
new = self.found()
self.garrisoned_home()
march = self.march(new)
game._muster_tick(self.world, T0 + game.MARCH_TIME)
pop = self.world["city"]["population"]
lines = game._reinforcements_fought(new, 0.4, 0.5, T0 + game.MARCH_TIME, random.Random(1))
self.assertIn("fell", lines[0])
self.assertEqual(march["guards"], 30 - int(30 * 0.25))
self.assertEqual(self.world["city"]["population"], pop - int(30 * 0.25))
def test_reinforcements_turn_a_raid(self):
new = self.found()
self.garrisoned_home()
march = self.march(new)
game._muster_tick(self.world, T0 + game.MARCH_TIME)
now = T0 + game.MARCH_TIME + 5
new["events"].append({"id": 901, "kind": "raid", "status": "upcoming", "fire_at": now, "slot": now, "strength": game.defence(new)["total"] - 1,
"sabotage": 0.0, "recon": 0, "jitter": 0, "group": "the Red Hand", "trait": "x", "announced": T0})
self.world["bank_risk_after"] = now + 1
game.tick(self.world, now, random.Random(1))
report = next(e for e in new["events"] if e["id"] == 901)["report"]
self.assertTrue(report["title"].startswith("Victory"))
self.assertGreater(report["parts"]["reinforcements"], 0)
self.assertEqual(march["status"], "returning")
def big_towns(self):
new = self.found()
new["city"]["tier"] = game.MAIN_TIER
new["city"]["population"] = 90.0
return new
def test_main_assault_keeps_the_kingdom_total(self):
new = self.big_towns()
total = sum(game.threat_base(world, T0) for world in (self.world, new))
shifts = []
for world in (self.world, new):
base = game.threat_base(world, T0)
shifts.append(base + game._assault_shift(world, {"slot": 1234.0}, base, T0))
self.assertAlmostEqual(sum(shifts), total)
def test_every_town_agrees_who_takes_the_main_assault(self):
new = self.big_towns()
for slot in range(40):
events = [{"slot": float(slot)}, {"slot": float(slot)}]
game._assault_shift(self.world, events[0], game.threat_base(self.world, T0), T0)
game._assault_shift(new, events[1], game.threat_base(new, T0), T0)
self.assertNotEqual(events[0]["main"], events[1]["main"])
def test_main_assault_needs_two_big_towns(self):
new = self.found()
event = {"slot": 1.0}
self.assertEqual(game._assault_shift(self.world, event, 100.0, T0), 0.0)
self.assertEqual(game._assault_shift(new, event, 100.0, T0), 0.0)
self.assertNotIn("main", event)
def test_scouts_only_spot_the_main_assault_at_full_intel(self):
new = self.big_towns()
game.tick(self.world, T0 + 1, random.Random(4))
threat = game.upcoming_raid(new) or game.upcoming_raid(self.world)
threat["main"] = True
world = new if threat in new["events"] else self.world
self.assertNotIn("main", game.event_view(world, threat, T0 + 1))
threat["recon"] = 10**6
self.assertIn("main", game.event_view(world, threat, threat["fire_at"] - 3600))
def test_old_saves_gain_towns(self): def test_old_saves_gain_towns(self):
doc = json.loads(json.dumps(self.world.doc)) doc = json.loads(json.dumps(self.world.doc))
doc["version"] = 39 doc["version"] = 39