2012-06-18 122 views
0
from random import * 

while True: 

    random1 = randint(1,20) 

    random2 = randint(1,20) 

    print("h = higher, l = lower, s = same, q = quit") 

    print(random1) 

    a = input() 

    if a.lower() == 'q': 
      break 

    print(random2) 

    if a.lower() == 'h' and random1 < random2: 

     print("Well done") 

    elif a.lower() == 'l' and random1 > random2: 

     print("Well done") 

    elif a.lower() == 's' and random1 == random2: 

     print("Well done") 
    else: 

     print("Loser") 

所以我想要做的就是將x作爲我的分數。當答案打印出「Well done」時,我希望它將10分添加到我的分數中,然後打印分數。事情是分數似乎重置整個遊戲時間的負載,我希望它可以添加10分或保持不變。有沒有人知道在我的程序中這樣做的方法。我無法想象這會太難,但我只是一個初學者,仍然在學習。目前,我的程序中沒有添加任何分數,只是讓您可以向我展示最簡單/最好的方法。感謝您的幫助:)如何將分數添加到更高或更低的遊戲

+1

請您談一下比分,但沒有嘗試實施評分。 –

回答

2
x = 0 # initialize the score to zero before the main loop 
while True: 

    ... 

    elif a.lower() == 's' and random1 == random2: 
     x += 10 # increment the score 
     print("Well done. Your current score is {0} points".format(x)) 

無論如何,整個代碼可以簡化爲:

from random import * 
x = 0 
while True: 
    random1 = randint(1,20) 
    random2 = randint(1,20) 
    print("h = higher, l = lower, s = same, q = quit") 
    print(random1) 
    a = input().lower() 
    if a == 'q': 
     break 

    print(random2) 

    if ((a == 'h' and random1 < random2) or 
     (a == 'l' and random1 > random2) or 
     (a == 's' and random1 == random2)): 
     x += 10 
     print("Well done. Your current score is: {0}".format(x)) 
    else: 
     print("Loser") 
+0

這是完美的。我看到了我犯的錯誤。我在主循環中有「x = 0」。這導致它每次都重置。現在它工作完美。感謝您的幫助:) –

2

只需添加一個變量:

score = 0 #Variable that keeps count of current score (outside of while loop) 

while True: 
... 
    elif a.lower() == 'l' and random1 > random2: 
     score += 10 #Add 10 to score 
     print("Well done") 
    else: 
     #Do nothing with score as it stays the same 
     print("Loser") 
+0

您的回答中不清楚'score'需要在while循環之外初始化。 – Junuxx

+0

修正了它。謝謝。 – tabchas