Two-player card game simulation
I was asked this
No reports yet. Sign in to say where you were asked it.
You are building the engine for a simple two-player card game. Players are named "A" and "B". The deck is a list of distinct integers, and a higher integer beats a lower one.
Implement a CardGame class:
-
CardGame(deck, seed=None, shuffle=True): shuffle the deck (useseedso a game can be replayed), then deal it one card at a time, alternating players, starting withA. If the deck has an odd number of cards, the last card is not dealt. -
play_round(): each player plays the top card of their hand. The player with the higher card puts both cards in their scoring pile. Return what was played and who won the round. -
play() -> str: play rounds until the hands are empty. Return"A","B", or"tie". -
scores() -> dict: each player's score, one point per card in their scoring pile.
Model the game with sensible types (at least a player type). Keep the code easy to extend. The interviewer will add rules once the base game works.
Constraints
-
0 <= len(deck) <= 10^5; card values are distinct integers. -
play_round()after the game has ended is an error.
Example 1 (no shuffle)
deck = [5, 2, 1, 8, 7, 3]
A's hand: [5, 1, 7] B's hand: [2, 8, 3]
Round 1: 5 vs 2 -> A Round 2: 1 vs 8 -> B Round 3: 7 vs 3 -> A
scores() == {"A": 4, "B": 2}; play() == "A"
Example 2 (no shuffle)
deck = [9, 1, 2, 8]
Round 1: 9 vs 1 -> A Round 2: 2 vs 8 -> B
scores() == {"A": 2, "B": 2}; play() == "tie"
Likely follow-ups: allow repeated card values (tied rounds), support more than two players, and the War variant, where won cards go back into the winner's hand and the game may never end.
Reconstructed from the reported question; details may differ from what interviewers ask.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
