Python - 二十一点

-2 投票
2 回答
4515 浏览
提问于 2025-04-15 23:36
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这个地方出错了,提示说不能把列表和整数结合在一起...

2 个回答

1

要计算一手牌的价值,你可以这样做:

compSum = sum(compCards)

不过,看起来你在帖子后面提到的#SUM,可能是想说你已经尝试过这个方法,但我不太明白你想表达什么。这个方法只有在Deal()返回整数的时候才有效。

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)是个好方法,但对于黑杰克的规则来说,这个方法其实太简单了。

撰写回答