如何在游戏中添加分数?

时间:2013-11-16 11:49:11

标签: python random

我想知道如何在这场比赛中加分? 我不明白如何添加一个分数,每当有人得到一个问题时,该分数就会增加一个。我尝试了很多方法,但是我不明白我是怎么做到的,所以我想知道是否有人可以帮助我,所以我可以在学校的计算机科学课上使用这个游戏。

import random
import time

name = input("What is your name? \n")
print(name, "Would you like to add or mulitply the questions?")

def main():
    num_1 = random.randint(1,100)
    num_2 = random.randint(1,100)
    answer = int(num_1) + int(num_2)
    answer_1 = int(num_1) * int(num_2)
    start = input("A - Add      B - Multiply      OR type STOP to get your score\n")
    start_n = start.upper()
    print(start_n)
    if start_n == "A":
        print("Add, " + str(num_1) + " and " + str(num_2))
        ans = input(">>> ")
        if int(ans) == int(answer):
            print("Well done, keep going!")
            main()
        else:
            print("Incorrect, but keep going!")
            print(answer)
            main()
    elif start_n == "B":
        print("Multiply, " + str(num_1) + " and " + str(num_2))
        ans = input(">>> ")
        if int(ans) == int(answer_1):
            print("Well done, keep going!")
            main()
        else:
            print("Incorrect, but keep going!")
            print(answer_1)
            main()
    elif start_n == "STOP":
        print(name + ", you got a score of - " + )
    else:
        print("Please only enter A or B")
        main()
main()

2 个答案:

答案 0 :(得分:0)

使用您当前的代码,解决方案是将当前分数作为参数传递给main(),但是......

你真的不应该像那样递归地调用main()函数 最好只使用这样的while循环:

def main():
    score = 0
    while True:
        # ask the questions and stuff
        if correct:
            score += 1
        # do other stuff
        if stop_condition:
            break
    print(name, ', you got a score of -', score)

答案 1 :(得分:0)

我同意@stranac的做法,并建议你遵循他的建议。

但是,如果添加以下内容,它也应该有效:

添加

scrore = 0
def main():之前

然后,将标记的行添加到以下代码段:

if int(ans) == int(answer):
            print("Well done, keep going!")
            global score    ## score is global
            score += 1      ## increment by one if answer is correct
            main()

最后

print(name + ", you got a score of - "+ str(score) )