"""Project 02: the battle window (Step 1). Click a soldier to select them. Light blue cells: one move. Yellow cells: a dash (both actions). Click a cell to move there. Hover an enemy to see your chance to hit; click it to shoot. The buttons do the rest: overwatch, hunker down, reload, medkit (on the most hurt soldier next to you, or yourself), grenade (then click where), pistol (then click an enemy: it never runs dry), smoke and flashbang (then click where: utility, Step 3c), end turn, and Auto (the AI plays your turn). Smoke is the pale haze; a dazed enemy is marked z. Fog: cells none of your squad can see are darker, and sleeping enemies there aren't shown. The unit (Step 3b): Squad 1 is blue, Squad 2 teal, each soldier marked with their squad's number. Run: python3 -m p02 (from the project-02 directory) """ from __future__ import annotations import tkinter as tk from tkinter import ttk from . import data as D from .tactics import Battle CELL = 32 MAX_TURNS = 40 # Auto battle gives up here: the squad pulls out (lost) GROUND, FOG, LOW, HIGH = "#d9cba3", "#9c937a", "#8a6a43", "#4a4036" MOVE, DASH = "#bcd8f0", "#efe2a2" SQUAD, ENEMY, PICK, AIM = "#1d3f8f", "#8e1b1b", "#f3d27a", "#e03030" SQUAD2 = "#14706a" # Squad 2 of the unit SMOKE = "#eeeeee" # a smoke cloud (Step 3c) LETTER = {"rifleman": "R", "scout": "S", "gunner": "G", "marksman": "M", "medic": "+", "engineer": "E", "militiaman": "m", "raider": "r", "sharpshooter": "s", "bruiser": "B"} class BattleView: def __init__(self, root, seed=None, battle=None, on_done=None, title="Project 02 — Battle"): """root: a Tk or Toplevel. battle: a prepared tactics.Battle (default: a new one from seed). on_done(battle): called once it's over and you click Back (campaign play).""" self.root, self.on_done = root, on_done root.title(title) self.b = battle or Battle.new(seed) self.sel, self.mode = None, None if on_done: root.protocol("WM_DELETE_WINDOW", self.on_close) self.c = tk.Canvas(root, width=D.GRID_W * CELL, height=D.GRID_H * CELL, background=GROUND, highlightthickness=0) self.c.pack(side="left", padx=6, pady=6) self.c.bind("", self.on_click) self.c.bind("", self.on_hover) side = ttk.Frame(root, padding=6) side.pack(side="right", fill="both", expand=True) self.status = ttk.Label(side, justify="left", width=40, wraplength=290) self.status.pack(anchor="w") grid = ttk.Frame(side) grid.pack(anchor="w", pady=6) self.buttons = {} for i, (text, fn) in enumerate((("Overwatch", self.on_overwatch), ("Hunker", self.on_hunker), ("Reload", self.on_reload), ("Medkit", self.on_medkit), ("Grenade", self.on_grenade), ("Pistol", self.on_pistol), ("Smoke", self.on_smoke), ("Flashbang", self.on_flash), ("Next soldier", self.on_next), ("End turn", self.on_end), ("Auto turn", self.on_auto), ("Auto battle", self.on_auto_all), ("Back", self.on_back))): b = ttk.Button(grid, text=text, width=13, command=fn) b.grid(row=i // 2, column=i % 2, padx=1, pady=1) self.buttons[text] = b self.hint = ttk.Label(side, justify="left", wraplength=290, foreground="#555") self.hint.pack(anchor="w") self.logbox = tk.Text(side, width=44, height=20, wrap="word", font=("Consolas", 9)) self.logbox.pack(fill="both", expand=True, pady=(6, 0)) self.shown = 0 self.on_next() # ── drawing ── def refresh(self): b, c = self.b, self.c c.delete("all") squad = [u for u in b.units if u.alive and u.side == "squad"] seen = {(x, y) for x in range(D.GRID_W) for y in range(D.GRID_H) if any(math_dist((u.x, u.y), (x, y)) <= D.SIGHT and b.los((u.x, u.y), (x, y)) for u in squad)} one = b.reach(self.sel, 1) if self.sel and self.sel.actions >= 1 and not self.mode else {} two = b.reach(self.sel, 2) if self.sel and self.sel.actions >= 2 and not self.mode else {} for x in range(D.GRID_W): for y in range(D.GRID_H): kind = b.obst.get((x, y)) fill = (HIGH if kind == "high" else LOW if kind == "low" else MOVE if (x, y) in one else DASH if (x, y) in two else GROUND if (x, y) in seen else FOG) c.create_rectangle(x * CELL, y * CELL, (x + 1) * CELL, (y + 1) * CELL, fill=fill, outline="#c2b48c" if fill in (GROUND, MOVE, DASH) else fill) if (x, y) in b.smoke: c.create_rectangle(x * CELL, y * CELL, (x + 1) * CELL, (y + 1) * CELL, fill=SMOKE, stipple="gray50", outline="", tags=("smoke",)) for u in b.units: if not u.alive or (u.side == "enemy" and (u.x, u.y) not in seen): continue cx, cy = u.x * CELL + CELL / 2, u.y * CELL + CELL / 2 col = (SQUAD2 if u.squad == 2 else SQUAD) if u.side == "squad" else ENEMY ring = (PICK if u is self.sel else AIM if self.sel and u.side == "enemy" and b.can_shoot(self.sel, u) else "#fff") c.create_oval(cx - 12, cy - 12, cx + 12, cy + 12, fill=col, outline=ring, width=3 if ring != "#fff" else 1) c.create_text(cx, cy, text=LETTER[u.kind], fill="#fff", font=("Segoe UI", 10, "bold")) for i in range(u.max_hp): # health pips c.create_rectangle(cx - 13 + i * 26 / u.max_hp, cy + 13, cx - 13 + (i + 1) * 26 / u.max_hp - 1, cy + 16, fill="#3c9a3c" if i < u.hp else "#555", outline="") if u.side == "squad" and u.squad: c.create_text(cx - 11, cy - 11, text=str(u.squad), fill="#000", font=("Segoe UI", 7, "bold")) if u.dazed: c.create_text(cx - 11, cy - 11, text="z", fill="#000", font=("Segoe UI", 8, "bold")) if u.overwatch: c.create_text(cx + 11, cy - 11, text="ow", fill="#000", font=("Segoe UI", 7, "bold")) if u.hunkered: c.create_text(cx + 11, cy - 11, text="H", fill="#000", font=("Segoe UI", 7, "bold")) self.show_status() new = b.log[self.shown:] if new: self.logbox.insert("end", "\n".join(new) + "\n") self.logbox.see("end") self.shown = len(b.log) def show_status(self): b, u = self.b, self.sel over = b.outcome is not None for name, btn in self.buttons.items(): back = name == "Back" btn.configure(state=("normal" if over and self.on_done else "disabled") if back else "disabled" if over else "normal") if over: squad = [s for s in b.units if s.side == "squad"] alive = sum(1 for s in squad if s.alive) self.status.configure(text=f"{'Mission won' if b.outcome == 'won' else 'Mission lost'}. " f"{alive} of {len(squad)} came home.\n" + ("Click Back to return to the bunker." if self.on_done else "Close the window and start it again for a new battle.")) return left = sum(1 for s in b.units if s.side == "squad" and s.alive and s.actions) if not u: self.status.configure(text=f"Turn {b.turn}. {left} soldiers still to act.\n" "Click a soldier (blue: Squad 1, teal: Squad 2).") return w = D.WEAPONS[u.weapon] extras = [] if u.grenades: extras.append(f"grenades {u.grenades}") if u.medkits: extras.append(f"medkits {u.medkits}") if u.smoke: extras.append(f"smoke {u.smoke}") if u.flashbangs: extras.append(f"flashbangs {u.flashbangs}") if u.armor: extras.append(f"armor {u.armor}") self.status.configure(text=f"Turn {b.turn}. {u.name} the {u.kind}" + (f", Squad {u.squad}" if u.squad else "") + "\n" f"health {u.hp}/{u.max_hp} actions {u.actions}/{D.ACTIONS} " f"aim {u.aim}\n{u.weapon}: ammo {u.ammo}/{u.clip}, " f"damage {w['damage'][0]}-{w['damage'][1]}" + (f"\n{u.sidearm}: damage {D.WEAPONS[u.sidearm]['damage'][0]}-" f"{D.WEAPONS[u.sidearm]['damage'][1]}, never runs dry" if u.sidearm else "") + (f"\n{', '.join(extras)}" if extras else "") + ({"grenade": "\nClick where to throw the grenade.", "smoke": "\nClick where to throw the smoke.", "flash": "\nClick where to throw the flashbang."}.get(self.mode, ""))) # ── input ── def cell(self, e): return int(e.x // CELL), int(e.y // CELL) def on_hover(self, e): x, y = self.cell(e) t = self.b.unit_at(x, y) if t and t.side == "enemy" and self.sel: pistol = self.mode == "pistol" hit, crit = self.b.odds(self.sel, t, sidearm=pistol) ok = self.b.can_shoot(self.sel, t, sidearm=pistol) self.hint.configure(text=f"{t.kind} ({t.hp}/{t.max_hp}): {D.ENEMIES[t.kind]['about']}.\n" + (f"To hit {hit}%, crit {crit}%. Click to shoot" + (" the pistol." if pistol else ".") if ok else "No shot from here.")) elif t and t.side == "enemy": self.hint.configure(text=f"{t.kind}: {D.ENEMIES[t.kind]['about']}.") else: self.hint.configure(text="") def on_click(self, e): b = self.b if b.outcome: return x, y = self.cell(e) t = b.unit_at(x, y) try: if self.mode in ("grenade", "smoke", "flash") and self.sel: mode, self.mode = self.mode, None {"grenade": b.grenade, "smoke": b.throw_smoke, "flash": b.flashbang}[mode](self.sel, x, y) elif t and t.side == "squad": self.sel, self.mode = t, None elif self.mode == "pistol" and self.sel: # an enemy: shoot; anywhere else: put it away self.mode = None if t: if not b.can_shoot(self.sel, t, sidearm=True): raise ValueError("no pistol shot at that") b.shoot(self.sel, t, sidearm=True) elif t and self.sel and b.can_shoot(self.sel, t): b.shoot(self.sel, t) elif not t and self.sel and self.sel.actions: b.move(self.sel, x, y) except ValueError as err: self.hint.configure(text=f"Can't: {err}.") self.after_action() def after_action(self): if self.sel and (not self.sel.alive or self.sel.actions == 0) and not self.mode: self.on_next(refresh=False) self.refresh() def act(self, fn, *args): if not self.sel or self.b.outcome: return try: fn(self.sel, *args) except ValueError as err: self.hint.configure(text=f"Can't: {err}.") self.after_action() def on_overwatch(self): self.act(self.b.overwatch) def on_hunker(self): self.act(self.b.hunker) def on_reload(self): self.act(self.b.reload) def on_medkit(self): if not self.sel: return near = [s for s in self.b.units if s.side == "squad" and s.alive and s.hp < s.max_hp and max(abs(s.x - self.sel.x), abs(s.y - self.sel.y)) <= 1] if not near: self.hint.configure(text="Nobody hurt next to you.") return self.act(self.b.medkit, min(near, key=lambda s: s.hp)) def on_grenade(self): if self.sel and self.sel.grenades and self.sel.actions: self.mode = "grenade" self.refresh() def on_smoke(self): if self.sel and self.sel.smoke and self.sel.actions: self.mode = "smoke" self.refresh() def on_flash(self): if self.sel and self.sel.flashbangs and self.sel.actions: self.mode = "flash" self.refresh() def on_pistol(self): """The next enemy clicked is shot with the pistol: it never runs dry.""" if self.sel and self.sel.sidearm and self.sel.actions: self.mode = None if self.mode == "pistol" else "pistol" self.hint.configure(text="Pistol out: click an enemy." if self.mode else "") self.refresh() def on_next(self, refresh=True): ready = [s for s in self.b.units if s.side == "squad" and s.alive and s.actions] if ready: i = ready.index(self.sel) + 1 if self.sel in ready else 0 self.sel = ready[i % len(ready)] else: self.sel = None self.mode = None if refresh: self.refresh() def on_end(self): self.sel = self.mode = None self.b.end_turn() self.on_next() def on_auto(self): self.sel = self.mode = None self.b.auto() self.on_next() def on_auto_all(self): self.sel = self.mode = None while not self.b.outcome and self.b.turn <= MAX_TURNS: self.b.auto() if not self.b.outcome: self.b.outcome = "lost" # out of time: they hold the field self.b.say("Out of time: the squad pulls out. Mission lost.") self.on_next() def on_back(self): if self.b.outcome and self.on_done: done, self.on_done = self.on_done, None self.root.destroy() done(self.b) def on_close(self): """Closing a campaign battle early lets the AI play it out: a mission always ends.""" self.on_auto_all() self.on_back() def math_dist(a, b): return ((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2) ** 0.5 def main(): """One battle on its own (the bunker is campaignview.main).""" root = tk.Tk() BattleView(root) root.mainloop() if __name__ == "__main__": main()