Python Rock Paper Scissors游戏

时间:2018-11-14 23:58:38

标签: python

我正在学习编程课程,并且被分配了“ Rock,Paper Scissors”游戏来写作。指导者规定,这些函数的名称应与我拥有的相同,并且如果不关闭程序就无法结束游戏循环。出于某种原因,当我运行此代码时,系统会告诉我未定义“随机数”。我究竟做错了什么?谢谢

import random
keepgoing = 1

def main():
    get_computermove()
    get_playermove()
    calculatewinner()

def get_computermove():
    computermove = random.randint(1, 3)
    randomnumber = computermove
    return randomnumber

def get_playermove():
    playermove = input('Please pick rock, paper, or scissors. ')
    return playermove

def calculatewinner():
    if randomumber == 1 and playermove == "rock":
        print('It is a tie!')
    elif randomnumber == 2 and playermove == "paper":
        print('It is a tie!')
    elif randomnumber == 3 and playermove == "scissors":
        print('It is a tie!')
    elif randomnumber == "1" and playermove == "Paper":
        print('Paper covers rock. You win!')
    elif randomnumber == "1" and playermove == "scissors":
        print('Rock breaks scissors. You lose.')
    elif randomnumber == "2" and playermove == "Rock":
        print('Paper covers rock. You lose.')
    elif randomnumber == "2" and playermove == "Scissors":
        print('Scissors cuts paper. You win!')
    elif randomnumber == "3" and playermove == "Rock":
        print('Rock breaks scissors. You win!')
    elif randomnumber == "3" and playermove == "Paper":
        print('Scissors cuts paper. You lose.')

while keepgoing == 1:
    main()

2 个答案:

答案 0 :(得分:0)

您已经创建了两个randomnumber变量:一个在get_computermove内部,另一个在calculate_winner内部。第二个没有定义值。离开该功能后,第一个消失。相反,请尝试以下操作:保存每个函数的返回值,然后将它们传递到最终例程中。

def main():
    computermove = get_computermove()
    playermove = get_playermove()
    calculatewinner(computermove, playermove)

...
def calculatewinner(randomnumber, playermove):

使用变量名可以做得更好,但这应该使其余代码保持完整。

答案 1 :(得分:0)

这是解决此问题的好方法,但是您需要知道,Python中返回的任何内容都不会存储为全局变量,除非您明确地这样做。每当调用get_computermove()函数时,它都会返回一个“随机数”,但是由于您没有将其存储在任何地方,它会丢失。另外,您还需要将其作为其中一个参数传递给calculatewinner()函数,以便在函数内部对其进行访问。

请注意,代码的第一行拼写了“ randomnumber”。