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分或保持不变。有谁知道在我的程序中这样做的方法。我无法想象这会太难,但我只是一个初学者而且还在学习。目前我没有得分加入我的程序,所以你可以告诉我最简单/最好的方法来解决这个问题。谢谢你的帮助:)
答案 0 :(得分: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")
答案 1 :(得分: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")