"""Drive the real battle window on a virtual display. Not part of the unit suite (it needs one): xvfb-run -a -s "-screen 0 1280x800x24" python3 tests/gui_smoke.py Opens a seeded battle, selects, moves by a click, then lets the AI play until it ends. Prints one line per check and exits non-zero on the first failure. """ import os import sys import time import tkinter as tk from tkinter import ttk from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) from p02 import data as D # noqa: E402 from p02.view import CELL, BattleView # noqa: E402 root = tk.Tk() root.geometry("1200x700") v = BattleView(root, seed=5) def pump(seconds): end = time.time() + seconds while time.time() < end: root.update() time.sleep(0.01) def check(ok, what): print(("ok " if ok else "FAIL ") + what) if not ok: root.destroy() sys.exit(1) def click(x, y): v.on_click(type("E", (), {"x": x * CELL + CELL // 2, "y": y * CELL + CELL // 2})) pump(0.1) pump(0.4) c = v.c check(len(c.find_all()) >= D.GRID_W * D.GRID_H, f"field drawn: {len(c.find_all())} items") check(v.sel is not None and v.sel.side == "squad", f"a soldier selected: {v.sel.name}") squad = [u for u in v.b.units if u.side == "squad"] other = squad[1] click(other.x, other.y) check(v.sel is other, f"clicked {other.name}: selected") cells = v.b.reach(other, 1) goal = max(cells, key=lambda q: (q[0], -q[1])) click(*goal) check((other.x, other.y) == goal and other.actions == 1, f"moved {other.name} to {goal}, 1 action left") v.on_overwatch() check(other.overwatch and other.actions == 0, f"{other.name} on overwatch") v.on_end() check(v.b.turn == 2 or v.b.outcome, f"turn ended: now turn {v.b.turn}") for _ in range(60): if v.b.outcome: break v.on_auto() pump(0.02) check(v.b.outcome in ("won", "lost"), f"battle over: {v.b.outcome} on turn {v.b.turn}") check("Mission" in v.status.cget("text"), "status says how it ended") root.destroy() # the fort and the map (Step 3a): brief a mission from its marker, fight it (AI), come home; # a temp save, never the real one import tempfile # noqa: E402 from p02 import campaign as K # noqa: E402 from p02.campaignview import Fort # noqa: E402 root = tk.Tk() save = Path(tempfile.mkdtemp()) / "save.json" f = Fort(root, camp=K.new_campaign(4), save_file=save) pump(0.4) check(len(f.cv.find_all()) > 115, f"map drawn: {len(f.cv.find_all())} items") texts = {f.cv.itemcget(i, "text") for i in f.cv.find_all() if f.cv.type(i) == "text"} check({"Phelps", "Cole", "Carter"} <= texts and not any("County" in t for t in texts), "map: a short name for each county") check(len(f.roster.get_children()) == len(D.START_ROSTER), "roster tab: everyone") check(len(f.markers) == len(f.c.missions) == 1, "a mission marker on the map") day = f.c.day f.wait(1) check(f.c.day == day + 1 and save.exists(), "a day passed, autosaved") # Step 3c part 3: the convoy window; trucks locked here, so nothing to fit on them f.open_convoy() pump(0.2) check(f.convoy_top.winfo_exists() and not any(k[0] == "trucks" for k in f.convoy_buttons), "convoy: open, trucks locked") f.convoy_top.destroy() # Step 3c: the armory for a rifleman: buy a surplus rifle; the roster shows it r = next(s for s in f.c.roster if s.cls == "rifleman") f.roster.selection_set(r.name) f.open_armory() pump(0.2) btns = f.armory_buttons check(str(btns[("rifle", 0)].cget("state")) == "disabled" and "carrying it" in btns[("rifle", 0)].cget("text"), "armory: carrying the scrap-built rifle") check(str(btns[("rifle", 2)].cget("state")) == "disabled" and "locked" in btns[("rifle", 2)].cget("text"), "armory: military locked") supplies = f.c.supplies btns[("rifle", 1)].invoke() pump(0.2) check(r.gun() == "pre-war surplus rifle" and f.c.supplies == supplies - D.WEAPON_TIERS[1]["cost"] and f.roster.set(r.name, "weapon") == "pre-war surplus rifle", "armory: bought, roster shows it") # armor and utility (3c part 2): a flak jacket (2 slots), then a smoke grenade in slot 1 pump(0.2) btns = f.armory_buttons check(str(btns[("armor", "Army plate")].cget("state")) == "disabled", "armor: Army plate locked") btns[("armor", "flak jacket")].invoke() pump(0.2) slot_labels = lambda: [w.cget("text") for box in f.armory_top.winfo_children() # noqa: E731 for w in box.winfo_children() if isinstance(w, ttk.Label) and w.cget("text").startswith("slot ")] check(r.armor == "flak jacket" and slot_labels() == ["slot 1: empty", "slot 2: empty"] and ("slot", 0, "medkit") in f.armory_buttons, f"armor: flak jacket on, 2 slots: {slot_labels()}") f.armory_buttons[("slot", 0, "smoke grenade")].invoke() pump(0.2) check(r.utility == ["smoke grenade"] and "slot 1: smoke grenade" in slot_labels(), "utility: smoke grenade packed, shown") check(str(f.armory_buttons[("slot", 1, "flashbang")].cget("state")) == "disabled", "utility: flashbang locked") f.armory_top.destroy() mid = f.mission_list[0].id next(m for m in f.c.missions if m.id == mid).expires = f.c.day + 10 # (it's in a far county: time to walk) x, y = f.markers[mid] f.on_map_click(type("E", (), {"x": int(x), "y": int(y)})) check(f.chosen is not None and f.chosen.id == mid and "Win:" in f.brief.cget("text"), "clicked the marker: the briefing") f.plan() pump(0.2) check(sum(v.get() for v in f.plan_picks.values()) == D.SQUAD_SIZE, f"plan: {D.SQUAD_SIZE} picked") # Step 3b: the four left over go in Squad 2; the unit is 12; travel offers what it can for n, v in f.plan_picks.items(): if v.get() == 0: v.set(2) f.plan_changed() pump(0.1) check("Squad 1: 8/8" in f.plan_count.cget("text") and "Squad 2: 4/8" in f.plan_count.cget("text"), f"plan: {f.plan_count.cget('text')}") check(str(f.plan_modes["on foot"].cget("state")) == "normal" and str(f.plan_modes["trucks"].cget("state")) == "disabled" and "needs an ally" in f.plan_modes["trucks"].cget("text"), "travel: on foot yes, trucks locked") check(str(f.plan_go.cget("state")) == "disabled" and "pick a side" in f.plan_go.cget("text") and len(f.planner.sides) == 2, "plan: an incursion, Go waits for a side") f.planner.sides[1].invoke() pump(0.1) check(str(f.plan_go.cget("state")) == "normal", "Go is live") f.go() pump(0.3) bv = f.battle_view check(bv is not None, "the battle opened") check(f.plan_mission.group == 1, "the side picked is the side backed") from p02.view import SQUAD2 # noqa: E402 mine = [u for u in bv.b.units if u.side == "squad"] check(sorted(u.squad for u in mine) == [1] * 8 + [2] * 4, "the battle has both squads") teal = [i for i in bv.c.find_all() if bv.c.type(i) == "oval" and bv.c.itemcget(i, "fill") == SQUAD2] check(len(teal) == 4, f"Squad 2 drawn teal: {len(teal)}") # the pistol: bring an enemy into plain sight; out of ammo, Pistol, click it u = mine[0] foe = next(t for t in bv.b.units if t.side == "enemy") spot = next((x, y) for x in range(D.GRID_W) for y in range(D.GRID_H) if 2 <= abs(x - u.x) + abs(y - u.y) <= 4 and bv.b.open(x, y) and bv.b.los((u.x, u.y), (x, y))) foe.x, foe.y, foe.awake = *spot, True bv.sel = u u.ammo = 0 bv.on_pistol() check(bv.mode == "pistol", "Pistol button: pistol out") bv.on_click(type("E", (), {"x": foe.x * CELL + CELL // 2, "y": foe.y * CELL + CELL // 2})) pump(0.1) check(any(f"{u.name} hits" in l or f"{u.name} misses" in l for l in bv.b.log) and u.ammo == 0 and bv.mode is None, "pistol shot with an empty clip") # smoke from the soldier who packed it: Smoke, click next to them; the haze is drawn sm = next(x for x in mine if x.name == r.name) if any(x.name == r.name for x in mine) else None if sm and sm.alive: bv.sel, sm.actions = sm, 2 bv.on_smoke() bv.on_click(type("E", (), {"x": sm.x * CELL + CELL // 2, "y": sm.y * CELL + CELL // 2})) pump(0.1) check(sm.smoke == 0 and (sm.x, sm.y) in bv.b.smoke and bv.c.find_withtag("smoke"), "smoke thrown and drawn") else: print(f"note {r.name} not in the unit: smoke not exercised here (unit tests cover it)") bv.on_auto_all() pump(0.1) before = f.c.day bv.on_back() pump(0.3) check(f.c.day == before + 1 and f.battle_view is None, f"home ({bv.b.outcome}): a day passed") check(K.load(save).day == f.c.day, "the save has it") # Step 3d: the facilities window, a build, the crew busy, the build done f.c.supplies = 1000 f.open_facilities() pump(0.1) fb = f.facility_buttons check(str(fb["drill yard"]["state"]) == "normal" and "70 supplies" in fb["drill yard"]["text"], "drill yard can be built") check("needs" not in fb["drill yard"]["text"] and str(fb["clear rubble"]["state"]) == "normal", "rubble can be cleared") fb["drill yard"].invoke() pump(0.1) fb = f.facility_buttons check(f.c.project and f.c.project["what"] == "drill yard" and f.c.supplies == 930, "build started, paid") check("being built" in fb["drill yard"]["text"] and str(fb["radio room"]["state"]) == "disabled", "crew busy") check("Building: drill yard" in f.fort_text["text"], "the Fort tab shows the build") if os.environ.get("P02_SHOT"): pump(0.3) os.system(f"xwd -root -silent > {os.environ['P02_SHOT']}") == 0 f.facilities_top.destroy() f.wait(f.c.project["done"] - f.c.day) pump(0.1) check(f.c.level("drill yard") == 1 and "drill yard 1" in f.fort_text["text"], "built, and on the Fort tab") check(K.load(save).facilities == {"drill yard": 1}, "the save has the facility") # Step 3e part 3: the war room closed with the unit on the road; the 2D window walks the rest c2 = K.new_campaign(4) c2.intel = 100 while not c2.missions: K.scout(c2) far = max(c2.missions, key=lambda m: K.travel_days(m.region, "on foot")) far.expires = c2.day + 30 set_out = c2.day days = K.depart(c2, far.id, [[s.name for s in c2.ready()[:4]]], "on foot", 0) if K.on_road(c2): K.road_day(c2) save2 = Path(tempfile.mkdtemp()) / "save.json" f2 = Fort(tk.Toplevel(root), camp=c2, save_file=save2) pump(0.6) check(f2.battle_view is not None and f2.c.trip["stage"] == "battle" and f2.c.day == set_out + days - 1, f"reopened on the road ({days} days): walked the rest, the battle opened") check(K.load(save2).trip["stage"] == "battle", "the save has it") # the plan stays open when Go is refused, and closes when it isn't from p02.campaignview import PlanDialog # noqa: E402 c3 = K.new_campaign(4) c3.intel = 100 while not c3.missions: K.scout(c3) answer = [] pd = PlanDialog(root, c3, c3.missions[0], lambda sq, tr, side: answer.pop() and side == 0) pd.sides[0].invoke() answer.append(False) pd.go_btn.invoke() pump(0.1) check(pd.top.winfo_exists(), "plan: refused Go stays open") answer.append(True) pd.go_btn.invoke() pump(0.1) check(not pd.top.winfo_exists(), "plan: Go closes it") # Step 3e part 4: the bunker's desks (the same windows, from a room): the roster with Recruit, # Pick skill and the Armory for the one picked; a build; a refusal said, not saved from p02.campaignview import BunkerDesks # noqa: E402 c4 = K.new_campaign(4) c4.supplies, c4.recruits = 1000, 1 said, changes = [], [] bd = BunkerDesks(root, c4, said.append, lambda: changes.append(c4.day)) bd.open_roster() pump(0.2) check(len(bd.roster.get_children()) == len(c4.roster) and bd.chosen_soldier(), "desks: the roster, one picked") bd.recruit_btn.invoke() pump(0.1) check(len(bd.roster.get_children()) == len(c4.roster) == len(D.START_ROSTER) + 1 and changes and "0 waiting" in bd.recruit_btn.cget("text"), "desks: recruited, the roster shows them") name = bd.chosen_soldier() bd.open_armory() pump(0.2) check(bd.armory_top.winfo_exists() and name in bd.armory_top.title(), f"desks: the armory for {name}") bd.armory_top.destroy() bd.roster_top.destroy() bd.open_armory() check(said[-1] == "Pick a soldier first.", "desks: no roster open, no soldier: said so") bd.open_facilities() pump(0.1) n = len(changes) bd.facility_buttons["radio room"].invoke() pump(0.1) check(c4.project["what"] == "radio room" and len(changes) == n + 1 and said[-1] == "", "desks: a build, saved") c4.supplies = 0 bd.open_convoy() pump(0.1) check(bd.convoy_top.winfo_exists(), "desks: the convoy") n = len(changes) bd.done(K.recruit, c4) check(said[-1].startswith("Can't:") and len(changes) == n, "desks: a refusal said, nothing saved") # Step 4 part 3: caravans, from the convoy window: a faction at 50 has a recruit and its weapon put by D.RAID_CHANCE = 0.0 # a quiet road here (the war room's smoke has the raid) c4.supplies = 500 c4.trip = None bd.open_caravans() pump(0.1) check(not bd.caravan_buttons, "caravans: nobody trades yet") c4.affinity["phelps:0"] = 50 pile = c4.pile("phelps", 0) weapon = next(i for i in D.REGIONS["phelps"]["groups"][0]["gear"] if i in D.WEAPONS) pile["recruits"], pile["items"] = 1, {weapon: 2} bd.open_convoy() pump(0.1) bd.open_caravans() pump(0.1) b = bd.caravan_buttons[("phelps", 0)] check(str(b.cget("state")) == "normal" and len(bd.caravan_buttons) == 1, "caravans: Rolla's faction, Send") b.invoke() pump(0.2) cp = bd.caravan_plan check(cp.top.winfo_exists() and "caravan to Rolla" in cp.top.title() and not cp.sides, "caravans: the plan, no side") for n, v in cp.picks.items(): v.set(1 if n == list(cp.picks)[0] else 0) cp.changed() pump(0.1) n_before = len(c4.roster) cp.go_btn.invoke() pump(0.2) check(not cp.top.winfo_exists() and c4.store.get(weapon) == 2 and len(c4.roster) == n_before + 1 and c4.trip is None, f"caravans: home with {weapon} x2 and a recruit") # Step 4 part 3b: in the 2D window a raided caravan's battle opens, and it's settled when it's over D.RAID_CHANCE = 1.0 c5 = K.new_campaign(6) c5.affinity["phelps:0"] = 25 c5.pile("phelps", 0)["recruits"] = 1 f5 = Fort(tk.Toplevel(root), camp=c5, save_file=Path(tempfile.mkdtemp()) / "save.json") pump(0.2) f5.open_caravans() f5.caravan_buttons[("phelps", 0)].invoke() pump(0.1) f5.caravan_plan.go_btn.invoke() pump(0.3) bv5 = f5.battle_view check(bv5 is not None and c5.trip and c5.trip["stage"] == "battle", "raid: ambushed, the battle opened") bv5.on_auto_all() pump(0.1) bv5.on_back() pump(0.2) check(c5.trip is None and any("caravan" in l for l in c5.log[-4:]), f"raid: settled ({bv5.b.outcome})") D.RAID_CHANCE = 0.0 # the armory fits from the store f5.c.store = {"medkit": 1} f5.roster.selection_set(next(x.name for x in f5.c.roster if not x.dead and len(x.utility) < D.ARMOR[x.armor]["slots"])) f5.open_armory() pump(0.1) who = f5.chosen_soldier() f5.store_buttons["medkit"].invoke() pump(0.1) check(f5.c.store == {} and "medkit" in f5.c.soldier(who).utility, f"store: a medkit fitted to {who}, free") # Step 3f: the memorial (the rec area): nobody yet, then the fallen with their records bd.open_memorial() pump(0.1) check(bd.memorial_top.winfo_exists() and not hasattr(bd, "memorial_list"), "memorial: no one has fallen") from p02 import briefs as B # noqa: E402 s0, s1 = c4.roster[0], c4.roster[1] s0.dead, s0.fate = True, {"how": "missing in action", "day": 9, "where": "The Rolla Plateau", "story": "shot by a raider with machete, turn 3"} s1.dead = True bd.open_memorial() pump(0.1) check(bd.memorial_list.size() == 2 and bd.memorial_list.get(0) == B.memorial_line(s0), "memorial: the wall, newest first") check(bd.memorial_text.get("1.0", "end").strip() == B.memorial_entry(s0), "memorial: the first one's record") bd.memorial_list.selection_clear(0) bd.memorial_list.selection_set(1) bd.memorial_list.event_generate("<>") pump(0.1) check("before the fort kept its records" in bd.memorial_text.get("1.0", "end"), "memorial: pick another, theirs") root.destroy() print("GUI SMOKE PASSED")