Python - 二十一点

时间:2010-06-05 21:14:36

标签: python blackjack

def showCards():
    #SUM
    sum = playerCards[0] + playerCards[1]
    #Print cards
    print "Player's Hand: " + str(playerCards) + " : " + "sum"
    print "Dealer's Hand: " + str(compCards[0]) + " : " + "sum"


    compCards = [Deal(),Deal()]    
    playerCards = [Deal(),Deal()]

如何将包含值的列表的整数元素加起来?在#SUM错误下可以组合像int这样的列表......

2 个答案:

答案 0 :(得分:1)

要在此处找到手牌的价值,您可以执行类似

的操作
compSum = sum(compCards)

但是看起来你可能已经尝试过从帖子的第二部分提到#SUM,我不知道你想说什么。这只有在Deal()返回整数时才有效。

答案 1 :(得分:1)

除了上面提到的注释之外,sum实际上是Python中的一个内置函数,可以完成您所寻找的内容 - 所以不要覆盖它并将其用作标识符名称!而是使用它。

还有一个所有Python程序员都应该遵循的样式指南 - 它有助于进一步区分Python代码与用其他语言编写的代码中经常遇到的难以理解的污泥,例如Perl或PHP。 Python中有更高的标准,而你却没有达到它。 Style

所以这里是对代码的重写以及一些猜测,以填补缺少的部分。

from random import randint

CARD_FACES = {1: "Ace", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 
              9: "9", 10: "10", 11: "Jack", 12: "Queen", 13: "King"}

def deal():
    """Deal a card - returns a value indicating a card with the Ace
       represented by 1 and the Jack, Queen and King by 11, 12, 13
       respectively.
    """
    return randint(1, 13)

def _get_hand_value(cards):
    """Get the value of a hand based on the rules for Black Jack."""
    val = 0
    for card in cards:
        if 1 < card <= 10:
            val += card # 2 thru 10 are worth their face values
        elif card > 10:
            val += 10 # Jack, Queen and King are worth 10

    # Deal with the Ace if present.  Worth 11 if total remains 21 or lower
    # otherwise it's worth 1.
    if 1 in cards and val + 11 <= 21:
        return val + 11
    elif 1 in cards:
        return val + 1
    else:
        return val    

def show_hand(name, cards):
    """Print a message showing the contents and value of a hand."""
    faces = [CARD_FACES[card] for card in cards]
    val = _get_hand_value(cards)

    if val == 21:
        note = "BLACK JACK!"
    else:
        note = ""

    print "%s's hand: %s, %s : %s %s" % (name, faces[0], faces[1], val, note)


# Deal 2 cards to both the dealer and a player and show their hands
for name in ("Dealer", "Player"):
    cards = (deal(), deal())
    show_hand(name, cards)

好吧,所以我被带走了,实际上写了整篇文章。正如另一张海报写的那样sum(list_of_values)是要走的路,但实际上对Black Jack规则来说过于简单。