Four-Player Trick-Taking Card Game Simulator

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Problem Statement

Build an object-oriented simulator for a deterministic trick-taking card game played clockwise around a table. Structure your code with explicit domain classes (such as card, deck, player, and rule components) and expose the top-level entry point:

def simulate_card_game(
    deck: List[str],
    player_names: List[str],
    starter: int,
    rank_order: List[str],
    suit_order: List[str],
    points: Dict[str, int],
    shuffle_order: List[int],
) -> Dict[str, object]:

Each element of deck is formatted as "<suit>_<rank>" (for instance, "D_10" or "S_A"). Seats are numbered 0 through p - 1 (where p = len(player_names), p = 4 in a standard four-seat table). Execute the match in three sequential phases:

  1. Permute, Deal, and Sort Hands

    • Reorder deck deterministically using shuffle_order so index i of the permuted deck receives deck[shuffle_order[i]].
    • Distribute every permuted card one by one starting at seat 0: card i goes to seat i % p, leaving the deck empty.
    • Sort each seat's hand in ascending order of (suit_order.index(suit), rank_order.index(rank)).
  2. Play All Tricks

    • Run len(deck) // p tricks. Seat starter leads the opening trick, and the winner of each trick leads the next one.
    • Within a trick led by seat leader, seats act in clockwise order (leader + offset) % p for offset = 0, 1, ..., p - 1.
    • Card choice rule: Every player removes and plays the earliest legal card in their sorted hand:
      • The trick leader has no suit constraint, plays hand[0], and sets lead_suit to that card's suit.
      • Each subsequent seat must play a card matching lead_suit if holding at least one (choosing the lowest-ranked card of lead_suit, i.e., the first matching card in sorted hand order). A seat holding zero cards of lead_suit (void) discards hand[0].
    • Trick resolution (no trump suit): Only cards matching lead_suit can win the trick; among those, the card with the largest index in rank_order wins. Off-suit discards never win regardless of rank.
    • Append the p played cards, in exact turn order, to the winner's captured pile, and record a trick dictionary with keys:
      • "starter": integer seat index of the trick leader,
      • "lead_suit": string suit established by the leader's card,
      • "plays": list of {"player": seat_index, "card": card_str} dictionaries in turn order,
      • "winner": integer seat index of the trick winner,
      • "score": integer sum of point values across the cards played in this trick (points.get(rank, 0) per card).
  3. Compute Final Totals and Overall Winner

    • Sum points.get(rank, 0) across every card in each player's captured pile to form "scores" (Dict[str, int] keyed by player name).
    • Pick "winner" as the name of the player with the highest total score; break ties for first place in favor of the smallest seat index (0 before 1, and so on).

Return a dictionary containing five keys: - "hands": List[List[str]] of remaining card strings per seat ([] per seat after all tricks finish), - "tricks": List[Dict[str, object]] of trick logs in play order, - "captured": List[List[str]] of captured card strings per seat in capture order, - "scores": Dict[str, int] mapping each player name to their point total, - "winner": str name of the overall winner.

Examples

Example 1

Input:

deck = ["S_A", "D_K", "C_K", "S_K", "D_5", "C_2", "C_10", "D_2"]
player_names = ["Maya", "Liam", "Nora", "Owen"]
starter = 0
rank_order = ["2", "5", "10", "K", "A"]
suit_order = ["C", "D", "H", "S"]
points = {"5": 5, "10": 10, "K": 10}
shuffle_order = [4, 1, 6, 7, 0, 5, 2, 3]

Output:

{
    "hands": [[], [], [], []],
    "tricks": [
        {
            "starter": 0,
            "lead_suit": "D",
            "plays": [
                {"player": 0, "card": "D_5"},
                {"player": 1, "card": "D_K"},
                {"player": 2, "card": "C_10"},
                {"player": 3, "card": "D_2"},
            ],
            "winner": 1,
            "score": 25,
        },
        {
            "starter": 1,
            "lead_suit": "C",
            "plays": [
                {"player": 1, "card": "C_2"},
                {"player": 2, "card": "C_K"},
                {"player": 3, "card": "S_K"},
                {"player": 0, "card": "S_A"},
            ],
            "winner": 2,
            "score": 20,
        },
    ],
    "captured": [
        [],
        ["D_5", "D_K", "C_10", "D_2"],
        ["C_2", "C_K", "S_K", "S_A"],
        [],
    ],
    "scores": {"Maya": 0, "Liam": 25, "Nora": 20, "Owen": 0},
    "winner": "Liam",
}

Explanation: Applying shuffle_order produces ["D_5", "D_K", "C_10", "D_2", "S_A", "C_2", "C_K", "S_K"]. Round-robin dealing and sorting yields hands Maya: ["D_5", "S_A"], Liam: ["C_2", "D_K"], Nora: ["C_10", "C_K"], and Owen: ["D_2", "S_K"]. - Trick 1: Seat 0 (Maya) leads "D_5". Seat 1 (Liam) skips "C_2" to follow suit "D" with "D_K". Seat 2 (Nora) has no "D" cards and discards "C_10". Seat 3 (Owen) follows with "D_2". Liam wins with "D_K" for 5 + 10 + 10 + 0 = 25 points and leads Trick 2. - Trick 2: Seat 1 (Liam) leads "C_2", Nora follows with "C_K", Owen discards "S_K", and Maya discards "S_A". Because off-suit cards cannot win, Nora takes Trick 2 with "C_K" for 0 + 10 + 10 + 0 = 20 points. Liam wins 25 to 20.

Example 2

Input:

deck = ["H_2", "H_5", "H_A", "H_3", "S_2", "S_A", "S_3", "S_5"]
player_names = ["Maya", "Liam", "Nora", "Owen"]
starter = 2
rank_order = ["2", "3", "5", "A"]
suit_order = ["H", "S"]
points = {"5": 5}
shuffle_order = [0, 1, 2, 3, 4, 5, 6, 7]

Output:

{
    "hands": [[], [], [], []],
    "tricks": [
        {
            "starter": 2,
            "lead_suit": "H",
            "plays": [
                {"player": 2, "card": "H_A"},
                {"player": 3, "card": "H_3"},
                {"player": 0, "card": "H_2"},
                {"player": 1, "card": "H_5"},
            ],
            "winner": 2,
            "score": 5,
        },
        {
            "starter": 2,
            "lead_suit": "S",
            "plays": [
                {"player": 2, "card": "S_3"},
                {"player": 3, "card": "S_5"},
                {"player": 0, "card": "S_2"},
                {"player": 1, "card": "S_A"},
            ],
            "winner": 1,
            "score": 5,
        },
    ],
    "captured": [
        [],
        ["S_3", "S_5", "S_2", "S_A"],
        ["H_A", "H_3", "H_2", "H_5"],
        [],
    ],
    "scores": {"Maya": 0, "Liam": 5, "Nora": 5, "Owen": 0},
    "winner": "Liam",
}

Explanation: Seat 2 (Nora) leads and wins Trick 1 with "H_A" (5 points from "H_5"), then leads Trick 2 where Seat 1 (Liam) wins with "S_A" (5 points from "S_5"). Liam and Nora tie at 5 points; seat index 1 < 2 breaks the tie in favor of "Liam".

Constraints

  • len(player_names) == 4 and all player names are distinct non-empty strings.
  • 0 <= starter < len(player_names).
  • len(deck) is a multiple of len(player_names) with 0 <= len(deck) <= 52 (52 cards in a standard 13-trick match), and all cards in deck are distinct.
  • Every card string has the form "<suit>_<rank>", where <suit> appears in suit_order and <rank> appears in rank_order.
  • shuffle_order is a permutation of 0 .. len(deck) - 1.
  • points maps zero or more rank strings to integer point values.

Step-by-step walkthrough

  1. Understand the three phases and the return shape

    We are building a deterministic four-seat trick-taking card game (a round-based card game where each seat plays one card into the center per round, and one seat captures the group of four cards, called a trick):

    1. Phase 1 — Permute, Deal, and Sort: Construct Card, Deck, and Player objects, reorder the deck using an injected index permutation so runs are 100% reproducible, deal round-robin across the four seats, and sort every hand by suit and rank.
    2. Phase 2 — Play All Tricks: Run len(deck) // 4 rounds (13 rounds for a full 52-card deck, or 2 rounds for an 8-card test deck). Round 0 begins at starter and proceeds clockwise via (leader + offset) % 4. Every follower must match the leader's lead suit when holding one; whoever plays the strongest card of lead_suit captures the trick and leads the next round.
    3. Phase 3 — Tally Points and Select the Winner: Sum the point values inside each player's captured pile (for instance, 5 points for 5s and 10 points for 10s and Ks) and determine the overall winner.

    The entry point simulate_card_game(...) returns a dictionary with five keys:

    • "hands": list of remaining card-string lists per seat (all [] once every round completes),
    • "tricks": list of per-trick logs {"starter", "lead_suit", "plays", "winner", "score"},
    • "captured": for each seat 0..3, the list of card strings won across the match in play order,
    • "scores": dictionary mapping each player's name to their total score,
    • "winner": the winning player's name.
  2. Settle every deterministic game rule

    Every turn and tie-breaker follows crisp, deterministic conventions:

    • Injected permutation: Position i of the shuffled deck receives deck[shuffle_order[i]].
    • Round-robin deal from seat 0: Card i of the shuffled deck goes to players[i % 4].
    • Sorted hand order: Ascending by (suit_order.index(suit), rank_order.index(rank)).
    • Deterministic card choice: Always play the earliest legal card in sorted hand order:
      • The trick leader has no suit restriction and plays hand[0].
      • A follower plays their lowest-ranked card of lead_suit if holding one; if void in lead_suit (holding zero cards of that suit), they discard hand[0].
    • Trick winner (no trump): Only cards matching lead_suit compete; the highest rank in rank_order wins (in Example 1's Trick 2, "C_K" beats an off-suit "S_A").
    • Overall score tie-breaker: If two or more players tie for the highest final score, the lowest seat index (0 before 1 before 2 before 3) wins (as in Example 2, where seat 1 beats seat 2).
  3. Separate state and rules into clean classes

    This problem has no hidden algorithmic trick — interviewers are grading how cleanly you separate card ownership from game rules so every transition can be inspected and tested:

    Card lifecycle (each of the 52 cards lives in exactly ONE place at any moment):
    
      Deck.cards  --(deal)-->  Player.hand  --(play_trick)-->  Player[winner].captured
    
    Rules object (read-only referee consulted by everyone):
      - hand_sort_key(card)       -> (suit_index, rank_index)
      - trick_winner(plays, suit) -> winning seat index
      - card_points(card)         -> integer points from the scoring table
    

    Keeping one Rules object guarantees that hand sorting, trick resolution, per-trick scores, and final player totals never drift out of sync.

  4. Build `Card` and `Rules`

    Two subtle string bugs trap careless implementations right away: 1. "H_10" has a two-character rank ("10"), so slicing text[2] produces "1" instead of "10". Splitting on "_" (text.split("_", 1)) handles ranks of any length cleanly. 2. Comparing rank strings directly ("10" > "2") is False in ASCII because character '1' comes before '2'! Mapping rank_order and suit_order to integer index dictionaries ({"2": 0, ..., "10": 8, ..., "A": 12}) makes every comparison an exact integer check.

    from typing import Dict, List, Tuple
    
    
    class Card:
        def __init__(self, text: str):
            # text: original card string like "H_10"; split on "_" so 2-char rank "10" stays intact.
            self.text = text
            self.suit, self.rank = text.split("_", 1)
    
    
    class Rules:
        """Single source of truth for suit ordering, rank strength, and card point values."""
    
        def __init__(
            self, rank_order: List[str], suit_order: List[str], points: Dict[str, int]
        ):
            # rank_index: maps rank string -> integer strength (e.g. {"2": 0, ..., "A": 12}),
            # avoiding raw string comparisons where "10" < "2".
            self.rank_index: Dict[str, int] = {}
            for index, rank in enumerate(rank_order):
                self.rank_index[rank] = index
    
            # suit_index: maps suit string -> integer hand-sort order (e.g. {"C": 0, "D": 1, ...}).
            self.suit_index: Dict[str, int] = {}
            for index, suit in enumerate(suit_order):
                self.suit_index[suit] = index
    
            # points: maps scoring rank -> point value (non-scoring ranks default to 0).
            self.points = points
    
        def hand_sort_key(self, card: Card) -> Tuple[int, int]:
            """Sort cards by suit order first, then by ascending rank order within each suit."""
            return (self.suit_index[card.suit], self.rank_index[card.rank])
    
        def card_points(self, card: Card) -> int:
            return self.points.get(card.rank, 0)
    
        def trick_winner(self, plays: List[Tuple[int, Card]], lead_suit: str) -> int:
            """Return the seat index of the highest-ranked card matching lead_suit (no trump)."""
            best_seat, best_card = plays[0]
            for seat, card in plays[1:]:
                # Off-suit discards can never win a trick, even if their rank is an Ace or King.
                if (
                    card.suit == lead_suit
                    and self.rank_index[card.rank] > self.rank_index[best_card.rank]
                ):
                    best_seat = seat
                    best_card = card
            return best_seat
    
  5. Build `Deck` and `Player`

    Once Player.sort_hand sorts self.hand at the end of Part 1, Player.play(lead_suit) becomes remarkably simple: - Start with chosen_index = 0 (self.hand[0]), which is already the right choice both when leading (lead_suit is None) and when void in lead_suit. - If lead_suit is set, scan self.hand from left to right; the first card with card.suit == lead_suit is guaranteed to be the lowest-ranked card of that suit because self.hand is sorted! - Calling self.hand.pop(chosen_index) removes that card by index, leaving all remaining cards in sorted order without ever needing to re-sort.

    from typing import List, Optional
    
    
    class Deck:
        def __init__(self, card_texts: List[str]):
            # cards: list of Card objects currently remaining in the undealt deck.
            self.cards: List[Card] = []
            for text in card_texts:
                self.cards.append(Card(text))
    
        def shuffle(self, shuffle_order: List[int]) -> None:
            """Apply an injected permutation: shuffled[i] receives self.cards[shuffle_order[i]]."""
            shuffled: List[Card] = []
            for source_index in shuffle_order:
                shuffled.append(self.cards[source_index])
            self.cards = shuffled
    
        def deal(self, players: List["Player"]) -> None:
            """Deal round-robin starting at seat 0 (card i goes to seat i % num_players)."""
            num_players = len(players)
            for index, card in enumerate(self.cards):
                players[index % num_players].hand.append(card)
            # Empty the deck once all cards have been transferred to player hands.
            self.cards = []
    
    
    class Player:
        def __init__(self, name: str):
            self.name = name
            # hand: sorted list of Card objects still held by this player.
            self.hand: List[Card] = []
            # captured: list of Card objects won in tricks, in exact play order.
            self.captured: List[Card] = []
    
        def sort_hand(self, rules: Rules) -> None:
            self.hand.sort(key=rules.hand_sort_key)
    
        def play(self, lead_suit: Optional[str]) -> Card:
            """Play the first legal card in sorted hand order and remove it from the hand."""
            # Default to index 0: used when leading (lead_suit is None) or when void in lead_suit.
            chosen_index = 0
            if lead_suit is not None:
                for index, card in enumerate(self.hand):
                    if card.suit == lead_suit:
                        chosen_index = index
                        break
            # Popping one element keeps the remaining hand sorted without re-sorting.
            return self.hand.pop(chosen_index)
    
  6. Run one trick and wire up the full game

    play_trick steps around the table using (starter + offset) % num_players for offset = 0, 1, 2, 3, sets lead_suit from the starter's card, asks rules.trick_winner who won, appends the played cards to players[winner].captured, and builds the trick dictionary.

    Then simulate_card_game runs Parts 1, 2, and 3 in sequence, updating current_starter = trick_record["winner"] after each round and using strict > (seat_totals[seat] > seat_totals[best_seat]) so ties stay with the lowest seat index:

    from typing import Dict, List, Optional, Tuple
    
    
    def play_trick(
        players: List[Player], starter: int, rules: Rules
    ) -> Dict[str, object]:
        """Run one 4-card trick starting at `starter`, update captured piles, and return its log."""
        num_players = len(players)
        # plays: list of (seat_index, Card) in clockwise turn order starting from `starter`.
        plays: List[Tuple[int, Card]] = []
        lead_suit: Optional[str] = None
    
        for offset in range(num_players):
            seat = (starter + offset) % num_players
            card = players[seat].play(lead_suit)
            if lead_suit is None:
                # The starter's card establishes the suit everyone else must follow if able.
                lead_suit = card.suit
            plays.append((seat, card))
    
        winner = rules.trick_winner(plays, lead_suit)
        trick_score = 0
        for _, card in plays:
            players[winner].captured.append(card)
            trick_score += rules.card_points(card)
    
        play_log = []
        for seat, card in plays:
            play_log.append({"player": seat, "card": card.text})
    
        return {
            "starter": starter,
            "lead_suit": lead_suit,
            "plays": play_log,
            "winner": winner,
            "score": trick_score,
        }
    
    
    def simulate_card_game(
        deck: List[str],
        player_names: List[str],
        starter: int,
        rank_order: List[str],
        suit_order: List[str],
        points: Dict[str, int],
        shuffle_order: List[int],
    ) -> Dict[str, object]:
        rules = Rules(rank_order, suit_order, points)
        players: List[Player] = []
        for name in player_names:
            players.append(Player(name))
    
        # Part 1: Build the deck, apply the injected shuffle, deal evenly, and sort each hand.
        game_deck = Deck(deck)
        game_deck.shuffle(shuffle_order)
        game_deck.deal(players)
        for player in players:
            player.sort_hand(rules)
    
        # Part 2: Play one trick per card in each hand; each trick's winner leads the next trick.
        tricks = []
        num_rounds = len(deck) // len(players)
        current_starter = starter
        for _ in range(num_rounds):
            trick_record = play_trick(players, current_starter, rules)
            tricks.append(trick_record)
            current_starter = trick_record["winner"]
    
        # Part 3: Sum points from each player's captured cards; break ties by lowest seat index.
        scores: Dict[str, int] = {}
        seat_totals: List[int] = []
        for player in players:
            total = 0
            for card in player.captured:
                total += rules.card_points(card)
            scores[player.name] = total
            seat_totals.append(total)
    
        best_seat = 0
        for seat in range(1, len(players)):
            # Strict `>` keeps the earlier (lower) seat index whenever top scores are tied.
            if seat_totals[seat] > seat_totals[best_seat]:
                best_seat = seat
    
        # Serialize remaining hands and captured piles back to plain card strings.
        hands_out: List[List[str]] = []
        captured_out: List[List[str]] = []
        for player in players:
            hand_texts = []
            for card in player.hand:
                hand_texts.append(card.text)
            hands_out.append(hand_texts)
    
            captured_texts = []
            for card in player.captured:
                captured_texts.append(card.text)
            captured_out.append(captured_texts)
    
        return {
            "hands": hands_out,
            "tricks": tricks,
            "captured": captured_out,
            "scores": scores,
            "winner": player_names[best_seat],
        }
    
  7. Trace Example 1 trick by trick

    In Example 1, deck = ["S_A", "D_K", "C_K", "S_K", "D_5", "C_2", "C_10", "D_2"] is permuted with shuffle_order = [4, 1, 6, 7, 0, 5, 2, 3] into ["D_5", "D_K", "C_10", "D_2", "S_A", "C_2", "C_K", "S_K"]. Dealing round-robin (i % 4) and sorting by suit_order = ["C", "D", "H", "S"] and rank_order = ["2", "5", "10", "K", "A"] sets up two tricks that exercise every rule:

    Initial sorted hands:
      Seat 0 (Maya): D_5, S_A
      Seat 1 (Liam): C_2, D_K    (dealt D_K then C_2 -> sorted to C_2, D_K)
      Seat 2 (Nora): C_10, C_K
      Seat 3 (Owen): D_2, S_K
    
    Trick 1 (starter = 0, Maya leads hand[0] = D_5 -> lead_suit = 'D'):
      Plays:  0:D_5 -> 1:D_K -> 2:C_10 -> 3:D_2
      Note:   Liam holds C_2 at hand[0], MUST skip it to follow Diamonds with D_K!
              Nora is void in Diamonds, so she discards hand[0] = C_10 (10 pts).
      Winner: Seat 1 (D_K is highest Diamond) | Score: 5 + 10 + 10 + 0 = 25 pts | Next starter: 1
    
    Trick 2 (starter = 1, Liam leads hand[0] = C_2 -> lead_suit = 'C'):
      Plays:  1:C_2 -> 2:C_K -> 3:S_K -> 0:S_A
      Note:   Owen and Maya are void in Clubs; Maya's off-suit S_A cannot win!
      Winner: Seat 2 (C_K is highest Club) | Score: 0 + 10 + 10 + 0 = 20 pts
    

    After Trick 2, all four hands are [], captured piles hold the exact trick cards in play order, and final totals are Maya 0, Liam 25, Nora 20, Owen 0 -> winner "Liam".

  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    class Card:
        def __init__(self, text: str):
            # text: original card string like "H_10"; split on "_" so 2-char rank "10" stays intact.
            self.text = text
            self.suit, self.rank = text.split("_", 1)
    
    
    class Rules:
        """Single source of truth for suit ordering, rank strength, and card point values."""
    
        def __init__(
            self, rank_order: List[str], suit_order: List[str], points: Dict[str, int]
        ):
            # rank_index: maps rank string -> integer strength (e.g. {"2": 0, ..., "A": 12}),
            # avoiding raw string comparisons where "10" < "2".
            self.rank_index: Dict[str, int] = {}
            for index, rank in enumerate(rank_order):
                self.rank_index[rank] = index
    
            # suit_index: maps suit string -> integer hand-sort order (e.g. {"C": 0, "D": 1, ...}).
            self.suit_index: Dict[str, int] = {}
            for index, suit in enumerate(suit_order):
                self.suit_index[suit] = index
    
            # points: maps scoring rank -> point value (non-scoring ranks default to 0).
            self.points = points
    
        def hand_sort_key(self, card: Card) -> Tuple[int, int]:
            """Sort cards by suit order first, then by ascending rank order within each suit."""
            return (self.suit_index[card.suit], self.rank_index[card.rank])
    
        def card_points(self, card: Card) -> int:
            return self.points.get(card.rank, 0)
    
        def trick_winner(self, plays: List[Tuple[int, Card]], lead_suit: str) -> int:
            """Return the seat index of the highest-ranked card matching lead_suit (no trump)."""
            best_seat, best_card = plays[0]
            for seat, card in plays[1:]:
                # Off-suit discards can never win a trick, even if their rank is an Ace or King.
                if (
                    card.suit == lead_suit
                    and self.rank_index[card.rank] > self.rank_index[best_card.rank]
                ):
                    best_seat = seat
                    best_card = card
            return best_seat
    
    
    class Deck:
        def __init__(self, card_texts: List[str]):
            # cards: list of Card objects currently remaining in the undealt deck.
            self.cards: List[Card] = []
            for text in card_texts:
                self.cards.append(Card(text))
    
        def shuffle(self, shuffle_order: List[int]) -> None:
            """Apply an injected permutation: shuffled[i] receives self.cards[shuffle_order[i]]."""
            shuffled: List[Card] = []
            for source_index in shuffle_order:
                shuffled.append(self.cards[source_index])
            self.cards = shuffled
    
        def deal(self, players: List["Player"]) -> None:
            """Deal round-robin starting at seat 0 (card i goes to seat i % num_players)."""
            num_players = len(players)
            for index, card in enumerate(self.cards):
                players[index % num_players].hand.append(card)
            # Empty the deck once all cards have been transferred to player hands.
            self.cards = []
    
    
    class Player:
        def __init__(self, name: str):
            self.name = name
            # hand: sorted list of Card objects still held by this player.
            self.hand: List[Card] = []
            # captured: list of Card objects won in tricks, in exact play order.
            self.captured: List[Card] = []
    
        def sort_hand(self, rules: Rules) -> None:
            self.hand.sort(key=rules.hand_sort_key)
    
        def play(self, lead_suit: Optional[str]) -> Card:
            """Play the first legal card in sorted hand order and remove it from the hand."""
            # Default to index 0: used when leading (lead_suit is None) or when void in lead_suit.
            chosen_index = 0
            if lead_suit is not None:
                for index, card in enumerate(self.hand):
                    if card.suit == lead_suit:
                        chosen_index = index
                        break
            # Popping one element keeps the remaining hand sorted without re-sorting.
            return self.hand.pop(chosen_index)
    
    
    def play_trick(
        players: List[Player], starter: int, rules: Rules
    ) -> Dict[str, object]:
        """Run one 4-card trick starting at `starter`, update captured piles, and return its log."""
        num_players = len(players)
        # plays: list of (seat_index, Card) in clockwise turn order starting from `starter`.
        plays: List[Tuple[int, Card]] = []
        lead_suit: Optional[str] = None
    
        for offset in range(num_players):
            seat = (starter + offset) % num_players
            card = players[seat].play(lead_suit)
            if lead_suit is None:
                # The starter's card establishes the suit everyone else must follow if able.
                lead_suit = card.suit
            plays.append((seat, card))
    
        winner = rules.trick_winner(plays, lead_suit)
        trick_score = 0
        for _, card in plays:
            players[winner].captured.append(card)
            trick_score += rules.card_points(card)
    
        play_log = []
        for seat, card in plays:
            play_log.append({"player": seat, "card": card.text})
    
        return {
            "starter": starter,
            "lead_suit": lead_suit,
            "plays": play_log,
            "winner": winner,
            "score": trick_score,
        }
    
    
    def simulate_card_game(
        deck: List[str],
        player_names: List[str],
        starter: int,
        rank_order: List[str],
        suit_order: List[str],
        points: Dict[str, int],
        shuffle_order: List[int],
    ) -> Dict[str, object]:
        rules = Rules(rank_order, suit_order, points)
        players: List[Player] = []
        for name in player_names:
            players.append(Player(name))
    
        # Part 1: Build the deck, apply the injected shuffle, deal evenly, and sort each hand.
        game_deck = Deck(deck)
        game_deck.shuffle(shuffle_order)
        game_deck.deal(players)
        for player in players:
            player.sort_hand(rules)
    
        # Part 2: Play one trick per card in each hand; each trick's winner leads the next trick.
        tricks = []
        num_rounds = len(deck) // len(players)
        current_starter = starter
        for _ in range(num_rounds):
            trick_record = play_trick(players, current_starter, rules)
            tricks.append(trick_record)
            current_starter = trick_record["winner"]
    
        # Part 3: Sum points from each player's captured cards; break ties by lowest seat index.
        scores: Dict[str, int] = {}
        seat_totals: List[int] = []
        for player in players:
            total = 0
            for card in player.captured:
                total += rules.card_points(card)
            scores[player.name] = total
            seat_totals.append(total)
    
        best_seat = 0
        for seat in range(1, len(players)):
            # Strict `>` keeps the earlier (lower) seat index whenever top scores are tied.
            if seat_totals[seat] > seat_totals[best_seat]:
                best_seat = seat
    
        # Serialize remaining hands and captured piles back to plain card strings.
        hands_out: List[List[str]] = []
        captured_out: List[List[str]] = []
        for player in players:
            hand_texts = []
            for card in player.hand:
                hand_texts.append(card.text)
            hands_out.append(hand_texts)
    
            captured_texts = []
            for card in player.captured:
                captured_texts.append(card.text)
            captured_out.append(captured_texts)
    
        return {
            "hands": hands_out,
            "tricks": tricks,
            "captured": captured_out,
            "scores": scores,
            "winner": player_names[best_seat],
        }
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine four friends sitting clockwise around a card table with a single printed rule sheet in the center: physical cards never duplicate or vanish, they simply move cleanly from one pile to the next (Deck.cards -> Player.hand -> the current trick, meaning the four cards played in one round -> Player[winner].captured), while the Rules sheet is the only place consulted for suit order, rank strength, and point values. To keep every game 100% reproducible in automated tests, we pass shuffle_order in from the outside (dependency injection, meaning supplying external behavior like shuffling or scoring as an explicit parameter instead of calling hidden globals like random.shuffle). Once each player's hand is sorted by (suit_index, rank_index), choosing the first legal card is effortless: scan left to right for the first card matching the lead suit (the suit played by whoever started the trick), or fall back to hand[0] when void (holding zero cards of the lead suit).

Why does a quick procedural script without explicit classes get messy and bug-prone? Treating cards as raw strings throughout the loop invites silent bugs like slicing "H_10"[2] into "1" or comparing ranks alphabetically where "10" < "2" and "A" < "K". Likewise, duplicating point tables between per-trick logging and end-of-game scoring lets rules drift out of sync across dealing, trick resolution, and final tallying.

Here is a tiny 1-trick, 4-card example (starter = 2, ranks ["2", "5", "10", "K"], points {"5": 5, "10": 10, "K": 10}):

Dealt 1-card hands: Seat 0: C_2 | Seat 1: D_K | Seat 2: C_5 | Seat 3: C_10

Trick 1 (turn order starting at starter = 2 -> seats 2, 3, 0, 1):
  Seat 2 leads C_5   -> sets lead_suit = "C"
  Seat 3 plays C_10  -> follows "C"
  Seat 0 plays C_2   -> follows "C"
  Seat 1 plays D_K   -> void in "C", discards D_K (off-suit King cannot win!)

Winner: Seat 3 (C_10 is the highest Club; there is no trump suit)
Captured by Seat 3: ["C_5", "C_10", "C_2", "D_K"] -> 5 + 10 + 0 + 10 = 25 points!

Complexity

Let n be the total number of cards in deck and p be the number of players (n = 52 and p = 4 in a standard game).

  • Time — O(n log(n / p) + n^2 / p): Shuffling and dealing touch each of the n cards once in O(n) time, sorting p hands of size n / p takes O(p * (n / p) log(n / p)) = O(n log(n / p)), each of the n card plays scans and pops from a hand of length at most n / p in O(n / p) time, and finding each trick's winner scans p plays (O(n) across all n / p tricks). For 52 cards and 4 players, the entire game finishes in a few hundred basic operations.
  • Space — O(n): Each Card object exists once (moving from Deck to Player.hand to Player.captured), the Rules lookup tables hold one integer per suit and rank, and the tricks log records each of the n plays once.

Edge cases

  • Player void in the lead suit: When no card in self.hand matches lead_suit, chosen_index stays 0, cleanly discarding the first card of the sorted hand.
  • Must follow suit even while holding an earlier suit at hand[0]: In Example 1's Trick 1, Liam holds C_2 at hand[0] when Diamonds are led, and must skip C_2 to follow with D_K.
  • Off-suit high cards score points for the winner without winning the trick: Because there is no trump suit (a special suit designated to beat all other suits), a discarded D_K on a Club lead never wins the trick, yet still contributes 10 points to whoever wins with the highest Club.
  • Multi-character rank "10": text.split("_", 1) splits on the underscore separator so "10" is never truncated.
  • Custom suit and rank orders: Rules builds suit_index and rank_index dynamically from the passed lists, so custom rules (such as Aces low or Hearts before Clubs) work without changing a single line of logic.
  • Ranks absent from points (or empty points = {}): self.points.get(card.rank, 0) safely defaults every non-scoring card to 0.
  • Tied top scores (including 0-all ties): Using strict > (seat_totals[seat] > seat_totals[best_seat]) guarantees the lowest seat index wins any tie.
  • Final trick: Each player holds 1 remaining card, plays it, and ends the game with hand == [].

Common mistakes

  • Comparing rank strings directly (card.rank > best.rank): Alphabetical string comparison ranks "10" below "2" and "A" below "K"; always compare self.rank_index[card.rank].
  • Allowing off-suit cards to win tricks: Forgetting card.suit == lead_suit inside trick_winner lets a void player win with an off-suit King or Ace.
  • Iterating seats 0..3 instead of (starter + offset) % num_players: Play must start with the previous trick's winner and wrap clockwise around the table.
  • Calling random.shuffle inside Deck.shuffle: Makes test runs non-deterministic and impossible for an automated judge to verify play-by-play.
  • Crediting points to the player who played a scoring card instead of the player who captured the trick: Scoring cards belong to the trick winner's captured pile.
  • Forgetting to remove played cards from self.hand: Causes players to replay the same card across multiple rounds and leaves non-empty hands at the end.

Follow-up questions

  • What event log schema would let you reconstruct any completed match turn for turn? Using event sourcing (storing an immutable sequence of state-changing events rather than only the final result), emit one MatchStarted header event containing (deck, player_names, starter, rank_order, suit_order, points, shuffle_order) followed by one CardPlayed event (trick_index, seat, card_text) per turn. To reconstruct the match, initialize Deck, Rules, and Player from the header, permute, deal, and sort hands identically, and feed each logged (seat, card_text) through a play_specific_card method that validates turn order and follow-suit legality before transferring the card. With deterministic bots the header alone reproduces every play, whereas with human or stochastic players the logged CardPlayed events guarantee an exact turn-by-turn replay; for long match archives, periodic round snapshots let you jump straight to trick k.
  • How could you plug in alternative point rules—such as penalty cards or a last-trick bonus—without modifying the trick-play engine? Extract scoring into a pluggable ScoringPolicy interface injected into Rules (the Strategy pattern, meaning swapping behavior by passing a different policy object that implements the same method contract), exposing trick_points(trick_index, plays, winner), final_scores(players), and pick_winner(seat_totals). Point-trick games sum card_points as today, while variants like Hearts (penalty cards where the lowest total wins, plus "shooting the moon" when one player captures every penalty card) or a +10 final-trick bonus (trick_index == num_rounds - 1) simply supply a new ScoringPolicy class while Deck, Player, and play_trick stay completely unchanged.

Follow-up questions

Similar questions

More Scale AI interview questions

All 29 Scale AI questions →