首页 > 解决方案 > Python乘法游戏。我的脚本需要有任意数量的玩家,每个玩家都必须轮流回答一个乘法问题

问题描述

基本上我需要制作一个游戏im python,它可以让任意数量的人交替回答一个乘法问题。但我的问题是我不知道如何让它保持运行,直到我达到 30 分。我尝试使用字典,其中键是玩家姓名,值是分数。但它在脚本只运行一次后停止。我尝试了一个while循环,但它一直持续下去。请帮忙!

import random as r

n = int(input("Insert number of players: "))
d = {}

for i in range(n):
    keys = input("Insert player name: ")
#to set the score to 0
    values = 0
    d[keys] = values
#to display player names
print("Player names are:")
for key in d:
    print(key)

for value in d.values():
    if value < 30:
        random1 = r.randint(0,9)
        random2 = r.randint(0,9)
        
        print(f"The two numbers you should multiplie is {random1} and {random2}")

        correct = random1*random2
        user_inp = input("Insert answer: ")
        user_inp = int(user_inp)
        if user_inp == correct:
            print("Correct!")
            d[keys] += 1
        else:
            print("Wrong!")
            d[keys] -= 2
    else:
        break

标签: python-3.xdictionaryfor-loopwhile-loop

解决方案


我认为这会奏效

    winner = False
    while not winner :
        for value in d.values():
            if value < 30:
                random1 = r.randint(0,9)
                random2 = r.randint(0,9)
                
                print(f"The two numbers you should multiplie is {random1} and {random2}")
    
                correct = random1*random2
                user_inp = input("Insert answer: ")
                user_inp = int(user_inp)
                if user_inp == correct:
                    print("Correct!")
                    d[keys] += 1
                else:
                    print("Wrong!")
                    d[keys] -= 2
            else:
                winner = True
                break

推荐阅读