Howdy folks welcome to another fun tutorial! In this tutorial, you will learn how to make a text-based choose your own adventure game in python3 using functions. This tutorial is intended for beginners in python, if you are a python beginner then take this tutorial.

You can download the final complete project code here from my Github repo - https://github.com/the-coding-pie/text-based-adventure-game-python

Now, without further ado, let's get started...

The Game Plan

As I said we are going to build a text-based choose your own adventure game. This is how the game works:

game map showing all the rooms

By the way, some part of the game story is taken from the book Learn Python The Hard Way written by Zed Shaw because I suck at storytelling 😂.

Now as you can see above in the game map, we first start the game. Then tell the player a story like "You are standing in a dark room. There is a door to your left and right, which one do you take? (l or r)". If the player types "l", then we lead him to the bear_room, or if he/she types "r", then we lead him to the monster_room like that. 

You can easily guess how the game works by looking at the map alone. To build this game in python, we need to take the input() from the user after showing some prompts like "you are in a _ room". Then lead the player according to his inputs. To make our work again simple, we are going to use functions in python3.

See its simple!

What you will learn?

By doing this simple project, you will learn the following

  • How to work with functions in python3.
  • How to take input().
  • How to print() output.
  • ifelifelse statements.
  • == equality operator.
  • lower() function to convert the string into a lower case.
  • And much much more.

Things you will need

  • The very first thing you will need is the python itself. I am going to use python3. You can read this post to learn how to setup python3 on any operating system - https://realpython.com/installing-python/
  • After setting up python3, you will need a modern code editor like visual studio code. Yes, of course, you can do this simple project inside the default python IDLE or things like that, but the benefit of using a modern code editor like visual studio code is that it comes pre-baked with all the things you will ever need during your programming journey. It has a pre-built terminal, Integrated Git, debugging tools, extensions, and much much more. And more than anything else, it is completely free and open-source. 

You can download visual studio code from here according to your Operating system - https://code.visualstudio.com/download.

With these things set up, now you are good to go.

Getting Started

  • Create a folder named Text Based Adventure anywhere on your computer.
  • Now just open visual studio code.
  •  Then inside visual studio code, click on File > Open Folder and choose the folder you created Text Based Adventure.
  • Now click on this icon (like below) to create a new file and name it as adventure.py:

new file creating icon in visual studio code

  • Now you will have something similar to this:

new file now created

That's it now you are good to write the python code.

Wait What are functions?

This part is for people who don't know the concept of functions in programming. If you are familiar with the concept of functions, then feel free to skip this part. We are not going to start making the game in this section though. 

If you are an absolute beginner to programming, then you may ask what is a function? If I give a formal definition, then it may bore you. So I am going to teach it in a practical way!

Now Imagine you have a cake-making robot! For the robot to make a cake, you should give certain commands. And assume that the following codes are those "certain commands". If you want to type this, feel free to do so inside the adventure.py file we just created:

print("Mix Ingredients for one cake")
print("Add Vanilla flavor")
print("Bake the cake")
print("Serve the cake")

 For the sake of simplicity, let's assume if we call the print() function, the robot will do that thing 😅.

Ok, by using the above commands, the robot will make only one cake of vanilla flavor, right? What would you do if you want 5 cakes?

You can do like this:

print("Mix Ingredients for one cake")
print("Add Vanilla flavor")
print("Bake the cake")
print("Serve the cake")

print("Mix Ingredients for one cake")
print("Add Vanilla flavor")
print("Bake the cake")
print("Serve the cake")

print("Mix Ingredients for one cake")
print("Add Vanilla flavor")
print("Bake the cake")
print("Serve the cake")

print("Mix Ingredients for one cake")
print("Add Vanilla flavor")
print("Bake the cake")
print("Serve the cake")
​
print("Mix Ingredients for one cake")
print("Add Vanilla flavor")
print("Bake the cake")
print("Serve the cake")

By seeing this alone you would agree that this is not the proper way to do it. So what we are going to do is that we are going to extract the pieces of code that needs repetition and put it under a particular name like below:

def make_cake():
  print("Mix Ingredients for one cake")
  print("Add Vanilla flavor")
  print("Bake the cake")
  print("Serve the cake")

This is what's called a function. To define a function in python, we use the def keyword, and following that we give the name of our function and the brackets - (). Then after semicolumn(:), we give the function body from the next line with indentation

Now if we want 5 cakes, then you don't have to hard code them. Instead, you can call the name of the function 5 times!

def make_cake():
  print("Mix Ingredients for one cake")
  print("Add Vanilla flavor")
  print("Bake the cake")
  print("Serve the cake")

make_cake()
make_cake()
make_cake()
make_cake()
make_cake()

But now you may say that we can do this exact thing using loops then why should I do it using a function?

That's a great question! Yes, we may have done it using loops, but here's the tricky part. What would you do if you want 5 cakes with 5 different flavors like vanilla, chocolate, orange, banana, and strawberry

If you are using functions, then you can easily do it like this:

def make_cake(flavor):
  print("Mix Ingredients for one cake")
  print("Add " + flavor + " flavor")
  print("Bake the cake")
  print("Serve the cake")

make_cake("vanilla")
make_cake("chocolate")
make_cake("orange")
make_cake("banana")
make_cake("strawberry")

The thing inside the brackets is what's called an argument. At the time of calling the function make_cake(), we can supply that argument like make_cake(argument). Then we can use it inside the function body where ever you want.

argument in function

making use of the argument inside function body

And of course, you can give more than one argument like this - make_cake(flavor, baking_time, something_else, something_else).

Phew, that was a lot. Now you understand what is a function, and how to create it, and many more things. So let's start working on our game. Just clear whatever you typed up to this point inside the adventure.py file and make it blank.

The Game

We are going to make our game according to the game map:

game map showing all the rooms

If you take a look at it, you can see there are so many boxes. Think of each box as a room and also as a function except the win box. So let's start by creating a function called start().

Type the following code inside the adventure.py file:

def start():
  # give some prompts.
  print("\nYou are standing in a dark room.")
  print("There is a door to your left and right, which one do you take? (l or r)")
  
  # convert the player's input() to lower_case
  answer = input(">").lower()

  if "l" in answer:
    # if player typed "left" or "l" lead him to bear_room()
    bear_room()
  elif "r" in answer:
    # else if player typed "right" or "r" lead him to monster_room()
    monster_room()
  else:
    # else call game_over() function with the "reason" argument
    game_over("Don't you know how to type something properly?")


# start the game
start()
  • Consider the start() function as the beginning of the game. First, we are prompting the player where he/she is currently standing and what are the options available to him/her.
  • After that, we take the input() whatever the player types and convert it into a lower() case string.
  • Then check if "l" is in the player's input. If the player typed "left" or "l", lead him to the bear_room(). It is another function which we will create in a bit.
  • If the player typed "right" or "r", lead him to the monster_room().
  • Else, if the player typed something else, call game_over() function with an argument called reason. We have to call this game_over() function in so many places whenever the player's game is over. The reason may be different in each situation. That's why we have to take it as an argument.
  • Finally at the very bottom, activate the start() function to begin the game.

We are not going to run this game yet. If we do so, we will get a bunch of errors. Because we have only called the bear_room(), monster_room(), and game_over() functions but haven't created it yet.

So we will create all the functions needed first, then only we are going to run this game.

Now let's create the bear_room(). Type the following code above the start() function definition:

# bear room
def bear_room():
  # give some prompts
  # '\n' is to print the line in a new line
  print("\nThere is a bear here.")
  print("Behind the bear is another door.")
  print("The bear is eating tasty honey!")
  print("What would you do? (1 or 2)")
  print("1). Take the honey.")
  print("2). Taunt the bear.")

  # take input()
  answer = input(">")
  
  if answer == "1":
    # the player is dead!
    game_over("The bear killed you.")
  elif answer == "2":
    # lead him to the diamond_room()
    print("\nYour Good time, the bear moved from the door. You can go through it now!")
    diamond_room()
  else:
    # else call game_over() function with the "reason" argument
    game_over("Don't you know how to type a number?")
  • It's pretty self-explanatory. First, we are giving some messages to the player to describe the current situation.
  • Then we take the player's choice as input().
  • Then we check if the player typed "1" or "2" or anything else.
  • If he/she typed "1", then the game is over. So call the game_over().
  • Else if he/she typed "2", lead them to the diamond_room(). We have to create it too.
  • Else, call the game_over().

Now the bear_room() is ready, let's head towards creating the monster_room(), diamond_room(), and the game_over().

Type the following code above bear_room() function. The following function is for creating the monster room:

# monster room
def monster_room():
  # some prompts
  # '\n' is to print the line in a new line
  print("\nNow you entered the room of a monster!")
  print("The monster is sleeping.\nBehind the monster, there is another door. What would you do? (1 or 2)")
  print("1). Go through the door silently.")
  print("2). Kill the monster and show your courage!")

  # take input()
  answer = input(">")

  if answer == "1":
    # lead him to the diamond_room()
    diamond_room()
  elif answer == "2":
    # the player is dead, call game_over() with "reason"
    game_over("The monster was hungry, he/it ate you.")
  else:
    # game_over() with "reason"
    game_over("Go and learn how to type a number.")

Pretty self-explanatory. I think no explanation is needed here. Just read it!

Now let's create the diamond_room(). Type this above the previous function:

# diamond room
def diamond_room():
  # some prompts
  print("\nYou are now in a room filled with diamonds!")
  print("And there is a door too!")
  print("What would you do? (1 or 2)")
  print("1). Take some diamonds and go through the door.")
  print("2). Just go through the door.")

  # take input()
  answer = input(">")
  
  if answer == "1":
    # the player is dead, call game_over() function with the "reason"
    game_over("They were cursed diamonds! The moment you touched it, the building collapsed, and you die!")
  elif answer == "2":
    # the player won the game
    print("\nNice, you're are an honest man! Congrats you win the game!")
    # activate play_again() function
    play_again()
  else:
    # call game_over() with "reason"
    game_over("Go and learn how to type a number.")
  • In the above function, besides the common things, there is another function called play_again(). If the player had won the game, or if his/her game is over, then we have to ask them if he/she wants to play again or not. That's what this play_again() will do. We will create it after creating the game_over() function. We can create it now though, but I am going in order. Again order has no significance here though.

Now create the game_over() function above the previous function:

# game_over function accepts an argument called "reason"
def game_over(reason):
  # print the "reason" in a new line (\n)
  print("\n" + reason)
  print("Game Over!")
  # ask player to play again or not by activating play_again() function
  play_again()
  • See this has that play_again() function too.

Finally create the play_again() function above the game_over() function:

# function to ask play again or not
def play_again():
  print("\nDo you want to play again? (y or n)")
  
  # convert the player's input to lower_case
  answer = input(">").lower()

  if "y" in answer:
    # if player typed "yes" or "y" start the game from the beginning
    start()
  else:
    # if user types anything besides "yes" or "y", exit() the program
    exit()

Again it is self-explanatory!

Now that's it you have just created an awesome yet simple text-based choose your own adventure game in python3 using functions!

Hooray, It's time to run the game! But before that just make sure whatever you have typed up to this point inside the adventure.py file is exactly like the following:

# function to ask play again or not
def play_again():
  print("\nDo you want to play again? (y or n)")
  
  # convert the player's input to lower_case
  answer = input(">").lower()

  if "y" in answer:
    # if player typed "yes" or "y" start the game from the beginning
    start()
  else:
    # if user types anything besides "yes" or "y", exit() the program
    exit()

# game_over function accepts an argument called "reason"
def game_over(reason):
  # print the "reason" in a new line (\n)
  print("\n" + reason)
  print("Game Over!")
  # ask player to play again or not by activating play_again() function
  play_again()

# diamond room
def diamond_room():
  # some prompts
  print("\nYou are now in a room filled with diamonds!")
  print("And there is a door too!")
  print("What would you do? (1 or 2)")
  print("1). Take some diamonds and go through the door.")
  print("2). Just go through the door.")

  # take input()
  answer = input(">")
  
  if answer == "1":
    # the player is dead, call game_over() function with the "reason"
    game_over("They were cursed diamonds! The moment you touched it, the building collapsed, and you die!")
  elif answer == "2":
    # the player won the game
    print("\nNice, you're are an honest man! Congrats you win the game!")
    # activate play_again() function
    play_again()
  else:
    # call game_over() with "reason"
    game_over("Go and learn how to type a number.")

# monster room
def monster_room():
  # some prompts
  # '\n' is to print the line in a new line
  print("\nNow you entered the room of a monster!")
  print("The monster is sleeping.\nBehind the monster, there is another door. What would you do? (1 or 2)")
  print("1). Go through the door silently.")
  print("2). Kill the monster and show your courage!")

  # take input()
  answer = input(">")

  if answer == "1":
    # lead him to the diamond_room()
    diamond_room()
  elif answer == "2":
    # the player is dead, call game_over() with "reason"
    game_over("The monster was hungry, he/it ate you.")
  else:
    # game_over() with "reason"
    game_over("Go and learn how to type a number.")

# bear room
def bear_room():
  # give some prompts
  # '\n' is to print the line in a new line
  print("\nThere is a bear here.")
  print("Behind the bear is another door.")
  print("The bear is eating tasty honey!")
  print("What would you do? (1 or 2)")
  print("1). Take the honey.")
  print("2). Taunt the bear.")

  # take input()
  answer = input(">")
  
  if answer == "1":
    # the player is dead!
    game_over("The bear killed you.")
  elif answer == "2":
    # lead him to the diamond_room()
    print("\nYour Good time, the bear moved from the door. You can go through it now!")
    diamond_room()
  else:
    # else call game_over() function with the "reason" argument
    game_over("Don't you know how to type a number?")

def start():
  # give some prompts.
  print("\nYou are standing in a dark room.")
  print("There is a door to your left and right, which one do you take? (l or r)")
  
  # convert the player's input() to lower_case
  answer = input(">").lower()

  if "l" in answer:
    # if player typed "left" or "l" lead him to bear_room()
    bear_room()
  elif "r" in answer:
    # else if player typed "right" or "r" lead him to monster_room()
    monster_room()
  else:
    # else call game_over() function with the "reason" argument
    game_over("Don't you know how to type something properly?")


# start the game
start()

Playing the Game in CLI

CLI which stands for Command Line Interface or the classic terminal window is where we are going to run our game.

To run this python program in the terminal, do the following:

  • From within visual studio code, click on the Terminal > New Terminal:

steps to open the terminal window inside visual studio code code editor

  • Now a terminal will pop up at the bottom. In that terminal, enter the following code and hit the Enter key:
python3 adventure.py
  • If you named your file something else, then instead of typing adventure.py in the above code please type your file name.

This is my output which I got:

final output which i got in my terminal window

Wrapping Up

I hope you enjoyed this tutorial. In some places, I intentionally skipped the explanation part. Because those codes were simple and self-explanatory. That's why I left it to you to decode it on your own.

True learning takes place when you try things on your own. By simply following a tutorial won't make you a better programmer. You have to use your brain. Tutorials are made to only kickstart your journey. The rest is in your hands. Keep trying new things and never stop learning. 

If you have any doubts, then please comment them below. Thank you ;)