From eeb100e485208757a025cc2b220a144f358a5c00 Mon Sep 17 00:00:00 2001 From: waldek Date: Thu, 28 Oct 2021 11:35:48 +0200 Subject: [PATCH] adds textbased game code --- learning_python3.md | 53 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/learning_python3.md b/learning_python3.md index 0657c65..d939a94 100644 --- a/learning_python3.md +++ b/learning_python3.md @@ -411,8 +411,61 @@ else: # A text based adventure game +We can use conditional logic to create quite elaborate decision processes. +Let's build a mini text based adventure game. +Granted it's not a *tripple A* game but it will train your `if` and `else` skills plus it will highlight some issues we'll overcome in the next section. +Consider the diagram below. + ![adventure game](./assets/text_based_adventure_game.png) +```python3 +answer = input("You're at a cross section. Do you go left or right?") +if answer.startswith("l"): + answer = input("Down this hall you encounter a bear. Do you fight it?") + if answer.startswith("y"): + print("The bear counter attack! He kills you") + print("game over!") + exit(0) + elif answer.startswith("n"): + print("It's a friendly bear! He transforms into a wizard!") + answer = input("The wizard asks you if you know the meaning of life?") + if answer == "42": + print("He knods approuvingly and upgrades you to wizard status!") + print("You win!") + exit(0) + else: + print("He shakes his head in disbelief. You fool!") + print("game over!") + else: + print("that's not a valid choice...") + print("game over!") + exit(0) +elif answer.startswith("r"): + answer = input("Down this hall you find some mushrooms. Do you eat them?") + if answer.startswith("n"): + print("You starve to dead...") + print("game over!") + exit(0) + elif answer.startswith("y"): + print("A wizard apprears out of thin air!") + answer = input("The wizard asks you if you know the meaning of life?") + if answer == "42": + print("He knods approuvingly and upgrades you to wizard status!") + print("You win!") + exit(0) + else: + print("He shakes his head in disbelief. You fool!") + print("game over!") + else: + print("that's not a valid choice...") + print("game over!") + exit(0) + pass +else: + print("game over!") + exit(0) +``` + # Creating your own functions ## Functions that *do* something