这是一个基本的游戏,就像石头剪刀布一样,但名称不同,我也为无注释的代码道歉。 我快要完成代码了,但是我在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!"
你应该移动
userInput = raw_input("python, ruby, or java?:")
randomInput = random.choice(gameList)
在while
循环内,以便每次运行循环时重新生成输入。
不要在函数中使用 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.
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():
这样它将再次运行,并显示结果。