除了上面提到的註釋之外,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)是要走的路,但實際上對於黑傑克規則而言太簡單了。
請修復您的代碼,使其正確縮進(對於Python是必需的 - *不要使用製表符,使用空格*)並且沒有額外的'''標記另外,請嘗試澄清究竟是什麼在不作爲函數的一部分進行初始化的各種變量中(您可能需要發佈更多的代碼) – Amber 2010-06-05 21:17:02
Deal()是做什麼的?它是否創建某種類型的Card對象,您可以從中獲取整數值? – David 2010-06-05 21:23:56