Python Game Design: Choose Your Own Adventure
Algorithms and Programming

Python Game Design: Choose Your Own Adventure

Grades 3–8
2 hr 7 min
11 steps
CSTA

Standards Alignment

CSTA

  • 1B-AP-10: Create programs that include sequences, events, loops, and conditionals.
  • 2-AP-10: Use flowcharts and/or pseudocode to address complex problems as algorithms.
  • 2-AP-12: Design and iteratively develop programs that combine control structures, including nested loops and compound conditionals.

Lesson Steps

1

👋 Welcome to Python Game Design!

4 min
 

 

What is Python?

 

Python is a programming language used throughout the world. People like Python because of its ease of use and its power. We will use Python to create games that you can actually play and enjoy!

Here’s a quick guide for Python syntax (how to code in the Python language). You may find this helpful as you program your project.

 

Teaching tips

Summary

Overview: Students will use the Python programming to code a Choose Your Own Adventure game on the Repl.it platform.

Time: About 1-3 class periods per project; can be completed at your own pace.

Programming Languages: Python

Programs and Software Used:

 

What’s Covered?

  • Conditionals
  • If/then statements
  • Elif (else/if)
  • Print
  • Packages
  • Refactoring
  • Variables
  • Boolean and While loops
  • Concatenation and strings
  • String formatting
  • Lists
  • Constant variables
  • Functions
  • Newline characters
  • Inputs and curly brackets

Prerequisites and Tech Requirements

Students: We recommend students ages 8+ with solid typing skills. If this is their first myBetabox Python project, we recommend starting with Rock, Paper, Scissors to cover some fundamentals.

System Compatibility: ✔️ Windows | ✔️ Mac | ⚠️ Chromebook | ✔️ iPad

Access: Make sure you and your students have the following domains whitelisted by your IT department (or a parent/guardian if remote learning) and have downloading permissions enabled:

  • repl.it

Lesson Steps

  1. Have students read the following sections:
    1. Welcome to Python Game Design!
    2. Setting Up Repl.it
    3. Keyboard Guide
  2. Guide your students into creating their Repl.it accounts. They may need to verify their accounts in their emails. Once they have them set up, they can share their progress with you.
  3. Introduce the Repl.it tools and interface in Setting Up Repl.it.
  4. Check for understanding on how to type the symbols in the Keyboard Guide.
  5. If you'd like, you can print out our Python cheat sheet and distribute to your students for their reference. This is also found in their Welcome to Python Game Design! section.
  6. Review the section vocabulary below.

Vocabulary

  • Code: Instructions that tells a computer or computer program what to do.
  • Verify: To prove.
  • Interface: The area where a user can interact with the computer, usually by clicking or typing.
  • Syntax: The format, or way, code typed. Syntax is different for different languages.
2

⚙️ Setting Up Repl.it

15 min

Repl.it Set Up

 

 
 

What is Repl.it?

 

Repl.it is the website that we will be using to code our game. This will prevent us from having to download anything such as Python or an IDE and will allow us to easily share our projects!

To use Repl.it, simply go to www.repl.it and click sign up in the top right of the site. Once you have set up your free account, we can start exploring the interface!

 

 

 

Repl.it Interface

 

The first step to coding on Repl.it is creating a new repl, which stands for…

  • Read (computer reads the code you typed)
  • Evaluate (runs the code)
  • Print (shows the results)
  • Loop (does R, E, and P in a loop)

Think of it repls like coding projects. You should notice a button on the top right that says ‘+ new repl.’

 

When you click this button, you will be asked what programming language you want to use. For now, we are simply going to click on Python and name it whatever you would like!

 

 

Now that our repl has been created we can see the coding interface. The far left of the screen is our file directory and will tell us what files and folders are in our project.

 

 

The middle section is our workspace where we will type our code…

 

 

…and the far right section is where we will see our code when we click run!

 

 

 

The other important part of this screen is the share button. This button will allow you to share your code with others in case you get stuck!

 

Teaching tips

Lesson Steps

  1. Have students read the following sections:
    1. Welcome to Python Game Design!
    2. Setting Up Repl.it
    3. Keyboard Guide
  2. Guide your students into creating their Repl.it accounts. They may need to verify their accounts in their emails. Once they have them set up, they can share their progress with you.
  3. Introduce the Repl.it tools and interface in Setting Up Repl.it.
  4. Check for understanding on how to type the symbols in the Keyboard Guide.
  5. If you'd like, you can print out our Python cheat sheet and distribute to your students for their reference. This is also found in their Welcome to Python Game Design! section.
  6. Review the section vocabulary below.

Vocabulary

  • Code: Instructions that tells a computer or computer program what to do.
  • Verify: To prove.
  • Interface: The area where a user can interact with the computer, usually by clicking or typing.
  • Syntax: The format, or way, code typed. Syntax is different for different languages.
3

⌨️ Keyboard Guide

3 min

Here are some handy guides for coding symbols. Hold the keys with a circle down at the same time.

 

Keyboard Guide

 

Tab = used for indenting lines

 

 

 : Colon = Shift + ; 

 

 

_ Underscore = Shift + -

 

 

( Left Parenthesis = Shift + 9

 

 

) Right Parenthesis = Shift + 0

 

 

[ Left Bracket

 

 

] Right Bracket

 

 

" Quotation Marks

 

 

\ Backslash

Teaching tips

Lesson Steps

  1. Have students read the following sections:
    1. Welcome to Python Game Design!
    2. Setting Up Repl.it
    3. Keyboard Guide
  2. Guide your students into creating their Repl.it accounts. They may need to verify their accounts in their emails. Once they have them set up, they can share their progress with you.
  3. Introduce the Repl.it tools and interface in Setting Up Repl.it.
  4. Check for understanding on how to type the symbols in the Keyboard Guide.
  5. If you'd like, you can print out our Python cheat sheet and distribute to your students for their reference. This is also found in their Welcome to Python Game Design! section.
  6. Review the section vocabulary below.

Vocabulary

  • Code: Instructions that tells a computer or computer program what to do.
  • Verify: To prove.
  • Interface: The area where a user can interact with the computer, usually by clicking or typing.
  • Syntax: The format, or way, code typed. Syntax is different for different languages.
4

📗 Design Your Story

15 min

What’s Storyboarding?

 

When designing a game, most designers will start out by getting the story written first. So the first thing we are going to do is write our story! Your Choose Your Own Adventure game can be about anything you want!

Choose Your Own Adventures are where the reader makes decisions on how the story progresses.

 

 

Your story should have branching decisions so that the adventure can go in many different directions. You can have multiple different endings or options to go back to the start, like if your character meets his doom (a dead end) so you have to start the story over. The possibilities are endless!

 

 

 

Plan out your CYOA game by writing your story on a piece of paper or journal. You can use these optional printed code blocks (download here) or write IF/THEN statements to integrate some code in your rough draft.

 

 

I encourage you to get as creative as possible here – you can draw pictures as well. Let the only limit be your imagination!

Teaching tips

Get your creative juices flowing by coming up with ideas for your stories.

Lesson Steps

  1. Have students navigate to the Design Your Story section.

  2. Students should have paper and pencils ready. Instruct them to come up with stories that have branching paths. They can refer to the tree diagram on their screen.
  3. For each decision making part of their stories, students will create two options:
    • A dead end (game over)
    • A good choice that continues the story
  4. If you'd like,  you can print out our story code blocks for students to glue onto their papers. This will help them incorporate some code into their rough drafts. They can also simply write in IF/THEN statements instead.
  5. Check for understanding and answer any questions they may have before moving on to the next section.
5

🌳 Starting the Story Tree Node

15 min
Keyboard Guide

Starting the Story Tree Node

 


 

Stuck? Copy & Paste the Code into Repl.it

 

class TreeNode:
  def __init__(self, story_piece):

 


 

The Code Explained

 

A class is a way to create an object and give that object properties. For example, let's say you want to create a class for summer shirts (the object). According to you, all summer shirts must have these properties:

  • Short sleeves
  • Bright colors
  • Cotton material

 

🌟 Classes create objects with the same properties and are written as class ClassName:

 

class TreeNode:

 

TreeNode is capitalized on the T and the N because that's how Python recognizes it as a class. If it weren't, it may be read as a variable instead.

The starting node is called the root node and this is where the story begins branching off into scenarios. Remember to indent this line of code if it's not lined up like in the video by using the tab key.

 

 def __init__(self, story_piece):

 

We define a function by typing def and remember that the function syntax always use parentheses. You cannot use a function before defining it because the computer won't understand what to do. It's like if I asked you to "Defenestrate the collagenous tallow posthaste!" would you know what to do? Probably not, unless I explained it first.

 

🌟  Functions are packets of code that do a certain task and are always followed by ( ). Here we have a __init__() function.

 

Every time we start a class we will code an initialization function to get it started.

The parameters we are passing through the initialization function are self and story_piece.

 

🌟  Parameters are things that get passed into a function.

 

Think of it like if you have a function called washDishes() and the order was soap, rinse, then dry. Now all the dinner plates and cups that need to be cleaned will be passed through this function and will get soaped, rinsed, and dried. I could say, "Hey buddy! I need you to washDishes()" and you'd know what to do.

Teaching tips

Let's start the foundation of our game.

Lesson Steps

  1. Have students navigate to the Starting the Story Tree Node section.

  2. Students should have another tab or window open with their Repl.it projects open so they can follow along with the videos.
  3. If they get stuck, there is code beneath they videos they can copy and paste into Repl.it but encourage them to practice typing out the code on their own. Note: Keep in mind that copy/pasting the code will replace any customized strings, variables etc...
  4. Point out the Keyboard Guide link at the top of every page if they need.
  5. Encourage students to read The Code Explained subsection below. Nearly all student-side sections will have information under the videos to help explain the code they are using as well as tips and analogies.
  6. Check for understanding and answer any questions they may have before moving on to the next section.
  7. Review the section vocabulary below.

Vocabulary

  • Class: Classes create objects with the same properties and are written as class ClassName:
  • Object: An element of a class.
  • Indent: Move a line of code to the right when format an syntax dictate.
  • Node: The location where branching occurs.
  • Function:
  • Function: Packets of code that do a certain task and are always followed by ( ). Here we have a __init__() function.
  • Parameter: Things that get passed through a function.
6

🤔 Setting Up the Framework for Choices

10 min
Keyboard Guide

Setting Up the Framework for Choices

 


 

Stuck? Copy & Paste the Code into Repl.it

 

class TreeNode:
  def __init__(self, story_piece):
    self.story_piece = story_piece
    self.choices = []

  def add_choices(self, choice_a, choice_b):
    self.choices.append(choice_a)
    self.choices.append(choice_b)

 


 

The Code Explained

 

Your nodes are the parts of your story where the reader makes a choice. For example, your node could be

 

The brave astronaut lands on a mysterious planet. Does she go to the left or to the right?

 

The story_piece acts the same way. Each part of the story is its own piece of the adventure, kind of like chapters. We are identifying that this node is the starting point of the story.

 

   self.story_piece = story_piece

 

Next we create a list that contains all our story options. Does the astronaut go left or right? You can think of lists like items on a shopping list!

 

🌟 Lists allow you to store different types of data in an order. Lists use square brackets and the data inside are separated by commas.

 

    self.choices = []

 

We will type out our actual choices for this list in the next section but for now let's create a function so we can do that.

 

    def add_choices(self, choice_a, choice_b):
      self.choices.append(choice_a)
      self.choices.append(choice_b)

 

The function add_choices() will add our story options for us. Going left could be choice_a and going right could be choice_b. Adding .append to the function will add the choices to the end of the list.

For example, if you had a shopping list called self.shopping = [apple, banana, milk] and you entered self.shopping.append(bread) then your list will add bread to the end of the list [apple, banana, milk, bread].

Teaching tips

Now let's set up the format for story options.

Lesson Steps

  1. Have students navigate to the Setting Up the Framework for Choices section.
  2. Students will follow along with the video to add code.
  3. Check for understanding and answer any questions they may have before moving on to the next section.
  4. Review the section vocabulary below.

Vocabulary

  • List: Allows you to store different types of data in an order. Lists use square brackets and the data inside are separated by commas.

  • Append: To add to the end of a list.
7

👉 Letting the Player Make a Choice

15 min
Keyboard Guide

Letting the Player Make a Choice

 

 

 


 

Stuck? Copy & Paste the Code into Repl.it

 

class TreeNode:
  def __init__(self, story_piece):
    self.story_piece = story_piece
    self.choices = []

  def add_choices(self, choice_a, choice_b):
    self.choices.append(choice_a)
    self.choices.append(choice_b)

  def tell_story(self):
    story_node = self
    print(story_node.story_piece)
    while len(story_node.choices) !=0:
      answer = int(input("Enter 0 or 1 to continue the story: "))
      if answer == 0 or answer == 1:
        choice = story_node.choices[answer]
        story_node = choice
        print(story_node.story_piece)
      else:
        print("Invalid answer! Try again!")

 


 

The Code Explained

 

Let's create a function to begin telling our story. Remember we have to define functions before we can use them.

 

def tell_story(self):

 

We need code that allows us to always access the node (part of the story) we are on and not lose our place in the adventure.

 

story_node = self

 

Print will create a message for this part of the story on the screen for the player to read.

🌟 Print sends text, variables, and other objects to the screen for the user to see. The syntax for print is print().

 

print(story_node.story_piece)

 

The while loop will keep checking the story for choices as long as the game is running. If there are no more choices because we reached a dead end then the loop will end.  How do we check for choices? The len function stands for length and will check to see how long our choices list is. If you can go left or right, then your list has 2 items. If you reached a dead end and the story ends, the list has 0 items indicating you've reached a dead end and the loop should stop. !=0 is the syntax that means the length of the story_node.choices list does not equal 0 (yes, there are there items in your list so the loop can continue and the story can go on).

 

while len(story_node.choices) !=0:

 

The variable answer will gives the player an option to type 0 or 1 to move the story along. Since we will use numbers as the means for advancing the story, we have to translate our responses into those. int stands for integer and turns our story options into numbers. Instead of "Do you go left or right?" it becomes "Do you pick 0 or 1?" where 0 is left and 1 is right.

If the answer is choice 0 or choice 1 then we can go to the next tree node scenario.

 

 answer = int(input("Enter 0 or 1 to continue the story:"))
 if answer == 0 or answer == 1:
   choice = story_node.choices[answer]

 

We have to now update and add our new options to the story_node.choices list. Remember how Python lists are ordered? The placement in the list is called an index and the first item actually has a starting position of 0, not 1. Weird, right? Let's take a look at that shopping list again.

🌟  An index is the position of an item in a list. The first item in a list has an index = 0, the second = 1 and so on.

 

self.shopping = [apple, banana, milk, bread]

 

Apple is the first item in the list so it has an index of 0. Banana is the second item. What comes after 0? 1! That's the index for banana. Any idea what the index is for bread? ...It's 3! Our newest story choices will be added to the end of our list.

Now we need to update the story based on our choice and turn the page. Think of it like moving a bookmark.

 

story_node = choice

 

Let's create a message that tells the player what the next part of the story says once we make a choice.

 

print(story_node.story_piece)

 

If the player makes a choice you didn't provide, like typing 382 or kitty then our program should create an in-game message saying that's not an option. This is where the else comes in since 0 or 1 wasn't entered.

 

else:
  print("Invalid answer! Try again!")

Teaching tips

On to the next part!

Lesson Steps

  1. Have students navigate to the Letting the Player Make a Choice section.
  2. Students will follow along with the video to add more code.
  3. Check for understanding and answer any questions they may have before moving on to the next section.
  4. Review the section vocabulary below.

Vocabulary

  • Print: A function that sends text, variables, and other objects to the screen for the user to see.
  • While Loop: A repeating line of code that continuously runs while a value is true.
  • Variable: Code that stores information and values such as characters (letters/words/symbols), numbers, and Booleans (true/false statements). Variables can change.
  • Index: The position of an item in a list. The first item in a list has an index = 0, the second = 1 and so on.
8

👩‍💻 Putting Your Story into Code

10 min
Keyboard Guide

Putting Your Story into Code

 

 


 

Stuck? Copy & Paste the Code into Repl.it

 

class TreeNode:
  def __init__(self, story_piece):
    self.story_piece = story_piece
    self.choices = []

  def add_choices(self, choice_a, choice_b):
    self.choices.append(choice_a)
    self.choices.append(choice_b)

  def tell_story(self):
    story_node = self
    print(story_node.story_piece)
    while len(story_node.choices) !=0:
      answer = int(input("Enter 0 or 1 to continue the story: "))
      if answer == 0 or answer == 1:
        choice = story_node.choices[answer]
        story_node = choice
        print(story_node.story_piece)
      else:
        print("Invalid answer! Try again!")

story_root = TreeNode("You awake in an empty room. There is a phone booth in the middle. \nDo you: \n 0 ) Investigate the phone booth. \n 1 ) Leave it alone.\n")

 


 

The Code Explained

 

story_root is where our story officially begins for the player. Think of it like the first page!

 

story_root = TreeNode()

 

When we type TreeNode() we are starting the scene and we will pass our first story_piece into it. In our example, we begin our scene with a phone booth in an otherwise empty room. Let's describe that as a string. This will be your first story setting!

🌟 A string is a sequence of characters (numbers, letters, symbols and spaces) and start and end with quotation marks. Think about it like a sentence.

 

story_root = TreeNode("You awake in an empty room. There is a phone booth in the middle. \nDo you: \n 0 ) Investigate the phone booth. \n 1 ) Leave it alone.\n")

 

Notice how we used a new line character to make the text look nicer in the game? This prevents the text from looking clumped together once the game runs.

🌟  Create a new line in Python by typing \n to give a line break.

 

Now is the time to type out your first scene and its story choices as the 0 and 1 options!

Teaching tips

Time to incorporate our stories into the rest of the code!

Lesson Steps

  1. Have students navigate to the Putting Your Story into Code and Adding the Next Story Choices sections.
  2. Students will follow along with the video to add code.
  3. Emphasize that their codes will differ from the video because of their unique storylines. Remind them to keep track of their dead end and continuation options for choice_a and choice_b as we progress.
  4. Check for understanding and answer any questions they may have before moving on to the next section.
  5. Review the section vocabulary below.

Vocabulary

  • String: A sequence of characters (numbers, letters, symbols and spaces) and start and end with quotation marks. Think about it like a sentence.
  • New Line Character: Type \n to create a line break for your game text.
9

↔️ Adding the Next Story Choices

10 min
Keyboard Guide

Adding the Next Story Choices

 

 


 

Stuck? Copy & Paste the Code into Repl.it

 

class TreeNode:
  def __init__(self, story_piece):
    self.story_piece = story_piece
    self.choices = []

  def add_choices(self, choice_a, choice_b):
    self.choices.append(choice_a)
    self.choices.append(choice_b)

  def tell_story(self):
    story_node = self
    print(story_node.story_piece)
    while len(story_node.choices) !=0:
      answer = int(input("Enter 0 or 1 to continue the story: "))
      if answer == 0 or answer == 1:
        choice = story_node.choices[answer]
        story_node = choice
        print(story_node.story_piece)
      else:
        print("Invalid answer! Try again!")

story_root = TreeNode("You awake in an empty room. There is a phone booth in the middle. \nDo you: \n 0 ) Investigate the phone booth. \n 1 ) Leave it alone.\n")
current_node = story_root
choice_a = TreeNode("You enter the phone booth and look around. You see a button that says 1980 and a button that says 3000. \nDo you: \n 0 ) Press 1980. \n 1 ) Press 3000.\n")
choice_b = TreeNode("You decide to leave the phone booth alone. You live out the rest of your life in boredom.\n")

 


 

The Code Explained

 

We have to update the current_node variable with the node we are now on.

 

current_node = story_root

 

Next, let's add in our official first story options! Note how these choices are technically nodes themselves which is why we have them set to TreeNode(). Type out your scenario as a string including your two prompts.

 

choice_a = TreeNode("You enter the phone booth and look around. You see a button that says 1980 and a button that says 3000. \nDo you: \n 0 ) Press 1980. \n 1 ) Press 3000.\n")
choice_b = TreeNode("You decide to leave the phone booth alone. You live out the rest of your life in boredom.\n")

 

Choice_a is what happens when we investigate the booth. Choice_b is what happens when we leave it alone. You'll notice that choice_b leads to a dead end.

You could make choice_a your dead end if you wish but keep track of which choices continue the story and which do not.

 

10

☠️ Sending the Player Back to the Beginning

10 min
Keyboard Guide

Sending the Player Back to the Beginning

 

 


 

Stuck? Copy & Paste the Code into Repl.it

 

class TreeNode:
  def __init__(self, story_piece):
    self.story_piece = story_piece
    self.choices = []

  def add_choices(self, choice_a, choice_b):
    self.choices.append(choice_a)
    self.choices.append(choice_b)

  def tell_story(self):
    story_node = self
    print(story_node.story_piece)
    while len(story_node.choices) !=0:
      answer = int(input("Enter 0 or 1 to continue the story: "))
      if answer == 0 or answer == 1:
        choice = story_node.choices[answer]
        story_node = choice
        print(story_node.story_piece)
      else:
        print("Invalid answer! Try again!")

story_root = TreeNode("You awake in an empty room. There is a phone booth in the middle. \nDo you: \n 0 ) Investigate the phone booth. \n 1 ) Leave it alone.\n")
current_node = story_root
choice_a = TreeNode("You enter the phone booth and look around. You see a button that says 1980 and a button that says 3000. \nDo you: \n 0 ) Press 1980. \n 1 ) Press 3000.\n")
choice_b = TreeNode("You decide to leave the phone booth alone. You live out the rest of your life in boredom.\n")
current_node.add_choices(choice_a, choice_b)

play_again = "y"
while play_again == "y":
  story_root.tell_story()
  play_again = input("Would you like to play again [y]/[n]?: ").lower()

 


 

The Code Explained

 

Let's add the choices we just typed out into our choices list by using the add_choices() function.

 

current_node.add_choices(choice_a, choice_b)

 

Before we continue adding to our story, let's create a means for sending the player back to the beginning of the story if they come across a dead end.

We'll do this by using a while loop. Our game will consistently check for if the player reaches a dead end and will then ask the player if they want to continue from the beginning.

🌟 While loops continue to endlessly run until it doesn't meet a certain condition. In this case, it will run as long as the player types y for yes.

 

play_again = "y"
while play_again == "y":
  story_root.tell_story()
  play_again = input("Would you like to play again [y]/[n]?: ").lower()

 

To make sure the player input is consistent with the code you've written, we need to make sure they both match. If you coded y for yes but the player types Y an error will occur because the computer thinks y and Y are different answers. Fix this by adding .lower() to this function.

🌟 Adding .lower() to the input() function will convert whatever the player types into lowercase. This would turn YES, YeS, yES into yes. We will just use y for this project.

 

Notice how we used == instead of = to see if the play_again variable matches y.

🌟 Use == as a comparison tool to see if two things are similar. Using = is typically used to define things such as variables and are not used for comparisons.

 

Teaching tips

Let's figure out how to keep the code up-to-date with our progress in the story. Then we'll set up the main game while loop to send the player back to the story start every time a dead end in reached.

Lesson Steps

  1. Have students navigate to the Sending the Player Back to the Beginning section.
  2. Students will follow along with the video to add code.
  3. Emphasize that their codes will differ from the video because of their unique storylines. Remind them to keep track of their dead end and continuation options for choice_a and choice_b as we progress.
  4. Check for understanding and answer any questions they may have before moving on to the next section.
  5. Review the vocabulary below.

Vocabulary

  • While Loop: Continue to endlessly run until it doesn’t meet a certain condition. In this case, it will run as long as the player types y for yes.
  • .lower(): A special function that turns all user input into lowercase.
  • ==: A comparison tool to see if two things are similar. Using = is typically used to define things such as variables and are not used for comparisons.
11

📖 Finishing the Rest of the Story

20 min
Keyboard Guide

Finishing the Rest of the Story

 

 


 

Stuck? Copy & Paste the Code into Repl.it

 

class TreeNode:
  def __init__(self, story_piece):
    self.story_piece = story_piece
    self.choices = []

  def add_choices(self, choice_a, choice_b):
    self.choices.append(choice_a)
    self.choices.append(choice_b)

  def tell_story(self):
    story_node = self
    print(story_node.story_piece)
    while len(story_node.choices) !=0:
      answer = int(input("Enter 0 or 1 to continue the story: "))
      if answer == 0 or answer == 1:
        choice = story_node.choices[answer]
        story_node = choice
        print(story_node.story_piece)
      else:
        print("Invalid answer! Try again!")

story_root = TreeNode("You awake in an empty room. There is a phone booth in the middle. \nDo you: \n 0 ) Investigate the phone booth. \n 1 ) Leave it alone.\n")
current_node = story_root
choice_a = TreeNode("You enter the phone booth and look around. You see a button that says 1980 and a button that says 3000. \nDo you: \n 0 ) Press 1980. \n 1 ) Press 3000.\n")
choice_b = TreeNode("You decide to leave the phone booth alone. You live out the rest of your life in boredom.\n")
current_node.add_choices(choice_a, choice_b)

current_node = choice_a
choice_a = TreeNode("You travel back to 1980 and get stuck in an arcade.\n")
choice_b = TreeNode("You travel forward to 3000 and see that not much has changed but people live underwater. \nDo you: \n 0 ) Swim into the city.\n 1 ) Stay in the phone booth.\n")
current_node.add_choices(choice_a, choice_b)

current_node = choice_b
choice_a = TreeNode("You swim into the city and meet some merpeople.\n Do you: \n 0 ) Try to talk to them. \n 1 ) Swim away in fear.\n")
choice_b = TreeNode("You stay in the phone booth and get sent back home.\n")
current_node.add_choices(choice_a, choice_b)

current_node = choice_a
choice_a = TreeNode("The merpeople welcome you to their city.")
choice_b = TreeNode("You swim out of the city and become lost.")
current_node.add_choices(choice_a, choice_b)

play_again = "y"
while play_again == "y":
  story_root.tell_story()
  play_again = input("Would you like to play again [y]/[n]?: ").lower()

 


 

The Code Explained

 

Time to finish your story! Give your game more scenarios and options to create an engaging adventure. Go back to line 28 (or under your last set of choices and above play_again = "y") and update the current_node.

Based on our last example, choice_a was the option that continued the story (it wasn't the dead end) so we will set the current_node to choice_a. If yours was choice_b you can write that instead.

 

current_node = choice_a

 

Type out your second scenario (including your story options) by following the same template. Feel free to copy and paste the previous chunk of code and replace it with new strings.

 

choice_a = TreeNode("You travel back to 1980 and get stuck in an arcade.\n")
choice_b = TreeNode("You travel forward to 3000 and see that not much has changed but people live underwater. \nDo you: \n 0 ) Swim into the city.\n 1 ) Stay in the phone booth.\n")
current_node.add_choices(choice_a, choice_b)

 

This time choice_b will continue the story and choice_a will be the dead end. Again, you can make either one the dead end but remember which choice it is for the next chunk of code.

 

current_node = choice_b
choice_a = TreeNode("You swim into the city and meet some merpeople.\n Do you: \n 0 ) Try to talk to them. \n 1 ) Swim away in fear.\n")
choice_b = TreeNode("You stay in the phone booth and get sent back home.\n")
current_node.add_choices(choice_a, choice_b)

 

Now you can keep going and add as many chapters as you want! If you'd like to create an official winning end to the game, type a string for the winning choice that says something like, "You've reached the end in one piece, congrats!" This will let the player know the game is over. It could look something like this:

 

current_node = choice_a
choice_a = TreeNode("\n The merpeople are allergic to dairy. YOU LOSE!")
choice_b = TreeNode("\nGrateful for your kindness and honesty, the king of the merpeople rewards you with the SAPPHIRE of the sea. YOU WIN!")
current_node.add_choices(choice_a, choice_b)

 

Keep in mind that this example assumes choice_a from the previous node wasn't the dead end. Yours could be different!

When you're finished, be sure to share it with friends and family and see if they can complete your adventure!

Teaching tips

Ahh, the final chapter!

Lesson Steps

  1. Have students navigate to the Finishing the Rest of the Story section.
  2. Allow students some time to enter in rest of their story 'chapters', complete with choices.
  3. Remind them to code an end-game scene so the player knows they've reached the true end of the story.
  4. Students will share their Repl.it CYOA projects with you and each other. This is a great opportunity for peer assessment and feedback.

Materials

  • Computer or Chromebook with Repl.it access — 1 per student
  • Paper and pencil — 1 per student
  • Python cheat sheet (printed) — 1 per student
  • Printed story code blocks
  • Glue

More robotics lessons

Ready to bring this lesson to your classroom?

Sign up to save this lesson, order supplies, and track student progress.