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"]andRANKS = ["A", "2", "3", ..., "10", "J", "Q", "K"], both listed from lowest to highest.Card(suit, rank): an immutable card.Deck():deck.cardsholds all 52 cards in standard order: every club from A to K, then every diamond, then hearts, then spades.Player(name): has anameand ahand(a list of cards, initially empty).Game(player_names): needs exactly four distinct names, otherwise raiseValueError.game.playersis the list ofPlayers in seating order;game.deckis aDeck.
Implement Game.deal_and_sort_hands(rng: random.Random) -> None:
- Throw away any cards players still hold and start from a fresh deck in standard order.
- Shuffle it by calling
rng.shuffle(self.deck.cards)exactly once (this makes the result reproducible). - 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 toplayers[1], ..., the 5th toplayers[0]again. Every player ends with 13 cards andself.deck.cardsends empty. - Sort each hand by suit (in
SUITSorder), then by rank (inRANKSorder).
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.