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 作为我的分数。当答案打印“做得好”时,我希望它在我的分数上加 10 分,然后打印分数。问题是分数似乎在整个游戏中重置了很多次,我希望它在分数上增加 10 或保持不变。有谁知道在我的程序中这样做的方法。我无法想象这会太难,但我只是一个初学者,还在学习。目前我的程序中根本没有任何分数,只是为了让您向我展示最简单/最好的方法也可以解决这个问题。谢谢您的帮助 :)

4

2 回答 2

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")
于 2012-06-18T11:37:18.713 回答
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")
于 2012-06-18T11:39:29.017 回答