-2
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 下的错误是可以组合像整数这样的列表...

4

2 回答 2

1

要在这里找到一手牌的价值,您可以执行类似的操作

compSum = sum(compCards)

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

于 2010-06-05T21:59:29.040 回答
1

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

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

因此,这是对您的代码的重写以及一些猜测以填补缺失的部分。

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 规则来说过于简单。

于 2010-06-05T22:12:49.353 回答