剪刀石头布分数不断重置

时间:2019-05-27 21:53:37

标签: python

我正在用指针系统制作石头,纸,剪刀的游戏,每次显示分数时,总是给我零值。感谢您的帮助。---------------------------------------------- -------------------------------------------------- -------------------------------------------------- -----------

def play():
    player = input("Which will you choose? Rock, Paper or Scissors? Type 'E' to exit ")

    elements = ['rock', 'paper', 'scissors']

    cpu = random.choice(elements)

    scoreplayer = 0

    scorecpu = 0 

    if player.lower() == cpu:
        print("This is a tie, no one scores a point")
        play()

    elif player.lower() == "rock":
        if cpu == "paper":
            print("Paper beats Rock, CPU gains 1 point")
            scorecpu = scorecpu + 1
            play()
        elif cpu == "scissors":
            print("Rock beats Scissors, you gain 1 point")
            scoreplayer = scoreplayer + 1
            play()

    elif player.lower() == "paper":
        if cpu == "scissors":
            print("Scissors beats Paper, CPU gains 1 point")
            scorecpu = scorecpu + 1
            play()
        elif cpu == "rock":
            print("Paper Beats Rock, you gain 1 point")
            scoreplayer = scoreplayer + 1
            play()

    elif player == "scissors":
        if cpu == "rock":
            print("Rock beats Scissors, CPU gains 1 point")
            scorecpu = scorecpu + 1
            play()
        elif cpu == "paper":
            print("Scissors beats Paper, you gain 1 point")
            scoreplayer = scoreplayer + 1
            play()

    elif player.lower() == "e":
        print("")
        print("You have " + str(scoreplayer) + " points")
        print("")
        print("CPU has " + str(scorecpu) + " points")
        sys.exit()

    else:
        play()

3 个答案:

答案 0 :(得分:2)

scoreplayer = 0和其他分配在每次调用play时运行,这每次都会创建值为0的新变量。将当前分数作为参数传递给play

def play(scoreplayer, scorecpu):
   # Get rid of these lines
   # scoreplayer = 0
   # scorecpu = 0 

   . . .
   # Update the scores here

   else:
        play(scoreplayer, scorecpu)


play(0, 0) # Start with scores of 0

或者从递归切换到使用类似while的循环结构,并在循环中更新得分。在像Python这样的语言中,递归在此并不适合。

答案 1 :(得分:0)

由于要在函数中设置变量,因此每次运行时都会按定义重置。就像@Carcigenicate所说的那样,您可以将它们作为参数传递给它,或者 使用while循环,但您可能还需要研究一下全局语句。

答案 2 :(得分:0)

如上所述,您每次调用play()函数都将重置乐谱。 解决您的问题的方法是使您的得分变量成为全局变量

scoreplayer = 0
scorecpu = 0 

def play():
    player = input("Which will you choose? Rock, Paper or Scissors? Type 'E' to exit ")

    elements = ['rock', 'paper', 'scissors']

    cpu = random.choice(elements)

    global scoreplayer
    global scorecpu

    # rest of your code

play()

在函数外定义变量时,我们可以使用全局关键字访问它们

您可以在此处了解有关全局关键字的更多信息:https://www.programiz.com/python-programming/global-keyword