Skip to content

C# Adventure 07: Conditional Statements

We have a good foundation for our game, but we need to add some player decisions. Adventure games usually have several choices for the player, such as which path they want to take. We'll use conditional statements to run different code based on what decisions the player makes.

Later, after we look at how to make conditional statements, you'll add your own path scenarios to make this game uniquely yours.

Conditional Statements

Statements that run only if a certain condition is met are called conditional. A test expression is used, and the result will be a Boolean value (true or false).

Common Data Types

We've used several strings so far in our Adventure Game. A string is just one type of data that you should know about. Common data types that you'll use often in programming include:

  • String (string): a string of characters
  • Integer (int): a whole number
  • Boolean (bool): true or false
  • Double (double): a large number that can include a decimal

Conditional: if

Let's look at an example of a conditional statement that will test whether an integer is less than or equal to zero.

int temperature = 0;

if (temperature <= 0)
{
    Console.WriteLine ("Water will freeze; the freezing point of water is 0°C.");
}
  • The variable temperature is initialized with value of zero.
  • The test expression within the parentheses will return true if the value of temperature is less than or equal to zero (temperature <= 0).
  • If true, the statements within the code block will run - in this case, it will write out a sentence to the console window.

Conditional: if / else

Conditional statements can have an alternative if the test expression in the parentheses is not true.

int temperature = 0;

if (temperature <= 0)
{
    Console.WriteLine ("Water will freeze; the freezing point of water is 0°C.");
}
else
{
    Console.WriteLine ("It is not yet cold enough for water to freeze.");
}

If the value of temperature is not less than or equal to zero, the statement within the second code block will run and "It is not yet cold enough for water to freeze." will be written to the console window.

Conditional: if / else if / else

We can also add more conditions to check for.

int temperature = 0;

if (temperature <= 0)
{
    Console.WriteLine ("Water will freeze; the freezing point of water is 0°C.");
}
else if (temperature >= 170 )
{
    Console.WriteLine ("A good temperature for brewing white and green teas.");
}
else
{
    Console.WriteLine ("Water is not cold enough to freeze,");
    Console.WriteLine ("nor a good temperature for brewing tea.");
}

You can add as many "else if" statements as you need.

int temperature = 0;

if (temperature <= 0)
{
    Console.WriteLine ("Water will freeze; the freezing point of water is 0°C.");
}
else if (temperature >= 208 )
{
    Console.WriteLine ("A good temperature for brewing black tea.");
}
else if (temperature >= 180 )
{
    Console.WriteLine ("A good temperature for brewing oolong tea.");
}
else if (temperature >= 170 )
{
    Console.WriteLine ("A good temperature for brewing white and green teas.");
}
else
{
    Console.WriteLine ("Water is not cold enough to freeze,");
    Console.WriteLine ("nor a good temperature for brewing tea.");
}

Try it out

Copy the Water Temperature code into a new project in Visual Studio. Enter in a temperature and test out the branching statements!

Could you modify the code to ask whether the temperature is Fahrenheit or Celsius, and then adjust the responses accordingly?

Flowcharts

It is helpful to use flowcharts when developing branching narratives. You can create ones that chart the flow of the player's experience, and you can make ones that chart the flow of your programming code.

A flowchart showing the program flow of a decision tree:

flowchart
Flowchart example

Show Free Online Flowchart Applications

There are many online flowchart applications. These three options allow you to jump in and start flowcharting for free, without making an account:

  • draw.io: Free, intuitive, and several options for saving (Google drive, dropbox, hard drive, etc.).
  • Diagramo: Free and open source.
  • Creately: Limited free use, allows collaboration.

Quick Quiz

A string of characters is what data type?

Correct
Incorrect

Which punctuators surround a code block?

Correct
Incorrect

Operators

An operator is a symbol that produces an action. Test expressions use relational and logical operators. We've already seen examples of relational operators in use in the above code (for example, checking whether an integer is greater than a specific number).

Common operators in C#

  • Assignment (=)
  • Mathematical (+, - , *, /)
  • Increment and Decrement (x=x+10, x+=10, x++, x--)
  • Relational (==, !=, >, >=, <, <=)
  • Logical (&&, ||, !)

Assignment and Equality Test

To assign a value, use one equal sign.

temperature = 170;

To test for equality use two equal signs:

if (temperature == 170)
{
     //statements
}

A common error for new programmers is to leave out one of the equal signs when testing for equality. The following code will throw an error.

if (temperature = 170)
{
     //statements (won't run - will throw error)
}

The compiler will assume that you are trying to set the value of the variable, not test whether it is equal to 170. In this particular case, it will probably give an error that you can't implicitly convert an integer to a Boolean value.

Remember that one equal sign assigns a value, and two tests for equality.

Relational Operators

  • == (is equal to)
  • != (is not equal to)
  • > (greater than)
  • >= (greater than or equal)
  • < (less than)
  • <= (less than or equal)

Logical Operators

  • && (and)
  • || (or)
  • ! (not)

Logical Examples

We can add logical operators to further refine our test expressions. For example, if we have a game where we track whether or not the player has found certain items, like a coin or a key, these variables could be Boolean values (true or false).

When the game starts, we could initialize our variables as false. If the player chooses a path where they would find one of the items, the value of the variable would then be set to true.

If we wanted to check that the player has found either a coin or key we could use the "or" operator - two vertical pipes (||).

using System;

namespace ConditionalExample
{
    class Program
    {
        static void Main(string[] args)
        {
            bool key = true;
            bool coin = false;

            if (key == true || coin == true)
            {
                Console.WriteLine("Player has found one or the other (or both).");
            }
            else
            {
                Console.WriteLine("Player has found neither.");
            }
            Console.Read();
        }
    }
}

If we want to check that the player has found both the key and the coin, we could use the "and" operator (&&).

using System;

namespace ConditionalExample
{
    class Program
    {
        static void Main(string[] args)
        {
            bool key = true;
            bool coin = false;

            if (key == true && coin == true)
            {
                Console.WriteLine("Player has found both.");
            }
            else
            {
                Console.WriteLine("Player has not found both.");
            }
            Console.Read();
        }
    }
}

Short form (no equal signs)

If you are testing for true or false you can alternatively leave out the equal signs.

if (key == true)
{
     //statements
}

This can be shortened to:

if (key)
{
     //statements
}

This works with logical operators as well.

using System;

namespace ConditionalExample
{
    class Program
    {
        static void Main(string[] args)
        {
            bool key = true;
            bool coin = true;

            if (key || coin)
            {
                Console.WriteLine("Player has found one or the other (or both).");
            }
            else
            {
                Console.WriteLine("Player has found neither.");
            }


            if (key && coin)
            {
                Console.WriteLine("Player has found both.");
            }
            else
            {
                Console.WriteLine("Player has not found both.");
            }
            Console.Read();
        }
    }
}

Pseudocode

Pseudocode is a set of simple instructions that you can later translate into a programming language. When you write pseudocode, you write out the logic itself without worrying about which programming language you will be using.

It is helpful to use pseudocode to sketch out functionality before you try to code it.

We could write some instructions to test whether the temperature is within a specific range in pseudocode like this:

If (the temperature is less than 170 OR greater than 212) then
it IS NOT a good temperature for brewing tea
else
it IS a good temperature for brewing tea

Practice Pseudocode

Instead of checking whether the temperature is less than or greater, can you check the opposite?

Translate the following pseudocode into C#:

If (the temperature is greater than 170 OR less than 212) then
it IS a good temperature for brewing tea
else
it IS NOT a good temperature for brewing tea

The statements have also been moved so the positive statement is first, the negative is second.

Example Answer

This is one possible way of translating the pseudocode to C#:

int temperature = 184;

if (temperature > 170 || temperature < 212)
{
    Console.WriteLine((temperature + " is a good temperature for brewing tea.");
}
else
{
    Console.WriteLine(temperature + " is not a good temperature for brewing tea.");
}
Console.Read();

Pseudocode to Code

Once we have our logic written out, we can use the OR logical operator (the two vertical pipes || ) to code an expression in C# to check whether the temperature of the water is within a specific range.

screenshot

If we set the value of the variable 'temperature' to 184, what do you think will be printed to the console window when the following code runs inside of our Main() function?

int temperature = 184;

if (temperature < 170 || temperature > 212)
{
    Console.WriteLine(temperature + " is not a good temperature for brewing tea.");
}
else
{
    Console.WriteLine(temperature + " is a good temperature for brewing tea.");
}
    Console.Read();

Escape Sequences

An escape sequence starts with a backslash (\) and then is followed by a specific letter or combination of alphanumeric characters.

An escape sequence can break long text so that words aren't split at the right of the screen. To add a new line in your text use the sequence \n.

Example:

Console.WriteLine("At the front of the imposing building you see a weathered old man with a cart.\nAs you near, you see the cart is filled with what looks like mostly junk and \nonly a few useful items. All you have on you is piece of a chalk.\nYou offer it to him, and he says he'll trade a flashlight or an umbrella for it.\nTo choose type either A for the flashlight, or B for the umbrella.");
Example of text with the escape sequence \n
Example of text with the escape sequence \n

Common Sequences

  • \n: new line
  • \": double-quote mark
  • \': single-quote mark
  • \\: back slash

If you want to include quotation marks inside your strings to indicate dialog, you will be indicating the end of a string to the compiler and will probably get an error. Instead, use the escape sequence \".

Example:

Console.WriteLine("At the front of the imposing building you see a weathered old man.\nHe says, \"Trade me for something shiny.\" You agree.");
Using the escape sequence \" for double quotes within a string
Using the escape sequence \" for double quotes within a string

Quick Quiz

A/An ______________ is a symbol that produces an action.

Correct
Incorrect

Which operator would you use in a test expression to see if the value of an integer was equal to 10? Choose the best operator to fill in the blank in the following code:

int score = 0;

if (score ____  10)
{Console.WriteLine ("You've gotten a perfect score!");}
Correct
Incorrect

Which data type holds either true or false?

Correct
Incorrect

To Do: Dynamic Design and Improve Interface

Assignments

  1. Create a small project experimenting with dynamic design (see below).
  2. Continue improving your game's interface. Add new line escape sequences if you have long lines of text. Improve the readability of your content.

Dynamic Design

Make a small project that changes ASCII design and/or color depending on variable values.

Dynamic Design Examples

One idea could be to allow players to select the color of something. Perhaps they are offered options for an animal companion, and can choose the color of it?

Another idea could be that designs and colors change depending on the location the player is at.

What other ideas can you think of?

Example application
Dynamic design: Menu options for locations

Example application
Dynamic design: Color and design change when Arcade is selected

Example application
Dynamic design: Color and design change when Bowling Alley is selected

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

You'll use your knowledge of conditional statements in the next section to make an example decision for the player. Once you have a model, you'll add in your own content.