Search code examples
pythonplaying-cards

Deck of cards, dealing alternately


import random
import itertools    
suit = 'CSHD'
rank = '23456789TJQKA'
deck_of_cards = [''.join(card) for card in itertools.product(rank, suit)]

def draw_card(deck,hand, count):
    for i in range(count):
        hand.append(deck.pop())

def hand_selection(deck):
    shuffled_deck = random.sample(deck, len(deck))
    dealer_hand = []
    player_hand = []
    draw_card(shuffled_deck, dealer_hand, 1)
    draw_card(shuffled_deck, player_hand, 1)
    draw_card(shuffled_deck, dealer_hand, 1)
    draw_card(shuffled_deck, player_hand, 1)
    return dealer_hand,player_hand

Trying to follow the principle of card dealing here. Initially I wanted to generate a card randomly, remove it from the shuffled_deck, but we don't deal cards by randomly scouring through the deck, are we? For my purpose, the code does what it is supposed to do, but it doesn't look too good. (Yes, the shuffled_deck, player_hand and dealer_hand are all globals actually, but it's irrelevant for the moment.)

What would be a more elegant(read: pythonic) solution to deal cards in this manner? E.g were we playing something like Chinese poker between, say, 3 players. Dealing one by one like this seems too tedious.


Solution

  • I would make the deck a class, to keep its related functionality together:

    class Deck(object):
    
        def __init__(self, suits='CSHD', ranks='23456789TJQKA'):
            self.cards = [''.join(card) for card in itertools.product(ranks, suits)]
    
        def shuffle(self):
            random.shuffle(self.cards)
    
        def deal_cards(self, hand, count=1):
            for _ in range(count):
                hand.append(self.cards.pop())
    
        def return_cards(self, hand):
            self.cards.extend(hand)
    

    And to simplify the dealing:

    deck = Deck()
    deck.shuffle()
    dealer_hand = []
    player_hand = []
    for _ in range(2): # number of rounds to deal
        for hand in (dealer_hand, player_hand): # hands to deal to
             deck.deal(hand)
    

    This is much more easily adapted to more players and/or more rounds.