所以我创造了这个数字猜谜游戏。它工作正常,直到需要play_again函数。我环顾四周试图找出如何重新启动程序。我已经在PyCharm IDE中对此进行了测试,它只是以退出代码0退出。实际重启程序的最佳方法是什么,以便在我的rand变量中生成一个新数字?
import os
from random import random
import sys
class Game:
"""
rand is declared by grabbing a number between 0 and 1, multiplying it by 100, and rounding to the nearest integer
guessed is declared as false in order to keep the while loop running until the number is guessed
"""
rand = round(random() * 100, 0)
guessed = False
print("Guess the number [0 - 100]")
# This function handles the number guessing and number formatting
def run_game(self):
# Assigns the 'answer' variable by grabbing user input from console
answer = input()
# Checks if the input from the console is a number, and if not, asks the user to enter a valid number
if answer.isdigit():
n = int(answer)
# Checks the input given against the random number generated
while not self.guessed:
if n > int(self.rand):
print("Number is less than " + str(n))
self.run_game()
elif n < int(self.rand):
print("Number is greater than " + str(n))
self.run_game()
else:
print("You have guessed the correct number!")
self.guessed = True
self.play_again()
else:
print("Please enter a number")
self.run_game()
return
def play_again(self):
reply = input("Play again? (y/n)")
if reply.lower() == "y":
python = sys.executable
os.execl(python, python, *sys.argv)
elif reply.lower() == "n":
print("Thanks for playing!")
else:
self.play_again()
if __name__ == "__main__":
game = Game()
game.run_game()
答案 0 :(得分:3)
您的代码中存在多个错误。最常见的是您使用递归作为循环结构。不要这样做。这是一个介绍bug的好方法,更不用说你的“循环”运行多次,你会达到递归限制。只需使用while
循环:
def run_game(self):
while True:
answer = input()
if answer.isdigit():
n = int(answer)
if n > int(self.rand):
print("Number is less than " + str(n))
elif n < int(self.rand):
print("Number is greater than " + str(n))
else:
print("You have guessed the correct number!")
reply = self.play_again()
if reply is False:
break
else:
print("Please enter a number")
注意修改后的播放器返回一个布尔值,指示用户是否想再次播放。正如我上面所说,你在玩家中犯了同样的错误。不要将递归用作循环,使用显式的while循环:
def play_again(self):
while True:
reply = input("Play again? (y/n)")
if reply.lower() == "y":
return True
elif reply.lower() == "n":
return False
else:
print("Enter 'y' or 'n'")
在不相关的旁注中,我认为没有理由在这里使用课程。您需要跟踪的全局状态或您尝试封装的任何数据。只需使用函数即可实现更清洁:
def run_game():
rand = randint(1, 100)
while True:
answer = input()
if answer.isdigit():
n = int(answer)
if n > rand:
print("Number is less than " + str(n))
elif n < rand:
print("Number is greater than " + str(n))
else:
print("You have guessed the correct number!")
if not play_again():
break
else:
print("Please enter a number")
def play_again():
while True:
reply = input("Play again? (y/n)")
if reply.lower() == "y":
return True
elif reply.lower() == "n":
return False
else:
print("Enter 'y' or 'n'")
if __name__ == "__main__":
print("Guess the number [0 - 100]")
run_game()
以下是我做的其他一些改进:
ranint()
代替randomm()
。由于您有特定的范围,只需使用randint()
。int()
的调用,因为不再需要这些调用。答案 1 :(得分:2)
这是重启游戏的一种非常糟糕的方法,你应该尽可能避免运行exec
。
另一种方法是根据用户输入返回False
或True
,并在函数返回True
时继续运行游戏:
import os
from random import random
import sys
class Game:
"""
rand is declared by grabbing a number between 0 and 1, multiplying it by 100, and rounding to the nearest integer
guessed is declared as false in order to keep the while loop running until the number is guessed
"""
rand = round(random() * 100, 0)
guessed = False
print("Guess the number [0 - 100]")
# This function handles the number guessing and number formatting
def run_game(self):
# Assigns the 'answer' variable by grabbing user input from console
answer = input()
# Checks if the input from the console is a number, and if not, asks the user to enter a valid number
if answer.isdigit():
n = int(answer)
# Checks the input given against the random number generated
while not self.guessed:
if n > int(self.rand):
print("Number is less than " + str(n))
self.run_game()
elif n < int(self.rand):
print("Number is greater than " + str(n))
self.run_game()
else:
print("You have guessed the correct number!")
self.guessed = True
return self.play_again() # Here we run play_again and return its result
else:
print("Please enter a number")
self.run_game()
return
def play_again(self):
reply = input("Play again? (y/n)")
if reply.lower() == "y":
return False # Game isn't finished
elif reply.lower() == "n":
print("Thanks for playing!")
return False # Game is finished
else:
return self.play_again()
if __name__ == "__main__":
game = Game()
game_is_finished = False
while not game_is_finished:
game_is_finished = game.run_game()