"""The campaign (Project 02, Step 3a; Dillon's design, 2026-11-10). You run a warband of US Army remnants out of the ruins of Fort Leonard Wood. The regions around it (data.REGIONS: real counties) are each contested by two groups: warlords, militias, fiefdoms. Every region has a dilemma, and comes down to one of them. LEAN each region leans from -100 (all its second group) to +100 (all its first). A mission is FOR one group and AGAINST the other: win it and the region leans the way of the group you helped (LEAN_WON); lose it, or let it expire, and it leans the other way. CONTROL at either end, that group takes the region for good. If you did more for them than for their rival, they're your ALLY: the fort gains their assets (weekly income, perks for every soldier, unlocks for later steps) and the rival's are lost for good, plus intel, recruits and supplies every week (ALLY_GIVES). If you didn't, they're HOSTILE. WIN/LOSE WIN_REGIONS allied regions win the campaign; LOSE_REGIONS hostile ones lose it. THE FORT pays a little every week (FORT_GIVES). Supplies hire recruits (if the pool has any); intel sends scouts out to turn up a mission now. FACILITIES (Step 3d) built in the fort's ruins, one project at a time, each on a plot: the machine shop (cheaper gear), infirmary (faster healing), drill yard (more XP) and radio room (intel, and missions that wait longer). Level 2 needs an ally's asset. Every level costs upkeep out of the week's supplies (data.FACILITIES). THE UNIT (Step 3b) Squad 1 and Squad 2, up to SQUAD_SIZE each, make the unit that goes out. It travels on foot, on animals or in vehicles (data.TRAVEL: tiers; animals and vehicles come from allies' assets). The fort runs on while it travels: days pass on the way out, and the way home keeps the soldiers tired as long again. Soldiers carry over from Step 2: a battle (tactics.py) with the unit you pick from who's ready. Downed in a battle you win, a soldier may pull through (DOWNED_LIVE) and is carried home; downed in a battle you lose is dead. Survivors come home wounded and tired, with XP, ranks and skills. Pure logic. Numbers in data.py. Saves to JSON (save/load), dice included. """ from __future__ import annotations import json import math import random from dataclasses import asdict, dataclass, field from pathlib import Path from . import data as D from .tactics import Battle STATS = ("hp", "aim", "mobility", "defense", "clip", "crit", "grenades", "medkits") class CampaignError(ValueError): """Something the campaign won't let you do. The message is shown as-is.""" @dataclass class Soldier: name: str cls: str xp: int = 0 rank: int = 0 skills: list = field(default_factory=list) pending: int = 0 wounded_until: int = 0 tired_until: int = 0 dead: bool = False kills: int = 0 missions: int = 0 weapon: str = "" # the family carried ("" = the class's own); Step 3c weapon_tier: int = 0 pistol_tier: int = 0 armor: str = "fatigues" # data.ARMOR; Step 3c part 2 utility: list = field(default_factory=list) # data.UTILITY items, one a slot record: list = field(default_factory=list) # every mission: {day, region, kind, for, against, won, kills, hurt} fate: dict | None = None # gone: {how ("killed in action" / "missing in action"), day, where, story} def family(self): return self.weapon or D.CLASSES[self.cls]["weapon"] def gun(self): """-> data.WEAPONS key of the weapon carried.""" return D.weapon_key(self.family(), self.weapon_tier) def pistol(self): return D.weapon_key("pistol", self.pistol_tier) def status(self, day): if self.dead: return "missing" if self.fate and self.fate["how"] == "missing in action" else "dead" if self.wounded_until > day: return f"wounded, {self.wounded_until - day} days" if self.tired_until > day: return f"tired, {self.tired_until - day} days" return "ready" @dataclass class Region: lean: int = 0 helped: list = field(default_factory=lambda: [0, 0]) # missions won for each group owner: int | None = None # 0 / 1 once a group holds it ally: bool | None = None # did they take it with your help? @dataclass class Mission: id: int region: str group: int | None # the group you back (0 or 1; you fight the other), None till you pick kind: str expires: int pods: list # the other side's fighters (made when you pick, if None till then) def sides(self): """The county's two groups, as (group 0, group 1).""" return tuple(g["name"] for g in D.REGIONS[self.region]["groups"]) def names(self): """(the group you back, the one you fight); before you've picked: the two, in order.""" a, b = self.sides() return (a, b) if self.group in (None, 0) else (b, a) def about(self): k = D.MISSION_KINDS[self.kind] if self.group is None: a, b = self.sides() return k["clash"].format(a=a, b=b) helped, fought = self.names() return k["about"].format(**{"for": helped, "against": fought}) @dataclass class Campaign: seed: int day: int = 1 supplies: int = D.START["supplies"] intel: int = D.START["intel"] recruits: int = D.START["recruits"] roster: list = field(default_factory=list) regions: dict = field(default_factory=dict) missions: list = field(default_factory=list) next_mission: int = 1 next_id: int = 1 log: list = field(default_factory=list) outcome: str | None = None rng_state: list | None = None trip: dict | None = None # the unit out: {"mission", "region", "travel", "days", "heal", "rest", # "squads", "gone": road days passed, "stage": "road" | "battle"} convoy: dict = field(default_factory=dict) # travel mode -> its utility items (3c part 3) facilities: dict = field(default_factory=dict) # facility -> level built (Step 3d) plots: int = D.PLOTS project: dict | None = None # what the build crew is on: {"what", "level", "done"} affinity: dict = field(default_factory=dict) # ":" -> your standing, 0..100 stock: dict = field(default_factory=dict) # ":" -> {"recruits": n, "items": {item: n}}: # what they've put by for your caravans (Step 4 part 3) store: dict = field(default_factory=dict) # item -> how many: what caravans have brought home # ── dice that survive a save ── @property def rng(self): r = random.Random() if self.rng_state is None: r.seed(self.seed) else: r.setstate((self.rng_state[0], tuple(self.rng_state[1]), self.rng_state[2])) return r def keep(self, r): st = r.getstate() self.rng_state = [st[0], list(st[1]), st[2]] # ── derived ── def allies(self): """[(region id, group dict)] for every region held by a group you helped to it.""" return [(rid, D.REGIONS[rid]["groups"][r.owner]) for rid, r in self.regions.items() if r.owner is not None and r.ally] def hostile(self): return [rid for rid, r in self.regions.items() if r.owner is not None and not r.ally] def unlocks(self): """Assets you have: every ally's, and every group's you stand at the top tier with.""" top = D.AFFINITY_TIERS[-1][0] mine = [g for _, g in self.allies()] + [D.REGIONS[rid]["groups"][g] for rid in D.REGIONS for g in (0, 1) if self.standing(rid, g) >= top] return sorted({u for g in mine for u in g.get("unlocks", [])}) def standing(self, rid, g): """Your affinity with group g of county rid, 0..100.""" return self.affinity.get(f"{rid}:{g}", 0) def pile(self, rid, g): """What group g of county rid has put by for you -> {"recruits": n, "items": {item: n}}.""" return self.stock.setdefault(f"{rid}:{g}", {"recruits": 0, "items": {}}) def trades(self, rid, g): """Will they send goods your way: tier 1 or better, or they're your ally?""" reg = self.regions[rid] return self.tier(rid, g) >= 1 or (reg.owner == g and bool(reg.ally)) def tier(self, rid, g): """How many affinity tiers you've reached with them (0: none yet).""" return sum(self.standing(rid, g) >= at for at, _ in D.AFFINITY_TIERS) def lost(self): """Assets gone for good: what the fallen group of every decided region had.""" gone = set() for rid, r in self.regions.items(): if r.owner is not None: gone |= set(D.REGIONS[rid]["groups"][1 - r.owner].get("unlocks", [])) return sorted(gone - set(self.unlocks())) def weekly(self): """What the fort takes in each week: its own, plus every ally's, less the facilities' upkeep.""" out = dict(D.FORT_GIVES) for _, g in self.allies(): for k, v in D.ALLY_GIVES.items(): out[k] += v for k, v in g.get("gives", {}).items(): out[k] += v out["intel"] += self.effect("radio room", "intel", 0) out["supplies"] -= self.upkeep() return out def level(self, facility): return self.facilities.get(facility, 0) def effect(self, facility, key, default): """What the built level of a facility gives (default if it isn't built).""" lv = self.level(facility) return D.FACILITIES[facility]["levels"][lv - 1][key] if lv else default def upkeep(self): return sum(D.FACILITIES[f]["levels"][i]["upkeep"] for f, lv in self.facilities.items() for i in range(lv)) def price(self, cost): """A gear or convoy price, after the machine shop's discount (rounded up).""" return -(-cost * (100 - self.effect("machine shop", "discount", 0)) // 100) def ready(self): return [s for s in self.roster if s.status(self.day) == "ready"] def soldier(self, name): s = next((s for s in self.roster if s.name == name and not s.dead), None) if s is None: raise CampaignError(f"no soldier called {name}") return s def extra(self, s): """What ranks, skills and allies' perks add to a soldier's class (tactics.soldier).""" out = dict.fromkeys(STATS, 0) out["aim"] += D.RANK_AIM * s.rank out["hp"] += s.rank // 2 options = dict(opt for tier in D.SKILLS[s.cls] for opt in tier) for name in s.skills: for k, v in options[name].items(): out[k] += v for _, g in self.allies(): for k, v in g.get("perks", {}).items(): out[k] += v for k, v in D.ARMOR[s.armor].items(): if k in ("hp", "armor", "defense", "mobility"): out[k] = out.get(k, 0) + v for item in s.utility: for k, v in D.UTILITY[item].items(): if k in ("clip", "grenades", "medkits", "smoke", "flashbangs"): out[k] = out.get(k, 0) + v return {k: v for k, v in out.items() if v} def heal_factor(self): f = self.effect("infirmary", "heal", 1.0) for _, g in self.allies(): f *= g.get("heal", 1.0) return f def say(self, line): self.log.append(f"Day {self.day}: {line}") # ── the road ── _MAP = None def region_km(rid): """Straight-line km from the fort to the middle of region rid (the Census map, missouri.json: the average of its counties' outline centres).""" global _MAP if _MAP is None: _MAP = json.loads(Path(__file__).with_name("missouri.json").read_text()) by_name = {c["name"].removesuffix(" County"): c for c in _MAP["counties"].values()} pts = [] for n in D.REGIONS[rid]["counties"]: ring = max(by_name[n]["outline"], key=len) pts.append((sum(x for x, _ in ring) / len(ring), sum(y for _, y in ring) / len(ring))) centre = (sum(x for x, _ in pts) / len(pts), sum(y for _, y in pts) / len(pts)) return math.dist(centre, _MAP["fort"]) def travel_days(rid, mode): return max(1, math.ceil(region_km(rid) / D.TRAVEL[mode]["km_day"])) def travel_options(c, m, soldiers): """[(mode, days, supplies, why not or None)] for a unit of `soldiers` going to mission m.""" out = [] for mode, t in D.TRAVEL.items(): days = travel_days(m.region, mode) cost = t["cost"] * soldiers why = None lock = needs_open(c, t["needs"], t.get("needs_all")) if lock: why = lock elif t.get("water") and m.region not in D.WATER_REGIONS: why = "no water route there" elif t["seats"] is not None and soldiers > t["seats"]: why = f"carries {t['seats']} at most" elif cost > c.supplies: why = f"costs {cost} supplies, you have {c.supplies}" elif c.day + days >= m.expires: why = f"{days} days out: the mission will be gone" out.append((mode, days, cost, why)) return out def _name(c, r): used = {s.name for s in c.roster} free = [n for n in D.NAMES if n not in used] return r.choice(free) if free else f"{r.choice(D.NAMES)} {len(c.roster) + 1}" def new_campaign(seed=None): seed = random.randrange(1, 10**6) if seed is None else seed c = Campaign(seed) r = c.rng for cls in D.START_ROSTER: c.roster.append(Soldier(_name(c, r), cls)) for rid in D.REGIONS: c.regions[rid] = Region(lean=r.randint(*D.LEAN_START)) c.keep(r) c.say("Fort Leonard Wood. What's left of the Army holds the ruins. Every county around it " "belongs to somebody. Choose who.") _new_mission(c) return c # ── the days ── def _open_regions(c): return [rid for rid, r in c.regions.items() if r.owner is None] def _new_mission(c): r = c.rng busy = {m.region for m in c.missions} # one incursion in a county at a time choices = [rid for rid in _open_regions(c) if rid not in busy] if not choices: return None rid = r.choice(choices) m = Mission(c.next_id, rid, None, r.choice(sorted(D.MISSION_KINDS)), # an incursion: you pick the side c.day + r.randint(*D.MISSION_LIFE) + c.effect("radio room", "life", 0), None) c.next_id += 1 c.missions.append(m) c.next_mission = c.day + r.randint(*D.MISSION_EVERY) c.keep(r) c.say(f"{D.REGIONS[rid]['name']}: {m.about()} (gone in {m.expires - c.day} days).") return m def _stand(c, rid, g, amount): """Your standing with group g of county rid goes up by amount (to 100 at most); say each tier you reach.""" before = c.tier(rid, g) c.affinity[f"{rid}:{g}"] = min(100, c.standing(rid, g) + amount) name = D.REGIONS[rid]["groups"][g]["name"] for at, what in D.AFFINITY_TIERS[before:c.tier(rid, g)]: c.say(f"{name} stand with you ({at}): " + {"trade": "they'll trade, and send recruits by caravan", "weapons": "their weapons are yours to collect", "armor and kit": "their armor and kit too", "their asset": "and their " + (", ".join(D.REGIONS[rid]["groups"][g].get("unlocks", [])) or "best") + "."}[what].rstrip(".") + ".") def _gear_kind(item): return "weapons" if item in D.WEAPONS else "armor and kit" def _produce(c): """The week: every faction that trades with you puts by what its tier (or being your ally) allows.""" for rid, info in D.REGIONS.items(): for g, grp in enumerate(info["groups"]): if not c.trades(rid, g): continue reg = c.regions[rid] tier = 3 if (reg.owner == g and reg.ally) else c.tier(rid, g) p = c.pile(rid, g) p["recruits"] = min(D.STOCK_CAP["recruits"], p["recruits"] + 1) for item in grp["gear"]: need = 2 if _gear_kind(item) == "weapons" else 3 if tier >= need: p["items"][item] = min(D.STOCK_CAP["item"], p["items"].get(item, 0) + 1) def _haul(c, rid): """The side you backed took county rid: the loser's goods go on the winner's pile.""" reg = c.regions[rid] loser = D.REGIONS[rid]["groups"][1 - reg.owner] p = c.pile(rid, reg.owner) p["recruits"] += D.HAUL for item in loser["gear"]: p["items"][item] = p["items"].get(item, 0) + D.HAUL c.say(f"{loser['name']} are beaten: their goods are waiting for your caravan in " f"{D.REGIONS[rid]['town']}.") def _lean(c, rid, group, amount): """Lean region rid toward group by amount; settle it if a group takes it.""" reg = c.regions[rid] reg.lean = max(-100, min(100, reg.lean + (amount if group == 0 else -amount))) if reg.owner is None and abs(reg.lean) >= 100: reg.owner = 0 if reg.lean > 0 else 1 reg.ally = reg.helped[reg.owner] > reg.helped[1 - reg.owner] info = D.REGIONS[rid] winner = info["groups"][reg.owner]["name"] if reg.ally: got = ", ".join(info["groups"][reg.owner].get("unlocks", [])) or "their goodwill" c.say(f"{winner} take {info['name']}, with your help. Allied: {got}.") _haul(c, rid) else: c.say(f"{winner} take {info['name']}, and they owe you nothing. It's hostile now.") for m in [m for m in c.missions if m.region == rid]: c.missions.remove(m) _check(c) def wait(c, days=1): """Let days pass. -> the log lines they added.""" start = len(c.log) for _ in range(days): if c.outcome: break c.day += 1 for m in list(c.missions): if m.expires <= c.day: c.missions.remove(m) if m.group is None: # nobody took a side: they fought it out alone a, b = m.sides() c.say(f"Too late in {D.REGIONS[m.region]['name']}: {a} and {b} fought it out without you.") continue helped, fought = m.names() c.say(f"Too late in {D.REGIONS[m.region]['name']}: {fought} gain ground.") _lean(c, m.region, 1 - m.group, D.LEAN_EXPIRED) if c.day >= c.next_mission and len(c.missions) < D.MAX_MISSIONS: _new_mission(c) if c.project and c.day >= c.project["done"]: what, lv = c.project["what"], c.project["level"] c.project = None if what == "clear rubble": c.plots += 1 c.say(f"The rubble is cleared: room for {c.plots} facilities now.") else: c.facilities[what] = lv c.say(f"The {what} is built" + (f" up to level {lv}" if lv > 1 else "") + f": {D.FACILITIES[what]['about']}.") if c.day % D.WEEK == 0: _produce(c) got = c.weekly() c.supplies = max(0, c.supplies + got["supplies"]) c.intel += got["intel"] c.recruits += got["recruits"] c.say(f"The week's take: {got['supplies']:+} supplies" + (f" (after {c.upkeep()} upkeep)" if c.upkeep() else "") + f", +{got['intel']} intel, +{got['recruits']} recruits.") for s in c.roster: if not s.dead and s.wounded_until == c.day: c.say(f"{s.name} is fit again.") _check(c) return c.log[start:] def _check(c): if c.outcome: return if len(c.allies()) >= D.WIN_REGIONS: c.outcome = "won" c.say(f"{len(c.allies())} regions stand with Fort Leonard Wood. The campaign is won.") elif len(c.hostile()) >= D.LOSE_REGIONS: c.outcome = "lost" c.say(f"{len(c.hostile())} regions are hostile. The fort is cut off. The campaign is lost.") # ── the fort ── def recruit(c): if c.recruits < 1: raise CampaignError("no recruits waiting: allies send more each week") if c.supplies < D.RECRUIT_COST: raise CampaignError(f"a recruit costs {D.RECRUIT_COST} supplies, you have {c.supplies}") r = c.rng s = Soldier(_name(c, r), r.choice(sorted(D.CLASSES))) c.keep(r) if "veterans" in c.unlocks(): # the Free Companies send trained hands s.xp, s.rank = D.RANKS[1], 1 c.supplies -= D.RECRUIT_COST c.recruits -= 1 c.roster.append(s) c.say(f"{s.name} the {s.cls} joins the warband.") return s def scout(c): """Spend intel: scouts go out and turn up a mission now.""" if c.intel < D.SCOUT_COST: raise CampaignError(f"scouting takes {D.SCOUT_COST} intel, you have {c.intel}") if len(c.missions) >= D.MAX_MISSIONS: raise CampaignError(f"there are already {D.MAX_MISSIONS} missions waiting") m = _new_mission(c) if m is None: raise CampaignError("nothing left to find") c.intel -= D.SCOUT_COST return m # ── the armory (Step 3c) ── def needs_open(c, needs, all_=False): """None if an ally gives any one of these assets (all_: every one of them; or none is needed), else why not.""" have = set(c.unlocks()) if all_ and not set(needs) <= have: return "needs allies with " + " and ".join(needs) if not all_ and needs and not set(needs) & have: return "needs an ally with " + " or ".join(needs) return None def tier_open(c, tier): """None if the fort can buy this weapon tier, else why not.""" return needs_open(c, D.WEAPON_TIERS[tier]["needs"]) def weapon_cost(family, tier): cost = D.WEAPON_TIERS[tier]["cost"] return math.ceil(cost * D.PISTOL_COST) if family == "pistol" else cost def armory(c, s): """[(family, tier, cost, why not or None)]: every weapon soldier s could carry, and the pistols.""" out = [] for family in D.CLASS_WEAPONS[s.cls] + ["pistol"]: for tier in range(len(D.WEAPON_TIERS)): cost = c.price(weapon_cost(family, tier)) mine = (s.pistol_tier == tier) if family == "pistol" else (s.family(), s.weapon_tier) == (family, tier) why = ("carrying it" if mine else tier_open(c, tier) or (f"costs {cost}, you have {c.supplies}" if cost > c.supplies else None)) out.append((family, tier, cost, why)) return out def arm(c, name, family, tier): """Buy soldier `name` a weapon (or a pistol) at the armory; the old one is scrapped.""" s = c.soldier(name) if family != "pistol" and family not in D.CLASS_WEAPONS[s.cls]: raise CampaignError(f"a {s.cls} can't carry a {family}") if not 0 <= tier < len(D.WEAPON_TIERS): raise CampaignError("no such tier") why = next(o[3] for o in armory(c, s) if o[:2] == (family, tier)) if why: raise CampaignError(f"{D.weapon_key(family, tier)}: {why}") cost = c.price(weapon_cost(family, tier)) c.supplies -= cost if family == "pistol": s.pistol_tier = tier else: s.weapon, s.weapon_tier = family, tier c.say(f"{s.name} the {s.cls} draws a {D.weapon_key(family, tier)}" + (f" ({cost} supplies)." if cost else ".")) def suit(c, name, armor): """Buy soldier `name` armor; the old is scrapped. Fewer slots: the last utility items go.""" s = c.soldier(name) if armor not in D.ARMOR: raise CampaignError(f"no armor called {armor}") a = D.ARMOR[armor] cost = c.price(a["cost"]) why = ("wearing it" if s.armor == armor else needs_open(c, a["needs"]) or (f"costs {cost}, you have {c.supplies}" if cost > c.supplies else None)) if why: raise CampaignError(f"{armor}: {why}") c.supplies -= cost s.armor = armor dropped = s.utility[a["slots"]:] s.utility = s.utility[:a["slots"]] c.say(f"{s.name} the {s.cls} puts on {armor}" + (f" ({cost} supplies)" if cost else "") + (f"; no room for {', '.join(dropped)}." if dropped else ".")) def fit(c, name, slot, item): """Put a utility item in a slot (bought; what was there is scrapped). item None: empty it.""" s = c.soldier(name) slots = D.ARMOR[s.armor]["slots"] if not 0 <= slot < slots: raise CampaignError(f"{s.armor} has {slots} utility slot{'s' * (slots != 1)}") if item is None: if slot < len(s.utility): s.utility.pop(slot) return if item not in D.UTILITY: raise CampaignError(f"no utility item called {item}") u = D.UTILITY[item] cost = c.price(u["cost"]) why = needs_open(c, u["needs"]) or (f"costs {cost}, you have {c.supplies}" if cost > c.supplies else None) if why: raise CampaignError(f"{item}: {why}") c.supplies -= cost if slot < len(s.utility): s.utility[slot] = item else: s.utility.append(item) c.say(f"{s.name} packs a {item} ({cost} supplies).") def from_store(c, name, item): """Fit soldier `name` with an item from the fort's store (Step 4 part 3: what caravans brought home), free: a faction's gear needs no unlock. A weapon or armor replaces what they had (scrapped, as at the armory); a utility item goes in the first empty slot.""" s = c.soldier(name) if s is None: raise CampaignError(f"nobody called {name}") if c.store.get(item, 0) < 1: raise CampaignError(f"no {item} in the store") if item in D.WEAPONS: w = D.WEAPONS[item] family = w.get("family") if family is None or (family != "pistol" and family not in D.CLASS_WEAPONS[s.cls]): raise CampaignError(f"a {s.cls} can't carry a {item}") if family == "pistol": s.pistol_tier = w["tier"] else: s.weapon, s.weapon_tier = family, w["tier"] what = f"draws a {item}" elif item in D.ARMOR: if s.armor == item: raise CampaignError(f"{item}: wearing it") s.armor = item s.utility = s.utility[:D.ARMOR[item]["slots"]] what = f"puts on {item}" elif item in D.UTILITY: if len(s.utility) >= D.ARMOR[s.armor]["slots"]: raise CampaignError(f"{s.name}'s {s.armor} has no empty slot") s.utility.append(item) what = f"packs a {item}" else: raise CampaignError(f"{item}: that goes on the convoy, not a soldier") c.store[item] -= 1 if not c.store[item]: del c.store[item] c.say(f"{s.name} the {s.cls} {what} from the store.") def fit_convoy(c, mode, slot, item): """Put a convoy item in a slot of a travel mode (bought; what was there is scrapped). The fort keeps it for every trip that way. item None: empty the slot.""" if mode not in D.TRAVEL: raise CampaignError(f"no way to travel called {mode}") t = D.TRAVEL[mode] lock = needs_open(c, t["needs"], t.get("needs_all")) if lock: raise CampaignError(f"{mode}: {lock}") if not 0 <= slot < t["slots"]: raise CampaignError(f"{mode} has {t['slots']} utility slot{'s' * (t['slots'] != 1)}") kit = c.convoy.setdefault(mode, []) if item is None: if slot < len(kit): kit.pop(slot) return if item not in D.CONVOY: raise CampaignError(f"no convoy item called {item}") cost = c.price(D.CONVOY[item]["cost"]) if cost > c.supplies: raise CampaignError(f"{item}: costs {cost}, you have {c.supplies}") c.supplies -= cost if slot < len(kit): kit[slot] = item else: kit.append(item) c.say(f"The {mode} carry {item} now ({cost} supplies).") # ── the facilities (Step 3d) ── def facility_options(c): """[(what, level, cost, days, why not or None)]: the next level of every facility, and clearing rubble for another plot.""" out = [] used = sum(1 for f in c.facilities if c.level(f)) # (a project in hand keeps the crew busy anyway) for f, info in D.FACILITIES.items(): lv = c.level(f) + 1 if lv > len(info["levels"]): out.append((f, lv, 0, 0, "built in full")) continue L = info["levels"][lv - 1] why = (("being built" if c.project and c.project["what"] == f else "the build crew is busy") if c.project else (f"no room: {c.plots} plots, all used" if lv == 1 and used >= c.plots else None) or needs_open(c, L["needs"]) or (f"costs {L['cost']}, you have {c.supplies}" if L["cost"] > c.supplies else None)) out.append((f, lv, L["cost"], L["days"], why)) why = (("being cleared" if c.project["what"] == "clear rubble" else "the build crew is busy") if c.project else ("there's no more room to clear" if c.plots >= D.MAX_PLOTS else None) or (f"costs {D.CLEAR['cost']}, you have {c.supplies}" if D.CLEAR["cost"] > c.supplies else None)) out.append(("clear rubble", c.plots + 1, D.CLEAR["cost"], D.CLEAR["days"], why)) return out def build(c, what): """Set the build crew on the next level of a facility, or on clearing rubble ("clear rubble"). Paid now; done when the days are up.""" row = next((o for o in facility_options(c) if o[0] == what), None) if row is None: raise CampaignError(f"no facility called {what}") _, lv, cost, days, why = row if why: raise CampaignError(f"{what}: {why}") c.supplies -= cost c.project = {"what": what, "level": lv, "done": c.day + days} c.say(("The crew starts clearing rubble for another plot" if what == "clear rubble" else f"The crew starts on the {what}" + (f", level {lv}" if lv > 1 else "")) + f": {cost} supplies, {days} days.") def skill_choices(s): if not s.pending: return [] tier = sum(1 for at in D.SKILL_AT if s.rank >= at) - s.pending return D.SKILLS[s.cls][tier] def choose_skill(c, name, which): s = c.soldier(name) options = skill_choices(s) if not options: raise CampaignError(f"{name} has no skill to pick") skill = options[which][0] s.skills.append(skill) s.pending -= 1 c.say(f"{name} learns {skill}.") return skill # ── missions ── def depart(c, mission_id, squads, travel="on foot", side=None): """The unit sets out: squads is [Squad 1's names, Squad 2's names] (a plain list of names is one squad); side: the group you back (0 or 1), needed for an incursion nobody has picked a side in yet. Pays for the travel and puts the unit on the road (c.trip). -> days on the road. Then road_day() until on_road() is False, then arrive(). launch() does all three at once.""" if c.outcome: raise CampaignError("the campaign is over") if on_road(c): raise CampaignError("the unit is already on the road") m = next((m for m in c.missions if m.id == mission_id), None) if m is None: raise CampaignError("no such mission") if m.group is None and side not in (0, 1): raise CampaignError("pick a side to back") if m.group is not None and side not in (None, m.group): raise CampaignError("you're already backing " + m.names()[0]) squads, names = _squads(c, squads) if travel not in D.TRAVEL: raise CampaignError(f"no way to travel called {travel}") mode, days, cost, why = next(o for o in travel_options(c, m, len(names)) if o[0] == travel) if why: raise CampaignError(f"{travel}: {why}") c.supplies -= cost if m.group is None: # the side is picked: who you'll be fighting m.group = side r = c.rng rival = D.REGIONS[m.region]["groups"][1 - side] n = 3 + min(2, c.day // 30) # it gets harder as the war goes on m.pods = [list(r.choice(rival["pods"])) for _ in range(n)] c.keep(r) c.say(f"You back {m.names()[0]} in {D.REGIONS[m.region]['name']}: {m.about()}.") kit = [D.CONVOY[i] for i in c.convoy.get(travel, [])] c.trip = {"mission": m.id, "travel": travel, "days": days, "heal": math.prod(k.get("heal", 1.0) for k in kit), "rest": sum(k.get("rest", 0) for k in kit), "region": m.region, "squads": squads, "gone": 0, "stage": "road"} c.say(f"The unit ({len(names)} soldiers, {len(squads)} squad{'s' * (len(squads) > 1)}) sets out " f"{D.TRAVEL[travel]['how']} for {D.REGIONS[m.region]['name']}: {days} day{'s' * (days > 1)} on the road" + (f", {cost} supplies" if cost else "") + ".") return days def _squads(c, squads): """Check a unit's squads (a plain list of names is one squad) -> (squads, all the names).""" if squads and isinstance(squads[0], str): squads = [squads] squads = [list(sq) for sq in squads if sq] if not squads: raise CampaignError("pick a squad") if len(squads) > D.SQUADS: raise CampaignError(f"a unit is at most {D.SQUADS} squads") for i, sq in enumerate(squads): if len(sq) > D.SQUAD_SIZE: raise CampaignError(f"Squad {i + 1} has {len(sq)}: a squad is at most {D.SQUAD_SIZE}") names = [n for sq in squads for n in sq] if len(set(names)) < len(names): raise CampaignError("a soldier can only be in one squad") for n in names: s = c.soldier(n) if s is None: raise CampaignError(f"nobody called {n} can go") if s.status(c.day) != "ready": raise CampaignError(f"{n} is {s.status(c.day)}") return squads, names class _Destination: """A caravan's end of the road, for travel_options: a county, and no day it has to be there by.""" def __init__(self, rid): self.region, self.expires = rid, 10 ** 9 def caravan_options(c, rid, soldiers): """travel_options for a caravan to county rid.""" return travel_options(c, _Destination(rid), soldiers) def depart_caravan(c, rid, g, squads, travel="on foot"): """A caravan sets out to group g of county rid, to bring home what they've put by (Step 4 part 3), sent like a mission's unit: squads, travel. -> days on the road. Then road_day() until on_road() is False, then arrive().""" if c.outcome: raise CampaignError("the campaign is over") if on_road(c) or c.trip: raise CampaignError("the unit is already out") grp = D.REGIONS[rid]["groups"][g] if not c.trades(rid, g): raise CampaignError(f"{grp['name']} don't trade with you yet: back them to " f"{D.AFFINITY_TIERS[0][0]}, or help them take {D.REGIONS[rid]['name']}") p = c.pile(rid, g) if not p["recruits"] and not any(p["items"].values()): raise CampaignError(f"{grp['name']} have nothing put by yet: it comes in each week") squads, names = _squads(c, squads) if travel not in D.TRAVEL: raise CampaignError(f"no way to travel called {travel}") mode, days, cost, why = next(o for o in caravan_options(c, rid, len(names)) if o[0] == travel) if why: raise CampaignError(f"{travel}: {why}") c.supplies -= cost kit = [D.CONVOY[i] for i in c.convoy.get(travel, [])] c.trip = {"mission": None, "caravan": [rid, g], "travel": travel, "days": days, "heal": math.prod(k.get("heal", 1.0) for k in kit), "rest": sum(k.get("rest", 0) for k in kit), "region": rid, "squads": squads, "gone": 0, "stage": "road"} c.say(f"A caravan ({len(names)} soldiers) sets out {D.TRAVEL[travel]['how']} for " f"{D.REGIONS[rid]['town']}, to {grp['name']}: {days} day{'s' * (days > 1)} on the road" + (f", {cost} supplies" if cost else "") + ".") return days def _collect(c, rid, g): """The caravan is at their town: everything they've put by is loaded. Recruits join the roster (the classes as ever: it's the gear that's theirs); items go to the fort's store. -> line.""" p = c.pile(rid, g) r = c.rng joined = [] for _ in range(p["recruits"]): s = Soldier(_name(c, r), r.choice(sorted(D.CLASSES))) c.roster.append(s) joined.append(f"{s.name} the {s.cls}") c.keep(r) items = {k: v for k, v in p["items"].items() if v} for k, v in items.items(): c.store[k] = c.store.get(k, 0) + v c.stock[f"{rid}:{g}"] = {"recruits": 0, "items": {}} got = (["recruits: " + ", ".join(joined)] if joined else []) + [f"{v} {k}" for k, v in sorted(items.items())] return "; ".join(got) def on_road(c): """Is the unit out with road still to go before it arrives? (The last day's road ends in the battle, so a trip of n days has n - 1 days to wait on the way.)""" t = c.trip return bool(t and t.get("stage") == "road" and t["gone"] < t["days"] - 1 and not c.outcome) def road_day(c): """One day on the road. -> the log lines it added.""" if not on_road(c): raise CampaignError("the unit is not on the road") c.trip["gone"] += 1 return wait(c, 1) def arrive(c): """The end of the road. -> tactics.Battle (play it, then finish()), or None if the mission was gone when they got there (they come home).""" t = c.trip if not t or t.get("stage") != "road": raise CampaignError("the unit is not on the road") if on_road(c): raise CampaignError("still on the road") squads, travel, days = t["squads"], t["travel"], t["days"] names = [n for sq in squads for n in sq] if t.get("caravan") and not c.outcome: # a caravan: raided, or load up and home rid, g = t["caravan"] r = c.rng raided = r.random() < D.RAID_CHANCE if raided: rival = D.REGIONS[rid]["groups"][1 - g] t["pods"] = [list(r.choice(rival["pods"])) for _ in range(D.RAID_PODS)] t["stage"] = "battle" c.keep(r) if raided: c.say(f"{rival['name']} ambush the caravan outside {D.REGIONS[rid]['town']}!") return _battle(c, squads, travel, t["pods"]) got = _collect(c, rid, g) for n in names: c.soldier(n).tired_until = c.day + 1 + days c.trip = None c.say(f"The caravan loads up in {D.REGIONS[rid]['town']} and turns for home: {got}.") wait(c, 1) return None m = next((m for m in c.missions if m.id == t["mission"]), None) if m is None or c.outcome: for n in names: c.soldier(n).tired_until = c.day + 1 + days c.trip = None c.say(f"The unit reached {D.REGIONS[t['region']]['name']} too late: it's over there. " "They turn for home.") if not c.outcome: wait(c, 1) return None t["stage"] = "battle" return _battle(c, squads, travel, m.pods) def _battle(c, squads, travel, pods): """The unit (squads, with what its travel and convoy kit add) against pods: a tactics.Battle.""" kit = [D.CONVOY[i] for i in c.convoy.get(travel, [])] extra = dict(D.TRAVEL[travel].get("extra", {})) for k in kit: for stat, v in k.get("extra", {}).items(): extra[stat] = extra.get(stat, 0) + v unit = [] for i, sq in enumerate(squads): for n in sq: s = c.soldier(n) e = c.extra(s) for k, v in extra.items(): e[k] = e.get(k, 0) + v unit.append((s.name, s.cls, e, i + 1, s.gun(), s.pistol())) r = c.rng seed = r.randrange(10**9) c.keep(r) return Battle.new(seed, squad=unit, pods=pods) def launch(c, mission_id, squads, travel="on foot", side=None): """Send the unit out and let the whole road pass: depart(), road_day() to the end, arrive(). -> tactics.Battle at the end of the road (play it, then finish()), or None if the mission was gone when they got there (they come home).""" depart(c, mission_id, squads, travel, side) while on_road(c): road_day(c) return arrive(c) def _settle(c, battle, won, rid, kind, helped, fought, road, heal, rest): """The squad home from a battle: kills, the record, the downed (pulled through, killed or missing), wounds, fatigue, XP and ranks.""" for u in battle.units: if u.side != "squad": continue s = c.soldier(u.name) s.kills += u.kills s.missions += 1 where = D.REGIONS[rid]["name"] s.record.append({"day": c.day, "region": where, "kind": kind, "for": helped, "against": fought, "won": won, "kills": u.kills, "hurt": "downed" if u.hp <= 0 else ("wounded" if u.hp < u.max_hp else "")}) if u.hp <= 0: r = c.rng lives = won and r.random() < D.DOWNED_LIVE missing = not won and r.random() < D.MIA_CHANCE c.keep(r) if not lives: s.dead = True how = "missing in action" if missing else "killed in action" story = (u.downed or "went down") + (". The field was lost and they were left on it" if missing else "") s.fate = {"how": how, "day": c.day, "where": where, "story": story} c.say(f"{s.name} the {s.cls} is missing in action in {where}." if missing else f"{s.name} the {s.cls} died in {where}.") continue s.wounded_until = c.day + 1 + math.ceil(D.DOWNED_DAYS * heal) s.tired_until = 0 c.say(f"{s.name} went down but the field was yours: carried home, " f"{s.wounded_until - c.day} days to mend.") continue lost = u.max_hp - u.hp if lost: s.wounded_until = c.day + 1 + math.ceil(lost * D.WOUND_DAYS_PER_HP * heal) s.tired_until = c.day + 1 + max(0, D.FATIGUE_DAYS + road - rest) gain = u.kills * D.XP_KILL + D.XP_MISSION s.xp += gain * (100 + c.effect("drill yard", "xp", 0)) // 100 while s.rank < len(D.RANKS) - 1 and s.xp >= D.RANKS[s.rank + 1]: s.rank += 1 if s.rank in D.SKILL_AT: s.pending += 1 c.say(f"{s.name} is promoted: {D.RANK_NAMES[s.rank]}" + (" (a skill to pick)" if s.rank in D.SKILL_AT else "") + ".") def raid_mission(c): """A caravan's raid as the views show a battle: a stand-in mission (id 0, never in c.missions) backing the caravan's faction against its county's other side.""" rid, g = c.trip["caravan"] return Mission(0, rid, g, "raid", c.day, c.trip.get("pods") or []) def _finish_caravan(c, battle): """The raid is over. Won: the goods come home. Lost: the raiders have them.""" start = len(c.log) t = c.trip rid, g = t["caravan"] won = battle.outcome == "won" m = raid_mission(c) road, heal, rest = t["days"], c.heal_factor() * t.get("heal", 1.0), t.get("rest", 0) c.trip = None _settle(c, battle, won, rid, "caravan", *m.names(), road, heal, rest) if won: c.say(f"The raiders are beaten off. The caravan comes home from {D.REGIONS[rid]['town']}: " f"{_collect(c, rid, g)}.") else: c.stock[f"{rid}:{g}"] = {"recruits": 0, "items": {}} c.say(f"{m.names()[1]} took the caravan's goods on the road from {D.REGIONS[rid]['town']}.") if not any(not s.dead for s in c.roster) and c.recruits == 0 and not c.outcome: c.outcome = "lost" c.say("Nobody is left to fight. The campaign is lost.") if not c.outcome: wait(c, 1) return c.log[start:] def finish(c, mission_id, battle): """Bring the squad home and settle the mission (or a caravan's raid: mission_id 0). -> report lines.""" if c.trip and c.trip.get("caravan"): return _finish_caravan(c, battle) m = next(m for m in c.missions if m.id == mission_id) start = len(c.log) won = battle.outcome == "won" c.missions.remove(m) trip = c.trip if c.trip and c.trip["mission"] == mission_id else {} road = trip.get("days", 0) # the way home heal = c.heal_factor() * trip.get("heal", 1.0) rest = trip.get("rest", 0) c.trip = None _settle(c, battle, won, m.region, m.kind, *m.names(), road, heal, rest) helped, fought = m.names() _stand(c, m.region, m.group, D.AFFINITY_WON if won else D.AFFINITY_LOST) if won: pay = D.MISSION_KINDS[m.kind]["supplies"] c.supplies += pay c.regions[m.region].helped[m.group] += 1 c.say(f"Won for {helped}: +{pay} supplies; {D.REGIONS[m.region]['name']} leans their way.") _lean(c, m.region, m.group, D.LEAN_WON) else: c.say(f"Lost against {fought}: they gain ground.") _lean(c, m.region, 1 - m.group, D.LEAN_LOST) if not any(not s.dead for s in c.roster) and c.recruits == 0 and not c.outcome: c.outcome = "lost" c.say("Nobody is left to fight. The campaign is lost.") if not c.outcome: wait(c, 1) return c.log[start:] # ── saving ── def save(c, path): Path(path).write_text(json.dumps(asdict(c))) # The eight regions of Steps 2-3 and their groups (group 0, group 1), for saves made before every county # had two factions of its own (Step 4 part 1). Each group now holds a county of its own (data.REGIONS). OLD_REGIONS = { "gasconade": ["The Ferrymen", "The Vienna Regulators"], "lake": ["The Dam Keepers", "The Marina Lords"], "plateau": ["The Miners' College", "The Iron Road Syndicate"], "crossroads": ["The Lebanon Traders' Union", "The Route 66 Riders"], "hills": ["The Cabool Grange", "The Hollow Clans"], "current": ["The River Saints", "The Lead Belt Company"], "truman": ["The Truman Dam Militia", "The Osage Cattle Barons"], "capital": ["The Capitol Remnant", "The Callaway Free Companies"]} def _migrate(d): """A save from before the counties (Step 4 part 1): its eight regions become the 24 counties. A group that held a region holds its own county (ally or hostile as before); a region leaning to a group leans that group's county the same way; missions won for a group become standing with it. Missions in the old regions are gone (new incursions come), and a unit out to one comes home.""" if set(d["regions"]) == set(D.REGIONS): return d home = {g["name"]: (rid, i) for rid, r in D.REGIONS.items() for i, g in enumerate(r["groups"])} regions = {rid: asdict(r) for rid, r in new_campaign(d["seed"]).regions.items()} affinity = dict(d.get("affinity", {})) for old, reg in d["regions"].items(): names = OLD_REGIONS.get(old) if not names: continue for i, name in enumerate(names): rid, g = home[name] won = reg.get("helped", [0, 0])[i] if won: affinity[f"{rid}:{g}"] = min(100, affinity.get(f"{rid}:{g}", 0) + won * D.AFFINITY_WON) regions[rid]["helped"][g] += won if reg.get("owner") is not None: rid, g = home[names[reg["owner"]]] regions[rid].update(owner=g, ally=reg.get("ally"), lean=100 if g == 0 else -100) elif reg.get("lean"): rid, g = home[names[0 if reg["lean"] > 0 else 1]] regions[rid]["lean"] = abs(reg["lean"]) * (1 if g == 0 else -1) d["regions"], d["affinity"] = regions, affinity d["missions"] = [m for m in d["missions"] if m["region"] in D.REGIONS and m["region"] not in OLD_REGIONS] t = d.get("trip") if t and (t.get("region") not in D.REGIONS or t.get("region") in OLD_REGIONS): d["trip"] = None d["next_mission"] = min(d.get("next_mission", d["day"]), d["day"] + 1) d["log"] = list(d.get("log", [])) + [f"Day {d['day']}: The war has broken up county by county: every " "county around the fort now has two sides of its own."] return d def load(path): d = _migrate(json.loads(Path(path).read_text())) d["roster"] = [Soldier(**s) for s in d["roster"]] d["missions"] = [Mission(**m) for m in d["missions"]] d["regions"] = {k: Region(**v) for k, v in d["regions"].items()} return Campaign(**d)