On this page

Design a Live Cricket Scoreboard (Cricbuzz-style)

During a big match, one scorer at the ground enters every delivery and millions of phones refresh the score. The scorer is human: they press "4" when the umpire signals four wides, and they need to fix it within seconds. The scorecard has to stay right through all of it, including the odd rules: a wide isn't a ball faced, a no-ball is, byes don't count against the bowler, and a run-out doesn't count to the bowler either.

The design move that makes this tractable is to treat each ball as an immutable event and the scorecard as something derived from the list of events. Corrections become "remove the last event and replay". New statistics become new ways of reading the same list. Readers get immutable snapshots, so one writer and many readers never need to share a lock. It's event sourcing in miniature (see event sourcing for the full version). This page follows the LLD interview framework.

1. Requirements

Clarifying questions and the answers we'll assume:

QuestionAssumption
Who writes?One official scorer per match. Everyone else reads.
Which formats?T20, ODI and Test, plus custom ones such as a Super Over.
How detailed?Ball by ball: runs, extras (wide, no-ball, bye, leg-bye), wickets with dismissal type, the bowler, and the incoming batter.
Corrections?Undo the last ball (repeatedly) and redo. Editing a ball from three overs ago is a follow-up.
What do readers see?The scorecard: totals, overs, extras, batting and bowling figures, who is on strike, free hit, result.
Live updates?Subscribers are pushed every change, including corrections.

Functional requirements

  1. Start an innings with two openers. Record deliveries one at a time.
  2. Apply the laws: wides and no-balls add a penalty run and aren't legal deliveries, an over is six legal balls, ends change after the over and on odd runs, the batting side is all out when one batter is left.
  3. Enforce bowling rules: no consecutive overs, no change mid-over, the format's per-bowler limit.
  4. In limited-overs formats, a no-ball gives a free hit on which, of the dismissals we model, only a run-out counts (rare ones such as obstructing the field are out of scope). The free hit carries over if the next delivery is a wide or another no-ball.
  5. Reject impossible dismissals: on a wide, only stumped, run out or hit wicket. On a no-ball, run out (again, among the dismissals we model).
  6. Derive the scorecard, target and result. Undo and redo the last entries.
  7. Notify subscribers after every change.

Non-functional requirements

  • Readers never see a half-applied ball, and never slow the scorer down.
  • Corrections are exact. After undo, the scorecard equals what it was before the mistake.
  • The log is the truth. Any read model can be rebuilt from the events.

Out of scope: Duckworth-Lewis-Stern, Test results (draws, follow-on), penalty runs for fielding offences, and short runs.

2. Core entities

EntityResponsibility
FormatOvers per innings (or none), innings per side, per-bowler over cap, free hit on/off. The Strategy.
InningsStarted, BallImmutable events. A Ball records what the scorer saw: bowler, runs, extra type, dismissal, incoming batter.
ProjectionFolds events into working state, enforcing the laws as it goes.
Scoreboard, InningsCard, BatterCard, BowlerCardThe immutable read model readers get.
MatchThe append-only event log, the current projection and the current snapshot. Owns the write lock.
RecordEvent, ScorerCommand objects and the undo/redo history.
ListenersObservers that receive (snapshot, event) after every change, with event = null for a correction.

The key choice is what goes in an event. A Ball holds only what the scorer saw, not derived facts like "striker" or "new total". Who's on strike is computed by the projection. If events stored derived facts, an undo three balls back would leave the later events claiming wrong strikers.

How each kind of delivery scores

DeliveryTeam runsTo batterBatter ball faced?Against bowlerLegal ball?
runs off the batrunsrunsyesrunsyes
Wide, runs run1 + runs0no1 + runsno
No-ball, runs off the bat1 + runsrunsyes1 + runsno
Bye or leg-bye, runsruns0yes0yes

Strike changes if the batters crossed an odd number of times (an odd number of runs that weren't a boundary), and again at the end of every over. A dismissed batter's replacement takes that batter's end. That's why the new batter is on strike after a catch, as the 2022 change to the Laws requires.

3. Class diagram

classDiagram
    class Format {
        +String name
        +Integer overs
        +int inningsPerSide
        +Integer maxOversPerBowler
        +boolean freeHit
    }
    class MatchEvent {
        <<interface>>
    }
    class InningsStarted {
        +String batting
        +String striker
        +String nonStriker
    }
    class Ball {
        +String bowler
        +int runs
        +Extra extra
        +Out out
        +String incoming
    }
    class Projection {
        +apply(MatchEvent)
        +snapshot(int) Scoreboard
    }
    class Scoreboard {
        +int version
        +List innings
        +boolean freeHit
        +String result
    }
    class InningsCard {
        +int runs
        +int wickets
        +int balls
        +overs() String
    }
    class Match {
        -List events
        -Scoreboard board
        +append(MatchEvent)
        +dropLast() MatchEvent
        +board() Scoreboard
    }
    class Command {
        <<interface>>
        +execute(Match)
        +undo(Match)
    }
    class RecordEvent
    class Scorer {
        +record(MatchEvent)
        +undo()
        +redo()
    }
    MatchEvent <|.. InningsStarted
    MatchEvent <|.. Ball
    Match o-- MatchEvent : log
    Match --> Projection
    Projection --> Format
    Projection ..> Scoreboard : builds
    Scoreboard o-- InningsCard
    Command <|.. RecordEvent
    Scorer o-- Command : history
    RecordEvent --> Match

4. Key flows

Recording a ball

sequenceDiagram
    participant S as Scorer
    participant M as Match
    participant P as Projection
    participant L as Subscribers
    S->>M: append(Ball)
    M->>M: take write lock
    M->>P: apply(ball)
    P->>P: validate bowler, dismissal, free hit
    P->>P: update runs, cards, strike, overs
    M->>M: add ball to log
    M->>P: snapshot(version + 1)
    M->>M: swap in the new immutable board
    M->>L: notify(board, ball)
    M->>M: release write lock

Validation happens before the event is stored, so the log only ever contains deliveries that were legal when entered. A rejected ball leaves no trace.

Undoing a wrong ball

sequenceDiagram
    participant S as Scorer
    participant C as RecordEvent
    participant M as Match
    participant L as Subscribers
    S->>C: undo()
    C->>M: dropLast()
    M->>M: remove last event
    M->>M: new Projection, replay every remaining event
    M->>M: publish a new version
    M->>L: notify(board, null) as a correction

Replay is O(n) in the number of balls. A full ODI has about 600 deliveries, and replaying them takes well under a millisecond. For a five-day Test (around 2,700 balls) it's still trivial. If it ever weren't, keep a snapshot at the start of every over and replay from the latest one, which is what snapshots are for.

Innings lifecycle

stateDiagram-v2
    [*] --> IN_PROGRESS : InningsStarted
    IN_PROGRESS --> IN_PROGRESS : ball
    IN_PROGRESS --> CLOSED : all out
    IN_PROGRESS --> CLOSED : overs complete
    IN_PROGRESS --> CLOSED : target reached
    CLOSED --> IN_PROGRESS : undo of the closing ball
    CLOSED --> [*] : next innings or result

Free hit

stateDiagram-v2
    [*] --> NORMAL
    NORMAL --> FREE_HIT_NEXT : no-ball, limited overs
    FREE_HIT_NEXT --> FREE_HIT_NEXT : wide or no-ball
    FREE_HIT_NEXT --> NORMAL : legal delivery

5. Patterns and why

PatternWhereWhy it fitsRejected alternative
Event sourcing (lite)the Match log plus ProjectionCorrections, audit and new statistics all fall out of one list of facts.Mutating a scorecard in place. Undo then needs an exact inverse for every rule, and one wrong inverse corrupts the card forever.
CommandRecordEvent, ScorerA uniform undo/redo history. Commands can also be queued and sent from a scorer's tablet to the server.Undo as "the UI calls dropLast()". It works until you add redo, batching or a second kind of command.
StrategyFormatT20, ODI, Test and Super Over differ in a few parameters. The projection asks the format.if (format == "T20") branches through the scoring code.
Observerlisteners on MatchPush to apps, commentary, alerts and stats without the scorer knowing about them.Readers polling. It's fine as a fallback, but it wastes requests and adds latency.
Immutable snapshotScoreboardReaders share one object without locks and can't corrupt it.Readers locking the live state, which makes the scorer wait for millions of reads.

Why undo replays instead of reversing. A ball touches seven things: total, extras, batter card, bowler card, strike, over count and free hit, sometimes a wicket and the innings status. Writing the inverse of each, and keeping it right as the rules grow, is where bugs live. Replaying from the log is always right, because it uses the same forward code that produced the state. That's also why the Command's undo is so short: the inverse of "append an event" is "drop it and replay".

Why Memento was rejected. Saving a full snapshot before each ball would also give undo. But it stores 600 copies of the scorecard for an ODI, and it doesn't give you the log, which you need for new statistics and for audit.

Formats as data, not classes. Each format is a record of parameters. That's still Strategy, because the projection delegates decisions to it. If a format ever needs behaviour rather than a number (Test declarations, The Hundred's five-ball sets), add methods to the interface then.

6. The code

The demo plays a Super Over (one over, two wickets), which is a real cricket format and short enough to check by hand. India bat: a four, a wide, a no-ball with a single, a six off the free hit, a wicket, a leg-bye, a catch. That's 14 for 2 in 0.5 overs. Australia chase 15. After three balls the scorer enters a four by mistake, undoes it, enters the four wides that actually happened, and Australia win off the next ball.

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.BiConsumer;

// ---------- formats (Strategy) ----------
record Format(String name, Integer overs, int inningsPerSide, Integer maxOversPerBowler, boolean freeHit) {
    static final Format T20 = new Format("T20", 20, 1, 4, true);
    static final Format ODI = new Format("ODI", 50, 1, 10, true);
    static final Format TEST = new Format("Test", null, 2, null, false);
    static final Format SUPER_OVER = new Format("Super Over", 1, 1, 1, true);
}

// ---------- events: the source of truth ----------
enum Extra { NONE, WIDE, NO_BALL, BYE, LEG_BYE }
enum Out {
    BOWLED("b"), CAUGHT("c"), LBW("lbw"), STUMPED("st"), RUN_OUT("run out"), HIT_WICKET("hit wkt");
    final String code;
    Out(String code) { this.code = code; }
}

sealed interface MatchEvent permits InningsStarted, Ball {}
record InningsStarted(String batting, String bowling, String striker, String nonStriker) implements MatchEvent {}
/** runs: off the bat, or byes/leg-byes/wides actually run. Penalty runs are added automatically. */
record Ball(String bowler, int runs, Extra extra, Out out, String dismissed, String incoming) implements MatchEvent {
    static Ball runs(String bowler, int runs) { return new Ball(bowler, runs, Extra.NONE, null, null, null); }
    static Ball extra(String bowler, int runs, Extra extra) { return new Ball(bowler, runs, extra, null, null, null); }
    static Ball wicket(String bowler, Out out, String incoming) { return new Ball(bowler, 0, Extra.NONE, out, null, incoming); }
}

final class ScoringException extends RuntimeException { ScoringException(String m) { super(m); } }

// ---------- read model: immutable snapshots ----------
record BatterCard(String name, int runs, int balls, int fours, int sixes, String out) {
    BatterCard(String name) { this(name, 0, 0, 0, 0, "not out"); }
}
record BowlerCard(String name, int balls, int runs, int wickets) {
    BowlerCard(String name) { this(name, 0, 0, 0); }
}
record InningsCard(String batting, int runs, int wickets, int balls, Map<Extra, Integer> extras,
                   Map<String, BatterCard> batters, Map<String, BowlerCard> bowlers, String striker, String nonStriker, boolean closed) {
    String overs() { return balls / 6 + "." + balls % 6; }
}
record Scoreboard(int version, List<InningsCard> innings, boolean freeHit, String result) {}

// ---------- the projection: fold events into state ----------
final class Projection {
    private static final class Innings {
        final String batting, bowling;
        String striker, nonStriker, overBowler, lastOverBowler;
        int runs, wickets, balls;
        boolean closed;
        final Map<Extra, Integer> extras = new EnumMap<>(Extra.class);
        final Map<String, BatterCard> batters = new LinkedHashMap<>();
        final Map<String, BowlerCard> bowlers = new LinkedHashMap<>();
        Innings(InningsStarted e) {
            batting = e.batting(); bowling = e.bowling(); striker = e.striker(); nonStriker = e.nonStriker();
            batters.put(striker, new BatterCard(striker));
            batters.put(nonStriker, new BatterCard(nonStriker));
        }
        void swap() { String t = striker; striker = nonStriker; nonStriker = t; }
    }

    private final Format fmt;
    private final Map<String, List<String>> squads;
    private final List<Innings> innings = new ArrayList<>();
    private boolean freeHit;

    Projection(Format fmt, Map<String, List<String>> squads) { this.fmt = fmt; this.squads = squads; }

    void apply(MatchEvent e) {
        switch (e) {
            case InningsStarted s -> {
                if ((!innings.isEmpty() && !last().closed) || result() != null) throw new ScoringException("previous innings still open, or match over");
                innings.add(new Innings(s));
                freeHit = false;
            }
            case Ball b -> {
                if (innings.isEmpty() || last().closed) throw new ScoringException("no innings in progress");
                ball(last(), b);
            }
        }
    }

    private Innings last() { return innings.get(innings.size() - 1); }

    private void ball(Innings inn, Ball b) {
        if (inn.overBowler == null) {                                          // first delivery of a new over
            if (b.bowler().equals(inn.lastOverBowler)) throw new ScoringException("a bowler cannot bowl consecutive overs");
            int bowled = inn.bowlers.getOrDefault(b.bowler(), new BowlerCard(b.bowler())).balls();
            if (fmt.maxOversPerBowler() != null && bowled >= fmt.maxOversPerBowler() * 6)
                throw new ScoringException(b.bowler() + " has bowled the maximum overs");
            inn.overBowler = b.bowler();
        } else if (!b.bowler().equals(inn.overBowler)) throw new ScoringException("change bowlers only between overs");
        if (b.out() != null) {
            boolean ok = switch (b.extra()) {
                case WIDE -> EnumSet.of(Out.STUMPED, Out.RUN_OUT, Out.HIT_WICKET).contains(b.out());
                case NO_BALL -> b.out() == Out.RUN_OUT;
                default -> true;
            };
            if (!ok || (freeHit && b.out() != Out.RUN_OUT)) throw new ScoringException(b.out() + " is impossible on this delivery");
        }

        boolean legal = b.extra() != Extra.WIDE && b.extra() != Extra.NO_BALL;
        int penalty = legal ? 0 : 1;
        int offBat = (b.extra() == Extra.NONE || b.extra() == Extra.NO_BALL) ? b.runs() : 0;
        int conceded = (b.extra() == Extra.BYE || b.extra() == Extra.LEG_BYE) ? 0 : b.runs() + penalty;   // byes are not the bowler's
        inn.runs += b.runs() + penalty;
        if (b.extra() != Extra.NONE) inn.extras.merge(b.extra(), penalty + (b.extra() == Extra.NO_BALL ? 0 : b.runs()), Integer::sum);

        BatterCard s = inn.batters.get(inn.striker);
        if (b.extra() != Extra.WIDE)                                            // a wide is not a ball faced
            inn.batters.put(inn.striker, new BatterCard(s.name(), s.runs() + offBat, s.balls() + 1,
                    s.fours() + (offBat == 4 ? 1 : 0), s.sixes() + (offBat == 6 ? 1 : 0), s.out()));
        BowlerCard bw = inn.bowlers.getOrDefault(b.bowler(), new BowlerCard(b.bowler()));
        boolean bowlersWicket = b.out() != null && b.out() != Out.RUN_OUT;
        inn.bowlers.put(b.bowler(), new BowlerCard(bw.name(), bw.balls() + (legal ? 1 : 0), bw.runs() + conceded, bw.wickets() + (bowlersWicket ? 1 : 0)));

        if (offBat != 4 && offBat != 6 && b.runs() % 2 == 1) inn.swap();        // they crossed an odd number of times
        if (b.out() != null) wicket(inn, b);
        if (legal && ++inn.balls % 6 == 0) {                                    // over complete: ends swap
            inn.swap();
            inn.lastOverBowler = inn.overBowler;
            inn.overBowler = null;
        }
        freeHit = fmt.freeHit() && (b.extra() == Extra.NO_BALL || (freeHit && !legal));
        Integer target = target();
        inn.closed = inn.wickets == squads.get(inn.batting).size() - 1
                || (fmt.overs() != null && inn.balls == fmt.overs() * 6)
                || (target != null && inn.runs >= target);
    }

    private void wicket(Innings inn, Ball b) {
        String out = b.dismissed() != null ? b.dismissed() : inn.striker;
        if (!out.equals(inn.striker) && !out.equals(inn.nonStriker)) throw new ScoringException(out + " is not batting");
        String how = b.out() == Out.RUN_OUT ? "run out" : b.out().code + " " + b.bowler();
        BatterCard c = inn.batters.get(out);
        inn.batters.put(out, new BatterCard(c.name(), c.runs(), c.balls(), c.fours(), c.sixes(), how));
        inn.wickets++;
        if (inn.wickets < squads.get(inn.batting).size() - 1) {
            if (b.incoming() == null || inn.batters.containsKey(b.incoming()) || !squads.get(inn.batting).contains(b.incoming()))
                throw new ScoringException("name a new batter from the squad");
            inn.batters.put(b.incoming(), new BatterCard(b.incoming()));
        }
        String next = b.incoming() == null ? "" : b.incoming();
        if (out.equals(inn.striker)) inn.striker = next; else inn.nonStriker = next;   // new batter takes that end
    }

    private Integer target() {
        if (innings.size() != 2 * fmt.inningsPerSide()) return null;
        String first = innings.get(0).batting;
        int a = innings.stream().filter(i -> i.batting.equals(first)).mapToInt(i -> i.runs).sum();
        int b = innings.subList(0, innings.size() - 1).stream().filter(i -> !i.batting.equals(first)).mapToInt(i -> i.runs).sum();
        return a - b + 1;
    }

    String result() {
        if (innings.size() < 2 * fmt.inningsPerSide() || !last().closed || fmt.overs() == null) return null;   // Test results out of scope
        Innings last = last();
        int target = target();
        if (last.runs >= target) return last.batting + " won by " + (squads.get(last.batting).size() - 1 - last.wickets) + " wickets";
        if (last.runs == target - 1) return "Match tied";
        return innings.get(0).batting + " won by " + (target - 1 - last.runs) + " runs";
    }

    Scoreboard snapshot(int version) {
        List<InningsCard> cards = innings.stream().map(i -> new InningsCard(i.batting, i.runs, i.wickets, i.balls,
                Map.copyOf(i.extras), Collections.unmodifiableMap(new LinkedHashMap<>(i.batters)),
                Collections.unmodifiableMap(new LinkedHashMap<>(i.bowlers)), i.striker, i.nonStriker, i.closed)).toList();
        return new Scoreboard(version, cards, freeHit, result());
    }
}

// ---------- the match: one writer, many readers ----------
final class Match {
    final Format fmt;
    final Map<String, List<String>> squads;
    final List<BiConsumer<Scoreboard, MatchEvent>> listeners = new CopyOnWriteArrayList<>();   // event is null on undo
    private final List<MatchEvent> events = new ArrayList<>();
    private Projection projection;
    private int version;
    private volatile Scoreboard board;                                          // replaced, never mutated: readers need no lock

    Match(Format fmt, Map<String, List<String>> squads) {
        this.fmt = fmt; this.squads = squads;
        projection = new Projection(fmt, squads);
        board = projection.snapshot(0);
    }

    Scoreboard board() { return board; }
    synchronized List<MatchEvent> events() { return List.copyOf(events); }

    synchronized void append(MatchEvent e) {
        projection.apply(e);                                                     // validates first: a bad event is never stored
        events.add(e);
        publish(e);
    }

    synchronized MatchEvent dropLast() {
        if (events.isEmpty()) throw new ScoringException("nothing to undo");
        MatchEvent e = events.remove(events.size() - 1);
        projection = new Projection(fmt, squads);
        events.forEach(projection::apply);                                       // rebuild from the log: cannot drift from the truth
        publish(null);
        return e;
    }

    private void publish(MatchEvent e) {
        board = projection.snapshot(++version);
        Scoreboard b = board;
        listeners.forEach(l -> l.accept(b, e));                                  // under the write lock: versions arrive in order
    }
}

// ---------- commands: what the scorer does, with undo and redo ----------
interface Command { void execute(Match m); void undo(Match m); }

record RecordEvent(MatchEvent event) implements Command {
    public void execute(Match m) { m.append(event); }
    public void undo(Match m) { m.dropLast(); }
}

final class Scorer {
    private final Match match;
    private final Deque<Command> done = new ArrayDeque<>(), undone = new ArrayDeque<>();
    Scorer(Match match) { this.match = match; }
    void record(MatchEvent e) { Command c = new RecordEvent(e); c.execute(match); done.push(c); undone.clear(); }
    void undo() { Command c = done.pop(); c.undo(match); undone.push(c); }
    void redo() { Command c = undone.pop(); c.execute(match); done.push(c); }
}

public class Main {
    static final Map<String, List<String>> SQUADS = Map.of("IND", List.of("Rohit", "Gill", "Kohli"), "AUS", List.of("Head", "Marsh", "Starc"));

    public static void main(String[] args) {
        Match match = new Match(Format.SUPER_OVER, SQUADS);
        List<String> seen = new ArrayList<>();
        match.listeners.add((board, e) -> {                                      // a sample live subscriber
            if (e == null) seen.add("v" + board.version() + ": correction");
            else if (e instanceof Ball b && (b.out() != null || (b.extra() == Extra.NONE && (b.runs() == 4 || b.runs() == 6))))
                seen.add("v" + board.version() + ": " + (b.out() != null ? "WICKET" : b.runs()));
        });
        Scorer scorer = new Scorer(match);

        scorer.record(new InningsStarted("IND", "AUS", "Rohit", "Gill"));
        for (Ball b : List.of(Ball.runs("Starc", 4), Ball.extra("Starc", 0, Extra.WIDE),
                Ball.extra("Starc", 1, Extra.NO_BALL),                                 // 2 runs, Rohit faced it, they crossed
                Ball.runs("Starc", 6),                                                 // free hit
                Ball.wicket("Starc", Out.BOWLED, "Kohli"), Ball.extra("Starc", 1, Extra.LEG_BYE),
                Ball.wicket("Starc", Out.CAUGHT, null))) scorer.record(b);              // two down: innings over
        InningsCard first = match.board().innings().get(0);
        assert first.runs() == 14 && first.wickets() == 2 && first.overs().equals("0.5") && first.closed();
        assert first.extras().equals(Map.of(Extra.WIDE, 1, Extra.NO_BALL, 1, Extra.LEG_BYE, 1));
        assert first.batters().get("Rohit").equals(new BatterCard("Rohit", 5, 3, 1, 0, "c Starc"));
        assert first.batters().get("Gill").equals(new BatterCard("Gill", 6, 2, 0, 1, "b Starc"));
        assert first.bowlers().get("Starc").equals(new BowlerCard("Starc", 5, 13, 2));

        scorer.record(new InningsStarted("AUS", "IND", "Head", "Marsh"));
        for (int r : new int[]{6, 2, 1}) scorer.record(Ball.runs("Kohli", r));
        Scoreboard before = match.board();
        scorer.record(Ball.runs("Kohli", 4));                                    // the scorer meant to enter four wides
        scorer.undo();
        assert match.board().innings().equals(before.innings()) && match.board().version() == before.version() + 2;
        scorer.record(Ball.extra("Kohli", 4, Extra.WIDE));                       // 5 wides
        scorer.record(Ball.runs("Kohli", 1));
        InningsCard chase = match.board().innings().get(1);
        assert chase.runs() == 15 && chase.wickets() == 0 && chase.overs().equals("0.4");
        assert "AUS won by 2 wickets".equals(match.board().result());
        assert chase.bowlers().get("Kohli").equals(new BowlerCard("Kohli", 4, 15, 0));
        assert seen.subList(0, 3).equals(List.of("v2: 4", "v5: 6", "v6: WICKET")) && seen.contains("v14: correction");
        try { scorer.record(Ball.runs("Kohli", 1)); throw new AssertionError("the match is over"); }
        catch (ScoringException expected) { }
        System.out.println("Main.java: all assertions passed");
    }
}
from __future__ import annotations

import threading
from dataclasses import dataclass, field, replace
from enum import Enum
from typing import Callable


# ---------- formats (Strategy) ----------
@dataclass(frozen=True)
class Format:
    name: str
    overs: int | None              # None: unlimited (Test)
    innings_per_side: int
    max_overs_per_bowler: int | None
    free_hit: bool                 # a no-ball gives the next delivery as a free hit


T20 = Format("T20", 20, 1, 4, True)
ODI = Format("ODI", 50, 1, 10, True)
TEST = Format("Test", None, 2, None, False)
SUPER_OVER = Format("Super Over", 1, 1, 1, True)


# ---------- events: the source of truth ----------
class Extra(Enum):
    NONE = "none"
    WIDE = "wd"
    NO_BALL = "nb"
    BYE = "b"
    LEG_BYE = "lb"


class Out(Enum):
    BOWLED = "b"
    CAUGHT = "c"
    LBW = "lbw"
    STUMPED = "st"
    RUN_OUT = "run out"
    HIT_WICKET = "hit wkt"


@dataclass(frozen=True)
class InningsStarted:
    batting: str
    bowling: str
    striker: str
    non_striker: str


@dataclass(frozen=True)
class Ball:
    bowler: str
    runs: int = 0                  # off the bat, or byes/leg-byes/wides actually run (penalty runs are added automatically)
    extra: Extra = Extra.NONE
    out: Out | None = None
    dismissed: str | None = None   # defaults to the striker
    incoming: str | None = None    # the new batter, unless the innings has ended


ALLOWED_OUTS = {Extra.WIDE: {Out.STUMPED, Out.RUN_OUT, Out.HIT_WICKET}, Extra.NO_BALL: {Out.RUN_OUT}}


class ScoringError(Exception):
    pass


# ---------- read model: immutable snapshots ----------
@dataclass(frozen=True)
class BatterCard:
    name: str
    runs: int = 0
    balls: int = 0
    fours: int = 0
    sixes: int = 0
    out: str = "not out"


@dataclass(frozen=True)
class BowlerCard:
    name: str
    balls: int = 0
    runs: int = 0
    wickets: int = 0


@dataclass(frozen=True)
class InningsCard:
    batting: str
    runs: int = 0
    wickets: int = 0
    balls: int = 0
    extras: tuple[tuple[str, int], ...] = ()
    batters: tuple[BatterCard, ...] = ()
    bowlers: tuple[BowlerCard, ...] = ()
    striker: str = ""
    non_striker: str = ""
    closed: bool = False

    @property
    def overs(self) -> str:
        return f"{self.balls // 6}.{self.balls % 6}"

    def batter(self, name: str) -> BatterCard:
        return next(b for b in self.batters if b.name == name)

    def bowler(self, name: str) -> BowlerCard:
        return next(b for b in self.bowlers if b.name == name)


@dataclass(frozen=True)
class Scoreboard:
    version: int
    innings: tuple[InningsCard, ...]
    free_hit: bool
    result: str | None


# ---------- the projection: fold events into state ----------
@dataclass
class _Innings:
    batting: str
    bowling: str
    striker: str
    non_striker: str
    runs: int = 0
    wickets: int = 0
    balls: int = 0
    extras: dict[str, int] = field(default_factory=lambda: {e.value: 0 for e in Extra if e is not Extra.NONE})
    batters: dict[str, BatterCard] = field(default_factory=dict)
    bowlers: dict[str, BowlerCard] = field(default_factory=dict)
    over_bowler: str | None = None      # bowler of the over in progress
    last_over_bowler: str | None = None
    closed: bool = False


class Projection:
    def __init__(self, fmt: Format, squads: dict[str, list[str]]) -> None:
        self.fmt, self.squads = fmt, squads
        self.innings: list[_Innings] = []
        self.free_hit = False

    def apply(self, e: InningsStarted | Ball) -> None:
        if isinstance(e, InningsStarted):
            if self.innings and not self.innings[-1].closed or self._result():
                raise ScoringError("previous innings still open, or match over")
            inn = _Innings(e.batting, e.bowling, e.striker, e.non_striker)
            for name in (e.striker, e.non_striker):
                inn.batters[name] = BatterCard(name)
            self.innings.append(inn)
            self.free_hit = False
            return
        if not self.innings or self.innings[-1].closed:
            raise ScoringError("no innings in progress")
        self._ball(self.innings[-1], e)

    def _ball(self, inn: _Innings, b: Ball) -> None:
        f = self.fmt
        if inn.over_bowler is None:                                  # first delivery of a new over
            if b.bowler == inn.last_over_bowler:
                raise ScoringError("a bowler cannot bowl consecutive overs")
            card = inn.bowlers.get(b.bowler, BowlerCard(b.bowler))
            if f.max_overs_per_bowler and card.balls >= f.max_overs_per_bowler * 6:
                raise ScoringError(f"{b.bowler} has bowled the maximum overs")
            inn.over_bowler = b.bowler
        elif b.bowler != inn.over_bowler:
            raise ScoringError("change bowlers only between overs")
        if b.out and (b.out not in ALLOWED_OUTS.get(b.extra, set(Out)) or (self.free_hit and b.out is not Out.RUN_OUT)):
            raise ScoringError(f"{b.out.name} is impossible on this delivery")

        legal = b.extra not in (Extra.WIDE, Extra.NO_BALL)
        penalty = 0 if legal else 1
        off_bat = b.runs if b.extra in (Extra.NONE, Extra.NO_BALL) else 0
        conceded = b.runs + penalty if b.extra in (Extra.NONE, Extra.NO_BALL, Extra.WIDE) else 0   # byes are not the bowler's
        inn.runs += b.runs + penalty
        if b.extra is not Extra.NONE:
            inn.extras[b.extra.value] += penalty + (0 if b.extra is Extra.NO_BALL else b.runs)

        s = inn.batters[inn.striker]
        if b.extra is not Extra.WIDE:                                # a wide is not a ball faced
            s = replace(s, balls=s.balls + 1, runs=s.runs + off_bat,
                        fours=s.fours + (off_bat == 4), sixes=s.sixes + (off_bat == 6))
        inn.batters[inn.striker] = s
        bw = inn.bowlers.get(b.bowler, BowlerCard(b.bowler))
        inn.bowlers[b.bowler] = replace(bw, balls=bw.balls + legal, runs=bw.runs + conceded,
                                        wickets=bw.wickets + (b.out is not None and b.out is not Out.RUN_OUT))

        if off_bat not in (4, 6) and b.runs % 2 == 1:                # they crossed an odd number of times
            inn.striker, inn.non_striker = inn.non_striker, inn.striker
        if b.out:
            self._wicket(inn, b)
        if legal:
            inn.balls += 1
            if inn.balls % 6 == 0:                                   # over complete: ends swap
                inn.striker, inn.non_striker = inn.non_striker, inn.striker
                inn.last_over_bowler, inn.over_bowler = inn.over_bowler, None
        self.free_hit = f.free_hit and (b.extra is Extra.NO_BALL or (self.free_hit and not legal))
        target = self._target()
        inn.closed = (inn.wickets == len(self.squads[inn.batting]) - 1
                      or (f.overs is not None and inn.balls == f.overs * 6)
                      or (target is not None and inn.runs >= target))

    def _wicket(self, inn: _Innings, b: Ball) -> None:
        out = b.dismissed or inn.striker
        if out not in (inn.striker, inn.non_striker):
            raise ScoringError(f"{out} is not batting")
        how = f"{b.out.value} {b.bowler}" if b.out is not Out.RUN_OUT else "run out"
        inn.batters[out] = replace(inn.batters[out], out=how)
        inn.wickets += 1
        if inn.wickets < len(self.squads[inn.batting]) - 1:
            if not b.incoming or b.incoming in inn.batters or b.incoming not in self.squads[inn.batting]:
                raise ScoringError("name a new batter from the squad")
            inn.batters[b.incoming] = BatterCard(b.incoming)
        nxt = b.incoming or ""
        if out == inn.striker:                                       # new batter takes the dismissed batter's end
            inn.striker = nxt
        else:
            inn.non_striker = nxt

    def _target(self) -> int | None:
        f = self.fmt
        if len(self.innings) != 2 * f.innings_per_side:
            return None
        first = sum(i.runs for i in self.innings if i.batting == self.innings[0].batting)
        second = sum(i.runs for i in self.innings[:-1] if i.batting != self.innings[0].batting)
        return first - second + 1

    def _result(self) -> str | None:
        f = self.fmt
        if len(self.innings) < 2 * f.innings_per_side or not self.innings[-1].closed or f.overs is None:
            return None                                              # Test results (draws, follow-on) are out of scope
        last, target = self.innings[-1], self._target() or 0
        if last.runs >= target:
            return f"{last.batting} won by {len(self.squads[last.batting]) - 1 - last.wickets} wickets"
        if last.runs == target - 1:
            return "Match tied"
        return f"{self.innings[0].batting} won by {target - 1 - last.runs} runs"

    def snapshot(self, version: int) -> Scoreboard:
        cards = tuple(InningsCard(i.batting, i.runs, i.wickets, i.balls, tuple(i.extras.items()),
                                  tuple(i.batters.values()), tuple(i.bowlers.values()),
                                  i.striker, i.non_striker, i.closed) for i in self.innings)
        return Scoreboard(version, cards, self.free_hit, self._result())


# ---------- the match: one writer, many readers ----------
Listener = Callable[[Scoreboard, "InningsStarted | Ball | None"], None]


class Match:
    def __init__(self, fmt: Format, squads: dict[str, list[str]]) -> None:
        self.fmt, self.squads = fmt, squads
        self.events: list[InningsStarted | Ball] = []
        self.listeners: list[Listener] = []
        self._projection = Projection(fmt, squads)
        self._version = 0
        self._write = threading.Lock()
        self.board = self._projection.snapshot(0)       # replaced, never mutated: readers need no lock

    def append(self, e: InningsStarted | Ball) -> None:
        with self._write:
            self._projection.apply(e)                   # validates first: a bad event is never stored
            self.events.append(e)
            self._publish(e)

    def drop_last(self) -> InningsStarted | Ball:
        with self._write:
            if not self.events:
                raise ScoringError("nothing to undo")
            e = self.events.pop()
            self._projection = Projection(self.fmt, self.squads)
            for old in self.events:                     # rebuild from the log: cannot drift from the truth
                self._projection.apply(old)
            self._publish(None)
            return e

    def _publish(self, e: InningsStarted | Ball | None) -> None:
        self._version += 1
        self.board = self._projection.snapshot(self._version)
        board = self.board
        for listener in self.listeners:                 # still under the write lock, so listeners see versions in order
            listener(board, e)


# ---------- commands: what the scorer does, with undo and redo ----------
class RecordEvent:
    def __init__(self, event: InningsStarted | Ball) -> None:
        self.event = event

    def execute(self, match: Match) -> None:
        match.append(self.event)

    def undo(self, match: Match) -> None:
        match.drop_last()


class Scorer:
    def __init__(self, match: Match) -> None:
        self.match = match
        self._done: list[RecordEvent] = []
        self._undone: list[RecordEvent] = []

    def record(self, event: InningsStarted | Ball) -> None:
        cmd = RecordEvent(event)
        cmd.execute(self.match)
        self._done.append(cmd)
        self._undone.clear()

    def undo(self) -> None:
        cmd = self._done.pop()
        cmd.undo(self.match)
        self._undone.append(cmd)

    def redo(self) -> None:
        cmd = self._undone.pop()
        cmd.execute(self.match)
        self._done.append(cmd)


SQUADS = {"IND": ["Rohit", "Gill", "Kohli"], "AUS": ["Head", "Marsh", "Starc"]}

if __name__ == "__main__":
    match = Match(SUPER_OVER, SQUADS)
    seen: list[str] = []

    def headlines(board: Scoreboard, e: InningsStarted | Ball | None) -> None:   # a sample live subscriber
        if e is None:
            seen.append(f"v{board.version}: correction")
        elif isinstance(e, Ball) and (e.out or (e.extra is Extra.NONE and e.runs in (4, 6))):
            seen.append(f"v{board.version}: {'WICKET' if e.out else e.runs}")

    match.listeners.append(headlines)
    scorer = Scorer(match)

    scorer.record(InningsStarted("IND", "AUS", "Rohit", "Gill"))
    for ball in [Ball("Starc", 4),
                 Ball("Starc", extra=Extra.WIDE),
                 Ball("Starc", 1, Extra.NO_BALL),           # 2 runs, Rohit faced it, they crossed: Gill on strike
                 Ball("Starc", 6),                          # free hit
                 Ball("Starc", out=Out.BOWLED, incoming="Kohli"),
                 Ball("Starc", 1, Extra.LEG_BYE),
                 Ball("Starc", out=Out.CAUGHT)]:            # two wickets: a Super Over innings is done
        scorer.record(ball)
    first = match.board.innings[0]
    assert (first.runs, first.wickets, first.overs, first.closed) == (14, 2, "0.5", True)
    assert dict(first.extras) == {"wd": 1, "nb": 1, "b": 0, "lb": 1}
    assert first.batter("Rohit") == BatterCard("Rohit", 5, 3, 1, 0, "c Starc")
    assert first.batter("Gill") == BatterCard("Gill", 6, 2, 0, 1, "b Starc")
    assert first.bowler("Starc") == BowlerCard("Starc", 5, 13, 2)

    scorer.record(InningsStarted("AUS", "IND", "Head", "Marsh"))
    for ball in [Ball("Kohli", 6), Ball("Kohli", 2), Ball("Kohli", 1)]:
        scorer.record(ball)
    before = match.board
    scorer.record(Ball("Kohli", 4))                         # the scorer meant to enter four wides
    scorer.undo()
    assert match.board.innings == before.innings and match.board.version == before.version + 2
    scorer.record(Ball("Kohli", 4, Extra.WIDE))             # 5 wides
    scorer.record(Ball("Kohli", 1))
    chase = match.board.innings[1]
    assert (chase.runs, chase.wickets, chase.overs) == (15, 0, "0.4")
    assert match.board.result == "AUS won by 2 wickets"
    assert chase.bowler("Kohli") == BowlerCard("Kohli", 4, 15, 0)
    assert seen[:3] == ["v2: 4", "v5: 6", "v6: WICKET"] and "v14: correction" in seen
    try:
        scorer.record(Ball("Kohli", 1))
        raise AssertionError("the match is over")
    except ScoringError:
        pass
    print("score.py: all assertions passed")
import assert from "node:assert/strict";

// ---------- formats (Strategy) ----------
export interface Format {
  readonly name: string; readonly overs: number | null; readonly inningsPerSide: number;
  readonly maxOversPerBowler: number | null; readonly freeHit: boolean;
}
export const T20: Format = { name: "T20", overs: 20, inningsPerSide: 1, maxOversPerBowler: 4, freeHit: true };
export const ODI: Format = { name: "ODI", overs: 50, inningsPerSide: 1, maxOversPerBowler: 10, freeHit: true };
export const TEST: Format = { name: "Test", overs: null, inningsPerSide: 2, maxOversPerBowler: null, freeHit: false };
export const SUPER_OVER: Format = { name: "Super Over", overs: 1, inningsPerSide: 1, maxOversPerBowler: 1, freeHit: true };

// ---------- events: the source of truth ----------
export type Extra = "none" | "wd" | "nb" | "b" | "lb";
export type Out = "b" | "c" | "lbw" | "st" | "run out" | "hit wkt";
export interface InningsStarted { readonly kind: "start"; readonly batting: string; readonly bowling: string; readonly striker: string; readonly nonStriker: string }
/** runs: off the bat, or byes/leg-byes/wides actually run. Penalty runs are added automatically. */
export interface Ball {
  readonly kind: "ball"; readonly bowler: string; readonly runs: number; readonly extra: Extra;
  readonly out?: Out; readonly dismissed?: string; readonly incoming?: string;
}
export type MatchEvent = InningsStarted | Ball;
export const ball = (bowler: string, runs = 0, extra: Extra = "none", more: Partial<Ball> = {}): Ball =>
  ({ kind: "ball", bowler, runs, extra, ...more });

const ALLOWED_OUTS: Partial<Record<Extra, readonly Out[]>> = { wd: ["st", "run out", "hit wkt"], nb: ["run out"] };
export class ScoringError extends Error {}

// ---------- read model: immutable snapshots ----------
export interface BatterCard { readonly name: string; readonly runs: number; readonly balls: number; readonly fours: number; readonly sixes: number; readonly out: string }
export interface BowlerCard { readonly name: string; readonly balls: number; readonly runs: number; readonly wickets: number }
export interface InningsCard {
  readonly batting: string; readonly runs: number; readonly wickets: number; readonly balls: number; readonly overs: string;
  readonly extras: Readonly<Record<string, number>>; readonly batters: readonly BatterCard[]; readonly bowlers: readonly BowlerCard[];
  readonly striker: string; readonly nonStriker: string; readonly closed: boolean;
}
export interface Scoreboard { readonly version: number; readonly innings: readonly InningsCard[]; readonly freeHit: boolean; readonly result: string | null }

const batter = (name: string): BatterCard => ({ name, runs: 0, balls: 0, fours: 0, sixes: 0, out: "not out" });
const bowler = (name: string): BowlerCard => ({ name, balls: 0, runs: 0, wickets: 0 });

interface InningsState {
  batting: string; bowling: string; striker: string; nonStriker: string; runs: number; wickets: number; balls: number;
  extras: Record<string, number>; batters: Map<string, BatterCard>; bowlers: Map<string, BowlerCard>;
  overBowler: string | null; lastOverBowler: string | null; closed: boolean;
}

// ---------- the projection: fold events into state ----------
export class Projection {
  private readonly innings: InningsState[] = [];
  private freeHit = false;
  constructor(private readonly fmt: Format, private readonly squads: Record<string, readonly string[]>) {}

  apply(e: MatchEvent): void {
    const last = this.innings.at(-1);
    if (e.kind === "start") {
      if ((last && !last.closed) || this.result()) throw new ScoringError("previous innings still open, or match over");
      this.innings.push({ batting: e.batting, bowling: e.bowling, striker: e.striker, nonStriker: e.nonStriker,
        runs: 0, wickets: 0, balls: 0, extras: { wd: 0, nb: 0, b: 0, lb: 0 },
        batters: new Map([[e.striker, batter(e.striker)], [e.nonStriker, batter(e.nonStriker)]]),
        bowlers: new Map(), overBowler: null, lastOverBowler: null, closed: false });
      this.freeHit = false;
      return;
    }
    if (!last || last.closed) throw new ScoringError("no innings in progress");
    this.ball(last, e);
  }

  private ball(inn: InningsState, b: Ball): void {
    const f = this.fmt;
    if (inn.overBowler === null) {                                          // first delivery of a new over
      if (b.bowler === inn.lastOverBowler) throw new ScoringError("a bowler cannot bowl consecutive overs");
      const bowled = inn.bowlers.get(b.bowler)?.balls ?? 0;
      if (f.maxOversPerBowler !== null && bowled >= f.maxOversPerBowler * 6) throw new ScoringError(`${b.bowler} has bowled the maximum overs`);
      inn.overBowler = b.bowler;
    } else if (b.bowler !== inn.overBowler) throw new ScoringError("change bowlers only between overs");
    const allowed = ALLOWED_OUTS[b.extra];
    if (b.out && ((allowed && !allowed.includes(b.out)) || (this.freeHit && b.out !== "run out")))
      throw new ScoringError(`${b.out} is impossible on this delivery`);

    const legal = b.extra !== "wd" && b.extra !== "nb";
    const penalty = legal ? 0 : 1;
    const offBat = b.extra === "none" || b.extra === "nb" ? b.runs : 0;
    const conceded = b.extra === "b" || b.extra === "lb" ? 0 : b.runs + penalty;   // byes are not the bowler's
    inn.runs += b.runs + penalty;
    if (b.extra !== "none") inn.extras[b.extra] += penalty + (b.extra === "nb" ? 0 : b.runs);

    const s = inn.batters.get(inn.striker)!;
    if (b.extra !== "wd")                                                    // a wide is not a ball faced
      inn.batters.set(inn.striker, { ...s, runs: s.runs + offBat, balls: s.balls + 1,
        fours: s.fours + (offBat === 4 ? 1 : 0), sixes: s.sixes + (offBat === 6 ? 1 : 0) });
    const bw = inn.bowlers.get(b.bowler) ?? bowler(b.bowler);
    inn.bowlers.set(b.bowler, { ...bw, balls: bw.balls + (legal ? 1 : 0), runs: bw.runs + conceded,
      wickets: bw.wickets + (b.out && b.out !== "run out" ? 1 : 0) });

    const swap = () => { [inn.striker, inn.nonStriker] = [inn.nonStriker, inn.striker]; };
    if (offBat !== 4 && offBat !== 6 && b.runs % 2 === 1) swap();           // they crossed an odd number of times
    if (b.out) this.wicket(inn, b);
    if (legal && ++inn.balls % 6 === 0) {                                     // over complete: ends swap
      swap();
      inn.lastOverBowler = inn.overBowler;
      inn.overBowler = null;
    }
    this.freeHit = f.freeHit && (b.extra === "nb" || (this.freeHit && !legal));
    const target = this.target();
    inn.closed = inn.wickets === this.squads[inn.batting].length - 1
      || (f.overs !== null && inn.balls === f.overs * 6)
      || (target !== null && inn.runs >= target);
  }

  private wicket(inn: InningsState, b: Ball): void {
    const out = b.dismissed ?? inn.striker;
    if (out !== inn.striker && out !== inn.nonStriker) throw new ScoringError(`${out} is not batting`);
    inn.batters.set(out, { ...inn.batters.get(out)!, out: b.out === "run out" ? "run out" : `${b.out} ${b.bowler}` });
    inn.wickets++;
    const squad = this.squads[inn.batting];
    if (inn.wickets < squad.length - 1) {
      if (!b.incoming || inn.batters.has(b.incoming) || !squad.includes(b.incoming)) throw new ScoringError("name a new batter from the squad");
      inn.batters.set(b.incoming, batter(b.incoming));
    }
    if (out === inn.striker) inn.striker = b.incoming ?? ""; else inn.nonStriker = b.incoming ?? "";   // new batter takes that end
  }

  private target(): number | null {
    if (this.innings.length !== 2 * this.fmt.inningsPerSide) return null;
    const first = this.innings[0].batting;
    const a = this.innings.filter((i) => i.batting === first).reduce((t, i) => t + i.runs, 0);
    const b = this.innings.slice(0, -1).filter((i) => i.batting !== first).reduce((t, i) => t + i.runs, 0);
    return a - b + 1;
  }

  result(): string | null {
    const last = this.innings.at(-1);
    if (this.innings.length < 2 * this.fmt.inningsPerSide || !last?.closed || this.fmt.overs === null) return null;
    const target = this.target()!;
    if (last.runs >= target) return `${last.batting} won by ${this.squads[last.batting].length - 1 - last.wickets} wickets`;
    if (last.runs === target - 1) return "Match tied";
    return `${this.innings[0].batting} won by ${target - 1 - last.runs} runs`;
  }

  snapshot(version: number): Scoreboard {
    const innings = this.innings.map((i): InningsCard => Object.freeze({
      batting: i.batting, runs: i.runs, wickets: i.wickets, balls: i.balls, overs: `${Math.floor(i.balls / 6)}.${i.balls % 6}`,
      extras: Object.freeze({ ...i.extras }), batters: Object.freeze([...i.batters.values()]), bowlers: Object.freeze([...i.bowlers.values()]),
      striker: i.striker, nonStriker: i.nonStriker, closed: i.closed }));
    return Object.freeze({ version, innings: Object.freeze(innings), freeHit: this.freeHit, result: this.result() });
  }
}

// ---------- the match: one writer, many readers ----------
export type Listener = (board: Scoreboard, e: MatchEvent | null) => void;   // null on undo

export class Match {
  readonly listeners: Listener[] = [];
  private readonly log: MatchEvent[] = [];
  private projection: Projection;
  private version = 0;
  board: Scoreboard;                                                        // replaced, never mutated

  constructor(readonly fmt: Format, readonly squads: Record<string, readonly string[]>) {
    this.projection = new Projection(fmt, squads);
    this.board = this.projection.snapshot(0);
  }

  get events(): readonly MatchEvent[] { return [...this.log]; }

  append(e: MatchEvent): void {
    this.projection.apply(e);                                               // validates first: a bad event is never stored
    this.log.push(e);
    this.publish(e);
  }

  dropLast(): MatchEvent {
    const e = this.log.pop();
    if (!e) throw new ScoringError("nothing to undo");
    this.projection = new Projection(this.fmt, this.squads);
    for (const old of this.log) this.projection.apply(old);                 // rebuild from the log
    this.publish(null);
    return e;
  }

  private publish(e: MatchEvent | null): void {
    this.board = this.projection.snapshot(++this.version);
    for (const l of this.listeners) l(this.board, e);
  }
}

// ---------- commands: what the scorer does, with undo and redo ----------
export interface Command { execute(m: Match): void; undo(m: Match): void }
export class RecordEvent implements Command {
  constructor(readonly event: MatchEvent) {}
  execute(m: Match): void { m.append(this.event); }
  undo(m: Match): void { m.dropLast(); }
}

export class Scorer {
  private readonly done: Command[] = [];
  private readonly undone: Command[] = [];
  constructor(private readonly match: Match) {}
  record(e: MatchEvent): void { const c = new RecordEvent(e); c.execute(this.match); this.done.push(c); this.undone.length = 0; }
  undo(): void { const c = this.done.pop()!; c.undo(this.match); this.undone.push(c); }
  redo(): void { const c = this.undone.pop()!; c.execute(this.match); this.done.push(c); }
}

export const SQUADS = { IND: ["Rohit", "Gill", "Kohli"], AUS: ["Head", "Marsh", "Starc"] };
export const start = (batting: string, bowling: string, striker: string, nonStriker: string): InningsStarted =>
  ({ kind: "start", batting, bowling, striker, nonStriker });

if (process.argv[1]?.endsWith("score.ts")) {
  const match = new Match(SUPER_OVER, SQUADS);
  const seen: string[] = [];
  match.listeners.push((board, e) => {                                      // a sample live subscriber
    if (e === null) seen.push(`v${board.version}: correction`);
    else if (e.kind === "ball" && (e.out || (e.extra === "none" && (e.runs === 4 || e.runs === 6))))
      seen.push(`v${board.version}: ${e.out ? "WICKET" : e.runs}`);
  });
  const scorer = new Scorer(match);

  scorer.record(start("IND", "AUS", "Rohit", "Gill"));
  for (const b of [ball("Starc", 4), ball("Starc", 0, "wd"),
    ball("Starc", 1, "nb"),                                                 // 2 runs, Rohit faced it, they crossed
    ball("Starc", 6),                                                       // free hit
    ball("Starc", 0, "none", { out: "b", incoming: "Kohli" }), ball("Starc", 1, "lb"),
    ball("Starc", 0, "none", { out: "c" })]) scorer.record(b);              // two down: innings over
  const first = match.board.innings[0];
  assert.deepEqual([first.runs, first.wickets, first.overs, first.closed], [14, 2, "0.5", true]);
  assert.deepEqual(first.extras, { wd: 1, nb: 1, b: 0, lb: 1 });
  assert.deepEqual(first.batters.find((b) => b.name === "Rohit"), { name: "Rohit", runs: 5, balls: 3, fours: 1, sixes: 0, out: "c Starc" });
  assert.deepEqual(first.batters.find((b) => b.name === "Gill"), { name: "Gill", runs: 6, balls: 2, fours: 0, sixes: 1, out: "b Starc" });
  assert.deepEqual(first.bowlers[0], { name: "Starc", balls: 5, runs: 13, wickets: 2 });

  scorer.record(start("AUS", "IND", "Head", "Marsh"));
  for (const r of [6, 2, 1]) scorer.record(ball("Kohli", r));
  const before = match.board;
  scorer.record(ball("Kohli", 4));                                          // the scorer meant to enter four wides
  scorer.undo();
  assert.deepEqual(match.board.innings, before.innings);
  assert.equal(match.board.version, before.version + 2);
  scorer.record(ball("Kohli", 4, "wd"));                                    // 5 wides
  scorer.record(ball("Kohli", 1));
  const chase = match.board.innings[1];
  assert.deepEqual([chase.runs, chase.wickets, chase.overs], [15, 0, "0.4"]);
  assert.equal(match.board.result, "AUS won by 2 wickets");
  assert.deepEqual(chase.bowlers[0], { name: "Kohli", balls: 4, runs: 15, wickets: 0 });
  assert.deepEqual(seen.slice(0, 3), ["v2: 4", "v5: 6", "v6: WICKET"]);
  assert.ok(seen.includes("v14: correction"));
  assert.throws(() => scorer.record(ball("Kohli", 1)), ScoringError);
  assert.throws(() => { (match.board.innings[0] as { runs: number }).runs = 99; }, TypeError);   // snapshots are frozen
  console.log("score.ts: all assertions passed");
}

Checking the first innings by hand against the table above:

  • Team: 4 + (1 wide) + (1 nb + 1) + 6 + 0 + 1 lb + 0 = 14. Extras are 1 wide, 1 no-ball and 1 leg-bye.
  • Rohit: 4, then the no-ball single. He faced the four, the no-ball and the catch, so 5 runs off 3 balls, caught.
  • Gill: 6 off the free hit, then bowled. 6 off 2.
  • Starc: 5 legal balls. He conceded 4 + 1 + 2 + 6 = 13, because the leg-bye isn't his. 2 wickets.

7. Concurrency

The shape is one writer, many readers, and the design exploits it.

StateWho touches itProtection
Event log and projectionthe scorer onlya write lock (synchronized / threading.Lock). There's one scorer, but the lock makes a double-submitted request safe.
board (current snapshot)the writer replaces it, everyone readsa single reference swap: volatile in Java, a plain attribute in Python, a property in Node
Snapshot contentseveryone readsimmutable, so nothing to protect

The writer builds a complete new Scoreboard and then publishes it with one reference assignment. A reader does one read of that reference and gets either the old board or the new one, never a mix. In Java the field must be volatile. Without it, the Java memory model doesn't guarantee another thread sees the new reference, or the fully constructed object behind it. Records with final fields plus a volatile publish give both. Python's attribute assignment is atomic under the interpreter, and TypeScript runs on one thread, so both need nothing extra.

sequenceDiagram
    participant W as Scorer thread
    participant M as Match
    participant R as Reader threads
    R->>M: read board v41
    W->>M: lock, apply ball, build v42
    R->>M: read board v41 again, still consistent
    W->>M: publish v42 with one reference swap
    R->>M: read board v42
    Note over R: never a board that is half v41 and half v42

The cost is allocating a new snapshot per ball. A scorecard is about 30 small objects, a ball arrives every 30 seconds or so, and the cost is nothing. Copy-on-write fits exactly when writes are rare and reads are constant.

Listeners run under the write lock, which is a deliberate choice here: it guarantees subscribers see versions in order. That only works because listeners are fast and in-process (they hand off to queues). A slow listener would delay the scorer. Network fan-out to millions of phones belongs behind a queue or a pub/sub system, fed by one fast listener.

The Python test below runs four reader threads during a full T20 innings and checks that every snapshot they read is internally consistent: runs equal batter runs plus extras, and versions never go backwards. I also ran the same check in Java with real parallel threads over 20 innings.

Across servers, the same idea scales out. The scorer's service appends to a durable log (a database table or a stream like Kafka), and read replicas consume it and maintain their own projections. Each replica serves its latest snapshot from memory or a cache. Clients get the version number, so they can ask "anything after v41?" and ignore stale pushes. This is the projection pattern.

8. The interviewer adds…

"Show runs and wickets per over" (a new read model)

The log already contains everything, so this is a new function, with no change to the writer. It also works for every match already scored.

from score import T20, Ball, InningsStarted, Match, Out, Projection, Scorer


def over_by_over(fmt, squads, events) -> list[list[tuple[str, int, int]]]:
    """A new read model built from the log alone: (over, runs in it, wickets in it) per innings.
    It works for matches scored before this feature existed, because the events never change."""
    proj, charts, prev = Projection(fmt, squads), [], None
    for e in events:
        proj.apply(e)
        if isinstance(e, InningsStarted):
            charts.append({})
            prev = None
            continue
        inn = proj.snapshot(0).innings[-1]
        before = prev or (0, 0)
        over = (inn.balls - 1) // 6 + 1 if inn.balls else 1
        runs, wkts = charts[-1].get(over, (0, 0))
        charts[-1][over] = (runs + inn.runs - before[0], wkts + inn.wickets - before[1])
        prev = (inn.runs, inn.wickets)
    return [[(f"over {o}", r, w) for o, (r, w) in sorted(c.items())] for c in charts]


m = Match(T20, {"A": [f"a{i}" for i in range(11)], "B": [f"b{i}" for i in range(11)]})
s = Scorer(m)
s.record(InningsStarted("A", "B", "a0", "a1"))
for r in [1, 0, 4, 0, 0, 6]:
    s.record(Ball("b0", r))
for ball in [Ball("b1", 2), Ball("b1", out=Out.BOWLED, incoming="a2"), Ball("b1", 1)]:
    s.record(ball)
assert over_by_over(m.fmt, m.squads, m.events) == [[("over 1", 11, 0), ("over 2", 3, 1)]]
print("ext_over_stats: ok")

"Push an alert when someone reaches 50, and fix it if the ball is undone"

A new observer. It compares consecutive snapshots, so it sees both the milestone and the correction that takes it away.

import assert from "node:assert/strict";
import { ball, Match, Scorer, start, T20, type Scoreboard } from "./score.ts";

/** Push "fifty" and "hundred" alerts. Compares consecutive snapshots, so it also sees undo. */
export class MilestoneAlerts {
  readonly sent: string[] = [];
  private prev: Scoreboard | null = null;
  constructor(match: Match, private readonly marks = [50, 100]) {
    match.listeners.push((board, e) => {
      const before = new Map((this.prev?.innings.at(-1)?.batters ?? []).map((b) => [b.name, b.runs]));
      for (const b of board.innings.at(-1)?.batters ?? []) {
        for (const mark of this.marks) {
          const was = before.get(b.name) ?? 0;
          if (was < mark && b.runs >= mark) this.sent.push(`${b.name} reaches ${mark}`);
          if (e === null && was >= mark && b.runs < mark) this.sent.push(`correction: ${b.name} back to ${b.runs}`);
        }
      }
      this.prev = board;
    });
  }
}

const squads = { A: Array.from({ length: 11 }, (_, i) => `a${i}`), B: Array.from({ length: 11 }, (_, i) => `b${i}`) };
const match = new Match(T20, squads);
const alerts = new MilestoneAlerts(match);
const scorer = new Scorer(match);
scorer.record(start("A", "B", "a0", "a1"));
for (let i = 0; i < 6; i++) scorer.record(ball("b0", 6));                     // a0: 36, then ends change
for (const r of [1, 6, 6, 6]) scorer.record(ball("b1", r));                      // a1 takes a single, a0 to 54
scorer.undo();                                                                    // that last six was a four
scorer.record(ball("b1", 4));
assert.deepEqual(alerts.sent, ["a0 reaches 50", "correction: a0 back to 48", "a0 reaches 50"]);
console.log("ext-milestones: ok");

"Support declarations in Test cricket"

Add an InningsDeclared event and one branch in Projection.apply that closes the innings. Then make Format decide whether declarations are allowed (Test: yes, limited overs: no). Old logs still replay, because they never contain the new event. That's the general rule for evolving an event-sourced model: add event types, never change the meaning of old ones.

9. Testing

The projection is a pure function of the events, which makes it easy to test: feed events in and assert on the snapshot. The most valuable test is replay equality: the scorecard built incrementally must equal one built by replaying the log from scratch. If they ever differ, some state is leaking outside the events. See designing for testability.

import threading

from score import (T20, TEST, Ball, Extra, InningsStarted, Match, Out, Projection, ScoringError, Scorer)

XI = {"A": [f"a{i}" for i in range(1, 12)], "B": [f"b{i}" for i in range(1, 12)]}


def t20(fmt=T20) -> tuple[Match, Scorer]:
    m = Match(fmt, XI)
    s = Scorer(m)
    s.record(InningsStarted("A", "B", "a1", "a2"))
    return m, s


def rejects(scorer: Scorer, ball: Ball) -> bool:
    try:
        scorer.record(ball)
    except ScoringError:
        return True
    return False


def test_bowler_rules_consecutive_overs_and_the_four_over_cap():
    m, s = t20()
    for over in range(8):
        for _ in range(6):
            s.record(Ball("b1" if over % 2 == 0 else "b2"))
        if over == 0:
            assert rejects(s, Ball("b1"))                     # straight after his own over
    assert rejects(s, Ball("b1"))                             # four overs bowled
    s.record(Ball("b3"))
    assert rejects(s, Ball("b4"))                             # mid-over change
    assert m.board.innings[0].overs == "8.1"


def test_free_hit_survives_a_wide_and_only_allows_run_out():
    m, s = t20()
    s.record(Ball("b1", extra=Extra.NO_BALL))
    s.record(Ball("b1", extra=Extra.WIDE))
    assert m.board.free_hit and rejects(s, Ball("b1", out=Out.BOWLED, incoming="a3"))
    s.record(Ball("b1", 1, out=Out.RUN_OUT, dismissed="a2", incoming="a3"))
    assert not m.board.free_hit and m.board.innings[0].wickets == 1


def test_test_cricket_has_no_free_hit_and_extras_have_the_right_dismissals():
    m, s = t20(TEST)
    s.record(Ball("b1", extra=Extra.NO_BALL))
    assert not m.board.free_hit
    assert rejects(s, Ball("b1", extra=Extra.NO_BALL, out=Out.LBW, incoming="a3"))
    s.record(Ball("b1", extra=Extra.WIDE, out=Out.STUMPED, incoming="a3"))
    assert m.board.innings[0].batter("a1").out == "st b1"


def test_byes_count_as_balls_faced_but_not_against_the_bowler():
    m, s = t20()
    s.record(Ball("b1", 4, Extra.BYE))
    inn = m.board.innings[0]
    assert (inn.runs, inn.batter("a1").balls, inn.batter("a1").runs, inn.bowler("b1").runs) == (4, 1, 0, 0)


def test_replaying_the_log_gives_the_same_scoreboard():
    m, s = t20()
    for r in [0, 1, 4, 6, 2, 3]:
        s.record(Ball("b1", r))
    s.record(Ball("b2", 1, Extra.LEG_BYE))
    s.undo()
    s.redo()
    fresh = Projection(T20, XI)
    for e in m.events:
        fresh.apply(e)
    assert fresh.snapshot(m.board.version) == m.board


def test_readers_never_see_a_half_applied_ball():
    m, s = t20()
    done, problems = threading.Event(), []

    def reader() -> None:
        last = -1
        while not done.is_set():
            board = m.board                                  # one read of one immutable object
            if board.version < last:
                problems.append("went backwards")
            last = board.version
            for inn in board.innings:
                if inn.runs != sum(b.runs for b in inn.batters) + sum(v for _, v in inn.extras):
                    problems.append(f"torn read at v{board.version}")

    readers = [threading.Thread(target=reader, daemon=True) for _ in range(4)]
    [r.start() for r in readers]
    try:
        for over in range(20):
            for ball in range(6):
                s.record(Ball(f"b{over % 5 + 1}", (over + ball) % 4))   # five bowlers, four overs each
    finally:
        done.set()
    [r.join() for r in readers]
    assert not problems, problems[:3]
    assert m.board.innings[0].closed


if __name__ == "__main__":
    for name, fn in list(globals().items()):
        if name.startswith("test_"):
            fn()
            print("ok", name)

Rules worth one test each: the four-over cap and consecutive overs, a free hit that survives a wide, no free hit in Tests, stumping off a wide, byes faced but not conceded, and the reader-consistency check.

10. Common mistakes

  1. Counting a wide as a ball faced, or not counting a no-ball as one. The table in section 2 is the whole rule.
  2. Charging byes and leg-byes to the bowler.
  3. Crediting run-outs to the bowler.
  4. Ending the over after six deliveries instead of six legal deliveries.
  5. Forgetting the end-of-over strike change, or applying it before the odd-run swap.
  6. Storing derived facts in events (striker, total). An undo earlier in the log then leaves later events wrong.
  7. Undo by hand-written inverses. One sign error and the card is permanently off.
  8. Readers locking the live state. The scorer then waits for readers. Publish immutable snapshots.
  9. A non-volatile snapshot reference in Java. Other threads may never see the update.
  10. Hard-coding T20 numbers (20 overs, 4 per bowler) instead of asking the format.

11. Interview follow-ups

How do you correct a ball from three overs ago? Replace the event at that index and replay everything after it. Validation might now reject a later event (say the corrected ball was a wicket, so the next ball names a batter who's no longer in). Surface those to the scorer to fix, rather than guessing. Notify subscribers with a correction covering the affected range.

How do you show ball-by-ball commentary? Commentary is another read model over the log: one line per event, with text added by a commentator and keyed by event index. Because it's keyed to events, an undo removes the line too.

Why not let two scorers enter balls? Two writers create conflicts that no merge can resolve ("was it a four or four leg-byes?"). Keep one authoritative writer per match, and have a backup scorer whose input is used only on failover.

How does a phone that reconnects catch up? It sends the last version it saw. The server sends the current snapshot, or, if the gap is small, the events since that version. Versions also let the client drop out-of-order pushes.

How would you compute career statistics? As projections across matches: consume every match's log and maintain per-player aggregates. Because the logs are the truth, a new statistic can be backfilled for every match ever scored.

How do you handle a format like The Hundred? Its "set" is five balls (or ten from one end), and it has no overs in the usual sense. Move the hard-coded "6 legal balls per over" into Format (ballsPerSet), and the rest of the projection doesn't change. Spotting a constant that's really a format parameter is exactly the Strategy refactor.

What's the hardest part to get right in production? The human. Scorers make mistakes under pressure, so undo must be instant and safe, validation must catch impossible entries (an LBW off a no-ball) without blocking legitimate rare ones, and every correction must reach every subscriber.