"""One battle (Project 02): your squad against a region group's fighters in a ruined town. The field is a grid (data.GRID_W x GRID_H, y down). Obstacles are "low" (wrecks, fences: half cover, see over them) or "high" (walls: full cover, block sight). A unit standing next to an obstacle is in its cover against a shooter on that side; with no cover toward the shooter it is FLANKED, and easier to crit. Each turn a unit has two actions. A move goes up to its mobility (diagonals cost 1.5); a second move is a dash. Shooting, overwatch and hunkering down end the turn; reloading, a medkit and a grenade use one action. Overwatch shoots the first enemy that moves in sight. Enemies wait in pods, asleep, until one of your squad sees them; then the pod scrambles for cover. To hit = aim + the weapon's range modifier - the target's defense - its cover. Damage is the weapon's range less the target's armor; a crit adds half again. Pure logic, no window (view.py draws it). Numbers in data.py. RNG injectable for tests. """ from __future__ import annotations import heapq import math import random from dataclasses import dataclass, field from . import data as D NEIGHBOURS = [(dx, dy) for dx in (-1, 0, 1) for dy in (-1, 0, 1) if dx or dy] @dataclass class Unit: name: str side: str # "squad" or "enemy" kind: str # class, or enemy type x: int y: int hp: int max_hp: int aim: int mobility: int defense: int weapon: str armor: int = 0 ammo: int = 0 grenades: int = 0 medkits: int = 0 actions: int = 0 overwatch: bool = False hunkered: bool = False pod: int | None = None # enemy: which pod awake: bool = True # enemy pods sleep until seen clip: int = 0 # rounds a reload gives (weapon's clip, plus skills) crit_bonus: int = 0 # from skills kills: int = 0 squad: int = 0 # yours: Squad 1 or Squad 2 of the unit sidearm: str = "" # yours: the pistol (data.WEAPONS key); never runs dry smoke: int = 0 # smoke grenades (utility, Step 3c) flashbangs: int = 0 dazed: bool = False # caught by a flashbang: one action and less aim, its next turn downed: str = "" # how it went down, for the record (the fort's memorial) @property def alive(self): return self.hp > 0 @property def melee(self): return D.WEAPONS[self.weapon].get("melee", False) def who(u): """A unit, as the record names it: one of yours by name, an enemy by what it is.""" return u.name if u.side == "squad" else f"a {u.kind}" def soldier(name, cls, x, y, extra=None, squad=1, weapon=None, pistol=None): """A soldier of class cls, in Squad 1 or 2. extra: what ranks, skills, allies and travel add (campaign.py): {"hp", "aim", "mobility", "defense", "clip", "crit", "grenades", "medkits"}. weapon, pistol: data.WEAPONS keys (default: the class's own family, and a pistol, scrap-built). A weapon's aim bonus counts when it fires (odds); its mobility counts here.""" c, e = D.CLASSES[cls], extra or {} weapon = weapon or D.weapon_key(c["weapon"]) w = D.WEAPONS[weapon] hp = c["hp"] + e.get("hp", 0) clip = w["clip"] + e.get("clip", 0) return Unit(name, "squad", cls, x, y, hp, hp, c["aim"] + e.get("aim", 0), c["mobility"] + e.get("mobility", 0) + w.get("mobility", 0), c["defense"] + e.get("defense", 0), weapon, armor=e.get("armor", 0), ammo=clip, clip=clip, crit_bonus=e.get("crit", 0), smoke=e.get("smoke", 0), flashbangs=e.get("flashbangs", 0), sidearm=pistol or D.weapon_key("pistol"), grenades=c.get("grenades", 0) + e.get("grenades", 0), medkits=c.get("medkits", 0) + e.get("medkits", 0), squad=squad) def enemy(kind, x, y, pod): e = D.ENEMIES[kind] clip = D.WEAPONS[e["weapon"]]["clip"] return Unit(kind, "enemy", kind, x, y, e["hp"], e["hp"], e["aim"], e["mobility"], e["defense"], e["weapon"], armor=e["armor"], ammo=clip, clip=clip, pod=pod, awake=False) def range_band(d): return 0 if d <= 4 else 1 if d <= 10 else 2 def dist(a, b): return math.dist((a.x, a.y), (b.x, b.y)) # ── The town ── def make_town(r): """-> {(x, y): "low" | "high"}. Buildings are rings of high wall with a doorway or two; low cover is scattered in the open. The bottom-left corner is kept clear for the squad.""" obst = {} for _ in range(r.randint(*D.BUILDINGS)): w, h = r.randint(*D.BUILDING_SIZE[0]), r.randint(*D.BUILDING_SIZE[1]) x0, y0 = r.randint(1, D.GRID_W - w - 1), r.randint(1, D.GRID_H - h - 1) if x0 < 7 and y0 + h > D.GRID_H - 6: continue # the landing zone stays open ring = [(x, y) for x in range(x0, x0 + w) for y in range(y0, y0 + h) if x in (x0, x0 + w - 1) or y in (y0, y0 + h - 1)] doors = r.sample([c for c in ring if c not in ((x0, y0), (x0 + w - 1, y0), (x0, y0 + h - 1), (x0 + w - 1, y0 + h - 1))], r.randint(1, 2)) for c in ring: if c not in doors: obst[c] = "high" open_cells = [(x, y) for x in range(D.GRID_W) for y in range(D.GRID_H) if (x, y) not in obst and not (x < 6 and y > D.GRID_H - 6)] for c in r.sample(open_cells, r.randint(*D.LOW_COVER)): obst[c] = "low" _open_up(obst, r) return obst def _reachable(obst, start): seen, todo = {start}, [start] while todo: x, y = todo.pop() for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)): n = (x + dx, y + dy) if 0 <= n[0] < D.GRID_W and 0 <= n[1] < D.GRID_H and n not in obst and n not in seen: seen.add(n) todo.append(n) return seen def _open_up(obst, r): """Every open cell must be reachable from the landing zone: knock a doorway through whatever seals a pocket off (a wall or a wreck between it and the rest of town).""" start = (1, D.GRID_H - 2) while True: reach = _reachable(obst, start) sealed = [(x, y) for x in range(D.GRID_W) for y in range(D.GRID_H) if (x, y) not in obst and (x, y) not in reach] if not sealed: return pocket = _reachable(obst, sealed[0]) doors = [c for c in obst if any((c[0] + dx, c[1] + dy) in pocket for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1))) and any((c[0] + dx, c[1] + dy) in reach for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)))] if doors: del obst[r.choice(sorted(doors))] else: # walled in two deep: fill the pocket instead for c in pocket: obst[c] = "high" @dataclass class Battle: rng: random.Random obst: dict units: list side: str = "squad" turn: int = 1 log: list = field(default_factory=list) outcome: str | None = None # "won" / "lost" smoke: dict = field(default_factory=dict) # cell -> the squad turn its cloud was thrown @classmethod def new(cls, seed=None, squad=None, pods=None): """A fresh battle: the squad lands bottom-left, the enemy's pods are spread over the far side of town, asleep. squad: [(name, class, extra)], optionally with squad number, weapon and pistol after it (default: one of each class, fresh); pods: lists of enemy kinds (default data.PODS).""" r = random.Random(seed) obst = make_town(r) if squad is None: squad = [(n, c, None) for n, c in zip(r.sample(D.NAMES, len(D.SQUAD)), D.SQUAD)] spots = [(x, y) for x in range(0, 6) for y in range(D.GRID_H - 5, D.GRID_H) if (x, y) not in obst] r.shuffle(spots) units = [soldier(s[0], s[1], *spots[i], s[2], *(s[3:] or (1,))) for i, s in enumerate(squad)] b = cls(r, obst, units) pods = D.PODS if pods is None else pods far = [(x, y) for x in range(8, D.GRID_W) for y in range(0, D.GRID_H - 3)] for p, pod in enumerate(pods): # Best spot of a few hundred tries: room for the whole pod (never drop a fighter), # then clear of your soldiers (POD_CLEAR), then as far from the other pods as it gets # (more than 6 cells is enough). best, best_score = None, None for _ in range(300): cx, cy = r.choice(far) cells = [(cx + dx, cy + dy) for dx, dy in [(0, 0)] + NEIGHBOURS] cells = [c for c in cells if b.open(*c)] if len(cells) < len(pod): continue cells = cells[:len(pod)] mine = min(math.dist(c, (u.x, u.y)) for c in cells for u in b.units if u.side == "squad") theirs = min((math.dist(c, (u.x, u.y)) for c in cells for u in b.units if u.side == "enemy"), default=99) score = (mine > D.POD_CLEAR, min(theirs, 6.5), mine) if best_score is None or score > best_score: best, best_score = cells, score if score[:2] == (True, 6.5): break for kind, c in zip(pod, best): b.units.append(enemy(kind, *c, p)) two = len({u.squad for u in units}) > 1 b.say(f"Turn 1. The {'unit' if two else 'squad'} lands. {len(pods)} enemy groups are " "somewhere in town.") b.start_turn() return b def say(self, line): self.log.append(line) # ── the map ── def inside(self, x, y): return 0 <= x < D.GRID_W and 0 <= y < D.GRID_H def unit_at(self, x, y): return next((u for u in self.units if u.alive and (u.x, u.y) == (x, y)), None) def open(self, x, y): return self.inside(x, y) and (x, y) not in self.obst and not self.unit_at(x, y) def los(self, a, b): """Line of sight from cell a to cell b: no high wall on the line between (ends excluded). Walks the line in small steps, so it never slips through a wall's corner.""" (x0, y0), (x1, y1) = a, b n = max(1, int(math.dist(a, b) * 3)) for i in range(1, n): t = i / n c = (round(x0 + (x1 - x0) * t), round(y0 + (y1 - y0) * t)) if c != a and c != b and self.obst.get(c) == "high": return False return True def sees(self, u, t): return dist(u, t) <= D.SIGHT and self.los((u.x, u.y), (t.x, t.y)) def visible(self, side="squad"): """Enemies of `side` that any of its units can see.""" mine = [u for u in self.units if u.alive and u.side == side] return [t for t in self.units if t.alive and t.side != side and any(self.sees(u, t) for u in mine)] def cover(self, t, x, y, sx, sy): """Cover t would have at (x, y) against a shooter at (sx, sy): the best obstacle next to it on the shooter's side (each axis the shooter is off by more than half a cell).""" best = 0 for ax, ay in ((1 if sx > x else -1, 0), (0, 1 if sy > y else -1)): if (ax and abs(sx - x) < 1) or (ay and abs(sy - y) < 1): continue best = max(best, D.COVER.get(self.obst.get((x + ax, y + ay)), 0)) return best # ── shooting ── def odds(self, a, t, ax=None, ay=None, reaction=False, sidearm=False): """(to-hit %, crit %) for a shooting at t, a standing at (ax, ay) (default: where it is), with its weapon or (sidearm) its pistol.""" ax, ay = (a.x, a.y) if ax is None else (ax, ay) w = D.WEAPONS[a.sidearm if sidearm else a.weapon] d = math.dist((ax, ay), (t.x, t.y)) if w.get("melee"): return (100 if d < 1.5 else 0), w["crit"] cov = self.cover(t, t.x, t.y, ax, ay) if t.hunkered: cov *= D.HUNKER hit = (a.aim + w.get("aim", 0) + w["range"][range_band(d)] - t.defense - cov + (D.OVERWATCH_AIM if reaction else 0) + (D.FLASH["aim"] if a.dazed else 0) - (D.SMOKE["defense"] if (t.x, t.y) in self.smoke else 0)) crit = w["crit"] + a.crit_bonus + (D.FLANK_CRIT if cov == 0 else 0) return max(0, min(100, hit)), max(0, min(100, crit)) def can_shoot(self, a, t, sidearm=False): if not (a.alive and t.alive and a.side != t.side and a.actions > 0 and a.side == self.side): return False if sidearm: return bool(a.sidearm) and self.sees(a, t) if a.melee: return dist(a, t) < 1.5 return a.ammo > 0 and self.sees(a, t) def shoot(self, a, t, reaction=False, sidearm=False): if not reaction and not self.can_shoot(a, t, sidearm): raise ValueError(f"{a.name} can't shoot {t.name}") hit, crit = self.odds(a, t, reaction=reaction, sidearm=sidearm) w = D.WEAPONS[a.sidearm if sidearm else a.weapon] if not w.get("melee") and not sidearm: a.ammo -= 1 if not reaction: a.actions = 0 if self.rng.randint(1, 100) > hit: self.say(f" {a.name} misses {t.name} ({hit}%)") return False dmg = max(1, self.rng.randint(*w["damage"]) - t.armor) crit_hit = self.rng.randint(1, 100) <= crit if crit_hit: dmg = math.ceil(dmg * 1.5) t.hp -= dmg self.say(f" {a.name} hits {t.name} for {dmg}" + (" (crit)" if crit_hit else "") + (f": {t.name} is down" if t.hp <= 0 else f" ({t.hp} left)")) if t.hp <= 0: t.overwatch = False a.kills += 1 how = "cut down" if w.get("melee") else "shot" t.downed = (f"{how} by {who(a)} with {a.sidearm if sidearm else a.weapon}" + (" (a critical hit)" if crit_hit else "") + (", firing on overwatch" if reaction else "") + f", turn {self.turn}") self.check() return True # ── moving ── def reach(self, u, actions=None): """Cells u can move to -> {(x, y): movement cost}, within one move (or `actions` moves). No corner cutting past an obstacle; units block.""" budget = u.mobility * (actions if actions is not None else 1) best, todo, out = {(u.x, u.y): 0.0}, [(0.0, u.x, u.y)], {} while todo: cost, x, y = heapq.heappop(todo) if cost > best.get((x, y), math.inf): continue for dx, dy in NEIGHBOURS: nx, ny = x + dx, y + dy if not self.open(nx, ny): continue if dx and dy and ((x + dx, y) in self.obst or (x, y + dy) in self.obst): continue nc = cost + (D.DIAGONAL if dx and dy else 1) if nc <= budget + 1e-9 and nc < best.get((nx, ny), math.inf): best[(nx, ny)] = nc out[(nx, ny)] = nc heapq.heappush(todo, (nc, nx, ny)) return out def path(self, u, goal, actions): """The cells from u to goal (excluding u's own), cheapest first-found.""" budget = u.mobility * actions prev, best, todo = {}, {(u.x, u.y): 0.0}, [(0.0, u.x, u.y)] while todo: cost, x, y = heapq.heappop(todo) if (x, y) == goal: break for dx, dy in NEIGHBOURS: nx, ny = x + dx, y + dy if not self.open(nx, ny) or (dx and dy and ((x + dx, y) in self.obst or (x, y + dy) in self.obst)): continue nc = cost + (D.DIAGONAL if dx and dy else 1) if nc <= budget + 1e-9 and nc < best.get((nx, ny), math.inf): best[(nx, ny)], prev[(nx, ny)] = nc, (x, y) heapq.heappush(todo, (nc, nx, ny)) cells, c = [], goal while c in prev: cells.append(c) c = prev[c] return cells[::-1] def move(self, u, x, y): """Move u to (x, y): one action if within a move, both if it takes a dash. Overwatch fires at it along the way; seeing a sleeping pod wakes it.""" if u.side != self.side or u.actions <= 0 or not u.alive: raise ValueError(f"{u.name} can't move now") one = self.reach(u, 1) if (x, y) in one: used = 1 elif u.actions >= 2 and (x, y) in self.reach(u, 2): used = 2 else: raise ValueError(f"{u.name} can't reach {x},{y}") steps = self.path(u, (x, y), used) u.actions -= used u.hunkered = False for c in steps: u.x, u.y = c self._reactions(u) if not u.alive or self.outcome: break self._wake() return used def _reactions(self, mover): for w in self.units: if w.alive and w.overwatch and w.side != mover.side and mover.alive \ and not w.melee and w.ammo > 0 and self.sees(w, mover): w.overwatch = False self.say(f" {w.name} fires on overwatch at {mover.name}") self.shoot(w, mover, reaction=True) def _wake(self): """Any sleeping pod a squad member can see wakes and scrambles for cover.""" seen = {t.pod for t in self.visible("squad") if not t.awake} for pod in sorted(seen): group = [t for t in self.units if t.alive and t.pod == pod] self.say(f" Enemy spotted: {', '.join(t.kind for t in group)}!") for t in group: t.awake = True spot = self._best_cell(t, cover_only=True) if spot: t.x, t.y = spot # ── other actions ── def overwatch(self, u): self._end_with(u, "overwatch") u.overwatch = True def hunker(self, u): self._end_with(u, "hunker") u.hunkered = True def _end_with(self, u, what): if u.side != self.side or u.actions <= 0: raise ValueError(f"{u.name} can't {what} now") u.actions = 0 self.say(f" {u.name} goes on {what}" if what == "overwatch" else f" {u.name} hunkers down") def reload(self, u): if u.side != self.side or u.actions <= 0: raise ValueError(f"{u.name} can't reload now") u.ammo = u.clip or D.WEAPONS[u.weapon]["clip"] u.actions -= 1 self.say(f" {u.name} reloads") def medkit(self, u, t): if u.medkits <= 0 or u.actions <= 0 or dist(u, t) >= 1.5 or t.side != u.side: raise ValueError(f"{u.name} can't patch up {t.name}") u.medkits -= 1 u.actions -= 1 healed = min(D.MEDKIT_HEAL, t.max_hp - t.hp) t.hp += healed self.say(f" {u.name} patches up {t.name} (+{healed})") def grenade(self, u, x, y): g = D.GRENADE if u.grenades <= 0 or u.actions <= 0 or math.dist((u.x, u.y), (x, y)) > g["range"] \ or not self.los((u.x, u.y), (x, y)): raise ValueError(f"{u.name} can't throw there") u.grenades -= 1 u.actions -= 1 hit = [] for t in self.units: if t.alive and max(abs(t.x - x), abs(t.y - y)) <= g["radius"]: t.hp -= max(1, g["damage"] - t.armor) hit.append(t.name + (" (down)" if t.hp <= 0 else "")) if t.hp <= 0: t.downed = f"caught in a grenade blast thrown by {who(u)}, turn {self.turn}" if t.hp <= 0 and t.side != u.side: u.kills += 1 for c in [(x + dx, y + dy) for dx, dy in [(0, 0)] + NEIGHBOURS]: if self.obst.get(c) == "low": del self.obst[c] # blows the low cover away self.say(f" {u.name} throws a grenade: " + (", ".join(hit) or "nobody caught in it")) self._wake() self.check() def _throw(self, u, x, y, have, spec, what): if getattr(u, have) <= 0 or u.actions <= 0 or math.dist((u.x, u.y), (x, y)) > spec["range"] \ or not self.los((u.x, u.y), (x, y)): raise ValueError(f"{u.name} can't throw a {what} there") setattr(u, have, getattr(u, have) - 1) u.actions -= 1 r = spec["radius"] return [(x + dx, y + dy) for dx in range(-r, r + 1) for dy in range(-r, r + 1) if self.inside(x + dx, y + dy)] def throw_smoke(self, u, x, y): """A cloud over the cells around (x, y): anyone in it is harder to hit (SMOKE defense) until the end of your next turn.""" for c in self._throw(u, x, y, "smoke", D.SMOKE, "smoke grenade"): self.smoke[c] = self.turn self.say(f" {u.name} throws smoke.") def flashbang(self, u, x, y): """Enemies caught wake, dazed: their next turn, one action and FLASH aim.""" cells = set(self._throw(u, x, y, "flashbangs", D.FLASH, "flashbang")) caught = [t for t in self.units if t.alive and t.side != u.side and (t.x, t.y) in cells] for t in caught: t.dazed = True t.overwatch = False for pod in {t.pod for t in caught if t.pod is not None}: for t in self.units: if t.pod == pod and not t.awake: t.awake = True self.say(f" {u.name} throws a flashbang: " + (", ".join(t.name for t in caught) + " dazed" if caught else "nobody caught in it")) # ── turns ── def check(self): if self.outcome: return if not any(t.alive for t in self.units if t.side == "enemy"): self.outcome = "won" self.say("The town is clear. Mission won.") elif not any(u.alive for u in self.units if u.side == "squad"): self.outcome = "lost" self.say("The squad is gone. Mission lost.") def start_turn(self): for u in self.units: if u.alive and u.side == self.side: u.actions = 1 if u.dazed else D.ACTIONS u.overwatch = False u.hunkered = False def end_turn(self): if self.outcome: return if self.side == "squad": self._clear("squad") self.smoke = {c: t for c, t in self.smoke.items() if t >= self.turn} # last turn's clouds go self.side = "enemy" self.start_turn() self.say("Enemy turn.") self.ai_turn() self._clear("enemy") if self.outcome: return self.side = "squad" self.turn += 1 self.say(f"Turn {self.turn}.") self.start_turn() def _clear(self, side): for u in self.units: if u.side == side: u.dazed = False # ── the AI: the enemy always, your squad when you let it ── def ai_turn(self): for u in [u for u in self.units if u.alive and u.side == self.side]: if self.outcome: return if u.side == "enemy" and not u.awake: continue self._act(u) def auto(self): """Play the squad's turn with the AI, then end it.""" if self.side == "squad" and not self.outcome: self.ai_turn() self.end_turn() def _foes(self, u): return [t for t in self.units if t.alive and t.side != u.side and (t.side == "squad" or t.awake)] def _act(self, u): while u.actions > 0 and u.alive and not self.outcome: foes = self._foes(u) if not foes: return self._advance(u) if u.melee: near = min(foes, key=lambda t: dist(u, t)) if self.can_shoot(u, near): self.shoot(u, near) return if not self._toward(u, (near.x, near.y), cover=False): return continue if u.ammo <= 0: pistol = [(self.odds(u, t, sidearm=True)[0], t) for t in foes if self.can_shoot(u, t, sidearm=True)] if u.actions == 1 and pistol and max(h for h, _ in pistol) >= 40: self.shoot(u, max(pistol, key=lambda s: s[0])[1], sidearm=True) return self.reload(u) continue shots = [(self.odds(u, t)[0], t) for t in foes if self.can_shoot(u, t)] here = max((h for h, _ in shots), default=0) if u.actions >= 2: spot = self._best_cell(u) if spot and self._score(u, *spot) > self._score(u, u.x, u.y) + 5: self.move(u, *spot) continue if shots and here >= 25: hit, t = max(shots, key=lambda s: (s[0], -s[1].hp)) self.shoot(u, t) return if u.grenades and u.actions: target = self._grenade_target(u) if target: self.grenade(u, *target) continue if u.actions >= 1 and not shots: spot = self._best_cell(u) if spot and self._score(u, *spot) > self._score(u, u.x, u.y): self.move(u, *spot) continue if self._close_in(u, foes): continue if u.side == "squad" and u.actions >= 1 and self._toward_sleepers(u): continue if shots: hit, t = max(shots, key=lambda s: s[0]) self.shoot(u, t) return self.overwatch(u) return def walk(self, goal): """Walking distance to goal from every cell, around walls (units don't block it: they move). -> {(x, y): cost}""" best, todo = {goal: 0.0}, [(0.0, goal)] while todo: cost, (x, y) = heapq.heappop(todo) if cost > best[(x, y)]: continue for dx, dy in NEIGHBOURS: n = (x + dx, y + dy) if not self.inside(*n) or n in self.obst: continue if dx and dy and ((x + dx, y) in self.obst or (x, y + dy) in self.obst): continue nc = cost + (D.DIAGONAL if dx and dy else 1) if nc < best.get(n, math.inf): best[n] = nc heapq.heappush(todo, (nc, n)) return best def _toward(self, u, goal, cover=True): """Move u one move nearer goal (x, y) by walking distance, preferring cover. -> moved?""" cells = self.reach(u, 1) if not cells: return False far = self.walk(goal) now = far.get((u.x, u.y), math.inf) best = min(cells, key=lambda c: far.get(c, math.inf) - (3 if cover and self._cover_any(c) else 0)) if far.get(best, math.inf) >= now: return False self.move(u, *best) return True def _close_in(self, u, foes): """No shot from anywhere near: walk toward the nearest foe, cover first. -> moved?""" goal = min(foes, key=lambda t: dist(u, t)) return self._toward(u, (goal.x, goal.y)) def _toward_sleepers(self, u): sleeping = [t for t in self.units if t.alive and t.side == "enemy" and not t.awake] if not sleeping: return False goal = min(sleeping, key=lambda t: dist(u, t)) return self._toward(u, (goal.x, goal.y)) def _advance(self, u): """Nobody to fight in sight: the squad moves up toward the far side of town.""" if u.side != "squad": u.actions = 0 return sleeping = [t for t in self.units if t.alive and t.side == "enemy"] if not sleeping: u.actions = 0 return goal = min(sleeping, key=lambda t: dist(u, t)) if not self._toward(u, (goal.x, goal.y)): u.actions = 0 return if u.actions: self.overwatch(u) def _cover_any(self, c): x, y = c return max((D.COVER.get(self.obst.get((x + dx, y + dy)), 0) for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1))), default=0) def _score(self, u, x, y): """How good (x, y) is for u: its best shot from there, plus its cover against the foes who could shoot it, minus being flanked.""" foes = self._foes(u) if not foes: return 0 best_shot = max((self.odds(u, t, x, y)[0] for t in foes if math.dist((x, y), (t.x, t.y)) <= D.SIGHT and self.los((x, y), (t.x, t.y))), default=0) covers = [self.cover(u, x, y, t.x, t.y) for t in foes if math.dist((x, y), (t.x, t.y)) <= D.SIGHT and self.los((x, y), (t.x, t.y))] safety = (sum(covers) / len(covers) - 30 * sum(1 for c in covers if c == 0)) if covers else 20 return best_shot + safety def _best_cell(self, u, cover_only=False): cells = self.reach(u, 1) if not cells: return None if cover_only: near = min(self._foes(u) or [u], key=lambda t: dist(u, t)) return max(cells, key=lambda c: (self.cover(u, c[0], c[1], near.x, near.y), -cells[c])) return max(cells, key=lambda c: (self._score(u, *c), -cells[c])) def _grenade_target(self, u): g = D.GRENADE best, score = None, 1 for t in self._foes(u): c = (t.x, t.y) if math.dist((u.x, u.y), c) > g["range"] or not self.los((u.x, u.y), c): continue caught = [s for s in self.units if s.alive and max(abs(s.x - c[0]), abs(s.y - c[1])) <= g["radius"]] if any(s.side == u.side for s in caught): continue if len(caught) > score: best, score = c, len(caught) return best def auto_battle(seed, max_turns=40): """Both sides played by the AI. -> the finished Battle.""" b = Battle.new(seed) while not b.outcome and b.turn <= max_turns: b.auto() return b