CODING
ADVENTURE
0 / 12 completed

CASE 11 / CHAPTER 12

Build your own choice

Branching and story state

IN THE STORY

Code Chronicles begins with a small story that readers can change. It uses scenes and decisions instead of a single fixed sequence.

The idea

A nested dictionary can hold choices for each story section. get retrieves a value and can supply a fallback if the key is missing. A state machine is a program whose current state and next input determine what happens next. The default in this example keeps the reader in the current section after an unknown choice.

Your mission

Complete the lookup so choice selects a destination within the current section.

Replace ____ with the missing expression, then choose Run code. Match the expected output before trying your own changes.

Before you run it

What should happen if the reader chooses a word the story does not recognise?

A little help?

Hint 1: a nudge

First retrieve the choices for section. Then look up choice.

Hint 2: a closer look

Use routes[section].get(choice, section).

How the answer works

The notebook choice leads to clue. Change the initial choice to ask and it leads to ally. The complete adventure game supplies text, input and a loop that continues until the ending.

This replaces the code in the editor. Save your version first if you want to keep it.

Make it yours

In Build Game Three, run christines_choice.py. Edit a copy of its scene text and add a route. Every route should reach an ending or offer a clear retry.

your_adventure.pyPYTHON 3

Four spaces indent a block. Ctrl / ⌘ + Enter runs your code. Tab moves to the next control.

OUTPUTPython loads when you run
Your program's output will appear here.

Take a guess. Try a line. See what happens.

Expected output

Next section: clue

Code runs on your device. The first run downloads the Python engine (about 10 MB); later runs use the browser cache. Stop ends a run without losing your code.