~/problems / Simulation & OOP design / Object-oriented design and extensible simulations

OA: Deal, sort and play tricks

medium 2 levels ~50 min OpenAIScale AIVerkada

Level 1 Shuffle, deal and sort

You're given the basic model of a four-player card game (it's already in the starter, keep it):

  • SUITS = ["CLUBS", "DIAMONDS", "HEARTS", "SPADES"] and RANKS = ["A", "2", "3", ..., "10", "J", "Q", "K"], both listed from lowest to highest.
  • Card(suit, rank): an immutable card.
  • Deck(): deck.cards holds all 52 cards in standard order: every club from A to K, then every diamond, then hearts, then spades.
  • Player(name): has a name and a hand (a list of cards, initially empty).
  • Game(player_names): needs exactly four distinct names, otherwise raise ValueError. game.players is the list of Players in seating order; game.deck is a Deck.

Implement Game.deal_and_sort_hands(rng: random.Random) -> None:

  1. Throw away any cards players still hold and start from a fresh deck in standard order.
  2. Shuffle it by calling rng.shuffle(self.deck.cards) exactly once (this makes the result reproducible).
  3. Deal from the front of the shuffled deck one card at a time, going round the table: the 1st card to players[0], the 2nd to players[1], ..., the 5th to players[0] again. Every player ends with 13 cards and self.deck.cards ends empty.
  4. Sort each hand by suit (in SUITS order), then by rank (in RANKS order).
game = Game(["Ada", "Bo", "Cy", "Di"])
game.deal_and_sort_hands(random.Random(7))
[len(p.hand) for p in game.players]    # [13, 13, 13, 13]
game.players[0].hand[:3]               # [Card("CLUBS", "7"), Card("DIAMONDS", "2"), Card("DIAMONDS", "5")]
game.deck.cards                        # []
Game(["Ada", "Bo", "Cy"])              # ValueError
Game(["Ada", "Ada", "Cy", "Di"])       # ValueError

Mind the rank order: "10" sorts after "9" and "A" is the lowest, so sorting by the rank strings themselves is wrong.

Show hint

Build lookup tables {suit: index} and {rank: index} once and sort with key=lambda c: (SUIT_ORDER[c.suit], RANK_ORDER[c.rank]). Dealing round the table is players[i % 4] for the i-th card.

Level 2 unlocks when level 1 passes.

Topic: Object-oriented design and extensible simulations. Classes that survive new requirements: games, payments, subscriptions, refactors.

0:00
Ctrl ' run · Ctrl ↵ submit
esc