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

时间:2015-03-20 02:45:18

标签: python while-loop python-3.3

我正在尝试为你输入特定命令的作业编写一个程序,你可以在计算机上玩Rock-Paper-Scissors-Lizard-Spock。 它完成并工作,直到我意识到任务指令要求我做到这一点,以便你继续玩游戏,直到一个人获得五次胜利。

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

这是我的代码。麻烦的while循环处于最底层。我几乎肯定了班级内部的一切工作。我想注意我已经尝试过(computerWins< 5和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!')

3 个答案:

答案 0 :(得分:3)

基本问题是rockpaperscissorslizardspock,您希望它是一个函数。当解析整个类定义时,它内部的代码只运行一次,而不是每次按照您的预期调用类时。

可以将相关代码放入__init__方法 - 这是Java构造函数的一个相当直接的模拟,因此每次运行 你打电话给全班。但是在这种情况下,你可能根本不需要它在一个类中 - 调用该类创建一个新实例(比如在Java中执行new MyClass()),你不使用它。在这种情况下(或者如果你把它变成一个函数)你也需要做一些更改,以确保游戏状态保持正常。

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

  1. 删除第class rockpaperscissorslizardspock:行(并在其下方取消所有内容)
  2. 获取课程下但不在函数中的所有代码 - 播放器中的所有内容都会选择确定该轮次的获胜者 - 并将其粘贴到底部rockpaperscissorslizardspock()的调用位置循环。

答案 1 :(得分:1)

第一件事是你正在使用一个你应该使用函数的类。

您的代码最初运行是因为python正在加载该类。

但是,行rockPaperScissorsLizardSpock()正在创建类的新匿名实例,它会调用您尚未定义的构造函数,因此它不执行任何操作。

关于python的一个有趣的事情是它允许嵌套函数,所以如果你将class更改为def,那么你几乎就在那里。

之后,您将在本地环境中遇到全局变量问题。该问题已在另一个StackOverflow问题中解释:Using global variables in a function other than the one that created them

答案 2 :(得分:1)

这是我对骨架提出更简单解决方案的建议。如果您愿意,请使用此处的一些想法。

import random

legal_shapes = ['r', 'p', 'sc', 'sp', 'l']
scoreboard = [0, 0]
print('SELECTION KEY:\nRock = r\nPaper = p\nScissors = sc\nLizard = l\n'
      'Spock = sp')

while(max(scoreboard) < 5):

    print("\nScore is {}-{}".format(*scoreboard))

    # pick shapes
    p1_shape = input('Enter your selection: ')
    if p1_shape not in legal_shapes:
        print('Not legal selection!')
        continue
    p2_shape = random.choice(legal_shapes)
    print('\np1 plays {} and p2 plays {}'.format(
        p1_shape.upper(), p2_shape.upper()))

    # determine int values and result indicator
    p1_shape_int = legal_shapes.index(p1_shape)
    p2_shape_int = legal_shapes.index(p2_shape)
    res = (p1_shape_int - p2_shape_int) % 5
    if res != 0:
        res = abs((res % 2) - 2)

    # Print winner
    if res == 0:
        print(' -> Draw!!')
    else:
        print(' -> p{} wins'.format(res))
        scoreboard[res-1] += 1

print("\nThe game is over!!")
print("p{} won with score {}-{}".format(res, *scoreboard))

输出类似

的内容
(env)➜ tmp python3 rsp.py
SELECTION KEY:
Rock = r
Paper = p
Scissors = sc
Lizard = l
Spock = sp

Score is 0-0
Enter your selection: T
Not legal selection!

Score is 0-0
Enter your selection: l

p1 plays L and p2 plays SP
 -> p2 wins

Score is 0-1
Enter your selection: l

p1 plays L and p2 plays SC
 -> p2 wins

...

The game is over!!
p2 won with score 2-5