0

I'm making a mini python based game where if the game is lost I ask the user to 'rerun the program' to play the game again.

I'm trying to find a more elegant way to achieve this using code. Is there a way I can do this programmatically? It'd require the program to close and reopen, or restart the program and I can manually reset the variable values.

Here's what I've got so far:

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)

Found this online but can't seem to get it to work.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Noobcoder
  • 326
  • 3
  • 14
  • @mkrieger1 quite possibly. Are you suggesting putting my game in a loop and just using sys.exit(0) if the user selects 'n', say? – Noobcoder May 25 '22 at 16:02
  • This might help you as well - https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response – Mortz May 25 '22 at 16:06

1 Answers1

3

You can create a function of the game and run it, like this:

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

Here you create a game loop that calls your function game and when finished if player doesn't want to continue it can end the game, and it ends game loop.

NoNameAv
  • 423
  • 2
  • 14
  • Why do you need the `active` variable when you can just use `break`? – Barmar May 25 '22 at 16:16
  • Breaking out of the loop rather than setting `active = False` is also an option, if you want to avoid running any code after the `active = False` – Mortz May 25 '22 at 16:16
  • Because I think it's bad practice to use break, some people may not think like me but that is my opinion. – NoNameAv May 25 '22 at 16:17
  • This doesn't work. The program bugs out when I put the game inside this function and just call it with game(). Just game() by itself seems to work, but the while loop messes it up – Noobcoder May 25 '22 at 16:17
  • You need to apply this you can't just copy paste – NoNameAv May 25 '22 at 16:17
  • 1
    i got it working. I put the restart inside the game function, and outside of it I just called game() and that seems to have done the trick, thanks. – Noobcoder May 25 '22 at 16:19