"""Coaches: situational play-calling for offense and defense, plus the drive loop. Rule-based (no learning): weights come from down/distance/field position, and each coach adjusts to what has worked or been seen earlier in the drive. Every call comes with a one-line reason a real coach can audit. """ from __future__ import annotations import math import random from engine import Sim from playbook import DEFENSE_CALLS, OFFENSE_PLAYS from rules import FIELD_WIDTH_YD as W, RuleProfile RUNS = {"Inside Zone", "Outside Zone", "Draw", "RPO Slant"} def snap_spot(pf: RuleProfile, y: float) -> float: """Ball is spotted on the nearest hash if the play ended outside the hashes (hash width is level-specific).""" mid, h = W / 2, pf.hash_half_yd y = min(W - 1, max(1, y)) return mid + math.copysign(h, y - mid) if abs(y - mid) > h else y class OffCoach: BASE = {"Inside Zone": 1.0, "Outside Zone": 0.6, "Draw": 0.35, "RPO Slant": 0.5, "Quick Slants": 0.8, "Mesh": 0.8, "Four Verticals": 0.45, "PA Post": 0.5, "RB Screen": 0.25, "Sideline Fade": 0.35} def __init__(self, rng): self.rng, self.stats, self.seen_blitz = rng, {}, 0 def call(self, s): w, why = dict(self.BASE), [] d, dn, yl = s["dist"], s["down"], s["yl"] if d <= 2: for p in ("Inside Zone", "Outside Zone"): w[p] *= 2.4 w["Quick Slants"] *= 1.3 w["Four Verticals"] *= 0.4 w["RB Screen"] *= 0.3 why.append("short yardage") elif d >= 8: for p in RUNS: w[p] *= 0.45 for p in ("Mesh", "Four Verticals", "PA Post", "Quick Slants", "Sideline Fade"): w[p] *= 1.7 why.append(f"{dn}&{d}: need chunk yards") if dn == 3 and d >= 5: w["Mesh"] *= 1.6 w["Quick Slants"] *= 1.3 why.append("3rd-down concepts") if yl >= 85: w["Four Verticals"] *= 0.3 w["Sideline Fade"] *= 2.0 why.append("red zone: compressed field") if yl <= 10: for p in RUNS: w[p] *= 1.4 w["RB Screen"] *= 0.2 why.append("backed up: protect the ball") if self.seen_blitz >= 2: w["RB Screen"] *= 2.5 w["Quick Slants"] *= 1.6 why.append("defense is blitzing: quick/screen answer") for p, (n, tot) in self.stats.items(): if n >= 2: w[p] *= math.exp(max(-1.0, min(1.0, 0.10 * (tot / n - 4.5)))) names = list(w) pick = self.rng.choices(names, [w[n] for n in names])[0] if pick in self.stats and self.stats[pick][0] >= 2: n, tot = self.stats[pick] why.append(f"{pick} averaging {tot / n:.1f}") return pick, "; ".join(why) or "base call" def record(self, play, yards, blitz): n, tot = self.stats.get(play, (0, 0.0)) self.stats[play] = (n + 1, tot + yards) self.seen_blitz = self.seen_blitz + 1 if blitz else max(0, self.seen_blitz - 1) class DefCoach: def __init__(self, rng): self.rng, self.hist = rng, [] def call(self, s): names = list(DEFENSE_CALLS) w = {n: 1.0 for n in names} why = [] d, dn, yl = s["dist"], s["down"], s["yl"] run_rate = sum(1 for p in self.hist[-5:] if p in RUNS) / max(1, len(self.hist[-5:])) if d <= 2: for n in names: if n.startswith("4-3") or "Blitz" in n: w[n] *= 2.0 why.append("short yardage: load the box") elif d >= 8: for n in names: if n.startswith("Nickel"): w[n] *= 2.0 why.append(f"{dn}&{d}: pass down, go nickel") if dn == 3 and d >= 6: for n in names: if "Blitz" in n: w[n] *= 1.8 why.append("3rd & long pressure") if yl >= 88: for n in names: if "Cover 1" in n or "Cover 0" in n: w[n] *= 1.8 why.append("goal line: tight man") if len(self.hist) >= 3 and run_rate >= 0.6: for n in names: if n.startswith("4-3") or n.startswith("3-4"): w[n] *= 1.6 why.append("offense is run-heavy") pick = self.rng.choices(names, [w[n] for n in names])[0] return pick, "; ".join(why) or "base call" def record(self, off_play): self.hist.append(off_play) def fourth_down(s, rng): goal = 100 - s["yl"] fg_len = goal + 17 if fg_len <= 55: if s["dist"] <= 1 and goal <= 3 and rng.random() < 0.5: return "go" return "fg" if s["yl"] >= 50 and s["dist"] <= 2 and rng.random() < 0.5: return "go" return "punt" def run_drive(pf: RuleProfile, off_team, def_team, yl=25, by=None, seed=0, max_plays=16, forced=None, def_forced=None): """Simulate a drive (or a single play if `forced` is given and max_plays == 1).""" rng = random.Random(seed) oc, dc = OffCoach(rng), DefCoach(rng) st = dict(down=1, dist=min(10, 100 - yl), yl=yl, by=by if by is not None else W / 2 - pf.hash_half_yd) st["by"] = snap_spot(pf, st["by"]) if by is None else by plays, points, end = [], 0, "Drive ends" n = 0 while n < max_plays: n += 1 s = dict(st) if s["down"] == 4 and forced is None: dec = fourth_down(s, rng) if dec == "fg": length = 100 - s["yl"] + 17 p = max(0.1, min(0.98, 0.995 - 0.0125 * max(0, length - 30))) good = rng.random() < p plays.append(dict(n=n, **s, kind="special", off_play=f"{length}-yd field goal", def_call="", off_why="4th down: in range", def_why="", outcome="fg" if good else "fg_miss", yards=0, text=f"{length}-yd field goal is {'GOOD' if good else 'NO GOOD'}", replay=None)) points += 3 if good else 0 end = "Field goal made" if good else "Field goal missed" break if dec == "punt": plays.append(dict(n=n, **s, kind="special", off_play="Punt", def_call="", off_why="4th down: out of range", def_why="", outcome="punt", yards=0, text=f"Punt (net {rng.randint(33, 46)} yds)", replay=None)) end = "Punt" break if forced: op, ow = forced, "coach's choice (you)" else: op, ow = oc.call(s) if def_forced: dcall, dw = def_forced, "coach's choice (you)" else: dcall, dw = dc.call(s) bx = 10 + s["yl"] sim = Sim(pf, off_team, def_team, op, dcall, bx, s["by"], seed=rng.randint(0, 10 ** 9)) res = sim.run() blitz = "Blitz" in dcall oc.record(op, res["yards"] if not res["penalty"] else 0, blitz) dc.record(op) rec = dict(n=n, **s, kind="play", off_play=op, off_why=ow, def_call=dcall, def_why=dw, outcome=res["outcome"], yards=res["yards"], text=res["text"], rule=res["rule"], penalty=res["penalty"], replay=sim.replay(), pressure=res["pressure"]) plays.append(rec) pen = res["penalty"] if pen: if pen["kind"] == "dpi": st["yl"] = min(99, st["yl"] + int(round(pen["yards"]))) st["down"], st["dist"] = 1, min(10, 100 - st["yl"]) else: st["yl"] = max(1, st["yl"] + pen["yards"]) st["dist"] = min(99, st["dist"] - pen["yards"]) continue if res["td"]: points, end = points + 7, "TOUCHDOWN" break if res["turnover"]: end = "Turnover" break gain = res["yards"] st["yl"] = max(1, min(99, st["yl"] + int(round(gain)))) if res["outcome"] not in ("incomplete",): st["by"] = snap_spot(pf, res["end_y"]) if gain >= st["dist"]: st["down"], st["dist"] = 1, min(10, 100 - st["yl"]) else: st["down"] += 1 st["dist"] = max(1, int(math.ceil(st["dist"] - gain))) if st["down"] > 4: end = "Turnover on downs" break if forced: break return dict(plays=plays, points=points, end=end, final_yl=st["yl"])