"""Project 02: the fort and the map, the campaign window (Step 3a, Dillon's design). The map of Missouri: the regions around Fort Leonard Wood tinted by who they lean toward (each region's two groups have a colour; the deeper the colour, the nearer that group is to taking it), the fort marked in its own county, and missions as numbered markers. Click a marker (or a mission in the list) for its briefing, then Plan the unit (Squad 1 and Squad 2, and how they travel) and go: the road takes days, the battle opens, and you come back to the map when it's over. The side tabs: Fort (supplies, intel, recruits, the weekly take, allies and their assets, what's lost), Roster (everyone; recruit; pick skills; the armory: weapons by tier), Regions (each one's dilemma and lean), Log. The campaign saves itself after everything you do (SAVE_FILE) and offers to carry on. Run: python3 -m p02 (from the project-02 directory) """ from __future__ import annotations import json import tkinter as tk from pathlib import Path from tkinter import messagebox, ttk from . import campaign as K from . import data as D from . import briefs as B from .briefs import mission_brief, mission_order from .rooms import does from .mapstate import EDGE, GROUP_COLOURS, HOME, LAND, RIVER, SEA, UNPICKED, blend, county_colour # noqa: F401 from .view import BattleView SAVE_FILE = Path.home() / "Project02 campaign.json" MAP_FILE = Path(__file__).with_name("missouri.json") NEWS = ("Too late", " take ", "week's take", "fit again", "gone in") MARK, MARK_EDGE = "#f3d27a", "#3b2a1a" def roster_tree(parent, height=24): """The roster as a table (one row a soldier, iid = name); fill it with fill_roster.""" tree = ttk.Treeview(parent, columns=("cls", "rank", "weapon", "kills", "state"), height=height, selectmode="browse") for col, title, w in (("#0", "name", 70), ("cls", "class", 70), ("rank", "rank", 75), ("weapon", "weapon", 175), ("kills", "kills", 35), ("state", "state", 110)): tree.heading(col, text=title) tree.column(col, width=w) tree.pack(fill="both", expand=True) return tree def fill_roster(tree, c): """Everyone, living first by rank; the selection kept.""" sel = tree.selection() tree.delete(*tree.get_children()) for s in sorted(c.roster, key=lambda s: (s.dead, -s.rank, s.name)): state = s.status(c.day) + (", skill to pick" if s.pending and not s.dead else "") tree.insert("", "end", iid=s.name, text=s.name, values=(s.cls, D.RANK_NAMES[s.rank], s.gun(), s.kills, state)) if sel and tree.exists(sel[0]): tree.selection_set(sel[0]) class Desks: """The fort's controls in their own windows: the convoy, the facilities, the armory, skills. Shared by the 2D window (Fort) and the bunker (BunkerDesks). Needs: self.root (Tk), self.c (the campaign), self.done(fn, *args) (do it; save and redraw), self.say(text), self.chosen_soldier() (a name or None).""" def open_convoy(self): """The fort's mounts and machines, line by line: what each carries, how fast, and its own utility slots to fill (kept for every trip that way).""" c = self.c if getattr(self, "convoy_top", None) and self.convoy_top.winfo_exists(): self.convoy_top.destroy() top = self.convoy_top = tk.Toplevel(self.root) top.title("The convoy") ttk.Label(top, text=f"Animal and mechanical lines: each tier bigger, carrying more, with more " f"room for its own utility. Supplies: {c.supplies}.", padding=8, wraplength=900).grid(row=0, column=0, columnspan=6, sticky="w") ttk.Button(top, text="Caravans...", command=self.open_caravans).grid(row=0, column=6, columnspan=2) self.convoy_buttons = {} row = 1 for kind in ("animal", "mechanical"): ttk.Label(top, text=kind.capitalize(), font=("Segoe UI", 10, "bold"), padding=(8, 6, 8, 0)).grid( row=row, column=0, sticky="w") row += 1 for mode, t in sorted(((m, t) for m, t in D.TRAVEL.items() if t["type"] == kind), key=lambda x: x[1]["tier"]): lock = K.needs_open(c, t["needs"], t.get("needs_all")) seats = "the whole unit" if t["seats"] is None else f"{t['seats']} soldiers" ttk.Label(top, text=f"tier {t['tier']}: {mode}\n{seats}, {t['km_day']} km a day, " f"{t['slots']} slot{'s' * (t['slots'] != 1)}" + (f"\n{lock}" if lock else ""), foreground="#888" if lock else "#222", padding=(16, 2)).grid(row=row, column=0, sticky="w") kit = c.convoy.get(mode, []) for slot in range(t["slots"]): have = kit[slot] if slot < len(kit) else None if lock or slot > len(kit): continue # fill the slots in order for j, (item, u) in enumerate(D.CONVOY.items()): cost = c.price(u["cost"]) why = f"costs {cost}" if cost > c.supplies else None b = ttk.Button(top, width=15, state="disabled" if why else "normal", text=f"{item}\n{why or str(cost) + ' supplies'}", command=lambda m=mode, sl=slot, it=item: self.convoy_buy(m, sl, it)) b.grid(row=row, column=2 + j, padx=1, pady=1) self.convoy_buttons[(mode, slot, item)] = b ttk.Label(top, text=f"slot {slot + 1}: {have or 'empty'}", width=22).grid(row=row, column=1) row += 1 if lock or not t["slots"] or len(kit) >= t["slots"]: row += 1 ttk.Label(top, text=" ".join(f"{i}: {u['about']}." for i, u in D.CONVOY.items()), padding=8, wraplength=900, foreground="#555").grid(row=row + 1, column=0, columnspan=8, sticky="w") def open_caravans(self): """Step 4 part 3: every faction that trades with you, what it has put by, and Send; and the fort's store (what caravans have brought home).""" c = self.c if getattr(self, "caravans_top", None) and self.caravans_top.winfo_exists(): self.caravans_top.destroy() top = self.caravans_top = tk.Toplevel(self.root) top.title("Caravans") ttk.Label(top, text="Factions put goods by for you as your standing grows (25: recruits; 50: their " "weapons; 75: their armor and kit; an ally: everything). A caravan, sent like " "a mission's unit, brings it home.", padding=8, wraplength=760).pack(anchor="w") out = bool(c.trip) self.caravan_buttons = {} rows = [(rid, g) for rid in D.REGIONS for g in (0, 1) if c.trades(rid, g)] if not rows: ttk.Label(top, text="Nobody trades with you yet: back a faction in its incursions.", padding=(16, 4)).pack(anchor="w") for rid, g in rows: info, p = D.REGIONS[rid], c.pile(rid, g) has = (([f"{p['recruits']} recruit{'s' * (p['recruits'] != 1)}"] if p["recruits"] else []) + [f"{v} {k}" for k, v in sorted(p["items"].items()) if v]) row = ttk.Frame(top, padding=(16, 2)) row.pack(anchor="w", fill="x") why = "the unit is out" if out else (None if has else "nothing put by yet") b = ttk.Button(row, text="Send" if not why else why, width=18, state="disabled" if why else "normal", command=lambda r=rid, gg=g: self.plan_caravan(r, gg)) b.pack(side="left") self.caravan_buttons[(rid, g)] = b ttk.Label(row, text=f"{B.standing_line(c, rid, g)}, {info['town']} ({info['name']}): " + (", ".join(has) or "nothing yet"), padding=(8, 0)).pack(side="left") stored = ", ".join(f"{v} {k}" for k, v in sorted(c.store.items()) if v) or "empty" ttk.Label(top, text=f"The fort's store: {stored}.", padding=8, wraplength=760).pack(anchor="w") def plan_caravan(self, rid, g): self.caravan_plan = PlanDialog(self.root, self.c, None, lambda sq, tr, side: self.caravan_go(rid, g, sq, tr), caravan=(rid, g)) def caravan_go(self, rid, g, squads, travel): """The caravan plan's Go: here (the 2D window) the whole road at once. -> True to close it.""" out = self.done(self.send_caravan, rid, g, squads, travel) if out is None: return False if getattr(self, "caravans_top", None) and self.caravans_top.winfo_exists(): self.caravans_top.destroy() return True def send_caravan(self, rid, g, squads, travel): days = K.depart_caravan(self.c, rid, g, squads, travel) while K.on_road(self.c): K.road_day(self.c) battle = K.arrive(self.c) if battle is not None and hasattr(self, "open_battle"): # raided: fight it out (the 2D window) self.open_battle(K.raid_mission(self.c), battle) return days def open_facilities(self): """The fort's facilities: what each level does and costs, and the build crew's project.""" c = self.c if getattr(self, "facilities_top", None) and self.facilities_top.winfo_exists(): self.facilities_top.destroy() top = self.facilities_top = tk.Toplevel(self.root) top.title("Facilities") used = sum(1 for lv in c.facilities.values() if lv) + bool( c.project and c.project["what"] != "clear rubble" and not c.level(c.project["what"])) crew = "free" if c.project: crew = (f"on {c.project['what']}" + (f" level {c.project['level']}" if c.project["what"] != "clear rubble" else "") + f", {c.project['done'] - c.day} days left") ttk.Label(top, text=f"Built in the ruins, one project at a time. Plots used: {used} of {c.plots}. " f"Build crew: {crew}. Supplies: {c.supplies}. Upkeep: {c.upkeep()} a week.", padding=8, wraplength=640).grid(row=0, column=0, columnspan=3, sticky="w") self.facility_buttons = {} rows = {o[0]: o for o in K.facility_options(c)} for i, (f, info) in enumerate(D.FACILITIES.items()): lv = c.level(f) lines = [f"{f}: level {lv}" if lv else f"{f}: not built"] for n, L in enumerate(info["levels"], 1): mark = "built" if n <= lv else (f"needs {' or '.join(L['needs'])}" if L["needs"] else "") lines.append(f" level {n}: {does(f, L)}; upkeep {L['upkeep']}" + (f" ({mark})" if mark else "")) ttk.Label(top, text="\n".join(lines), justify="left", padding=(8, 4)).grid(row=1 + i, column=0, sticky="w") _, nxt, cost, days, why = rows[f] note = "locked" if why and why.startswith("needs") else why b = ttk.Button(top, width=22, state="disabled" if why else "normal", text=(f"Build level {nxt}" if nxt <= len(info["levels"]) else "Built") + "\n" + (note or f"{cost} supplies, {days} days"), command=lambda w=f: self.facility_build(w)) b.grid(row=1 + i, column=1, padx=6, pady=2) self.facility_buttons[f] = b _, nxt, cost, days, why = rows["clear rubble"] r = 1 + len(D.FACILITIES) ttk.Label(top, text=f"rubble: clear it for plot {min(nxt, D.MAX_PLOTS)} of {D.MAX_PLOTS}", padding=(8, 4)).grid(row=r, column=0, sticky="w") b = ttk.Button(top, width=22, state="disabled" if why else "normal", text=f"Clear rubble\n{why or f'{cost} supplies, {days} days'}", command=lambda: self.facility_build("clear rubble")) b.grid(row=r, column=1, padx=6, pady=2) self.facility_buttons["clear rubble"] = b ttk.Label(top, text="Level 2 of each needs an ally's asset. Upkeep comes out of the week's supplies.", padding=8, foreground="#555", wraplength=640).grid(row=r + 1, column=0, columnspan=3, sticky="w") def facility_build(self, what): self.facilities_top.destroy() self.done(K.build, self.c, what) self.open_facilities() def convoy_buy(self, mode, slot, item): self.convoy_top.destroy() self.done(K.fit_convoy, self.c, mode, slot, item) self.open_convoy() def open_armory(self): """The armory for the selected soldier: every weapon their class can carry and every pistol, by tier, with the price or why not.""" name = self.chosen_soldier() if not name: self.say("Pick a soldier first.") return s = next(s for s in self.c.roster if s.name == name) if s.dead: self.say(f"{s.name} is dead.") return if getattr(self, "armory_top", None) and self.armory_top.winfo_exists(): self.armory_top.destroy() top = self.armory_top = tk.Toplevel(self.root) top.title(f"Armory: {s.name}") ttk.Label(top, text=f"{s.name} the {s.cls} carries a {s.gun()} and a {s.pistol()}. " f"Supplies: {self.c.supplies}. The old one is scrapped.", padding=8, wraplength=620).grid(row=0, column=0, columnspan=6, sticky="w") self.armory_buttons = {} rows = K.armory(self.c, s) families = list(dict.fromkeys(f for f, *_ in rows)) for t, tier in enumerate(D.WEAPON_TIERS): ttk.Label(top, text=tier["name"], font=("Segoe UI", 9, "bold")).grid(row=1, column=t + 1, padx=4) for r, family in enumerate(families): w = D.WEAPONS[D.weapon_key(family)] bits = ["never runs dry"] if w.get("sidearm") else [f"clip {w['clip']}"] if w.get("mobility"): bits.append(f"{w['mobility']:+d} move") ttk.Label(top, text=f"{family} ({', '.join(bits)})").grid(row=r + 2, column=0, sticky="w", padx=8) for fam, t, cost, why in rows: if fam != family: continue wt = D.WEAPONS[D.weapon_key(fam, t)] note = why or f"{cost} supplies" if note.startswith("needs an ally with "): note = "locked" text = f"dmg {wt['damage'][0]}-{wt['damage'][1]}, aim +{wt['aim']}, crit {wt['crit']}\n{note}" b = ttk.Button(top, text=text, width=27, state="disabled" if why else "normal", command=lambda f=fam, t=t: (top.destroy(), self.done(K.arm, self.c, s.name, f, t), self.open_armory())) b.grid(row=r + 2, column=t + 1, padx=2, pady=2) self.armory_buttons[(fam, t)] = b locks = " ".join(f"{t['name']}: an ally with {' or '.join(t['needs'])}." for t in D.WEAPON_TIERS if t["needs"]) ttk.Label(top, text=f"Locked tiers open with allies. {locks}", padding=8, wraplength=620, foreground="#555").grid(row=len(families) + 2, column=0, columnspan=6, sticky="w") self.armor_section(top, s, len(families) + 3) self.store_section(top, s) def store_section(self, top, s): """Step 4 part 3: what caravans brought home, fitted free (K.from_store).""" box = ttk.Frame(top, padding=8) box.grid(row=999, column=0, columnspan=8, sticky="w") items = [(k, v) for k, v in sorted(self.c.store.items()) if v and k not in D.CONVOY] ttk.Label(box, text="From the store (free): " + ("" if items else "nothing yet: caravans bring " "factions' gear home"), font=("Segoe UI", 9, "bold")).pack(anchor="w") self.store_buttons = {} for k, v in items: b = ttk.Button(box, text=f"{k} (x{v})", command=lambda it=k: (top.destroy(), self.done(K.from_store, self.c, s.name, it), self.open_armory())) b.pack(side="left", padx=2) self.store_buttons[k] = b def armor_section(self, top, s, row): """Armor (heavier: more protection, fewer utility slots) and what fills each slot.""" c = self.c def buy(fn, *args): top.destroy() self.done(fn, c, s.name, *args) self.open_armory() slots = D.ARMOR[s.armor]["slots"] ttk.Label(top, text=f"Armor: {s.name} wears {s.armor}, {slots} utility slot{'s' * (slots != 1)}. " "Light armor 3 slots, medium 2, heavy 1.", font=("Segoe UI", 9, "bold"), padding=(8, 6, 8, 2)).grid(row=row, column=0, columnspan=6, sticky="w") box = ttk.Frame(top, padding=(8, 0)) box.grid(row=row + 1, column=0, columnspan=6, sticky="w") for i, (name, a) in enumerate(D.ARMOR.items()): short = {"hp": "hp", "armor": "armor", "defense": "def", "mobility": "move"} gives = ", ".join(f"{short[k]} {a[k]:+d}" for k in short if a.get(k)) or "nothing" cost = c.price(a["cost"]) why = ("wearing it" if s.armor == name else K.needs_open(c, a["needs"]) or (f"costs {cost}" if cost > c.supplies else None)) note = "locked" if why and why.startswith("needs") else why b = ttk.Button(box, width=30, state="disabled" if why else "normal", text=f"{name} ({a['weight']}, {a['slots']} slot{'s' * (a['slots'] != 1)})\n{gives}\n" + (note or f"{cost} supplies"), command=lambda n=name: buy(K.suit, n)) b.grid(row=i // 4, column=i % 4, padx=2, pady=2) self.armory_buttons[("armor", name)] = b ttk.Label(top, text="Utility: one item a slot, restocked after every mission. What's there is scrapped.", font=("Segoe UI", 9, "bold"), padding=(8, 6, 8, 2)).grid(row=row + 2, column=0, columnspan=6, sticky="w") box = ttk.Frame(top, padding=(8, 0, 8, 8)) box.grid(row=row + 3, column=0, columnspan=6, sticky="w") for slot in range(slots): have = s.utility[slot] if slot < len(s.utility) else None ttk.Label(box, text=f"slot {slot + 1}: {have or 'empty'}", width=24).grid(row=slot, column=0, sticky="w") if slot > len(s.utility): continue # fill the slots in order for j, (item, u) in enumerate(D.UTILITY.items()): cost = c.price(u["cost"]) why = K.needs_open(c, u["needs"]) or (f"costs {cost}" if cost > c.supplies else None) note = "locked" if why and why.startswith("needs") else why b = ttk.Button(box, width=16, state="disabled" if why else "normal", text=f"{item}\n{note or str(cost) + ' supplies'}", command=lambda sl=slot, it=item: buy(K.fit, sl, it)) b.grid(row=slot, column=j + 1, padx=1, pady=1) self.armory_buttons[("slot", slot, item)] = b if have: b = ttk.Button(box, text="empty\nfree", width=8, command=lambda sl=slot: buy(K.fit, sl, None)) b.grid(row=slot, column=len(D.UTILITY) + 1, padx=1) self.armory_buttons[("slot", slot, None)] = b locked = [f"{n} ({' or '.join(x['needs'])})" for n, x in list(D.ARMOR.items()) + list(D.UTILITY.items()) if K.needs_open(c, x["needs"])] if locked: ttk.Label(top, text="Locked until an ally has: " + ", ".join(locked) + ".", padding=(8, 0, 8, 8), wraplength=900, foreground="#555").grid(row=row + 4, column=0, columnspan=6, sticky="w") def pick_skill(self): name = self.chosen_soldier() if not name: self.say("Pick a soldier first.") return s = next(s for s in self.c.roster if s.name == name) options = K.skill_choices(s) if not options or s.dead: self.say(f"{s.name} has no skill to pick.") return top = tk.Toplevel(self.root) top.title(f"{s.name}: pick a skill") ttk.Label(top, text=f"{s.name} the {s.cls}, {D.RANK_NAMES[s.rank]}. Pick one:", padding=8).pack() for i, (name, stats) in enumerate(options): what = ", ".join(f"+{v} {k}" for k, v in stats.items()) ttk.Button(top, text=f"{name} ({what})", command=lambda i=i: (top.destroy(), self.done(K.choose_skill, self.c, s.name, i)) ).pack(fill="x", padx=8, pady=2) class Fort(Desks): def __init__(self, root, camp=None, save_file=SAVE_FILE): self.root, self.save_file = root, save_file root.title("Project 02 — Fort Leonard Wood") root.geometry("1280x760") self.map = json.loads(MAP_FILE.read_text()) self.by_name = {c["name"].removesuffix(" County"): f for f, c in self.map["counties"].items()} self.c = camp or self.start() self.region_of = {self.by_name[n]: rid for rid, r in D.REGIONS.items() for n in r["counties"]} top = ttk.Frame(root, padding=6) top.pack(fill="x") self.head = ttk.Label(top, font=("Segoe UI", 10, "bold")) self.head.pack(side="left") for text, fn in (("Wait a day", lambda: self.wait(1)), ("Wait for news", self.wait_news)): ttk.Button(top, text=text, command=fn).pack(side="right", padx=2) self.msg = ttk.Label(top, foreground="#7a1f1f") self.msg.pack(side="right", padx=10) body = ttk.Frame(root) body.pack(fill="both", expand=True) self.cv = tk.Canvas(body, width=760, height=680, background=SEA, highlightthickness=0) self.cv.pack(side="left", padx=6, pady=6) self.cv.bind("", self.on_map_click) self.cv.bind("", self.on_map_hover) side = ttk.Frame(body, padding=4) side.pack(side="left", fill="both", expand=True) self.tabs = ttk.Notebook(side) self.tabs.pack(fill="both", expand=True) fort, roster, regions, log = (ttk.Frame(self.tabs, padding=6) for _ in range(4)) for frame, text in ((fort, "Fort"), (roster, "Roster"), (regions, "Regions"), (log, "Log")): self.tabs.add(frame, text=text) self.fort_tab, self.roster_tab, self.regions_tab, self.log_tab = fort, roster, regions, log self.build_fort(fort) self.build_roster(roster) self.build_regions(regions) self.logbox = tk.Text(log, width=50, height=36, wrap="word", font=("Consolas", 8)) self.logbox.pack(fill="both", expand=True) self.hint = tk.Label(self.cv, justify="left", wraplength=380, background="#fbf7ea", relief="solid", borderwidth=1, padx=6, pady=4, text="Click a mission marker on the map for its briefing.") self.hint.place(x=8, rely=1.0, y=-8, anchor="sw") self.shown = 0 self.fit_map() self.refresh() if self.c.trip and self.c.trip.get("stage") == "road": root.after(300, self.carry_on) # the war room was closed on the road def carry_on(self): """The unit is out on the road (the war room closed mid-way): walk the rest, then the battle.""" mid = self.c.trip["mission"] while K.on_road(self.c): K.road_day(self.c) m = next((x for x in self.c.missions if x.id == mid), None) battle = K.arrive(self.c) if battle is not None and self.c.trip.get("caravan"): m = K.raid_mission(self.c) self.save() self.refresh() if battle is None: self.tabs.select(self.log_tab) else: self.open_battle(m, battle) # ── the campaign file ── def start(self): if self.save_file and self.save_file.exists(): if messagebox.askyesno("Project 02", "Carry on the saved campaign?\n(No starts a new one " "and replaces it.)", parent=self.root): try: return K.load(self.save_file) except (ValueError, KeyError, TypeError) as err: messagebox.showwarning("Project 02", f"The save couldn't be read ({err}). " "Starting a new campaign.", parent=self.root) return K.new_campaign() def save(self): if self.save_file: K.save(self.c, self.save_file) # ── the map ── def fit_map(self): xs = [x for c in self.map["counties"].values() for r in c["outline"] for x, _ in r] ys = [y for c in self.map["counties"].values() for r in c["outline"] for _, y in r] w, h = int(self.cv["width"]), int(self.cv["height"]) self.scale = 0.95 * min(w / (max(xs) - min(xs)), h / (max(ys) - min(ys))) self.ox = (w - (max(xs) - min(xs)) * self.scale) / 2 - min(xs) * self.scale self.oy = (h - (max(ys) - min(ys)) * self.scale) / 2 + max(ys) * self.scale def xy(self, x, y): return self.ox + x * self.scale, self.oy - y * self.scale def region_centre(self, rid): """The middle of a region: the average of its counties' outline centres.""" pts = [] for n in D.REGIONS[rid]["counties"]: ring = max(self.map["counties"][self.by_name[n]]["outline"], key=len) pts.append((sum(x for x, _ in ring) / len(ring), sum(y for _, y in ring) / len(ring))) return (sum(x for x, _ in pts) / len(pts), sum(y for _, y in pts) / len(pts)) def draw_map(self): cv, c = self.cv, self.c cv.delete("all") for fips, county in self.map["counties"].items(): fill, hostile = county_colour(c, fips, self.region_of) for ring in county["outline"]: pts = [v for x, y in ring for v in self.xy(x, y)] cv.create_polygon(pts, fill=fill, outline=EDGE, width=1, stipple="gray50" if hostile else "") for r in self.map["rivers"]: pts = [v for x, y in r["line"] for v in self.xy(x, y)] cv.create_line(pts, fill=RIVER, width=3 if r["name"] in ("Missouri", "Mississippi") else 2) for rid, info in D.REGIONS.items(): x, y = self.xy(*self.region_centre(rid)) reg = c.regions[rid] label = info["counties"][0] # a county each (Step 4); who holds it: the side panel if reg.owner is not None: label += "\n" + ("ALLY" if reg.ally else "HOSTILE") cv.create_text(x, y - 12, text=label, font=("Segoe UI", 7, "bold"), fill="#222", justify="center", width=80) fx, fy = self.xy(*self.map["fort"]) cv.create_polygon(fx, fy - 9, fx + 3, fy - 3, fx + 9, fy - 3, fx + 4, fy + 2, fx + 6, fy + 9, fx, fy + 5, fx - 6, fy + 9, fx - 4, fy + 2, fx - 9, fy - 3, fx - 3, fy - 3, fill=MARK, outline=MARK_EDGE, width=2) cv.create_text(fx, fy + 18, text="Fort Leonard Wood", font=("Segoe UI", 9, "bold"), fill="#fff") self.markers = {} per_region = {} for i, m in enumerate(self.mission_list): x, y = self.xy(*self.region_centre(m.region)) k = per_region.get(m.region, 0) per_region[m.region] = k + 1 x += (k - 0.5) * 26 col = GROUP_COLOURS[m.group] if m.group is not None else UNPICKED cv.create_oval(x - 11, y - 1, x + 11, y + 21, fill=col, outline="#fff", width=2, tags=("mission", f"m{m.id}")) cv.create_text(x, y + 10, text=str(i + 1), fill="#fff" if m.group is not None else "#222", font=("Segoe UI", 9, "bold"), tags=("mission", f"m{m.id}")) self.markers[m.id] = (x, y + 10) def say(self, text): self.msg.configure(text=text) def chosen_soldier(self): sel = self.roster.selection() return sel[0] if sel else None # ── the side tabs ── def build_fort(self, tab): self.fort_text = ttk.Label(tab, justify="left", wraplength=440) self.fort_text.pack(anchor="w") row = ttk.Frame(tab) row.pack(anchor="w", pady=6) self.recruit_btn = ttk.Button(row, command=lambda: self.done(K.recruit, self.c)) self.recruit_btn.pack(side="left") ttk.Button(row, text=f"Send scouts ({D.SCOUT_COST} intel)", command=lambda: self.done(K.scout, self.c)).pack(side="left", padx=4) ttk.Button(row, text="Convoy", command=self.open_convoy).pack(side="left") ttk.Button(row, text="Facilities", command=self.open_facilities).pack(side="left", padx=4) ttk.Label(tab, text="Missions", font=("Segoe UI", 9, "bold")).pack(anchor="w", pady=(8, 0)) self.missions = tk.Listbox(tab, width=62, height=6, activestyle="none") self.missions.pack(anchor="w") self.missions.bind("<>", lambda e: self.brief_selected()) self.brief = ttk.Label(tab, justify="left", wraplength=440, foreground="#333") self.brief.pack(anchor="w", pady=4) self.plan_btn = ttk.Button(tab, text="Plan the unit", command=self.plan, state="disabled") self.plan_btn.pack(anchor="w") def build_roster(self, tab): self.roster = roster_tree(tab) row = ttk.Frame(tab) row.pack(anchor="w", pady=4) ttk.Button(row, text="Pick skill", command=self.pick_skill).pack(side="left") ttk.Button(row, text="Armory", command=self.open_armory).pack(side="left", padx=4) def build_regions(self, tab): self.region_text = tk.Text(tab, width=58, height=40, wrap="word", font=("Segoe UI", 9), background="#f4f0e4", relief="flat") self.region_text.pack(fill="both", expand=True) for g, col in enumerate(GROUP_COLOURS): self.region_text.tag_configure(f"g{g}", foreground=col, font=("Segoe UI", 9, "bold")) self.region_text.tag_configure("head", font=("Segoe UI", 10, "bold")) # ── drawing ── def refresh(self): c = self.c self.head.configure(text=f"Day {c.day} Supplies {c.supplies} Intel {c.intel} " f"Recruits waiting {c.recruits} Allied regions " f"{len(c.allies())}/{D.WIN_REGIONS} Hostile {len(c.hostile())}/{D.LOSE_REGIONS}") self.mission_list = mission_order(c) self.draw_map() wk = c.weekly() allies = "\n".join(f" {D.REGIONS[rid]['name']}: {g['name']}" for rid, g in c.allies()) or " none yet" built = ", ".join(f"{f} {lv}" for f, lv in c.facilities.items() if lv) or "none yet" if c.project: p = c.project built += (f"\nBuilding: {'rubble clearing' if p['what'] == 'clear rubble' else p['what']}" + (f" level {p['level']}" if p['what'] != 'clear rubble' and p['level'] > 1 else "") + f", {p['done'] - c.day} days left") self.fort_text.configure(text=f"Fort Leonard Wood, day {c.day}. Next week's take: " f"{wk['supplies']:+} supplies" + (f" (after {c.upkeep()} upkeep)" if c.upkeep() else "") + f", +{wk['intel']} intel, " f"+{wk['recruits']} recruits.\n\nFacilities ({c.plots} plots): {built}" f"\n\nAllies:\n{allies}\n\n" f"Assets: {', '.join(c.unlocks()) or 'none yet'}\n" f"Lost for good: {', '.join(c.lost()) or 'nothing'}") self.recruit_btn.configure(text=f"Recruit ({D.RECRUIT_COST} supplies, {c.recruits} waiting)") self.missions.delete(0, "end") for i, m in enumerate(self.mission_list): helped, fought = m.names() self.missions.insert("end", f"{i + 1}. {D.REGIONS[m.region]['name']}: for {helped} " f"({m.expires - c.day} days)") self.brief.configure(text="Pick a mission (here or on the map) for its briefing.") self.plan_btn.configure(state="disabled") self.chosen = None fill_roster(self.roster, c) t = self.region_text t.configure(state="normal") t.delete("1.0", "end") for rid, info in D.REGIONS.items(): reg = c.regions[rid] t.insert("end", info["name"] + "\n", "head") t.insert("end", f"{', '.join(info['counties'])} counties. {info['dilemma']}\n") for g, grp in enumerate(info["groups"]): t.insert("end", grp["name"], f"g{g}") t.insert("end", f": {grp['about']}. Gives: {self.gives(grp)}. You've won {reg.helped[g]} " f"for them.\n") if reg.owner is None: lead = info["groups"][0 if reg.lean >= 0 else 1]["name"] t.insert("end", f"Leaning {abs(reg.lean)}/100 toward {lead}.\n\n") else: t.insert("end", f"Held by {info['groups'][reg.owner]['name']}: " f"{'ALLY' if reg.ally else 'HOSTILE'}.\n\n") t.configure(state="disabled") new = c.log[self.shown:] if new: self.logbox.insert("end", "\n".join(new) + "\n") self.logbox.see("end") self.shown = len(c.log) if c.outcome: self.msg.configure(text="The campaign is won!" if c.outcome == "won" else "The campaign is lost. Delete the save to start over.") @staticmethod def gives(grp): bits = [f"+{v} {k}/week" for k, v in grp.get("gives", {}).items()] bits += [f"+{v} {k} for all" for k, v in grp.get("perks", {}).items()] if grp.get("heal"): bits.append("wounds heal faster") bits += grp.get("unlocks", []) return ", ".join(bits) or "nothing" # ── missions ── def on_map_click(self, e): hit = [t for i in self.cv.find_overlapping(e.x - 2, e.y - 2, e.x + 2, e.y + 2) for t in self.cv.gettags(i) if t.startswith("m") and t != "mission"] if hit: mid = int(hit[-1][1:]) m = next(m for m in self.mission_list if m.id == mid) self.show_brief(m) def on_map_hover(self, e): hit = [t for i in self.cv.find_overlapping(e.x - 2, e.y - 2, e.x + 2, e.y + 2) for t in self.cv.gettags(i) if t.startswith("m") and t != "mission"] if hit: m = next((m for m in self.mission_list if m.id == int(hit[-1][1:])), None) if m: helped, fought = m.names() self.hint.configure(text=f"{D.REGIONS[m.region]['name']}: {m.about()}.\nClick for the briefing.") def brief_selected(self): sel = self.missions.curselection() if sel: self.show_brief(self.mission_list[sel[0]]) def show_brief(self, m): self.chosen = m text = mission_brief(self.c, m) self.brief.configure(text=text) self.hint.configure(text=text) self.plan_btn.configure(state="normal") self.tabs.select(self.fort_tab) def plan(self): """Plan the unit for the chosen mission (PlanDialog), then go.""" m = self.chosen if not m: return if not self.c.ready(): self.msg.configure(text="Nobody is ready: wait for the wounded and the tired.") return d = PlanDialog(self.root, self.c, m, self.go_with) self.planner = d self.plan_picks, self.plan_count, self.plan_modes = d.picks, d.count, d.modes self.plan_travel, self.plan_go, self.plan_top, self.plan_mission = d.travel, d.go_btn, d.top, m def plan_squads(self): return self.planner.squads() def plan_changed(self): self.planner.changed() def go(self): self.planner.go() def go_with(self, squads, travel, side=None): """PlanDialog's Go: send the unit (the whole road at once, here). -> True to close the plan.""" m = self.plan_mission battle = self.done(K.launch, self.c, m.id, squads, travel, side) if battle is None: if self.msg.cget("text"): # an error: keep the plan open return False self.tabs.select(self.log_tab) # no error: they got there too late return True self.open_battle(m, battle) return True def open_battle(self, m, battle): win = tk.Toplevel(self.root) helped, fought = m.names() self.battle_view = BattleView(win, battle=battle, title=f"{D.REGIONS[m.region]['name']}: " f"against {fought}", on_done=lambda b, mid=m.id: self.back(mid, b)) def back(self, mission_id, battle): self.battle_view = None K.finish(self.c, mission_id, battle) self.save() self.refresh() self.tabs.select(self.log_tab) if self.c.outcome: messagebox.showinfo("Project 02", "The campaign is won!" if self.c.outcome == "won" else "The campaign is lost.", parent=self.root) # ── the rest ── def done(self, fn, *args): try: out = fn(*args) except K.CampaignError as err: self.msg.configure(text=f"Can't: {err}.") return None self.msg.configure(text="") self.save() self.refresh() return out def wait(self, days): self.done(K.wait, self.c, days) def wait_news(self): for _ in range(7): lines = K.wait(self.c, 1) if self.c.outcome or any(n in l for l in lines for n in NEWS): break self.save() self.refresh() class BunkerDesks(Desks): """The fort's controls for the 3D bunker (bunker.py): the same windows as the 2D one, and the roster in a window of its own (the barracks and the armory hold it). say(text): a line for the player; on_change(): after anything is done (save, redraw).""" def __init__(self, root, c, say, on_change, on_caravan=None): self.root, self.c, self.on_change = root, c, on_change self.say = say self.on_caravan = on_caravan # a caravan set out: the war room walks it (warroom.py) self.roster_top = None def send_caravan(self, rid, g, squads, travel): """Here the caravan goes a day at a time on the war table, like a mission's unit (with no war room to walk it: the whole road at once, as in the 2D window).""" if not self.on_caravan: return Desks.send_caravan(self, rid, g, squads, travel) days = K.depart_caravan(self.c, rid, g, squads, travel) self.on_caravan() return days def done(self, fn, *args): try: out = fn(*args) except K.CampaignError as err: self.say(f"Can't: {err}.") return None self.on_change() self.say("") # after on_change: the line as things are now if self.roster_top is not None and self.roster_top.winfo_exists(): fill_roster(self.roster, self.c) self.recruit_btn.configure(text=f"Recruit ({D.RECRUIT_COST} supplies, {self.c.recruits} waiting)") return out def chosen_soldier(self): if self.roster_top is None or not self.roster_top.winfo_exists(): return None sel = self.roster.selection() return sel[0] if sel else None def open_roster(self): """Everyone, with Recruit, Pick skill and the Armory for the one picked.""" if self.roster_top is not None and self.roster_top.winfo_exists(): self.roster_top.destroy() top = self.roster_top = tk.Toplevel(self.root) top.title("The roster") self.roster = roster_tree(top, height=16) fill_roster(self.roster, self.c) first = next((s.name for s in sorted(self.c.roster, key=lambda s: (s.dead, -s.rank, s.name)) if not s.dead), None) if first: self.roster.selection_set(first) row = ttk.Frame(top, padding=6) row.pack(anchor="w") self.recruit_btn = ttk.Button(row, text=f"Recruit ({D.RECRUIT_COST} supplies, {self.c.recruits} waiting)", command=lambda: self.done(K.recruit, self.c)) self.recruit_btn.pack(side="left") ttk.Button(row, text="Pick skill", command=self.pick_skill).pack(side="left", padx=4) ttk.Button(row, text="Armory", command=self.open_armory).pack(side="left") def open_memorial(self): """The rec area's memorial: everyone lost, and what the fort remembers of each (briefs.py).""" if getattr(self, "memorial_top", None) is not None and self.memorial_top.winfo_exists(): self.memorial_top.destroy() top = self.memorial_top = tk.Toplevel(self.root) top.title("The memorial") gone = B.fallen(self.c) if not gone: ttk.Label(top, text="No one has fallen. Keep it that way.", padding=16).pack() return names = self.memorial_list = tk.Listbox(top, width=46, height=18, exportselection=False) names.pack(side="left", fill="y", padx=(8, 0), pady=8) for s in gone: names.insert("end", B.memorial_line(s)) text = self.memorial_text = tk.Text(top, width=72, height=18, wrap="word") text.pack(side="left", fill="both", expand=True, padx=8, pady=8) def show(_=None): sel = names.curselection() text.configure(state="normal") text.delete("1.0", "end") text.insert("1.0", B.memorial_entry(gone[sel[0] if sel else 0])) text.configure(state="disabled") names.bind("<>", show) names.selection_set(0) show() class PlanDialog: """Plan the unit for mission m: for an incursion, which side to back (and your standing with each); each ready soldier stays, or goes in Squad 1 or Squad 2; then how they travel (what each way costs and how long it takes, or why it can't be used). Go calls on_go(squads, travel, side), which returns True to close the plan. Used by the 2D window and the war room alike.""" def __init__(self, root, c, m, on_go, caravan=None): self.caravan = caravan # (county, group): plan a caravan, not a mission if caravan: m = K._Destination(caravan[0]) self.c, self.m, self.on_go = c, m, on_go ready = sorted(c.ready(), key=lambda s: (-s.rank, s.name)) top = tk.Toplevel(root) info = D.REGIONS[m.region] top.title(f"The caravan to {info['town']}" if caravan else f"The unit for {info['name']}") self.top = top km = K.region_km(m.region) what = (f"A caravan to {info['town']}, {info['name']}, to {info['groups'][caravan[1]]['name']}, for " f"what they've put by. The rival side may be watching the road." if caravan else f"{m.about()}.\n{info['name']}, {km:.0f} km from the fort. {m.expires - c.day} days left.") ttk.Label(top, text=f"{what}\nTwo squads make the unit: up to {D.SQUAD_SIZE} soldiers in each.", padding=8, wraplength=560, justify="left").pack(anchor="w") self.side = tk.IntVar(value=0 if caravan else (-1 if m.group is None else m.group)) self.sides = {} box = ttk.Frame(top, padding=(8, 0, 8, 6)) box.pack(anchor="w") if caravan: pass elif m.group is None: # an incursion: you pick who to back ttk.Label(box, text="Back", font=("Segoe UI", 9, "bold")).pack(anchor="w") info = D.REGIONS[m.region] for g, grp in enumerate(info["groups"]): rb = ttk.Radiobutton(box, variable=self.side, value=g, command=self.changed, text=f"{B.standing_line(c, m.region, g)}. {grp['about'].capitalize()}. " f"You'd fight {info['groups'][1 - g]['name']}.") rb.pack(anchor="w") self.sides[g] = rb else: ttk.Label(box, text=f"Backing {m.names()[0]}, against {m.names()[1]}.").pack(anchor="w") grid = ttk.Frame(top, padding=(8, 0)) grid.pack(anchor="w") per_col = 16 self.picks = {} for i, s in enumerate(ready): col, row = divmod(i, per_col) v = tk.IntVar(value=1 if i < D.SQUAD_SIZE else 0) self.picks[s.name] = v ttk.Label(grid, text=f"{s.name}, {s.cls}, {D.RANK_NAMES[s.rank]}").grid( row=row, column=col * 4, sticky="w", padx=(0 if col == 0 else 16, 4)) for k, text in enumerate(("stay", "1", "2")): ttk.Radiobutton(grid, text=text, value=k, variable=v, command=self.changed).grid(row=row, column=col * 4 + 1 + k) self.count = ttk.Label(top, padding=(8, 6), font=("Segoe UI", 9, "bold")) self.count.pack(anchor="w") ttk.Label(top, text="Travel", padding=(8, 0), font=("Segoe UI", 9, "bold")).pack(anchor="w") self.travel = tk.StringVar(value="on foot") self.modes = {} box = ttk.Frame(top, padding=(8, 0)) box.pack(anchor="w") for mode in D.TRAVEL: rb = ttk.Radiobutton(box, variable=self.travel, value=mode, command=self.changed) rb.pack(anchor="w") self.modes[mode] = rb self.go_btn = ttk.Button(top, text="Go", command=self.go) self.go_btn.pack(pady=8) self.changed() def squads(self): return [[n for n, v in self.picks.items() if v.get() == k] for k in (1, 2)] def changed(self): squads = self.squads() n = sum(len(sq) for sq in squads) over = [k + 1 for k, sq in enumerate(squads) if len(sq) > D.SQUAD_SIZE] self.count.configure( text=f"Squad 1: {len(squads[0])}/{D.SQUAD_SIZE} Squad 2: {len(squads[1])}/{D.SQUAD_SIZE}" f" The unit: {n}" + (f" Too many in Squad {over[0]}" if over else ""), foreground="#7a1f1f" if over or not n else "#222") options = K.travel_options(self.c, self.m, max(1, n)) for mode, days, cost, why in options: t = D.TRAVEL[mode] kit = self.c.convoy.get(mode, []) text = (f"{mode} ({t['type']}, tier {t['tier']}): {days} day{'s' * (days > 1)} out, " f"{cost} supplies. {t['about']}" + (f"; carrying {', '.join(kit)}" if kit else "") + (f" [{why}]" if why else "")) self.modes[mode].configure(text=text, state="disabled" if why else "normal") usable = [o[0] for o in options if not o[3]] if self.travel.get() not in usable and usable: self.travel.set(usable[0]) picked = self.side.get() in (0, 1) self.go_btn.configure(state="normal" if n and not over and usable and picked else "disabled", text="Go" if picked else "Go (pick a side)") def go(self): side = None if self.caravan else (self.side.get() if self.m.group is None else None) if self.on_go(self.squads(), self.travel.get(), side): self.top.destroy() def main(): root = tk.Tk() Fort(root) root.mainloop() if __name__ == "__main__": main()