Build a Flexible Tennis Game Score Tracker
Data Structure DesignModel answerLast updated
Create a scoring system for a single tennis game that records points, displays readable scores, detects game completion, and supports multiple rule variants.
Problem
You need to implement a scoring tracker for a single tennis game between two players. The system must accomplish four things:
- Record points — track which player wins each point as the game progresses
- Display current score — present the score in standard tennis terminology (Love, 15, 30, 40, Deuce, Advantage)
- Detect game end — recognize when the game finishes and identify the winner
- Support rule variations — allow different scoring rules (standard vs. no-ad) without scattering conditionals throughout your code
Standard Tennis Scoring Rules
- The first four points are called Love (0), 15, 30, and 40
- When both players reach 40 (three points each), the score is Deuce
- From Deuce, winning a point gives you Advantage
- From Advantage, if you win another point you win the game; if your opponent wins, it returns to Deuce
- A player wins by reaching four points with at least a two-point margin
Requirements
- Player identity must be stable regardless of name changes or duplicates
- Behavior after game completion must be well-defined (no undefined states)
- Rule variants should be encapsulated, not mixed into game logic
- The design should be testable and maintainable
Things to Consider
- Should you store the full point history or just current tallies?
- How do you handle invalid operations (scoring after game ends, etc.)?
- Can the rule set change mid-game, or is it fixed at creation?
- What's your API surface for creating games, recording points, and querying state?
Hints
Hint 1
Separate the record of what happened from the interpretation of those events
Hint 2
Consider the Strategy pattern to encapsulate rule variations
Hint 3
Think about immutability vs. mutation for score state
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is to separate facts from policy: the game object records what happened (which player won each point), while a pluggable scoring policy interprets those facts to produce displays and determine winners.
Architecture
Game Object
- Maintains player identities (by ID, not name)
- Records point winners in sequence
- Delegates score interpretation to a policy
Scoring Policy Interface
getDisplayScore(pointsA, pointsB)→ readable stringgetWinner(pointsA, pointsB)→ player ID or null- Encapsulates all rule-specific logic
Policy Implementations
- StandardPolicy: implements Deuce/Advantage rules
- NoAdPolicy: first to four points wins (no Deuce extension)
Design Decisions
Event sourcing vs. counter state: Storing the full point sequence allows:
- Replay and debugging
- Derived metrics (streak analysis, clutch points)
- Undo operations
- Audit trails for disputes
The cost is memory proportional to game length (typically 10–20 points). For this use case, the benefits outweigh the cost.
Immutable player identity: Use opaque IDs or objects rather than names. This prevents bugs when two players share a name or a name is displayed differently. The game references players by ID; names are display-only metadata.
Post-completion behavior: Once getWinner() returns non-null, further recordPoint() calls should either:
- Throw an exception (fail-fast, clear contracts)
- Return a result object indicating the game is already complete
- Be silently ignored (lenient, harder to debug)
I recommend explicit errors for correctness.
Policy immutability: Fix the policy at game creation. Changing rules mid-game creates ambiguity about which historical points were played under which rules.
Code Structure
class TennisGame:
def __init__(self, player_a, player_b, scoring_policy):
self.player_a = player_a # Player object with id, name
self.player_b = player_b
self.policy = scoring_policy
self.points = [] # List of player IDs who won each point
def record_point(self, winner):
if self.get_winner() is not None:
raise GameCompleteError("Cannot score after game ends")
if winner not in (self.player_a, self.player_b):
raise InvalidPlayerError()
self.points.append(winner)
def get_score_display(self):
points_a = self.points.count(self.player_a)
points_b = self.points.count(self.player_b)
return self.policy.get_display_score(points_a, points_b)
def get_winner(self):
points_a = self.points.count(self.player_a)
points_b = self.points.count(self.player_b)
winner_id = self.policy.get_winner(points_a, points_b)
if winner_id == 0:
return self.player_a
elif winner_id == 1:
return self.player_b
return None
class StandardScoringPolicy:
DISPLAY = ["Love", "15", "30", "40"]
def get_display_score(self, points_a, points_b):
if points_a < 4 and points_b < 4:
if points_a == points_b == 3:
return "Deuce"
return f"{self.DISPLAY[points_a]}-{self.DISPLAY[points_b]}"
diff = points_a - points_b
if diff == 0:
return "Deuce"
elif diff == 1:
return "Advantage Player A"
elif diff == -1:
return "Advantage Player B"
else:
# Winner already determined, still show advantage for consistency
return "Game"
def get_winner(self, points_a, points_b):
if points_a >= 4 and points_a - points_b >= 2:
return 0 # Player A
if points_b >= 4 and points_b - points_a >= 2:
return 1 # Player B
return None
class NoAdScoringPolicy:
DISPLAY = ["Love", "15", "30", "40"]
def get_display_score(self, points_a, points_b):
if points_a < 4 and points_b < 4:
if points_a == points_b == 3:
return "Deuce (next point wins)"
return f"{self.DISPLAY[points_a]}-{self.DISPLAY[points_b]}"
return "Game"
def get_winner(self, points_a, points_b):
if points_a >= 4:
return 0
if points_b >= 4:
return 1
return None
Complexity
- Time: O(1) per point recorded; O(n) to compute winner/score by counting
- Space: O(n) for point history where n is points played
For optimization, cache counts and update incrementally when recording points, reducing winner checks to O(1).
Common Mistakes
- Using names as identity — breaks when names collide
- Mixing rule logic into game class — violates open/closed principle
- Undefined behavior after game ends — causes test flakiness
- Mutable policies — creates temporal coupling and bugs
- No validation — allows invalid states like negative points
Extensions
- Serialization: Convert point history to JSON for persistence or network transfer
- Undo: Remove the last point from the history
- Statistics: Win rate on serve, break points converted, etc.
- Time-based rules: Shot clock violations, medical timeouts
- Multi-game scoring: Extend to sets and matches with recursive structure