Search code examples
pythonpython-3.xblackjack

Dealing One Card to Each Player Before Dealing a Second Card - Blackjack Game in Python


I have made the following code in Python. Where deck = deck_of_cards(). My question is how to I fix the second function so that it must deal a first card to each player before dealing a second card. The way it is right now seems to deal two cards to a player before dealing cards to the other players and I don't know how to fix it.

import random
def deck_of_cards():
    suits = ['D', 'C', 'H', 'S']
    denominations = ['2', '3', '4', '5', '6', '7', '8', 
                     '9', 'T', 'J', 'Q', 'K', 'A']
    deck = []
    for suit in suits:
        for denomination in denominations:
            ds = denomination + suit
            deck.append(ds)

    random.shuffle(deck)      
    return deck

def deal_cards(deck, players):
    hands = []

    for j in range(players):
        player_hand = []
        for i in range(2):
            cards = deck.pop(0)
            player_hand.append(cards)

        hands.append(player_hand)  
    return hands 

Solution

  • You need to swap your for loops so you iterate over all players for the first cars, then the second:

    def deal_cards(deck, players):
        hands = [[] for player in range(players)]
    
        for _ in range(2):
            for hand in hands:
                hand.append(deck.pop(0))
    
        return hands