Chapter 16

Choose Your Own Adventure

Imagine you’re climbing a tree. If you climb up one branch, you’ll see certain things, such as a bird’s nest or a balloon that got stuck up there during your birthday party. If you climb a different branch, you might see other things, like the neighbor’s garage. In JavaScript, the technique of using if…else or switch statements to choose between two or more paths is called branching.

In this chapter, we use branching to write a choose-your-own-adventure game that asks for user input at key moments to change the story.

image

Planning the Story

Any good story needs a plot. The plot is the outline of events that happen over the course of the story. When writing a story where the user’s input influences the plot, the writer needs to pay close attention to managing the different plot lines. Each plot line has the same beginning, but the middle and ending are different based on input from the user.

Creating a flow chart

Considering all of the different options — and planning for each possibility — in a branching program is a valuable skill to have as a programmer.

We’ll begin by creating a simple story that poses a question. This creates two branches. Each of these branches will have a question that creates two more branches. Eventually, every choice will lead back to one of two possible endings.

A useful tool for visualizing branches of a story ...

Get JavaScript For Kids For Dummies now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.