2010-06-05 43 views
-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錯誤是可以組合列表像整數...Python - Blackjack

+1

請修復您的代碼,使其正確縮進(對於Python是必需的 - *不要使用製表符,使用空格*)並且沒有額外的'''標記另外,請嘗試澄清究竟是什麼在不作爲函數的一部分進行初始化的各種變量中(您可能需要發佈更多的代碼) – Amber 2010-06-05 21:17:02

+0

Deal()是做什麼的?它是否創建某種類型的Card對象,您可以從中獲取整數值? – David 2010-06-05 21:23:56

回答

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) 

好吧,所以我被帶走了,實際上寫了整個事情。正如另一張海報寫的總和(list_of_values)是要走的路,但實際上對於黑傑克規則而言太簡單了。

1

在這裏找到手的價值,你可以做類似

compSum = sum(compCards) 

但它看起來像你可能試圖從第二你提到#SUM的部分內容,我不知道你想說什麼。這隻會在Deal()返回整數時起作用。

+1

他/她正在覆蓋函數第一行中的'sum'名稱,所以這可能是問題所在。 – 2010-06-05 22:47:26