python - Python 初学者 - 为什么我的 while 循环不起作用?

标签 python while-loop python-3.3

我正在尝试为一项作业编写一个程序,您可以在其中输入特定命令,然后您可以对着计算机玩石头剪刀石头布蜥蜴史波克游戏。 它已经完成并开始工作,直到我意识到作业说明要我做到这一点,以便您继续玩游戏直到一个人获得五场胜利。

所以我想,没什么大不了的,让我们加入一个 while 循环和一些变量来跟踪胜利。但是当我运行程序时,它仍然只运行一次。我不知道我做错了什么 - 因为这应该有效。这是我第一次使用 Python(3.3 版)和这个 IDE,所以我真的需要一些帮助。通常我只是调试,但我不知道如何在这个 IDE 中使用它。

这是我的代码。麻烦的 while 循环在底部。我几乎肯定类里面的一切都有效。我想指出,我已经尝试过 while(computerWins < 5 and userWins < 5),所以我认为条件不是问题所在。

import random

computerWins = 0
userWins = 0
print ('SELECTION KEY:\nRock = r\nPaper = p\nScissors = sc\nLizard = l\nSpock = sp')

class rockPaperScissorsLizardSpock:
#Two methods for converting from strings to numbers

    #convert name to number using if/elif/else
    #also converts abbreviated versions of the name
    def convertName(name):
        if(name == 'rock' or name == 'r'):
            return 0
        elif(name == 'Spock' or name == 'sp'):
            return 1
        elif(name == 'paper' or name == 'p'):
            return 2
        elif(name == 'lizard' or name == 'l'):
            return 3
        elif(name == 'scissors' or name == 'sc'):
            return 4
        else:
            print ('Error: Invalid name')

    #convert number to a name using if/elif/else
    def convertNum(number):
        if(number == 0):
            return 'rock'
        elif(number == 1):
            return 'Spock'
        elif(number == 2):
            return 'paper'
        elif(number == 3):
            return 'lizard'
        elif(number == 4):
            return 'scissors'
        else:
            print ('Error: Invalid number')

    #User selects an option, and their selection is saved in the 'choice' variable    
    #Using a while loop so that the user cannot input something other than one of the legal options
    prompt = True
    while(prompt):
        i = input('\nEnter your selection: ')
        if(i=='r' or i=='p' or i=='sc' or i=='l' or i=='sp'):
            prompt = False
        else:
            print('Invalid input.')
    prompt = True

    #Convert the user's selection first to a number and then to its full string
    userNum = convertName(i)
    userChoice = convertNum(userNum)

    #Generate random guess for the computer's choice using random.randrange()
    compNum = random.randrange(0, 4)

    #Convert the computer's choice to a string
    compChoice = convertNum(compNum)

    print ('You chose', userChoice)
    print ('The computer has chosen', compChoice)

    #Determine the difference between the players' number selections
    difference = (compNum - userNum) % 5

    #Use 'difference' to determine who the winner of the round is
    if(difference == 1 or difference == 2):
        print ('The computer wins this round.')
        computerWins = computerWins+1
    elif (difference == 4 or difference == 3):
        print ('You win this round!')
        userWins = userWins+1
    elif(difference == 0):
        print ('This round ended up being a tie.')

#Plays the game until someone has won five times
while(computerWins != 5 and userWins != 5):
    rockPaperScissorsLizardSpock()

if(computerWins == 5 and userWins != 5):
    print ('The computer wins.')
elif(computerWins != 5 and userWins == 5):
    print ('You win!')

最佳答案

本质问题是rockpaperscissorslizardspock是一个,您希望它是一个函数。当整个类定义被解析时,其中的代码只运行一次,而不是像您预期的那样在每次调用该类时运行。

可以将相关代码放入 __init__ 中方法 - 这是 Java 构造函数的相当直接的模拟,因此每次调用该类时 都会运行。但在这种情况下,您可能根本不需要它在一个类中 - 调用该类会创建一个新实例(就像在 Java 中执行 new MyClass()),您不会使用它。在这种情况下(或者如果您将其变成一个函数)您还需要进行更多修改以确保游戏状态正确持续。

最简单的实际解决方案是:

  1. 删除行class rockpaperscissorslizardspock: (并取消缩进它下面的所有内容)
  2. 获取类下但不在函数中的所有代码——从玩家做出选择到确定回合获胜者的所有代码——并将其粘贴到对 rockpaperscissorslizardspock() 的调用处在底部循环中。

关于python - Python 初学者 - 为什么我的 while 循环不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29158536/

相关文章:

Java 列出不同的名称

c++ - 用 while 循环替换 for 循环时我做错了什么?

Python 查找字符串是否是彼此字符串的变位词

Python 3.3 HTTP Cookie 错误

python - 为什么连接字符串比连接它们运行得更快?

python - 像素/数组位置到 lat long gdal Python

python - 如何在没有 root 权限的机器上安装 virtualenv

python - 动态创建静态变量(枚举 hack)

python - Django 和 Ajax

python - 如何使用包 url 来 pip 列表