← Questions

Two-player card game simulation

0
AmazonCoding

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 (use seed so a game can be replayed), then deal it one card at a time, alternating players, starting with A. 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.

Write and test your solution herePython in your browser, the question's tests level by level, saved for you.Sign in to start coding