**Question** Ending a Game

Question: How do I end a game only in certain scenario’s?

You need to be more specific. Please tell us what programming language you are using and preferably provide the link to the Repl or a code snippet.

1 Like

Ok, I’m doing Python and the code snippet is this:
print(‘The creature rips off your head and you die. Please restart the game.’)
END

1 Like

There are many ways to do this:

exit()
quit()
import sys
sys.exit()

And even more.

2 Likes

Basically you want the game to be in a loop. You can add multiple criteria. Without seeing your code, I can only give you basic examples. Also your message for losers is a little, um, gruesome.

Here the game is a while loop which is broken by a wrong answer.

while True:
  choice = input("yes or no\n")
  if choice == "yes":
    print("yay")
  else:
    print("You lose.")
    break # break ends the loop

Here the game is a function which loops itself if the answer is correct.

def main():
  choice = input("yes or no?\n")
  if choice == "yes":
    print("yay")
    main() # this puts user in a loop. Execute a different function if you'd like
  else:
    print("You lose.")
main()

Here the game is a while loop which is broken by a wrong answer.

while input("yes or no?\n") == "yes":
  print("yay")
print("You lose.") # This only goes after while loop is broken

You can use quit(), exit(), if you want a custom end message in red you can use

raise SystemError(“I’m ending this code”)

Or other errors if you want, just remember to set sys.tracebacklimit = 0 if you don’t want a huge traceback to pop out

2 Likes