简单的程序岩石纸剪刀,而循环

时间:2013-09-26 00:23:23

标签: python

这是一个基本的游戏,就像摇滚剪刀一样,但名字不同,我也为无评论的代码道歉。我几乎要到达我的代码的末尾,但是我在使用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!"    

3 个答案:

答案 0 :(得分:3)

你应该移动

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

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

答案 1 :(得分: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.

答案 2 :(得分:-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():

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