Python布莱克

2024-10-01 15:46:03 发布

您现在位置:Python中文网/ 问答频道 /正文

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()]

如何将包含to值的列表的整数元素相加?SUM error is can combinated list like ints…在“总和错误”下,可以组合像整数这样的列表。。。在


Tags: 列表def整数cardsplayersumprinthand
2条回答

除了上面提到的注释之外,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(列出你的值)是一种可行的方法,但实际上对于黑杰克规则来说过于简单化了。在

要想在这里找到一只手的价值你可以做一些

compSum = sum(compCards)

但从你的帖子的第二部分来看,我不知道你想说什么。如果这个整数()只能处理,则返回。在

相关问题 更多 >

    热门问题