简体   繁体   English

如何为更高或更低的游戏增加分数

[英]how to add score to higher or lower game

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")

So what I am trying to do is have x as my score. 所以我想做的是将x作为我的分数。 And when the answer prints "Well Done" I would like it to add 10 points to my score and then print the score. 当答案打印“ Well Done”时,我希望它为我的分数加10分,然后打印分数。 The thing is the score seems to reset loads of times throughout the game and I would like it to either add 10 to the score or stay the same. 问题是得分似乎在整个游戏中重置了时间负荷,我希望它可以将得分增加10或保持不变。 Does anyone know a way of doing this in my program. 有谁知道在我的程序中执行此操作的方法。 I can't imagine it would be too hard but I am only a beginner and still learning. 我无法想象这太难了,但我只是一个初学者,还在学习。 At the moment I have no score at all added to my program, just so you can show me the easiest/ best way too approach this. 目前,我的程序完全没有评分,因此您可以向我展示最简单/最佳的方法。 Thanks for the help :) 谢谢您的帮助 :)

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))

anyway, the whole code could be shortened to: 无论如何,整个代码可以简化为:

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")

Simply add a variable: 只需添加一个变量:

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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM