dark mode light mode Search Menu
Search

Code a Choose Your Adventure Game

Kalen Emsley on Unsplash

Choose Your Own Adventure (CYOA) experiences were huge in the 1980s. Kids could read these entertaining books and, depending on the choices they made during the story, could experience over 25 different endings. Today, CYOA experiences are available on streaming services. As a coder, you can program your own CYOA game in Python using functions.

You may already know what a function is. In Python, user-created sequences of commands are called functions. In Scratch, you can create reusable blocks of code, called My Blocks, that can be called on to run as needed. In both languages, functions are preferable to long lines of code as they are quicker to edit and less prone to bugs.

You can view our project (below under Learn More) for inspiration, but before you start coding, you need a good story. You can use pencil and paper or Google Drawings to organize a story flowchart (see a screenshot of ours). It’s a good idea to start small. As seen in the flowchart, our story has an intro, 3 initial decisions, 2 choices for each decision, and 6 possible endings. 

A good place to house, write, and run your project is in Trinket. Create a new Python project and start off by assigning variables. We assigned most of the story text to variables. Within variables, the story text can easily be modified and the code in the functions will look less messy without all the text from the storylines.

There are only two functions in the program, one for users to replay the game and another to start a new game.  The new_game() function asks users to make their first choice using the built-in input function, which prompts users to type in an answer. It’s important to note that a function like input is not created by the user, it is built into Python and is always available.

The same is not true for the functions we make, which must be defined. Notice how the code says def new_game(): – def stands for define – and any code written after that will be executed once the function is called. Within our new_game() function is an if-elif-else conditional (and even a conditional within it). This is the heart of the CYOA game. If a user selects choice 1, they will follow one path but if they select choice 2 or 3, they’ll go somewhere else.  If users mistakenly type an option that doesn’t exist, the new_game() function will be called again, making users type an actual choice. 

Functions can even call other functions, and after each of the 6 endings in our program, there is a call to the replay_game() function, which asks users if they want to play again. If they do, the new_game() function is simply called again. 

What adventure and how many endings can you come up with?

Learn More

 This Project on Trinket

https://trinket.io/python/a4e4e18a78

Related Posts