我最近开始使用python编程。在我的研究和学习中,我所做的其中一个课程是Code Academy上的简单计数游戏。我对它很感兴趣,并希望扩展它的功能并同时将其用作学习工具。
到目前为止,我已经从中学到了很多东西,但是我此刻已经遇到了一个问题,如果他们想要再次播放,我会尝试让用户提示。我认为最好的方法是将游戏嵌套在循环中,如果他们拒绝,则exit()
。
然而,我遇到的问题是,即使他们再次进入"y"
进行游戏,游戏仍然会退出。我已经考虑过递归地调用main()
,但我已经知道这是一个糟糕的编程习惯,因为它只是叠加你使用它越多。即使是测试它,它也不起作用。
from random import randint
def main():
random_number = randint(1, 10)
play = "y"
while "y" in play:
guesses_left = 3
while guesses_left > 0:
try:
guess = int(raw_input("Guess your number(1 to 10): "))
except ValueError:
print "Enter a valid number"
continue
if guess == random_number:
print "You win!"
play = raw_input("Would you like to play again (y/n): ")
if "n" or "N" in play:
exit()
else:
break
if guess not in range(1, 10):
print "Please enter a number between 1 and 10"
continue
guesses_left -= 1
if guesses_left > 0:
if guess > random_number:
print "That was wrong. Guess a lower number"
continue
if guess < random_number:
print "That was wrong. Guess a higher number"
continue
if guesses_left == 0:
print "You lose! The correct number was %s" % random_number
play_again = raw_input("Would you like to play again?(y/n):")
if "n" or "N" in play:
exit()
else:
break
main()