0

这是一个基本的游戏,就像石头剪刀布一样,但名称不同,我也为无注释的代码道歉。我的代码快要结束了,但是我在使用 while 循环时遇到了困难。我已经完成了我的所有陈述,但是如何实现一个while循环?我希望游戏在我完成后再次运行,所以它会要求我提供另一个输入。如果我运行它,它正在等待给我一个答案,但从来没有,因为它是一个无限循环。

import random
def pythonRubyJava():
    gameList = ["python","ruby","java"]
    userInput = raw_input("python, ruby, or java?:")
    randomInput = random.choice(gameList)
    print randomInput
    while True:
        if userInput not in gameList:
            print "The game is over"
        elif userInput == randomInput:
            print "stalemate"
        elif userInput == "python" and randomInput == "ruby":
            print "You win!"
        elif userInput == "ruby" and randomInput == "java":
            print "You win!"
        elif userInput == "java" and randomInput == "python":
            print "You win!"        
        elif userInput == "python" and randomInput == "java":
            print "You Lose!"    
        elif userInput == "ruby" and randomInput == "python":
            print "You Lose!"        
        elif userInput == "java" and randomInput == "ruby":
            print "You Lose!"    
4

3 回答 3

3

你应该搬家

userInput = raw_input("python, ruby, or java?:")
randomInput = random.choice(gameList)

while循环内部,以便每次运行循环时重新生成输入。

于 2013-09-26T00:26:10.023 回答
2

不要在函数中使用while循环,只需再次调用该函数!从您的函数中删除 while 循环。

在函数之外,您可以执行以下操作:

pythonRubyJava() # Call the function first
while 1:
    ans = raw_input('Do you want to play again? Y/N ')
    if ans == 'Y':
        pythonRubyJava()
    else:
        print "bye!"
        break # Break out of the while loop.
于 2013-09-26T00:26:18.953 回答
-1
import random
def pythonRubyJava():
    gameList = ["python","ruby","java"]
    userInput = raw_input("python, ruby, or java?:")
    randomInput = random.choice(gameList)

    print randomInput
    while True:
        if userInput not in gameList:
            print "The game is over"
            [change the while boolean statement in here]
        elif userInput == randomInput:
            print "stalemate"
        elif userInput == "python" and randomInput == "ruby":
            print "You win!"
        elif userInput == "ruby" and randomInput == "java":
            print "You win!"
        elif userInput == "java" and randomInput == "python":
            print "You win!"        
        elif userInput == "python" and randomInput == "java":
            print "You Lose!"    
        elif userInput == "ruby" and randomInput == "python":
            print "You Lose!"        
        elif userInput == "java" and randomInput == "ruby":
            print "You Lose!"  

 pythonRubyJava():

这样它会再次运行,并显示结果。

于 2013-09-26T00:44:44.907 回答