"""Project 02, Step 3e parts 1 and 2: the war room and its pieces (Dillon, 2026-11-12). Needs Panda3D: skipped where it isn't installed. Run with the 3D venv: ~/venvs/p02-3d/bin/python -m unittest tests.test_warroom (on a display, or under xvfb-run: it renders offscreen).""" import math import unittest from p02 import briefs as B from p02 import campaign as K from p02 import data as D from p02 import mapstate as MS try: from panda3d.core import GeomVertexReader, PNMImage, loadPrcFileData except ImportError: # pragma: no cover GeomVertexReader = None BASE = None def setUpModule(): global BASE if GeomVertexReader is None: return loadPrcFileData("", "window-type offscreen\nwin-size 320 200\naudio-library-name null\n") from direct.showbase.ShowBase import ShowBase BASE = ShowBase() def first_colour(np): geom = np.node().getGeom(0) r = GeomVertexReader(geom.getVertexData(), "color") return tuple(r.getData4()) def hexrgb(h): return tuple(int(h[i:i + 2], 16) / 255 for i in (1, 3, 5)) @unittest.skipIf(GeomVertexReader is None, "Panda3D is not installed") class TheRoom(unittest.TestCase): def setUp(self): from p02 import warroom as W self.W = W for n in BASE.render.findAllMatches("war room"): n.removeNode() # the last test's room (not the camera) self.c = K.new_campaign(4) self.room = W.WarRoom(BASE, self.c) def test_every_county_on_the_table(self): W = self.W counties = MS.the_map()["counties"] self.assertEqual(set(self.room.counties), set(counties)) for fips, n in self.room.counties.items(): lo, hi = n.getTightBounds() self.assertGreater(lo.x, -W.TABLE[0] / 2, fips) self.assertLess(hi.x, W.TABLE[0] / 2, fips) self.assertGreater(lo.y, -W.TABLE[1] / 2, fips) self.assertLess(hi.y, W.TABLE[1] / 2, fips) self.assertAlmostEqual(lo.z, W.MAP_Z, places=4) self.assertGreater(W.MAP_Z, W.TABLE_Z) # on the paper, above the table top normals = GeomVertexReader(n.node().getGeom(0).getVertexData(), "normal") while not normals.isAtEnd(): # every piece faces up, to the camera self.assertGreater(normals.getData3().z, 0.99, fips) def test_lit_by_the_lamp(self): from panda3d.core import LightAttrib, PointLight lights = self.room.root.getAttrib(LightAttrib) kinds = [type(lights.getOnLight(i).node()).__name__ for i in range(lights.getNumOnLights())] self.assertIn("PointLight", kinds) lamp = next(lights.getOnLight(i) for i in range(lights.getNumOnLights()) if isinstance(lights.getOnLight(i).node(), PointLight)) p = lamp.getPos(BASE.render) self.assertAlmostEqual((p.x, p.y), (0, 0)) # over the middle of the table self.assertTrue(self.W.TABLE_Z < p.z < self.W.HALL) def test_the_map_keeps_its_shape(self): # one scale both ways: the state isn't stretched to fit the table W = self.W x0, y0, x1, y1 = MS.extent() (ax, ay), (bx, by) = W.table_xy(x0, y0), W.table_xy(x1, y1) self.assertAlmostEqual((bx - ax) / (x1 - x0), (by - ay) / (y1 - y0)) self.assertAlmostEqual((ax + bx) / 2, 0) self.assertAlmostEqual((ay + by) / 2, 0) fx, fy = W.table_xy(*MS.the_map()["fort"]) self.assertTrue(ax < fx < bx and ay < fy < by) def test_coloured_as_the_campaign_stands(self): W = self.W regions = MS.region_of() for fips, n in self.room.counties.items(): want, hostile = MS.county_colour(self.c, fips, regions) self.assertEqual(self.room.colours[fips], MS.blend(want, "#6b6b6b", 0.35) if hostile else want) got = first_colour(n)[:3] for g, w in zip(got, hexrgb(MS.blend(self.room.colours[fips], W.PAPER, 0.15))): self.assertAlmostEqual(g, w, places=2) home = next(f for f, c in MS.the_map()["counties"].items() if c["name"] == f"{D.HOME} County") self.assertEqual(self.room.colours[home], MS.HOME) def test_an_ally_shows(self): rid = next(iter(D.REGIONS)) self.c.regions[rid].owner, self.c.regions[rid].ally = 0, True room = self.W.WarRoom(BASE, self.c) fips = next(f for f, r in MS.region_of().items() if r == rid) self.assertEqual(room.colours[fips], MS.blend(MS.LAND, MS.GROUP_COLOURS[0], 0.85)) self.c.regions[rid].ally = False room = self.W.WarRoom(BASE, self.c) self.assertEqual(room.colours[fips], MS.blend(MS.blend(MS.LAND, MS.GROUP_COLOURS[0], 0.4), "#6b6b6b", 0.35)) def test_you_come_in_by_the_door_and_end_looking_down_on_the_whole_map(self): W, cam, r = self.W, BASE.camera, self.room top = W.map_pose(r.view, r.fov()) r.at(0) self.assertEqual(tuple(round(v, 3) for v in cam.getPos()), W.DOOR_POSE[0]) self.assertFalse(r.overhead.isHidden()) # the ceiling and the lamp, at the door r.at(W.INTRO_SECONDS) self.assertAlmostEqual(math.dist(cam.getPos(), top[0]), 0, places=4) r.at(W.INTRO_SECONDS + 10) self.assertAlmostEqual(math.dist(cam.getPos(), top[0]), 0, places=4) # and stays self.assertAlmostEqual(cam.getP(), W.OUT_PITCH, places=3) # looking straight down self.assertTrue(r.overhead.isHidden()) # nothing between the view and the map r.at(W.INTRO_SECONDS / 2) mid = cam.getPos() self.assertTrue(top[0][2] > mid.z > W.DOOR_POSE[0][2]) self.assertLess(W.DOOR_POSE[0][1], top[0][1]) # the door is behind the table def test_the_staff_are_at_work(self): r = self.room self.assertEqual(len(r.staff), 3) r.at(1.0) a = r.clerk.getPos(), r.clerk_arms[0].getP(), r.radio_head.getP(), r.officer_arms[1].getP() r.at(4.0) b = r.clerk.getPos(), r.clerk_arms[0].getP(), r.radio_head.getP(), r.officer_arms[1].getP() self.assertGreater((a[0] - b[0]).length(), 0.5) # the clerk walked for i in (1, 2, 3): self.assertNotAlmostEqual(a[i], b[i], places=1) r.at(13.0) # a round is 12 s self.assertAlmostEqual((r.clerk.getPos() - a[0]).length(), 0, places=4) ys = [] for t in range(0, 12): r.at(t) ys.append(r.clerk.getY()) self.assertTrue(-7.6 < r.clerk.getX() < 7.6) # stays in the room self.assertGreater(max(ys) - min(ys), 2.5) def test_a_frame_shows_the_map(self): W = self.W self.room.at(W.INTRO_SECONDS + 1) for _ in range(2): BASE.graphicsEngine.renderFrame() img = PNMImage() self.assertTrue(BASE.win.getScreenshot(img)) w, h = img.getXSize(), img.getYSize() if __import__("os").environ.get("P02_SHOT"): img.write(__import__("panda3d.core", fromlist=["Filename"]).Filename(__import__("os").environ["P02_SHOT"])) middle = [img.getXel(int(w * fx), int(h * fy)) for fx in (0.3, 0.5, 0.7) for fy in (0.3, 0.45, 0.6)] warm = [p for p in middle if p[0] > 0.45 and p[0] > p[2]] # paper-coloured: warm and light self.assertGreaterEqual(len(warm), 7, middle) corners = [img.getXel(2, h - 3), img.getXel(w - 3, h - 3)] self.assertTrue(all(sum(p) / 3 < 0.45 for p in corners)) # the floor: dark def busy_campaign(): """Missions in several regions (two in one), an ally, a hostile, a lean.""" c = K.new_campaign(4) c.intel = 100 for _ in range(D.MAX_MISSIONS - len(c.missions)): K.scout(c) m = c.missions[0] # one with its side picked, and a second in its county m.group, m.pods = 1, [["raider", "raider"]] c.missions.append(K.Mission(c.next_id, m.region, 0, "defend", m.expires + 1, [["militiaman"]])) c.next_id += 1 rids = list(D.REGIONS) c.regions[rids[0]].owner, c.regions[rids[0]].ally = 0, True c.regions[rids[1]].owner, c.regions[rids[1]].ally = 1, False c.regions[rids[2]].lean = -40 c.regions[rids[3]].lean = 0 return c def screen_point(n): """Where the middle of NodePath n shows on screen, -1..1 each way (None if off screen).""" from panda3d.core import Point2 lo, hi = n.getTightBounds(BASE.cam) p = Point2() return (p.x, p.y) if BASE.camLens.project((lo + hi) / 2, p) else None def main_part(key, n): """The solid you'd click on a piece: the bunker, a toy soldier, a mission's flag, a block.""" parts = {"fort": "bunker", "unit": "toy soldier 1-body"} return n.find("**/" + parts.get(key, "flag" if key.startswith("mission") else "block")) @unittest.skipIf(GeomVertexReader is None, "Panda3D is not installed") class ThePieces(unittest.TestCase): """Step 3e part 2: toy pieces on the table, and clicking one for its briefing.""" def setUp(self): from p02 import warroom as W self.W = W for n in BASE.render.findAllMatches("war room"): n.removeNode() self.c = busy_campaign() self.room = W.WarRoom(BASE, self.c) self.room.at(W.INTRO_SECONDS + 1) def test_a_piece_for_everything(self): c, r = self.c, self.room want = {"fort", "unit"} | {f"region:{rid}" for rid in D.REGIONS} | {f"mission:{m.id}" for m in c.missions} self.assertEqual(set(r.pieces), want) self.assertGreaterEqual(len(c.missions), 3) def test_standing_on_the_map(self): W = self.W for key, n in self.room.pieces.items(): lo, hi = n.getTightBounds(BASE.render) self.assertAlmostEqual(lo.z, W.MAP_Z, places=3, msg=key) # on the paper, not in it or above self.assertTrue(-W.TABLE[0] / 2 < lo.x and hi.x < W.TABLE[0] / 2, key) self.assertTrue(-W.TABLE[1] / 2 < lo.y and hi.y < W.TABLE[1] / 2, key) self.assertLess(hi.z - lo.z, 0.6, key) # toys, not furniture def test_where_they_stand(self): W, r = self.W, self.room fx, fy = W.table_xy(*MS.the_map()["fort"]) self.assertAlmostEqual(r.pieces["fort"].getX(), fx) self.assertAlmostEqual(r.pieces["fort"].getY(), fy) u = r.pieces["unit"].getPos() self.assertLess(math.dist((u.x, u.y), (fx, fy)), 0.5) # home: beside the fort for m in self.c.missions: cx, cy = W.table_xy(*MS.region_centre(m.region)) p = r.pieces[f"mission:{m.id}"].getPos() self.assertLess(math.dist((p.x, p.y), (cx, cy)), 0.6, m.region) spots = [(round(n.getX(), 3), round(n.getY(), 3)) for k, n in r.pieces.items() if k.startswith("mission")] self.assertEqual(len(spots), len(set(spots))) # two in a region don't stack def test_the_unit_goes_out(self): W, c = self.W, self.c m = c.missions[0] c.trip = {"mission": m.id, "travel": "on foot", "days": 3} room = W.WarRoom(BASE, c) cx, cy = W.table_xy(*MS.region_centre(m.region)) u = room.pieces["unit"].getPos() self.assertLess(math.dist((u.x, u.y), (cx, cy)), 0.5) def test_flags_numbered_as_the_2d_map(self): for i, m in enumerate(B.mission_order(self.c)): n = self.room.pieces[f"mission:{m.id}"] texts = {t.node().getText() for t in n.findAllMatches("**/flag number")} self.assertEqual(texts, {str(i + 1)}) flag = first_colour(n.find("**/flag"))[:3] want = MS.GROUP_COLOURS[m.group] if m.group is not None else MS.UNPICKED # cream: no side yet for g, w in zip(flag, hexrgb(want)): self.assertAlmostEqual(g, w, places=2) self.assertTrue(any(m.group is None for m in self.c.missions)) # (both kinds were checked) self.assertTrue(any(m.group is not None for m in self.c.missions)) def test_region_blocks_show_who_holds_it(self): r, W = self.room, self.W for rid, reg in self.c.regions.items(): n = r.pieces[f"region:{rid}"] block = n.find("**/block") lo, hi = block.getTightBounds(n) h = hi.z - lo.z col = first_colour(block)[:3] cap = n.find("**/cap") if reg.owner is not None: want, wh = MS.GROUP_COLOURS[reg.owner], 0.16 self.assertFalse(cap.isEmpty(), rid) c = first_colour(cap)[:3] self.assertTrue(sum(c) / 3 > 0.8 if reg.ally else sum(c) / 3 < 0.2, rid) else: self.assertTrue(cap.isEmpty(), rid) if reg.lean: want, wh = MS.GROUP_COLOURS[0 if reg.lean > 0 else 1], 0.08 else: want, wh = W.TOY_WOOD, 0.06 self.assertAlmostEqual(h, wh, places=3, msg=rid) for g, w in zip(col, hexrgb(want)): self.assertAlmostEqual(g, w, places=2, msg=rid) def test_click_a_piece_for_its_briefing(self): r = self.room self.assertEqual(r.brief_text.getText(), self.W.HINT) for key, n in r.pieces.items(): xy = screen_point(main_part(key, n)) self.assertIsNotNone(xy, key) self.assertEqual(r.pick(*xy), key) r.show(r.pick(*xy)) self.assertEqual(r.chosen, key) self.assertEqual(r.brief_text.getText(), r.brief(key)) m = B.mission_order(self.c)[1] self.assertTrue(r.brief(f"mission:{m.id}").startswith("Mission 2. " + B.mission_brief(self.c, m)[:20])) self.assertEqual(r.brief("fort"), B.fort_brief(self.c)) self.assertEqual(r.brief("unit"), B.unit_brief(self.c)) rid = next(iter(D.REGIONS)) self.assertEqual(r.brief(f"region:{rid}"), B.region_brief(self.c, rid)) def test_no_piece_stands_on_another(self): # every region with two missions, and the unit out to each in turn: footprints never meet W = self.W c = self.c proto = c.missions[0] c.missions = [K.Mission(i * 2 + j + 1, rid, j % 2, proto.kind, c.day + 5 + j, proto.pods) for i, rid in enumerate(D.REGIONS) for j in range(2)] for out in [None] + c.missions[::2]: c.trip = {"mission": out.id, "travel": "on foot", "days": 3} if out else None room = W.WarRoom(BASE, c) boxes = {k: n.getTightBounds(BASE.render) for k, n in room.pieces.items()} keys = sorted(boxes) for i, a in enumerate(keys): for b in keys[i + 1:]: (alo, ahi), (blo, bhi) = boxes[a], boxes[b] apart = (ahi.x + 0.01 < blo.x or bhi.x + 0.01 < alo.x or ahi.y + 0.01 < blo.y or bhi.y + 0.01 < alo.y) self.assertTrue(apart, f"{a} and {b} (unit out to {out and out.region})") room.at(W.INTRO_SECONDS + 1) for key, n in room.pieces.items(): # and from where you stand, each can be clicked lo, hi = n.getTightBounds(BASE.render) self.assertTrue(-W.TABLE[0] / 2 < lo.x and hi.x < W.TABLE[0] / 2) self.assertEqual(room.pick(*screen_point(main_part(key, n))), key, f"(unit out to {out and out.region})") room.root.removeNode() def test_the_map_itself_is_not_a_piece(self): r = self.room far = r.counties[next(f for f, c in MS.the_map()["counties"].items() if c["name"] == "Atchison County")] xy = screen_point(far) # the far corner of the state: no piece there self.assertIsNotNone(xy) self.assertIsNone(r.pick(*xy)) self.assertIsNone(r.pick(-0.98, -0.98)) # the floor r.show("fort") r.show(r.pick(-0.98, -0.98)) # clicking nothing puts the hint back self.assertEqual(r.brief_text.getText(), self.W.HINT) @unittest.skipIf(GeomVertexReader is None, "Panda3D is not installed") class TimeOnTheTable(unittest.TestCase): """Step 3e part 3: the unit's piece crosses the map a day at a time; the view leans in; the battle; the piece comes home.""" def setUp(self): from p02 import warroom as W self.W = W for n in BASE.render.findAllMatches("war room"): n.removeNode() self.c = busy_campaign() self.m = max(self.c.missions, key=lambda m: K.travel_days(m.region, "on foot")) self.m.expires = self.c.day + 30 self.saves = [] self.battles = [] self.room = W.WarRoom(BASE, self.c, save=lambda c: self.saves.append(c.day)) self.room.on_arrive = lambda m, b: self.battles.append((m, b)) self.t0 = W.INTRO_SECONDS + 1 self.room.at(self.t0) def unit_xy(self): p = self.room.pieces["unit"].getPos() return p.x, p.y def send(self, n=4): r = self.room r.show(f"mission:{self.m.id}") self.assertTrue(r.can_plan()) self.assertFalse(r.plan_btn.isHidden()) day = self.c.day side = 0 if self.m.group is None else None # pick a side for an incursion self.assertTrue(r.send([[s.name for s in self.c.ready()[:n]]], "on foot", side)) self.assertEqual(self.saves, [day]) # saved as it sets out return self.c.trip["days"] def test_the_plan_button_is_for_missions_when_the_unit_is_home(self): r = self.room for key in ("fort", "unit", f"region:{self.m.region}", None): r.show(key) self.assertTrue(r.plan_btn.isHidden(), key) r.show(f"mission:{self.m.id}") self.assertFalse(r.plan_btn.isHidden()) self.send() r.show(f"mission:{self.m.id}") self.assertTrue(r.plan_btn.isHidden()) # the unit is out def test_a_day_at_a_time_across_the_map(self): W, r, c = self.W, self.room, self.c home = r.unit_home day = c.day days = self.send() self.assertGreaterEqual(days, 3) target = r.journey["to"] self.assertEqual(c.day, day) # setting out takes no day self.assertIn(f"Day {day}.", r.hud_text.getText()) last = math.dist(home, target) for k in range(1, days): r.at(self.t0 + k * W.DAY_SECONDS - 0.01) self.assertEqual(c.day, day + k - 1, k) # not yet r.at(self.t0 + k * W.DAY_SECONDS + 0.01) self.assertEqual(c.day, day + k, k) # a day passed self.assertEqual(self.saves[-1], c.day) # and was saved self.assertIn(f"Day {c.day}.", r.hud_text.getText()) self.assertIn(f"day {k + 1} of {days}", r.hud_text.getText()) here = math.dist(self.unit_xy(), target) self.assertLess(here, last, k) # closer every day frac = math.dist(home, self.unit_xy()) / math.dist(home, target) self.assertAlmostEqual(frac, (k + 0.01 / W.DAY_SECONDS) / days, places=2) last = here r.at(self.t0 + (k + 0.5) * W.DAY_SECONDS) # and halfway through a day frac = math.dist(home, self.unit_xy()) / math.dist(home, target) self.assertAlmostEqual(frac, (k + 0.5) / days, places=4) self.assertEqual(self.battles, []) def test_the_end_of_the_road_leans_in_then_the_battle(self): W, r, c = self.W, self.room, self.c days = self.send() target = r.journey["to"] end = self.t0 + days * W.DAY_SECONDS r.at(end - 0.01) cam_far = BASE.camera.getPos() r.at(end + 0.01) self.assertAlmostEqual(math.dist(self.unit_xy(), target), 0, places=5) # there self.assertEqual(r.journey["phase"], "lean") self.assertEqual(c.day, self.saves[-1]) r.at(end + W.LEAN_SECONDS - 0.01) self.assertEqual(self.battles, []) # leaning in, not yet r.at(end + W.LEAN_SECONDS + 0.01) self.assertEqual(len(self.battles), 1) m, b = self.battles[0] self.assertEqual(m.id, self.m.id) self.assertEqual(sum(u.side == "squad" for u in b.units), 4) self.assertEqual(c.trip["stage"], "battle") cam = BASE.camera.getPos() self.assertLess(math.dist((cam.x, cam.y, cam.z), (*target, W.MAP_Z)), math.dist((cam_far.x, cam_far.y, cam_far.z), (*target, W.MAP_Z)) - 2) # leaned in r.at(end + W.LEAN_SECONDS + 5) self.assertEqual(len(self.battles), 1) # once self.assertIn("in battle", r.hud_text.getText()) def test_home_after_the_battle(self): W, r, c = self.W, self.room, self.c days = self.send() target = r.journey["to"] t = self.t0 + days * W.DAY_SECONDS + W.LEAN_SECONDS + 0.01 r.at(t) m, b = self.battles[0] b.outcome = "won" day = c.day r.battle_done(b) self.assertIsNone(c.trip) self.assertEqual(c.day, day + 1) # finish(): a day self.assertEqual(self.saves[-1], c.day) self.assertNotIn(f"mission:{m.id}", r.pieces) # the pin is gone self.assertAlmostEqual(math.dist(self.unit_xy(), target), 0, places=5) r.at(t + W.HOME_SECONDS / 2) self.assertIn("coming home", r.hud_text.getText()) r.show(f"mission:{self.c.missions[0].id}") self.assertTrue(r.plan_btn.isHidden()) # not till they're home mid = self.unit_xy() self.assertTrue(0 < math.dist(mid, target) < math.dist(target, r.unit_home)) r.at(t + W.HOME_SECONDS + 0.01) self.assertAlmostEqual(math.dist(self.unit_xy(), r.unit_home), 0, places=5) self.assertIsNone(r.journey) self.assertIn("at the fort", r.hud_text.getText()) cam = BASE.camera.getPos() self.assertAlmostEqual(math.dist(cam, W.map_pose(r.view, r.fov())[0]), 0, places=4) # view back def test_too_late_turns_for_home(self): W, r, c = self.W, self.room, self.c days = self.send() self.m.expires = c.day + 1 # gone on the first day r.at(self.t0 + days * W.DAY_SECONDS + W.LEAN_SECONDS + 0.01) self.assertEqual(self.battles, []) self.assertIsNone(c.trip) self.assertEqual(r.journey["phase"], "home") self.assertIn("too late", "\n".join(c.log[-3:])) r.at(self.t0 + days * W.DAY_SECONDS + W.LEAN_SECONDS + W.HOME_SECONDS + 0.1) self.assertAlmostEqual(math.dist(self.unit_xy(), r.unit_home), 0, places=5) def test_closed_on_the_road_carries_on(self): W, c = self.W, self.c days = self.send() self.room.at(self.t0 + W.DAY_SECONDS + 0.01) self.assertEqual(c.trip["gone"], 1) target = self.room.journey["to"] self.room.root.removeNode() room = W.WarRoom(BASE, c) # opened again room.on_arrive = lambda m, b: self.battles.append((m, b)) p = room.pieces["unit"].getPos() frac = math.dist(room.unit_home, (p.x, p.y)) / math.dist(room.unit_home, target) self.assertAlmostEqual(frac, 1 / days, places=3) # where it was self.assertEqual(room.journey["phase"], "out") room.at((days - 1) * W.DAY_SECONDS + W.LEAN_SECONDS + 0.01) self.assertEqual(len(self.battles), 1) def test_a_refused_plan_stays_home(self): r, c = self.room, self.c r.show(f"mission:{self.m.id}") hurt = c.ready()[0] hurt.wounded_until = c.day + 5 self.assertFalse(r.send([[hurt.name]], "on foot", 0 if self.m.group is None else None)) self.assertIsNone(r.journey) self.assertIsNone(c.trip) self.assertIn(f"Can't: {hurt.name} is wounded", r.brief_text.getText()) self.assertEqual(self.saves, []) @unittest.skipIf(GeomVertexReader is None, "Panda3D is not installed") class TheBase(unittest.TestCase): """Step 3f (Dillon, 2026-11-16): the fort cut away, every room on view; tabs and clicks glide the view room to room; the command room is the war room's table; each room holds its window.""" def setUp(self): from p02 import cutaway as CW self.CW = CW for n in BASE.render.findAllMatches("war room") + BASE.render.findAllMatches("cutaway"): n.removeNode() self.c = busy_campaign() self.c.supplies = 2000 self.saves = [] self.g = CW.Cutaway(BASE, self.c, save=lambda c: self.saves.append(c.day)) self.g.room.on_arrive = lambda m, b: None self.t = 10.0 self.g.at(self.t) def tearDown(self): if self.g.room.tk is not None: self.g.room.tk.destroy() self.g.root.removeNode() # out of the way of the tests that follow for n in BASE.aspect2d.findAllMatches("cutaway *"): n.removeNode() def run_for(self, seconds, step=0.05): end = self.t + seconds while self.t < end - 1e-9: self.t = min(end, self.t + step) self.g.at(self.t) def go(self, key): self.g.go_to(key) self.run_for(self.CW.GLIDE_SECONDS + 0.01) def cam(self): return BASE.camera.getPos(self.g.root) def lit(self): return [k for k, b in self.g.tabs.items() if b["frameColor"][1] > 0.4] def test_an_old_save_opens(self): # Dillon's crash, 2026-11-17: KeyError 'miller' building the table from a save made before the # counties (tests/fixtures/save-3f.json, written by the Step 3f code) from pathlib import Path c = K.load(Path(__file__).with_name("fixtures") / "save-3f.json") g = self.CW.Cutaway(BASE, c) g.at(self.t) g.go_to("command") g.at(self.t + self.CW.GLIDE_SECONDS + 0.1) self.assertEqual(g.place, "command") self.assertEqual(len(g.room.counties), len(MS.the_map()["counties"])) g.root.removeNode() def test_it_opens_on_the_whole_base_every_room_in_view(self): g, CW = self.g, self.CW self.assertEqual((g.place, g.key), ("base", None)) self.assertTrue(g.room.root.isHidden()) self.assertAlmostEqual(math.dist(self.cam(), CW.base_pose()[0]), 0, places=4) for key, n in g.cells.items(): xy = screen_point(n) self.assertIsNotNone(xy, key) self.assertTrue(-1 < xy[0] < 1 and -0.86 < xy[1] < 0.8, (key, xy)) # above the tabs self.assertEqual(g.say_text.getText(), CW.BASE_HINT) self.assertEqual(self.lit(), ["base"]) self.assertTrue(BASE.render.find("**/commander*").isEmpty()) # no walking figure def test_the_tabs_along_the_bottom(self): g = self.g self.assertEqual([(k, b["text"]) for k, b in g.tabs.items()], [("command", "Command"), ("barracks", "Barracks"), ("armory", "Armory"), ("engineering", "Engineering"), ("garage", "Garage"), ("research", "Research"), ("rec", "Rec"), ("base", "Base")]) xs = [b.getPos()[0] for b in g.tabs.values()] self.assertEqual(xs, sorted(xs)) for b in g.tabs.values(): self.assertLess(b.getPos()[2], -0.9) # along the bottom def test_rooms_have_their_own_ground_and_walls_never_cross_a_wide_room(self): CW = self.CW boxes = {k: CW.cell(k) for k in self.g.rooms} keys = list(boxes) for i, a in enumerate(keys): x0, x1, z0, z1 = boxes[a] self.assertTrue(x1 > x0 and z1 > z0) for b in keys[i + 1:]: u0, u1, w0, w1 = boxes[b] self.assertFalse(x0 < u1 and u0 < x1 and z0 < w1 and w0 < z1, (a, b)) for key in ("command", "garage"): x0, x1, z0, z1 = boxes[key] for wall in self.g.fort.findAllMatches("wall"): lo, hi = wall.getTightBounds(self.g.fort) inside = x0 < (lo.x + hi.x) / 2 < x1 and z0 < (lo.z + hi.z) / 2 < z1 self.assertFalse(inside, key) def test_a_tab_glides_back_across_and_into_the_room(self): g, CW = self.g, self.CW day = self.c.day start, end = CW.base_pose()[0], CW.room_pose("barracks")[0] g.tabs["barracks"]["command"](*g.tabs["barracks"]["extraArgs"]) self.assertEqual(self.lit(), ["barracks"]) self.run_for(CW.GLIDE_SECONDS / 2) mid = self.cam() self.assertLess(mid.y, (start[1] + end[1]) / 2 - 1.0) # backed off on the way self.assertEqual(g.place, "moving") self.run_for(CW.GLIDE_SECONDS / 2 + 0.01) self.assertEqual((g.place, g.key), ("room", "barracks")) self.assertAlmostEqual(math.dist(self.cam(), end), 0, places=4) self.assertEqual(g.use_btn["text"], "The roster") self.assertFalse(g.use_btn.isHidden()) self.assertIn(g.rooms["barracks"]["about"], g.say_text.getText()) self.assertEqual(self.c.day, day) # moving about costs no days self.go("base") self.assertEqual((g.place, g.key, self.lit()), ("base", None, ["base"])) self.assertTrue(g.use_btn.isHidden()) def test_a_click_mid_glide_does_not_turn_it(self): g = self.g xy = screen_point(g.cells["armory"].find("back wall")) g.go_to("rec") self.run_for(0.05) g.click_at(*xy) self.assertEqual(g.move["to"], "rec") self.run_for(self.CW.GLIDE_SECONDS) self.assertEqual(g.key, "rec") def test_click_a_room_on_the_cutaway(self): g = self.g for key in ("armory", "plot:1", "garage"): self.go("base") xy = screen_point(g.cells[key].find("back wall")) self.assertEqual(g.pick(*xy), key) g.click_at(*xy) self.run_for(self.CW.GLIDE_SECONDS + 0.01) self.assertEqual(g.key, key) def test_the_command_room_is_the_war_room_table(self): from p02 import warroom as W g, CW = self.g, self.CW g.room.show(f"mission:{self.c.missions[0].id}") self.assertTrue(g.room.plan_btn.isHidden()) # not while you're out self.go("command") self.assertEqual(g.place, "command") self.assertTrue(g.root.isHidden() and g.say_np.isHidden()) self.assertFalse(g.room.root.isHidden() or g.room.brief_np.isHidden() or g.room.plan_btn.isHidden()) self.assertLess(math.dist(BASE.camera.getPos(), W.DOOR_POSE[0]), 0.2) # the glide in to the table self.run_for(W.INTRO_SECONDS) self.assertTrue(g.room.in_map()) g.go_to("armory") # off the table, by a tab self.assertTrue(g.room.root.isHidden() and g.room.plan_btn.isHidden()) self.assertFalse(g.root.isHidden()) g.at(self.t) self.assertAlmostEqual(math.dist(self.cam(), CW.room_pose("command")[0]), 0, places=4) self.run_for(CW.GLIDE_SECONDS + 0.01) self.assertEqual((g.place, g.key), ("room", "armory")) def test_each_room_holds_its_window(self): g = self.g self.c.roster[0].dead = True for key, top in (("barracks", "roster_top"), ("armory", "roster_top"), ("garage", "convoy_top"), ("engineering", "facilities_top"), ("plot:0", "facilities_top"), ("rec", "memorial_top")): self.go(key) g.use() w = getattr(g.desks, top) self.assertTrue(w.winfo_exists(), key) w.destroy() self.go("research") # a placeholder, for now self.assertTrue(g.use_btn.isHidden()) self.assertIn("Closed for now", g.say_text.getText()) g.use() def test_rubble_is_only_a_look(self): g = self.g rubble = next(d for d in g.rooms.values() if d["kind"] == "rubble") self.go(rubble["key"]) self.assertTrue(g.use_btn.isHidden()) self.assertIn(rubble["about"], g.say_text.getText()) g.use() self.assertIsNone(g.desks) def test_a_build_from_a_plot_saves_and_shows(self): g = self.g sign = lambda key: g.cells[key].find("**/+TextNode").node().getText() # noqa: E731 self.assertIn("EMPTY PLOT", sign("plot:0")) self.go("plot:0") g.use() g.desks.facility_buttons["infirmary"].invoke() self.assertEqual(self.c.project["what"], "infirmary") self.assertEqual(self.saves, [self.c.day]) self.assertIn("INFIRMARY (BUILDING)", sign("plot:0")) # the cutaway rebuilt self.assertIn("building the infirmary", g.say_text.getText()) def test_a_build_done_while_at_the_table_shows_when_you_come_out(self): g = self.g sign = lambda key: g.cells[key].find("**/+TextNode").node().getText() # noqa: E731 K.build(self.c, "radio room") g.build() self.assertIn("RADIO ROOM (BUILDING)", sign("plot:0")) self.go("command") K.wait(self.c, self.c.project["done"] - self.c.day) self.go("base") self.assertIn("RADIO ROOM 1", sign("plot:0")) def test_the_memorial_wall_has_a_plaque_for_each_of_the_fallen(self): g = self.g self.assertEqual(g.plaques, 0) for s in self.c.roster[:3]: s.dead = True self.run_for(0.1) # the base sees it self.assertEqual(g.plaques, 3) names = {n.node().getText() for n in g.cells["rec"].findAllMatches("**/+TextNode")} self.assertTrue({s.name for s in self.c.roster[:3]} <= names) def test_a_refused_build_says_why(self): g = self.g self.c.supplies = 0 self.go("engineering") g.the_desks().done(K.build, self.c, "infirmary") self.assertIn("Can't:", g.say_text.getText()) self.assertEqual(self.saves, []) def test_the_trip_plays_on_out_in_the_base(self): from p02 import warroom as W g = self.g m = max(self.c.missions, key=lambda m: K.travel_days(m.region, "on foot")) m.expires = self.c.day + 30 g.room.show(f"mission:{m.id}") self.assertTrue(g.room.send([[s.name for s in self.c.ready()[:4]]], "on foot", 0 if m.group is None else None)) self.go("barracks") day = self.c.day # (a day went by on the glide) self.run_for(2 * W.DAY_SECONDS + 0.1) self.assertEqual(self.c.day, day + 2) self.assertEqual(g.key, "barracks") self.assertIn("on the road", g.room.hud_text.getText()) @unittest.skipIf(GeomVertexReader is None, "Panda3D is not installed") class TheMainMenu(unittest.TestCase): """Dillon, 2026-11-17: a main menu with new game and load game, as in most games.""" def setUp(self): import shutil import tempfile from pathlib import Path from p02 import menu as M self.M = M self.dir = Path(tempfile.mkdtemp()) self.addCleanup(shutil.rmtree, self.dir) self.started, self.quit = [], [] def menu(self, legacy=None): for n in BASE.aspect2d.findAllMatches("main menu"): n.removeNode() return self.M.MainMenu(BASE, lambda c, p: self.started.append((c, p)), save_dir=self.dir / "saves", legacy=legacy, on_quit=lambda: self.quit.append(1)) def live(self, m): return {k for k, b in m.buttons.items() if b["state"] != "disabled"} def test_first_time_new_game_and_quit_only(self): m = self.menu() self.assertEqual([b["text"] for b in m.buttons.values()], ["Continue", "New Game", "Load Game", "Quit"]) self.assertEqual(self.live(m), {"new", "quit"}) m.buttons["quit"]["command"]() self.assertEqual(self.quit, [1]) m.buttons["new"]["command"]() (c, p), = self.started self.assertEqual(p.name, "Campaign 1.json") self.assertEqual(K.load(p), c) self.assertTrue(m.root.isEmpty()) # the menu is gone def test_continue_plays_the_newest_and_load_lists_them_all(self): import os import shutil import time old = self.dir / "Project02 campaign.json" shutil.copy(Path_fixture(), old) _, p1 = self.M.new_game(self.dir / "saves", seed=3) now = time.time() os.utime(old, (now, now)) os.utime(p1, (now - 100, now - 100)) m = self.menu(legacy=old) self.assertEqual(self.live(m), {"continue", "new", "load", "quit"}) m.buttons["load"]["command"]() self.assertEqual([i["path"] for i, _ in m.save_buttons], [old, p1]) m.save_buttons[1][1]["command"]() # load the older one self.assertEqual(self.started[-1][1], p1) m = self.menu(legacy=old) m.buttons["continue"]["command"]() # the newest: the old save c, p = self.started[-1] self.assertEqual((p, c.day, len(c.regions)), (old, 10, len(D.REGIONS))) # converted as it loads def test_the_game_starts_from_the_menu_and_saves_where_it_came_from(self): from p02 import warroom as W m = self.menu() m.buttons["new"]["command"]() c, p = self.started[-1] g = W.start_game(BASE, c, p) self.addCleanup(lambda: (BASE.taskMgr.remove("war room"), g.root.removeNode(), [n.removeNode() for n in BASE.aspect2d.findAllMatches("cutaway *")])) self.assertTrue(BASE.taskMgr.hasTaskNamed("war room")) self.assertEqual(g.place, "base") c.supplies = 777 g.room.saved() self.assertEqual(K.load(p).supplies, 777) def Path_fixture(): from pathlib import Path return Path(__file__).with_name("fixtures") / "save-3f.json" @unittest.skipIf(GeomVertexReader is None, "Panda3D is not installed") class TheMapView(unittest.TestCase): """Dillon, 2026-11-16: the map seen from the top down, zoom in and out, move across it.""" def setUp(self): from p02 import warroom as W self.W = W for n in BASE.render.findAllMatches("war room"): n.removeNode() self.c = busy_campaign() self.room = W.WarRoom(BASE, self.c) self.t = W.INTRO_SECONDS + 1 self.room.at(self.t) def corners_seen(self): r = self.room return [r.table_point(x, y) for x in (-0.98, 0.98) for y in (-0.98, 0.98)] def test_zoomed_out_the_whole_map_is_in_view_from_straight_above(self): W, r = self.W, self.room self.assertEqual(r.view, (0.0, 0.0, 1.0)) for fips, n in r.counties.items(): # every county on screen self.assertIsNotNone(screen_point(n), fips) self.assertEqual(self.corners_seen(), [None] * 4) # the screen corners are past the map self.assertAlmostEqual(BASE.camera.getP(), W.OUT_PITCH, places=3) self.assertEqual(W.clamp_view((3.0, -2.0, 1.0), r.fov()), (0.0, 0.0, 1.0)) # nowhere to move self.assertEqual(W.zoom_at(r.view, 1 / W.ZOOM_STEP, None, r.fov()), (0.0, 0.0, 1.0)) # no further out def test_the_wheel_zooms_in_on_the_point_under_the_mouse(self): W, r = self.W, self.room for mx, my in ((0.4, 0.3), (-0.4, -0.3), (0.0, 0.0)): # (nearer the edge, the edge stops it) r.view = (0.0, 0.0, 1.0) r.at(self.t) before = r.table_point(mx, my) self.assertIsNotNone(before) r.zoom_on(W.ZOOM_STEP ** 3, (mx, my)) r.at(self.t) self.assertGreater(r.view[2], 1.7) after = r.table_point(mx, my) self.assertLess(math.dist(before, after), 0.01, (mx, my)) # the same place stays under it self.assertGreater(BASE.camera.getP(), W.OUT_PITCH) # tilted a little, zoomed in r.view = W.zoom_at(r.view, 1000, None, r.fov()) self.assertEqual(r.view[2], W.MAX_ZOOM) # no further in self.assertEqual(W.clamp_view((0.0, 0.0, 99.0), r.fov())[2], W.MAX_ZOOM) self.assertEqual(W.clamp_view((0.0, 0.0, 0.2), r.fov())[2], 1.0) x, y, _ = W.zoom_at((0.0, 0.0, 1.0), 2.0, (1.0, 0.6), r.fov()) # the first guess, before the tilt self.assertAlmostEqual(x, 0.5) # is fixed: halfway to the point self.assertAlmostEqual(y, 0.3) r.at(self.t) self.assertGreater(BASE.camera.getZ(), W.MAP_Z + 0.5) # still well above the paper self.assertAlmostEqual(BASE.camera.getP(), W.IN_PITCH, places=3) def test_zoomed_in_the_view_moves_across_the_map_but_not_off_it(self): W, r = self.W, self.room r.view = (0.0, 0.0, 3.0) for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)): r.view = (0.0, 0.0, 3.0) r.pan(dx, dy, 0.25) x, y, z = r.view self.assertEqual((z, x * dx > 0 or dx == 0, y * dy > 0 or dy == 0), (3.0, True, True), (dx, dy)) for dx, dy in ((1, 1), (-1, -1), (1, -1), (-1, 1)): r.view = (0.0, 0.0, 3.0) for _ in range(200): r.pan(dx, dy, 0.1) # hold the keys a long time r.at(self.t) x, y, _ = r.view self.assertLess(abs(x), W.TABLE[0] / 2) self.assertLess(abs(y), W.TABLE[1] / 2) self.assertIsNotNone(r.table_point(0, 0)) # the middle of the screen is map self.assertIsNotNone(r.table_point(-0.9 * dx, -0.9 * dy)) # and the far side of the view r.view = (0.0, 0.0, 1.0) r.pan(1, 1, 1.0) self.assertEqual(r.view, (0.0, 0.0, 1.0)) # zoomed out: nowhere to go def test_the_map_follows_a_right_drag(self): W, r = self.W, self.room r.view = (0.0, 0.0, 2.5) r.at(self.t) grabbed = r.table_point(0.2, 0.1) r.drag = (0.2, 0.1, r.view) r.drag_to(-0.3, -0.2) r.at(self.t) self.assertLess(math.dist(r.table_point(-0.3, -0.2), grabbed), 0.35) # what you grabbed came along self.assertGreater(r.view[0], 0) r.drag_end() self.assertIsNone(r.drag) def test_clicks_still_find_the_pieces_zoomed_in(self): W, r = self.W, self.room fort = r.pieces["fort"] x, y, _ = fort.getPos(BASE.render) r.view = W.clamp_view((x, y, 4.0), r.fov()) r.at(self.t) xy = screen_point(main_part("fort", fort)) self.assertIsNotNone(xy) self.assertEqual(r.pick(*xy), "fort") def test_input_waits_for_the_glide_in_and_the_room(self): W, r = self.W, self.room self.assertTrue(r.in_map()) r.at(W.INTRO_SECONDS / 2) self.assertFalse(r.in_map()) # still coming in by the door r.wheel(W.ZOOM_STEP) self.assertEqual(r.view[2], 1.0) r.at(self.t) r.set_shown(False) self.assertFalse(r.in_map()) # out in the bunker r.wheel(W.ZOOM_STEP) r.whole_map() self.assertEqual(r.view, (0.0, 0.0, 1.0)) r.set_shown(True) r.at(self.t) r.wheel(W.ZOOM_STEP) self.assertAlmostEqual(r.view[2], W.ZOOM_STEP) # in the room: it zooms r.whole_map() self.assertEqual(r.view, (0.0, 0.0, 1.0)) if __name__ == "__main__": unittest.main()