【问题标题】:Dealing One Card to Each Player Before Dealing a Second Card - Blackjack Game in Python在发第二张牌之前向每个玩家发一张牌 - Python 中的二十一点游戏
【发布时间】:2018-05-18 15:46:31
【问题描述】:

我在 Python 中编写了以下代码。其中甲板 = deck_of_cards()。我的问题是如何修复第二个功能,以便它必须在发第二张牌之前向每个玩家发第一张牌。现在的方式似乎是先给一个玩家发两张牌,然后再给其他玩家发牌,我不知道如何解决。

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 

【问题讨论】:

    标签: python python-3.x blackjack


    【解决方案1】:

    您需要交换您的 for 循环,以便遍历所有玩家以获得第一辆车,然后是第二辆:

    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 
    

    【讨论】:

    • 这里的问题是player_hand的实现。您开始迭代,实例化player_hand,然后为每个玩家附加该手牌。每个玩家都需要一只新手。具有hand 属性和add_to_hand() 方法的Player 类将是干净的。
    • 是的,我现在修好了。
    • 是的,适用于所有有效的密集型目的。但是我们怎么知道哪个玩家有什么牌呢?我把它留给 OP 在课堂设计中解决。解决方案回答了问题。
    • 双手与玩家的顺序相同,假设玩家是有序集合
    • 我同意你的观点@pstatix,OO 非常适合这个应用程序;然而,当他决定改变他的设计、面临困难并请求关于 SO 的帮助时,我们将需要等待 OP 的问题。
    猜你喜欢
    • 2017-05-16
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2020-06-18
    • 2018-04-02
    • 2020-09-26
    • 2021-06-10
    • 2014-09-21
    相关资源
    最近更新 更多