Skip to content

C# Adventure 08: Branching Narrative

Let's add a player decision that will branch the game's story. The pattern we create can be extended as we add more content to the branching narrative later.

Program Flow

Branching Narrative flowchart

The basic pattern lets the player choose between two choices, A or B. Something different should be shown depending on their choice. When you are developing your content later, the "something different" for each path will be story elements.

For example, the player could be told that there is a fork in the road; do they want to go left or right? If the player chooses left, perhaps they find a special coin on the road. If they go right, perhaps they help someone and are rewarded with a cupcake.

The story content is entirely up to you, but each choice the player makes should be meaningful. If they choose between two paths, have a different experience for the player for each one. This can also encourage them to play again to find out what they missed.

Branching Narrative Structure

Add a new method to your Game class. It will hold code that tracks which choice the player has made. In this example, it is called 'Choice'.

static void Choice()
{
}

Then add a variable to store the player's choice.

static void Choice()
{
     string input = "";
}

Write out an instruction for the player to choose between two options. In this example we are just using A and B as placeholders. Later you will rewrite the choices as game content.

static void Choice()
{
     string input = "";
     Console.WriteLine("Which will you choose? A or B?");
}

Just like we did with the character name, we will read in what the player types. Add a statement that will save the player's choice as the variable input.

static void Choice()
{
     string input = "";
     Console.WriteLine("Which will you choose? A or B?");
     input = Console.ReadLine();
}

Next we will use an if/then statement to write out what happens depending on the player's choice. Add the conditional statement.

static void Choice()
{
     string input = "";
     Console.WriteLine("Which will you choose? A or B?");
     input = Console.ReadLine();
     if (input == "A")
     {
         Console.WriteLine ("You've chosen path A!");
     }
     else
     {
         Console.WriteLine ("You've chosen path B!");
     }
}

To personalize the path question, add CharacterName. Use concatenation (the + operator).

Console.WriteLine(CharacterName + ", which path will you choose? A or B?");

Method Call

The final step before we can test it is to call the new method. Add the statement. (Write it yourself before you look at the example code below.)

Test your code to make sure you don't have any errors.

Show code example

/*
 * [Your Title]
 * by Your Name, Date
 *  
 * This work is a derivative of 
 * "C# Adventure Game" by http://programmingisfun.com, used under CC BY.
 * https://creativecommons.org/licenses/by/4.0/
 */

using System;

namespace Adventure
{
    public static class Game
    {

        static string CharacterName;

        public static void StartGame()
        {
            Console.WriteLine("Game Title");
            Console.WriteLine("Welcome to ...");
            NameCharacter();
            Choice();
        }
        static void Choice()
        {
            string input = "";
            Console.WriteLine(CharacterName + " which path will you choose? A or B?");
            input = Console.ReadLine();
            if (input == "A")
            {
                Console.WriteLine("You've chosen path A!");
            }
            else
            {
                Console.WriteLine("You've chosen path B!");
            }
        }
        static void NameCharacter()
        {
            Console.WriteLine("What would you like your character's name to be?");
            CharacterName = Console.ReadLine();

            Console.WriteLine("Great! Your character is now named " + CharacterName);
        }
    }
    class Item
    {

    }
    class Program
    {
        static void Main()
        {
            Game.StartGame();
            Console.Read();
        }

    }
}

Branching Narrative

Uppercase and Lowercase Entries

Right now path A is shown only if the player types in an uppercase A. Let's fix this so they can type either upper or lower case.

After the line that reads in whether the player typed A or B, add this line:

input = input.ToUpper();

Our variable "input" is an instance of the String class that we created by assigning a string literal to a String variable. One of the methods of the String class is ToUpper(), and we can access ToUpper() with dot notation: input.ToUpper().

Lowercase Option

Instead of making the input uppercase, we could make it lowercase and then see if it matches the lowercase 'a'. Either option works.

string input = "";
Console.WriteLine(CharacterName + " which path will you choose? A or B?");
input = Console.ReadLine();
input = input.ToLower();

if (input == "a")
{
    Console.WriteLine("You've chosen path A!");
}
else
{
    Console.WriteLine("You've chosen path B!");
}

Learning new .NET Framework classes

Once you know the object-oriented basics of C# you can look up new classes in the MSDN Reference and learn how to use them.

For example, let's look up the String class at MSDN.

string-class

Scrolling down you'll see syntax, constructors, properties and methods. We haven't talked about constructors yet, but we've talked about properties and methods. They are both accessed with dot notation.

string-class2

Properties

One of the properties listed is Length. How would you write the length of CharacterName to the console window? Take a few minutes to try it out in Visual Studio.

CharacterName Length example

Use dot notation: CharacterName.Length. To print it to the console window, pass it into the WriteLine method.

Console.WriteLine("Your code name is confirmed to be " + CharacterName + ". Good luck!\n\n");
Console.WriteLine("The name you entered is " + CharacterName.Length + " characters.");

In your adventure game it could appear like this:

Example of how the length property of CharacterName might be used
Example of how the length property of CharacterName might be used

Methods

On the MSDN site can see the ToUpper() and ToLower() methods:

string-class3

Just like with the Length property, we use dot notation to access methods. So to change the CharacterName string to uppercase or lowercase letters we would use CharacterName.ToUpper() or CharacterName.ToLower().

Test Your Code

Test your application again. You should be able to type A or a, B or b, and have it still show the correct response.

Now that we've built the simple pattern with two choices, it can be repeated. But before we extend our existing Choice() function to handle multiple scenarios, it is time for you come up with some creative content!

You've built a branching narrative structure!

Quick Quiz

Which of the following operators would be used for checking equality?

Correct
Incorrect

The hierarchy path expressed in the code below with dots (periods) between elements is called .

System.Console.WriteLine()
Correct
Incorrect

To Do: Create Game Content

Make game content. Think of three scenarios that you can include in your game. Type them up so you can copy/paste your text into your code. For each scenario include text that will have a choice, what will happen for each choice, and followup text that incorporates any items or bonuses that happened because of a decision the player made. At the end add another line that can act as a transition to the next scenario.

Example

"At the front of the imposing building you see a weathered old man with a cart. As you near, you see the cart is filled with what looks like mostly junk and only a few useful items. All you have on you is piece of a chalk. You offer it to him, and he says he'll trade a flashlight or an umbrella for it. Which do you choose?"

(Player makes choice and moves into the building.)

  • Flashlight: "It is dark. The power in the building has gone out - luckily you have a flashlight! You move the light around and a large animal is frightened by the sudden brightness and takes off. As you move the light again, something glitters. You reach down and pick up a coin!"
  • Umbrella: "The power in the building goes out! As you move down the hallway you hear what sounds like a large animal nearby. You move the umbrella in a widening arc in front of you to scare it, and the animal skitters off."

Both paths: "The lights return and you move into a room at the end of the hall. There is a vending machine."

  • If they have a coin (flashlight path): "Luckily you have that coin you found and you buy yourself a snack."
  • No coin (umbrella path): "Too bad you don't have a coin on you, or you would have been able to get a snack."

Both paths (transition after the choices): "You begin to climb the stairs to the next floor...."

Optional Template

If you'd like to copy/paste your content into an existing code structure that we'll be making, you can follow the template below. You can use a different structure if you'd like, you will just need to adjust the code to fit.

  1. Choice introduction and options
  2. [Player makes a choice]
  3. Depending on choice one of two paths is shown
  4. Story continues (for both paths)
  5. Player has something different happen depending on choice made and path - perhaps finding an item (like a coin)
  6. Followup text that will transition to the next part of the game

Hopefully you can already see how easy it would be to code this scenario with the knowledge you have!

Code Files

If you have errors, or just want to check how your code compares in terms of progress, the code examples for this chapter are linked below.

Next Step

In the next section we'll look at a couple more programming concepts, then we'll integrate your scenarios into the adventure game and build out your branching narrative.