岩石,纸,剪刀(python 3.3)

时间:2014-02-12 15:51:39

标签: python python-3.x

嗨我正在制作一个石头剪刀游戏,到目前为止我已经制作了以下剧本:

def main():
    from random import randint
    UserChoices = input("'rock', 'paper' or 'scissors'? \n Input: ")
    if UserChoices == "rock":
        UserChoice = 1
    elif UserChoices == "paper":
        UserChoice = 2
    elif UserChoices == "scissors":
        UserChoice = 3
    CpuChoice = randint(1,3) 
    if UserChoice == CpuChoice:
        print("DRAW!")
    elif UserChoice == "1" and CpuChoice== "3":
        print("Rock beats scissors PLAYER WINS!")
        main()
    elif UserChoice == "3" and CpuChoice== "1":
        print("Rock beats scissors CPU WINS")
        main()
    elif UserChoice == "1" and CpuChoice== "2":
        print("Paper beats rock CPU WINS!")
        main()
    elif UserChoice == "2" and CpuChoice== "1":
        print("paper beats rock PLAYER WINS!")
        main()
    elif UserChoice == "2" and CpuChoice== "3":
        print("Scissors beats paper CPU WINS!")
        main()
    elif UserChoice == "3" and CpuChoice== "2":
        print("Scissors beats paper PLAYER WINS!")
        main()
    elif UserChoice == "1" and CpuChoice== "2":
        print("cpu wins")
        main()
    else:
        print("Error: outcome not implemented")
main()

但是当我运行它时,我得到了我犯的错误“错误:结果未实现”有人可以告诉我为什么会这样吗?谢谢。

4 个答案:

答案 0 :(得分:2)

这和所有其他类似的比较:

elif UserChoice == "1" and CpuChoice == "3":

......应该是:

elif UserChoice == 1 and CpuChoice == 3:

换句话说,您应该将intint s进行比较,而不是将int s与正在发生的字符串进行比较。

答案 1 :(得分:2)

用户选择设置为整数,但是将其与字符串进行比较。它应该如下

if userChoice == 1: #Note no quotation marks 

此外,您允许CPU从3个整数中进行选择。但是,它可以节省行数,并且从数组中选择随机数会更有效率

CPU_Moves = ['Rock','Paper','Scissors']
cpuchoice = random.choice(CPUMoves)

这会将cpuchoice设置为数组中的随机数之一,然后您可以在用户输入与cpuchoice的比较中使用它。这意味着您根本不需要设置userChoice,您可以使用用户直接输入的内容。

答案 2 :(得分:1)

如前所述,您最后将字符串与整数进行比较。 避免使用这么多条件是个好主意。这是我写的“紧凑版本”,以防你感兴趣:

from random import randrange

def RPS(user_choice = ''):
    choices = ('rock', 'paper', 'scissors')
    results = ('Draw!', 'You Win!', 'Cpu Wins!')
    while user_choice not in choices:
        user_choice = input("Choose: rock, paper or scissors? ")
    user_num = choices.index(user_choice)
    cpu_num = randrange(3)
    diff = (user_num - cpu_num) % 3
    print("You chose:", user_choice, "-", "Cpu chose:", choices[cpu_num])
    print(results[diff])

RPS('rock')  # User choice can be passed as an argument.

注意如何通过减法和模运算来计算胜利者。这在Rock,paper,剪刀,lizzard,Spock游戏中更有用,你有5个选择而不是3个。

答案 3 :(得分:0)

从if else语句中删除引号。条件是寻找要比较的字符串,而岩石纸和剪刀被指定为整数。这些不是以同样的方式处理。你需要改变你的if elif以便在数字周围没有引号。它打印出DRAW,因为它比较像项目,它给出和错误,因为它不是相同的变量类型。