Skip to content


TBAG 1.11: Comments

In the preceding example, you’ll see some text after two slashes (”// define function”). These are comments. You can mark up your code, put little notes in, whatever you want to do. When the program is compiled, any comment is ignored.

A single line comment follows the two slashes. It ends when the line ends.

You can comment an entire block by using a slash-asterisk combo: /* comment */. This spans however many lines you need it to. It starts with /* and ends with */.

It’s recommended you comment as much as you can. Actually, it’s recommended you comment every single line. Obviously I’m not doing that here. But comments are great for making notes, or for commenting out blocks of code you think might be screwing up your program.

The TBAG entries are where I blog building a Text Based Adventure Game (rather unfortunate acronym that). The project teaches the building blocks of computer science using C++ to build a text game. To view the entire series, click here.

Posted in Uncategorized.

TBAG 1.10: Functions

I covered function before, but so far we haven’t really used any besides main.

One thing about the previous examples is they’re very linear. The user traces a straight path through the game and then exits. However, that’s not the way games usually go. You have options of going many different places, and then you can backtrack. It would be advantageous if each room, or location, was its own little chunk of code, and each choice along the path led to another chunk of code.

Functions are a way to break up your code into small, reusable chunks. When you use functions you’re skipping to a relevant piece of code, as many times as you need, completing one small task, and then resuming your code where you left off.

void thisIsAFunction ();        // define function

void main ()
{
    thisIsAFunction ();         // call function in main
}

void thisIsAFunction ()         // the function itself
{
    cout << "Code goes here";
}

The first thing you need to do is define your function. This comes before the main function and is like declaring a variable. This way the program knows what it’s dealing with when it gets to a function call. You tell the computer what return value the function will have (or “void” if it isn’t returning a value), the function name, and then the arguments or values you pass to the function.

When you call the function, you just use the function name, and whatever values you pass to the function.

The function itself looks a lot like the definition, but with curly braces and code.

Here’s the function again, only this time it’s passing and returning variables.

int thisIsAFunction (int b, int c);     // define function

void main ()
{
    int a;

    a = thisIsAFunction (2, 4);         // call function in main
    cout << endl << "The value is " << a;
}

int thisIsAFunction (int b, int c)     // the function itself
{
    int d;
    d = b + c;
    return d;
}

The function will return an integer data type, so I’ve replaced the “void” with an “int” in both the definition and the function. I’m also going to pass two integers to the function, so I need to declare those as arguments.

Since the function returns an integer, we need to have a place to put it. We can’t have the function return a value to nowhere. So, I create the integer “a” and return the value into that. I’ll pass the values two and four as arguments. These will go into the function as the integers “b” and “c” as parameters. This is similar to declaring variables in the start of the function.

In the function, I declare an integer “d”. I then say “d” is the sum of “b” and “c”. I then return“d”. The function then passes “d” back to main where it gets loaded into “a”.

And that, in a nutshell, is how you use functions.

The TBAG entries are where I blog building a Text Based Adventure Game (rather unfortunate acronym that). The project teaches the building blocks of computer science using C++ to build a text game. To view the entire series, click here.

Posted in Uncategorized.

TBAG 1.9: Loops, or Iterative Structures

Earlier, we set up a separate “else” statement in case of user error. That way the program wouldn’t crash if they accidently typed something other than “R”, “r”, “L” or “l”. The problem with what we did is, while the program wouldn’t hang, it would just end. That seems a little severe for a typo.

It would be better to give the user a second chance, maybe even a third and fourth chance. Actually it’d be nice if the program just looped, constantly prompting the user, until the user figures out exactly what answer to give. And we can do this!

There are three main ways of doing a loop, or an iterative structure. Two of them are based around the while statement, the other is a for statement. The for statement is more of a counter; the while statement will loop as long as a control expression, the part in parenthesis, is true. That is, while this condition is true, do the action in the curly braces. The do while statement does the same thing, except the code in curly braces is run before the condition is checked. That is exactly what we want. We want to prompt the user for the direction, get the variable, then check if it’s right. If it is, we jump out of the loop. If it isn’t, we repeat the loop.

First we need to figure out under what condition(s) do we run the loop? We, if we don’t get an “R”, “r”, “L” or “l” we need to repeat it. A quick truth table will help us figure out the conditions we want. Well, with four possible outcomes it won’t be “quick” exactly…

d == R

d == r

d == L

d == l

REPEAT

d != R

d != r

d != L

d != l

REPEAT

F

F

F

F

T

T

T

T

T

T

F

F

F

T

F

T

T

T

F

F

F

F

T

F

F

T

T

F

T

F

F

F

T

T

F

T

T

F

F

F

F

T

F

F

F

T

F

T

T

F

F

T

F

T

F

T

F

T

F

F

F

T

T

F

F

T

F

F

T

F

F

T

T

T

F

T

F

F

F

F

T

F

F

F

F

F

T

T

T

F

T

F

F

T

F

F

T

T

F

F

T

F

T

F

F

F

T

F

T

F

T

F

T

T

F

F

T

F

F

F

T

T

F

F

F

F

F

T

T

F

T

T

F

T

F

F

F

T

F

F

T

T

T

F

F

F

F

F

T

F

T

T

T

T

F

F

F

F

F

F

 

Looking at this, we can see there are 15 possibilities in which we want to skip out of the loop, but only one time in which we want the loop to be repeated. We can apply a few of our logical conditionals to see which one we need to make this loop work.

 

d == R

d == r

d == L

d == l

REPEAT

AND

!AND

AND !=

OR

!OR

F

F

F

F

T

F

T

T

F

T

F

F

F

T

F

F

T

F

T

F

F

F

T

F

F

F

T

F

T

F

F

F

T

T

F

F

T

F

T

F

F

T

F

F

F

F

T

F

T

F

F

T

F

T

F

F

T

F

T

F

F

T

T

F

F

F

T

F

T

F

F

T

T

T

F

F

T

F

T

F

T

F

F

F

F

F

T

F

T

F

T

F

F

T

F

F

T

F

T

F

T

F

T

F

F

F

T

F

T

F

T

F

T

T

F

F

T

F

T

F

T

T

F

F

F

F

T

F

T

F

T

T

F

T

F

F

T

F

T

F

T

T

T

F

F

F

T

F

T

F

T

T

T

T

F

T

F

F

T

F

 

Truth tables can be an excellent way of checking logic. They can also be an excellent way of finding quicker ways of doing the same thing. I’m not going to get into optimization now, just keep in mind that working up a quick truth table can be one way to minimize operations.

We can now see there are two ways of doing this properly. The first is ORing each of the four possibilities together and then seeing if looping if the result is false. We can also check to see if each of the possibilities are false, then AND the results. I’m going to use that method because it’s what we’re really doing. If “d” does not equal “R” and “d” does not equal “r” and “d” does not equal “L” and “d” does not equal “l” then we need to prompt for a new answer. That’s probably not ideal, since we’re both negating the answer and checking for OR, but I’ll take the slight performance hit on this. There’s a lot more leeway with these things on a tiny text game than there would be on a huge, complex 3D game, or on airplane controls or medical equipment.

void main()
{
    char d;

    cout << endl;
    cout << endl << "You are in a room.";
    cout << endl << "There are two doors, one on the right,";
    cout << endl << "one on the left.";
    do
    {
        cout << endl << "Which do you want to do? (R/L) : ";
        cin >> d;
    } while ( d != 'R' && d != 'r' && d != 'L' && d != 'l' );

    if (d == 'R' || d == 'r')
    {
        cout << endl << "You went through the door on the right";
    }
    else if (d == 'L' || d == 'l')
    {
        cout << endl << "You went through the door on the left";
    }
    cout << endl;
}

So the part in curly braces is run. The user is asked what to do, then is prompted to enter a response. The user does, and we check it. The user has to give a correct answer before the program will continue.

While operates in the same manner, only the condition is checked before the code is run. That won’t work for this example, since our prompt is inside the code. Unless we prompt twice, once outside the code to get the initial response, then in the loop.

    a = 0;
    while ( a < 100)
    {
        cout << endl << "a is " << a;
        a++;
    }

This is probably a bad example of while. First, we declare “int a;” which we set to zero. We check to see if “a” is less than 100. It is, so we print it.

The next part may look a little different. We want to increment a by 1. We could do this by saying “a = a + 1;” but C++ uses a shortcut to this. In fact, notice that “a++” and “C++” are a lot alike. C++ is mostly just the C language, with a few extensions. Therefore we say C++ is one increment past C. Just like here, a++ is a plus 1, or one increment past a.

As a sidebar, C is a descendent of a language called B. There was never an A language, so far as I know. The Java and C# languages borrow heavily from C++, so you could say they’re descendants of C++.

We can also use a decrement, or a–, if we want to subtract one from a.

There are two variations of the increment and decrement: pre- and post-increment. Pre-increment (++a) means the variable is incremented before being used, while post-increment means it is incremented after use.

Anyway, going back to our while loop that counts to 100. The loop is correct, but there’s actually another loop that’s built specifically for counting: the for iterative structure.

    for (a=0; a<100; a++)
    {
        cout << endl << "a is " << a;
    }

The for control expression is broken up into three parts. The first is the loop index, or control variable. It sets the variable. The second is the condition. The third is the increment or decrement value.

The increment value doesn’t have to be a “plus 1″ value. You can mix it up however you like. Just mind the conditional. If you run something like “a=0; a==2; a=a+3″ you’ll get an infinite loop. However, the following is perfectly valid.

    for (a=0; a<99; a=a+3)
    {
        cout << endl << "a is " << a;
    }

In this case, the statement will start at zero. It will print “a is 0″. Then it will increment by 3 and print that result. It will keep doing that as long as a is less than 99. Note that condition is less than 99; it does not include 99.

So that is how we approach programs logically. We declare variables so the program can manipulate data. We use conditionals and logic operators to give the program choices. We use loops to cycle through data and perform actions, or to stick the user in a sort of limbo until we get the data we need.

We still have some ground to cover before we really dive into building a game. But we could build a game right now. We could set up a while loop (while the user hasn’t “quit”) containing a bunch of if statements navigating through a maze. If you’re into homework, I’d recommend you make a small game using these techniques. Nothing fancy, just two or three rooms.

The rest of this section will cover functions, a way to break the program into small, re-usable parts. After that, we’ll start building a map.

The TBAG entries are where I blog building a Text Based Adventure Game (rather unfortunate acronym that). The project teaches the building blocks of computer science using C++ to build a text game. To view the entire series, click here.

Posted in Uncategorized.

TBAG 1.8: Logic: Or, Xor, And, Not and Mod

In one of the previous examples, we were discussing whether to eat out or in. We asked it in the form of an if/then statement, with one little exception. “IF you’re out of groceries OR you don’t feel like fixing something, THEN you may go to a restaurant.” We later expressed if the user types the little “r” for going right, or the big “R”. We used a set of pipes, “||”, typically found above the “enter” key, to specify the “or” operator.

    if (d == 'R' || d == 'r')

The “or” operator is one of a handful of logic operators. It takes two or more values and, depending on the outcome, returns a true or a false. In the case of or, it returns true if one or both conditions are true. If they are both false, it returns the value false and, in this case, skips the contents of the “if” statement. This is easiest to represent using a truth table.

Condition

Outcome

d == “R”

d == “r”

OR (||)

F

F

F

F

T

T

T

F

T

T

T

T

 

Related is the exclusive or, the XOR operator. In that case, one condition has to be true while the other false. They cannot both be false, nor can they both be true.

Condition

Outcome

d == “R”

d == “r”

XOR

F

F

F

F

T

T

T

F

T

T

T

F

 

The XOR operator may seem a little strange, and a little pointless. But these operators have their roots in transistor circuits. They’re called logic gates. Two signals (high or low) go in, one signal comes out. You know, the Thunderdome syndrome. The signal that comes out depends on the type of logic gate you use. I won’t go too deeply into it here, but at the lowest level of computing, the XOR gate is extremely useful. You might even use it in code someday. Mostly, you’ll use OR, AND, NOT and MOD however.

The “not” operator, representing in C++ as an exclamation mark, simply negates things. For example, you could say that if it’s NOT the case that d is “R” OR d is “L”, then throw an error.

Condition

Outcome

Outcome

d == “R”

d == “r”

OR

NOT (!)

F

F

F

T

F

T

T

F

T

F

T

F

T

T

T

F

 

The AND operator (two ampersands) is a little less forgiving than OR. The only time the outcome is true is when both conditions are true.

Condition

Outcome

d == “R”

d == “r”

AND (&&)

F

F

F

F

T

F

T

F

F

T

T

T

 

The MOD operator is not a logic operator, but it’s kind of funky so I’m throwing it in here. MOD stands for the modulo operation, and is often represented by a percentage sign. Modulus is the remainder of a division statement. For example, five divided by two would leave a remainder of one. Therefore, five mod two would equal one.

This can be extremely useful in checking for, say, an even number. If the remainder of x divided by two is zero, then x is even. If not, x is odd. You can write this as:

If (x % 2 == 0) { cout<<”The number is even”; }

Or, you can use the negation operator for force the zero into a “true” statement:

If (!(x%2)) { cout << “The number is even”; }

If (x%2) { cout << “The number is odd”; }

If (x%2 != 0) { cout << “The number is odd”; }

Likewise, modulo is useful for counting. Say you want a particular action on every third number. Then you would use if (x%3==0).

One aspect of this is what’s called short circuit evaluation. Take the statement:

    if (a <= 0 && b >= 14)

Now AND is only true when both cases are true. So if there’s ever a case where ‘a’ is greater than zero, the evaluation will short circuit. It will end itself at that point, rather than checking ‘b’. That can save some precious computation power in some cases.

The TBAG entries are where I blog building a Text Based Adventure Game (rather unfortunate acronym that). The project teaches the building blocks of computer science using C++ to build a text game. To view the entire series, click here.

Posted in tbag. Tagged with , , .

TBAG 1.7 If, or the Selection Structure

We make decisions every day. You’re hungry. Do you raid the refrigerator, or go to a restaurant? That could be determined by a several factors. If you’re out of groceries or you don’t feel like fixing something, then you may go to a restaurant. But what restaurant? That depends on what kind of food you feel like eating.

Computer programs do much the same thing, only they express it with a selection structure. There are three variations of the selection structure: if, if else, and switch. All are variations on a theme. If a condition is true, work on a particular piece of code. Otherwise, skip it.

In C++, we form a conditional by the keyword “if”, followed by the condition in parenthesis, and then the code to work on in curly braces.

    if (d == 'R')
    {
        cout << endl << "You took the trail on the right.";
        cout << endl << "You come to a large oak tree, long since dead.";
        cout << endl << "Insects crawl through it like a corpse.";
    }

In this case, we’re looking to see if the user wanted to go right. We prompt the user to enter “R” if they do. So the user would type in “R”, the program would assign that value to the variable “d”, and then we would check to see if “d” equals “R”.

Here we get into the difference between the assignment operator (”=”) and the equality operator (”==”). In your day-to-day math, you’d use the equal sign for both. Humans can figure out the difference between the two just by looking at them, but computers need to be more literal. So we use the double equal sign for comparing two items, and the single equal sign to assign a value to a variable.

The double equal sign is part of the relational operators group.

Relational Operator

Description

<

Less Than

<=

Less Than or Equal To

>

Greater Than

>=

Greater Than or Equal To

==

Equal To

!=

Not Equal To

 

If the user did not enter “R” then the program skips the code in braces. What if they entered “L” instead? We need to create an “if” statement in case they did. We can write an “else” statement: if the user typed “R” then the program will run the code in the first set of curly brace, anything else the user enters will run the code in the second set of curly braces, following the keyword else.

There are a few problems with that, in this example. For one thing, what if the user enters “r” instead of “R”? It’s always a good idea to error-proof the program. So in the first if we’ll set the conditional that if the user enters “R” or the user enters “r” then the first group of code will run. And to error-proof further, what if the user accidentally types “E”, which is right beside the “R”? The if/else statement would have the user going left because of a typo.

The solution is to use an if/else if/else statement, which gives us as many options as we’d like to write. For this program, three would be fine. If they pick “r” or “R”, do this; else if they pick “l” or “L” do that; else, for all other choices that don’t have any action associated with it, throw an error…

    if (d == 'R' || d == 'r')
    {
        cout << endl << "You took the trail on the right.";
        cout << endl << "You come to a large oak tree, long since dead.";
        cout << endl << "Insects crawl through it like a corpse.";
    }
    else if (d == 'L' || d == 'l')
    {
        cout << endl << "You took the trail on the left";
        cout << endl << "You pass a pond, darkened by low-hanging trees.";
    }
    else
    {
        cout << endl << "You didn't pick R or L";
    }

For this example, the if/else if/else statement is fairly easy to manage. However if we expand the commands a user can enter, like “B” for “Back”, “Q” for “Quit”, “I” for “inventory”, and so on and so forth… well, that would rapidly turn into an ugly mess with if/else if/else if/ else if on down the line. Fortunately, C++ has a shortcut called the switch statement.

    switch(d)
    {
        case 'r':
        case 'R':
            cout << endl << "You took the trail on the right.";
            cout << endl << "You come to a large oak tree, long since dead.";
            cout << endl << "Insects crawl through it like a corpse.";
            break;
        case 'l':
        case 'L':
            cout << endl << "You took the trail on the left";
            cout << endl << "You pass a pond, darkened by low-hanging trees.";
            break;
        default:
            cout << endl << "You didn't pick R or L";
            break;
    }

The switch statement is basically the same thing as if/else if/else if/else; it’s just a little neater way of doing it. And when you discover a bug somewhere in a mass of code, keeping things neat turns into a good thing.

Rather than have nested curly braces, the switch statement uses the “break” keyword to separate cases. It’s customary at the end to provide a “default” condition, which is used as error checking if none of the cases were met.

Getting back to the if statement, you can nest if statements, as deep as you want. For example:

    if ( a == b)
    {
        if (b == c)
        {
            if (c == d)
            {
                if (d == e)
                {
                    cout << "Stop it!";
                }
            }
        }
    }

One last thing. There is a C++ statement that is a shorthand method of writing the if/then/else structure, providing they are single lined statements.

    d == 'r' ? goRight = true : goRight = false;

This is called a ternary conditional operator. This line would tranlate as: if d is equal to ‘r’, then (?) goRight is true, else (:) goRight is false. I personally don’t use that very often, but I remember when I first saw that in code I couldn’t figure out what it was.

The TBAG entries are where I blog building a Text Based Adventure Game (rather unfortunate acronym that). The project teaches the building blocks of computer science using C++ to build a text game. To view the entire series, click here.

Posted in tbag. Tagged with , , .

TBAG 1.6: Naming Variables

Of course “g” and “d” are really terrible names for these variables. The rule of thumb is to assume some poor, hapless programmer will have to update your code in ten years. That programmer might even be you. Are there enough clues for this programmer to figure out what the code is doing? Will you remember as you scour your code ten years hence what “d” stood for? If they find “d” scattered throughout the program, will they automatically know what that means? On this program, sure. On a large program, perhaps not. That’s why naming is so important.

On this, I probably should have picked the name “user input”. That sums up exactly what the variable is for. However, C++ does not accept names with spaces in it. The compiler looks for spaces to break up each statement into commands. So it would read “user”, recognize that we want it as a variable, then try to figure out what “input” is, and get all confused and break down sobbing.

We take care of that by merging the two into “userinput”. The computer likes that, but I don’t. Visually, it’s hard to read. I could put an underscore in between the words “user_input” but I’m going to use what’s called Camel case, which is fairly common in the programming industry. We leave the first letter lowercase, and then uppercase the start of each word: “userInput”. Pascal case is the same as Camel case, only with the first word also capitalized.

C++ is what’s known as a strongly typed language, that is, you cannot change the type midway through the program. Sometimes programmers will use extra notation to describe the data type, in order to remember what data type they were dealing with. Hungarian notation is Pascal case, with extra characters describing the data type. So in this example we would use a “c” for “character” and write “cUserInput”.

The “best choice” for data naming open for debate. Some companies will require you to use one or the other on their projects. I tend to use the Camel case and let the compiler tell me the type, if I need to be reminded. Regardless, I definitely name my variables something self-descriptive, that I can remember when I’m pouring through code looking for bugs at 2 a.m.

One exception that you’ll pick up on quickly is counter variables. That is, if a programmer uses a variable to count to a hundred, that programmer will tend to use “i”, “j” or “k”. This is standard practice and one of the few times you’ll see single-letter variables.

The first letter of a variable name has to be either an underscore or a letter. You can use letters, numbers or the underscore throughout the variable name. C++ is case sensitive, so “userinput” would be considered a different variable than “userInput”.

There are also certain words, called keywords, you cannot use. These are words the compiler sets aside for itself. For example, char, int and float are all keywords. If you use something like “char int;” the compiler will throw an error, uncertain of what you’re intending to do.

Common Reserved Keywords

asm

else

operator

this 

auto

enum

private

throw 

break

extern

protected

true 

case

false

public

try 

catch

float

register

typedef 

char

for

return

union 

class

friend

short

unsigned 

const

goto

signed

virtual 

continue

if

sizeof

void 

default

inline

static

volatile 

delete

int

struct

while 

do

long

switch

 

double

new

template

 

 

And that is way more than I wanted to talk about on variables. Sorry. I actually could have gone on for awhile longer, but I imagine your eyes are starting to glaze over and some of you are muttering “dude, I swear you mentioned something about building a game…” So onward to conditionals!

The TBAG entries are where I blog building a Text Based Adventure Game (rather unfortunate acronym that). The project teaches the building blocks of computer science using C++ to build a text game. To view the entire series, click here.

Posted in tbag. Tagged with , , .

TBAG 1.5: Thinking in Binary

It’s pretty common knowledge that computers communicate with ones and zeroes. These ones and zeroes can be represented several different ways: true or false, a low (0v) or high (5v) voltage, a pit or valley on a disc, a magnetic material polarized this way or that. At the end of the day, it all boils down to a one or a zero. All the data that’s stored in the computer’s memory, the program, the data, music or video or pictures, are all a very long string of ones and zeroes.

Declaring a variable tells the computer how many ones and zeroes the variable is going to use, and how much memory to set aside.

The reason why it needs to reserve space, to oversimplify, is that when a program tries to set aside as much space in memory as it needs. This way any programs started after the first won’t hog all the resources. The code for the program itself is stored in memory, then enough room for all the data it may be working with.

All very well and good, but how one actually use binary notation, those ones and zeroes, to represent numbers? It’s actually very similar to how we the decimal system. Take a large number, such as 256. Each digit in there represents a particular value. The two is in the hundreds slot, the 5 is in the tens slot. What that means, actually, is 2 is times a hundred; 5 is times ten; 6 is times one. Not only that, but each thing we’re multiplying is actually 10 to the power of a number, hence decimal (ten) notation. One is 100, ten is 101, 100 is 102, and so on.

In other words, 0256 would actually be:

(0 * 103) + (2 * 102) + (5 * 101) + (6 * 100)

(0 * 1000) + (2 * 100) + (5 * 10) + (6 * 1)

(0000) + (200) + (50) + (6)

0256

Of course, who thinks about doing that? The number 256 is 256, not “(2 * 102) + (5 * 101) + (6 * 100)”. And yet, that’s exactly how you translate it. The same principle applies to binary. But rather than have each digit multiplied by 10x, we multiple each digit, or bit in this case, by 2x. For example, 0101 would translate to:

(0 * 23) + (1 * 22) + (0 * 21) + (1 * 20)

(0 * 8 ) + (1 * 4) + (0 * 2) + (1 * 1)

0 + 4 + 0 + 1

5

Fortunately, binary has an easy pattern that you can pick up on, rather than going through that mess each time. You start with one on the right (also called the least significant bit). Going left (towards the most significant bit) you double that number; then double it again and again.

x 

15 

14 

13 

12 

11 

10 

9 

8 

7 

6 

5 

4 

3 

2 

1 

0 

value 

32768 

16384 

8192 

4096 

2048 

1024 

512 

256 

128 

64 

32 

16 

8 

4 

2 

1 

 

Eight bits is called a byte. Four bits is called a nibble. Sixteen bits is called a word. Different variable types take up different amounts of space and do different things.

Data Type

Space Taken 

Lower Bounds 

Upper Bounds 

char

8 bits (1 byte) 

-128 

127 

unsigned char 

8 bits (1 byte) 

255 

short int 

16 bits (2 bytes) 

-32,768 

32,767 

unsigned short int 

16 bits (2 bytes) 

65,535 

Int

32 bits (4 bytes) 

-2,147,483,648 

2,147,483,647 

unsigned int

32 bits (4 bytes) 

4,294,967,295 

long int

Same as int

   

Float

32 bits (4 bytes)

3.4 x 10-38

3.4 x 1038

double 

64 bits (8 bytes) 

1.7 x 10-308

1.7 x 10308

bool

1 bit

0

1

 

Now when we say “char d;” we’re really telling the computer to set aside a byte in memory. Throughout the program we’ll reference this with “d”. So when a user enters “R”, that will become the value of “d”.

So, what does an “R” look like in binary? A lot like a binary integer: 1010010, or the number 82. An “L” looks like 1001100, or 76; an “r” looks like 1110010 or 114, and an “l” looks like 1101100, or 108. Characters are simply another number. In fact, you can force it into being treated as a number if you don’t want to waste four bytes for an integer. The computer looks up the number in a table and prints out the appropriate character.

When you declare a variable, it’s going to be full of junk. You can assign a value to it when you declare it. In fact, that’s recommended, even if it’s just zero or null. You do that by the assignment operator, which we normally call the equals sign:

int g = 10;

You can also assign a value to it anytime during the program.

g = 10;

The TBAG entries are where I blog building a Text Based Adventure Game (rather unfortunate acronym that). The project teaches the building blocks of computer science using C++ to build a text game. To view the entire series, click here.

Posted in tbag. Tagged with , , .

TBAG 1.4: Intro to Variables

One of the main purposes of computer programs has always been to store, retrieve and manipulate data. Computers are particularly suited to running through huge, monotonous mounds of information.

Data can obtained from all sorts of different ways: from other computers across a network; from a file on the disc drive; from the disc drive itself; from the user, entering it when prompted by the program; from the programmer, who builds the data into the program itself.

But no matter how you get the data, it must be stored somewhere while the program uses it. To store it, we use variables.

A variable is a storage slot for data that will be changed during the course of the program. There are several different kinds of variables. Mostly the differences have to do with how big of a storage slot you use. It also has to do with how the variable is treated by the program.

For example, “char d;” tells the program, or declares, that you need a character variable. We call it “d” for direction. Once declared, the program will create a slot in memory to store a single character. Eventually, something will be saved in it, but for now the computer just has to reserve some space.

Besides “char”, you’ll mostly be using “int” for integers and “float” for floating point notation. There is also the “bool” data type, which is strictly for zero or one, false or true. This is a very useful data type, but not at all compilers accept bool.

Most data types can be signed or unsigned. If a type is signed, it can have either positive or negative values. However, data types have an upper and lower bound. If signed, that upper and lower bound is split between negative and positive values. For example, if you forced an unsigned “char” type into dealing with numbers, it would only contain numbers from zero to 255. Making it signed would cut that upper bound in half, but would give you an equal amount of negatives values, -127 to 127 in this case.

One thing you can do is make a variable a “constant”. That is, it won’t change during the course of the program. This is good for mathematical constants. For example, pi will always be 3.14.

There are two ways of creating constants. You can declare it in the header as a compiler directive: #define PI 3.14. What that does is, before the program is compiled, the compiler will run through the program and replace any instance of PI with 3.14.

More commonly, you can add the “const” keyword to any variable declaration: “const float PI = 3.14;”. This has the effect of locking the variable.

Now a “char” data type only contains one character. Sometimes you need to store an entire word, or even a sentence. To do this, you need to bundle a bunch of char types together in an array. In the case of characters, an array is commonly called a string. Arrays have many uses when dealing with data, but also several limitations. We’ll get to those in greater detail later.

The TBAG entries are where I blog building a Text Based Adventure Game (rather unfortunate acronym that). The project teaches the building blocks of computer science using C++ to build a text game. To view the entire series, click here.

Posted in tbag. Tagged with , , .

TBAG 1.3: Two Road Diverged in a Wood

Now that we’ve made our “Hello World” program, it’s time to start creating games. We’re going to focus on a few simple ones that will expand our knowledge of C++.

In this example, a user is walking along a trail and gets to a fork in the road. How do we ask the user which way to go? How does the program go in the direction the user wants?
We do it kind of like this…

#include
#include
#include
using namespace std;

void main()
{
    char d;

    cout &lt;&lt; endl;
    cout &lt;&lt; endl &lt;&lt; &quot;You are walking along a narrow dirt trail.&quot;;
    cout &lt;&lt; endl &lt;&lt; &quot;On either side of you, crickets chirp in the tall, brown grass.&quot;;
    cout &lt;&lt; endl &lt;&lt; &quot;You come to a fork in the trail.&quot;;
    cout &lt;&lt; endl &lt;&gt; d;

    if (d == 'R' || d == 'r')
    {
        cout &lt;&lt; endl &lt;&lt; &quot;You took the trail on the right.&quot;;
        cout &lt;&lt; endl &lt;&lt; &quot;You come to a large oak tree, long since dead.&quot;;
        cout &lt;&lt; endl &lt;&lt; &quot;Insects crawl through it like a corpse.&quot;;
    }
    else if (d == &#39;L&#39; || d == &#39;l&#39;)
    {
        cout &lt;&lt; endl &lt;&lt; &quot;You took the trail on the left&quot;;
        cout &lt;&lt; endl &lt;&lt; &quot;You pass a pond, darkened by low-hanging trees.&quot;;
    }
    else
    {
        cout &lt;&lt; endl &lt;&lt; &quot;You didn&#39;t pick R or L&quot;;
    }
    cout &lt;&lt; endl;
}

You’ll notice the structure is the same as the “Hello World” program; there are the compiler directives, followed by the main function. The header has a few new things in it. The header file “stdio.h” has been replaced by “iostream”. The io stands for “input / output”. That is, what we print out to the screen, and what the user types in. Think of it as two streams, one pushing data out of the program, and one in which data is rushing in to the program. In this case, I’m using “cout” rather than “fprint()” to show to the screen…

    cout &lt;&lt; endl &lt;&lt; &quot;You are walking along a narrow dirt trail.&quot;;

This is the same thing as saying printf(“\nYou are walking…”);. To use cout I needed a different header file, iostream, to replace stdio. Unfortunately this version of Visual Studio didn’t accept iostream, so I had to add a few other things to the header file. You may wonder why I’m using cout instead of printf. After the hassle of figuring out why cout no longer worked with iostream.h, so am I. It does make input easier at least.

There are three other differences between this and the Hello World program. First, you’ll note a line that says “char d”. This is called a variable, and is a quick way for you to store information the program will need later. Then you’ll see the program is broken up by “if” and “if else” and “else”, each with their own set of curly braces. These are conditional statements, and are a way of directing the flow of your program. Finally you’ll notice a bunch of weird code inside the “if” statement’s parenthesis. These are logic operators.
So we’re going to split these lessons up, explore them, then revisit the program to explore a fourth topic.

The TBAG entries are where I blog building a Text Based Adventure Game (rather unfortunate acronym that). The project teaches the building blocks of computer science using C++ to build a text game. To view the entire series, click here.

Posted in tbag. Tagged with , , , .

TBAG 1.2: Using a Compiler

With a web site, you can easily create your pages in a text editor, such as Notepad that comes with Windows. You can then save the file, open it in a browser and have everything work. Most computer languages aren’t so easy. We’ll be using the C++ language to build a game. However, computers can’t actually read C++. The language is a sort of compromise for the programmer between what computers can process and what humans can comprehend. To run a C++ program, the code must be translated to something the computer can actually use.

There are two main ways of translating a computer language: before distribution or after. Web-based languages are translated after, or interpreted right on the spot. These are usually small and translated quickly. They have to be because they are translated each time they are run, dragging down a computer’s performance. Also, they are designed for many different computer environments. Whoever is reading your web site may have Windows, an Apple or be running Linux or some other open-source operating system. The reader may be using Internet Explorer, Firefox, Safari, Chrome, Netscape’s Navigator, or a text based browser designed for command line environments. They may be using a phone to browse the web, or a device for the blind. With web sites, you cannot really target your audience. So whatever code you write needs to be translated on the reader’s computer.

The programs we’ll be writing, however, can be targeted to a particular computer. This means we can translate our code into something the computer can recognize. It’s an extra step for us, but it does have some advantages. For one, speed. The user’s computer doesn’t need to translate it every time it opens the file. It’s also written for a specific computer, so it can really be optimized for the computer itself. It also bundles multiple files, and hides the code.

This is a long way of saying, since we’re going to do this program in C++, we need to use a compiler to translate our code into something the machine can use.

I’m using Microsoft Visual Studios 2008 to compile the examples for this project. Microsoft has a free version of their Visual Studios C++ compiler on their Coding 4 Fun site. Linux had a free compiler called GCC. It doesn’t have a GUI (also known as an IDE), and doesn’t come with a text editor, but it’s free and worked fine back in the day (like, four years ago). Linux also has VI and Emacs to use as a text editor, but I’m not going to get into the endless debate about which one is better. I’m sure Mac OSX has some compiler tools as well. Information and up-to-date instructions should be all over the web.

I really hesitate to give much advice about compilers. Things change, you know. However, I’ll take you through the steps I would use in Microsoft Visual Studio 2008 so you can get an idea of how to use a compiler. That may not be how you would do it, but it might give you some useful notions.

Visual Studio Compiler

To begin with, I open Microsoft Visual Studios 2008. I go to file, then “New Project”. Next, I have to tell the compiler what kind of program I’ll be working with. There are many, many choices there, but we want to use C++. Since the program is text-based, and doesn’t require any GUI or graphics processing, I want to write for console application.

It then gives me the choice of what to call the Project, where to store all the files, and what to call the program or “solution” as it’s called here. The compiler then creates a folder for all the files, and puts a few files of its own in there, mostly to manage all the code you’re about to create.

New Project

Next you have an overview screen. I pick “application settings” and am given a few more options. I want to make sure this is on “console application”, and I select “empty project”. A non-empty project is one where Visual Studios will add a bunch of helpful code to minimize your work. We don’t really need their help for this program, however. So click “finish”.

Application Settings

And after all that, you don’t even get a file! On the right (usually) is a pane that tells what files and folders are associated with your project. I right click on the name of the project, and go to add, new item.

It will ask me what kind of new item to add. Again, you can see many, many choices. In this case, I just want a simple CPP file. I’ll name it, and confirm it’s going where it should be going.

New Item

New Item

Visual Studios will then create a file, add it to your project, and throw a blank page up on the screen. You can add many files to your project, and have many files open at once, accessible using the tabs along the top. On the left are tool boxes, but we won’t be using those for this example.

Go ahead and type your “Hello World” program into the blank page. When it’s done, you need to build it. That is, compile it into a program. Go to build, and then “build HelloWorld” (or whatever you called this). You’ll see a box pop up on the bottom. This tells you what’s going on as the compiler builds the program and, when done, if there are any errors and what those errors are. As an example, try removing the semi-colon at the end of the “printf” line. When you re-build the program, you’ll get a “syntax error” message. Double-clicking on this message will drop your cursor at the guilty line.

Build Hello World

Next, it’s time to run the program. Click Debug, then “Start without Debugging”. This will run the program. You can also navigate to the project folder and look for an exe file. The problem doing that is, the console will terminate along with the program. Not very practical for this program. It will just print and vanish!

Start Without Debugging

And there you have it! It’s pretty easy to use a compiler, depending on what you’re doing of course. Later I might re-visit this with something a bit more complex and show you how to use the debugger. Until then, let’s go ahead and run the Hello World program!

Hello World

I should point out that there are some languages that are in between being compiled and interpreted; for example, Java and the .net platform. These are partially compiled by the coder, and then interpreted by the user for his or her specific environment. It’s sort of a middle ground between the two.

Anyway, now that you should now be able to write, compile and run a C++ program, we’re now going to start building a foundation of C++ before getting into the main game.

The TBAG entries are where I blog building a Text Based Adventure Game (rather unfortunate acronym that). The project teaches the building blocks of computer science using C++ to build a text game. To view the entire series, click here.

Posted in tbag. Tagged with , , , .