How to randomly shuffle a deck of cards among players?

前端 未结 3 1465
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-28 02:33

I am having trouble using one function in another to deal cards. Here is what I have so far.

import random as rand 

def create(): 
     ranks = [\'2\', \'3\',          


        
3条回答
  •  死守一世寂寞
    2021-01-28 03:10

    There are certainly other ways to do it, but you could complete your function as so, in order to return a dictionary of your players and their hands:

    def cards_dealt(num_cards, num_players, deck):
        rand.shuffle(deck)
        return {player:[deck.pop() for _ in range(num_cards)] for player in range(num_players)}
    

    Then, create your deck (that is where your "deck is not defined" problem comes in) and call your function:

    my_deck = create()
    
    print(cards_dealt(5, 3, my_deck))
    

    Which returns:

    {0: [['10S'], ['8S'], ['7D'], ['6S'], ['4C']], 
     1: [['JD'], ['AC'], ['QD'], ['2D'], ['JS']], 
     2: [['6D'], ['4H'], ['AS'], ['4S'], ['9S']]}
    

    The equivalent cards_dealt function, but with loops instead of the dict and list comprehensions is:

    def cards_dealt (num_cards, num_players, deck): 
         rand.shuffle(deck)
         player_hands = {i:[] for i in range(num_players)}
         for player in range(num_players):
             for num in range(num_cards):
                 player_hands[player].append(deck.pop())
         return player_hands
    

提交回复
热议问题