2015-02-07 20 views
-2
def hit(): 
    global hitsum 
    hitsum = 0 
    v=random.choice(cards) 
    c=random.choice(suits) 
    if v=="Ace": 
     hitsum=hitsum+1 
     print "You were dealt","a",v,"of",c 
    elif v=="Jack": 
     hitsum=hitsum+11 
     print "You were dealt","a",v,"of",c 
    elif v=="Queen": 
     hitsum=hitsum+12 
     print "You were dealt","a",v,"of",c 
    elif v=="King": 
     hitsum=hitsum+13 
     print "You were dealt","a",v,"of",c 
    else: 
     hitsum=hitsum+v 
     print "You were dealt","a",v,"of",c 

computer() 

choice=raw_input("Would you like to hit or stay? ") 
if choice=="hit": 
    hit() 
    totalsum = hitsum + usersum 
    print "Your total is", totalsum 

elif choice=="stay": 
    totalsum=usersum 

else: 
    print "Invalid request" 

此代碼是從我的二十一點遊戲摘錄。我做了一個用戶定義的函數,用於在有人要求命中時隨機生成一張卡片。但是,這隻適用於一種選擇。如果我選擇一次,我沒有選擇再次選擇它。我該如何糾正?如何在Python中多次使用'if'循環?

+0

你需要一個while循環或for循環使用範圍 – 2015-02-07 10:16:29

回答

0
choice=raw_input("Would you like to hit or stay? ") 
while choice=="hit": 
    hit() 
    totalsum = hitsum + usersum 
    print "Your total is", totalsum 
    choice=raw_input("Would you like to hit or stay? ") 

我會強烈建議改變如何hithitsum進行處理。爲什麼不把它變成全球性的呢?所以在hit末,你會

return hitsum 

所以後來在呼叫你可以做

totalsum = usersum + hit() 

我看到其他一些問題在這裏。下一次通過choice==hit循環,usersum將回到以前的狀態。我不認爲這就是你想要的。當然你想增加usersumhitsum。在這種情況下,更換totalsum = ...通過

usersum += hit() 

最後,在hit功能,爲什麼定義hitsum=0開頭?

+0

注意 - 只是注意到我在我的初始代碼片段中有一個錯誤。我只是糾正它。所以如果你抓住了早期版本,你想更新它。 – Joel 2015-02-07 10:59:42

+0

謝謝喬爾!通過所有的建議,它真的幫助我解決我的問題。 – 2015-02-08 12:19:27