是否有办法从同一程序内重新运行python程序?



我正在制作一个基于python的迷你游戏,如果游戏输了,我会要求用户"重新运行程序"来再次玩游戏。

我试图找到一个更优雅的方式来实现这使用代码。有一种方法,我可以做到这一点程序化吗?它需要程序关闭并重新打开,或者重新启动程序,我可以手动重置变量值。

这是我到目前为止得到的:

restart = input("nDo you want to restart the program? [y/n] > ")
if restart == "y":
os.execl(sys.executable, os.path.abspath(__file__), *sys.argv)
else:
print("nThe programm will be closed...")
sys.exit(0)

在网上找到了这个,但似乎不能使它工作

你可以创建一个游戏的函数并运行它,像这样:

def game():
print('GAME STUFF')
active = True
while active:
game()
restart = input("n Do you want to restart the program? [y/n] > ")
if restart.lower() == "n":
active = False

这里你创建了一个游戏循环,调用你的函数game,当玩家不想继续时,它可以结束游戏,并结束游戏循环。

最新更新