XNA Game Making

Resources for making games with XNA

Chapter 2: Data and Operators

 To get the free pdf or to buy a printed version go to the book page at  lulu.com.

Data, that is to say information, is the main thing that programs work on. We can think of computer programs as doing nothing more than reading in data, doing some kind of manipulation on the data, and spitting it back out.  This is true for all video game programs even if it may not seem immediately obvious. All games do is read in some art and other data, manipulate it to display it onscreen, then read in more data (keyboard presses, other input) and do some more things and output some more data (pictures, audio, etc.)

 

In this chapter we'll look at how data is used in programs and different operations that change it. Specifically we'll cover:

 

l  What variables are and how to implement them in code.

l  The different simple types of variables in C#

l  C#'s basic operators

l  Start making a simple text based game, “Finding the Gold”

 

Data

The simplest type of data is a simple variable. A variable is just a place in memory to store some information, and a name to describe where it is at. The information that is stored in the variable is called the value of the variable. Variables also have specific types (number, letter, string) depending on what kind of data they're storing. For instance the following:

 

int age;

 

Creates a variable of the integer type (a number) named age. We can then assign the variable a value, such as:

 

age = 142;

 

So later in the program (unless we change it) when we read what age is it will be 142. This is the basic concept of variables; let's go through some more facts about them.

 

Declaring Variables

Before we can use any variables we have to declare them; that is to tell the compiler about the variable before doing anything with it. The basic syntax of this is:

 

type name;

 

As in the age example above, we had to give the type, int for integer, and the name of the variable (age). The most common basic types are bool (true/false), int (integer), float (a decimal number) and char (a single character.) (We'll go over these types in more detail in a moment, but there are a few more points to cover first.) When we declare a variable we can also initialize it to a value. In the age example, we could have written it as:

 

int age = 142;

 

Variables should be assigned a value before they are used in C#.

 

Assigning Variables

We used the equal’s symbol above to initialize the age variable to a value. Notice the equals sign in C# doesn't mean equals in the mathematical sense. It is actually the assignment operator; it takes the value to the right of it and assigns it to the variable on the left of the sign. Again for example

 

age = 142;

 

Says to take the value to the right of the equals sign, 142, and assign it to the variable age. This is called assigning the variable. (The equals sign in C# isn't =, but as we’ll see in the next section, is two equals signs, ==.)

 

As we said before C# requires that a variable be initialized before it is used. A program like the following:

 

int test;

Console.WriteLine(test.ToString());

 

will generate an error for using the variable test when it is unassigned. In regular code not using an unassigned variable is a must and when we create objects it is not required (a default value will be created) but is still the preferred thing to do.

 

Simple Variable Types

Now that we looked at how variables are declared and how to store information in them (assign them values), let’s go back over some of the different simple variable types we can use.

 

bool – boolean. Boolean variables are pretty simple, they either have one of two values, “true” or “false” These types come up when we start doing logic testing. There are a lot of places in programming where we need to decide if something is true or not (like if a game is currently paused) and these variables come in handy for that.

 

// A bool variable

bool testBool = true;

 

int – integer In case you don't remember from math class, integers are numbers that are “whole”, in that they don't have any fractional components, no decimals. These numbers can be negative, positive, or zero. Integers come up a lot in programming; they are especially useful whenever we need to count something.

 

// An int variable

int testInt = 5;

 

float – floating point number These are decimal numbers, like 3.14, 0.0001, etc. Basically whenever we need any type of decimal number this is the type of variable we'll be using. The only catch with this is that any floating point number we type in we'll need to put a little “f” after it to say that it is a float. For example:

 

// float variables

float piGood = 3.14f; // Better, the little f ends our problems

float piBad = 3.14; // Compiler will call this an error

 

double – another decimal number. Doubles are similar to floats; they are also decimal numbers, only you don't have to include the little “f” after them. The difference between float and double is that double uses much more memory (we can think of it as using double the memory of a float.) We mostly use float for decimal numbers, as memory is important and we don't want to use excess if we don't have to, and (more importantly) the larger numbers are less efficient and take more time to do calculations than the floats. If on the other hand we are doing something very precise, like a complex physics calculation where we want to have as little error as possible, we'll need the numbers to be more precise (use more memory) and we'll use double instead of float.

 

// A double variable

double testDouble = 3.14;

 

char – a single character. Enough numbers, this simple type is a variable that just stores a single character as its value. The letter has to be put in single quotes.

 

 

// A char variable

char letter = 'a';

 

string –A series of characters. Not technically a simple type, but used just as much as the others. A string is a series of characters, like a line of text. The string, unlike the char, is denoted by putting it in regular quotes:

 

// A string variable

string lineOfText = “This is a test string”;

 

Strings come up everywhere in programming, and it is a class that we'll be using a lot. We'll cover strings in more detail in chapter 3.

 

These aren't all of the simple types we can use in C#. Each C# type also has an equivalent type in the .Net framework. If you're curious about the .Net types check the documentation in Visual C#. We'll only be using the simple types described above.

 

Type Conversion

We have all of these different variable types in C#, but the language is pretty strict about type conversion, converting from one type to another. The following code will generate an error:

 

float piFloat = 3.14f;

int piInt = piFloat;

 

This code will generate the error message: 

 

Cannot implicitly convert type 'float' to 'int'. An explicit conversion exists (are you missing a cast?)         

 

In some languages, like C++, assigning a float variable to an integer is OK (the pi code will compile in C++); the int variable will just ignore the decimal part. But in C# we need to make our conversions explicit, meaning we have to specifically state a conversion is going on. We do this by putting the variable type we want to convert to in parenthesis is front of it:

 

float piFloat = 3.14f;

int piInt = (int) piFloat;

 

The above code will compile just fine (piInt will have a value of 3). We can also convert using the .Net Convert method, which we'll see a bit later in this chapter.

 

C# also does implicit conversion if the type being converted from is a subset of the type converting too. This means that since all ints are simpler than floats, we don't have to implicitly convert ints to floats.

 

// The following will run OK:

int basicNumber = 5;

float basicFloat = basicNumber;

 

Variable Naming

When we start making large games there will be many, many variables in them. One of the most important things to do when naming a variable is to make it clear and easy to recognize what the variable means. For example, let's say we're making a car game and we need to keep track of the maximum speed the car can go. A good variable name would be something like:

 

float maxSpeed;

 

But even this might not good enough if we're using different units for speed in different parts of the game (like miles per hour, feet per second.) A better name would then be:

 

float maxSpeedMph;

 

A bad variable name for maximum speed would be:

 

float ms;

 

This might be easier to type and at first ms for maximum speed makes sense. But later as the program grows the variable ms could be ambiguous (someone could confuse it for meters per second.) Always make variable names clear.

 

In addition we usually name simple variables using lowerCamelCase, which means multiple words are combined using a capital letter for each new word (and the first word is lower case) For class and functions names we use UpperCamelCase, which is like lower camel case except the first letter is also capitalized.

 

Mathematical Operators

So we now have that ability to declare variables and assign them values. let's look at how to do more things with them using operators. An operator is special function that does some action on a variable. The assignment (equals sign) is an operator; it performs the action of putting a new value in a variable.  The first class of operators we'll take a quick look at our C#'s mathematical operators, these are operators we can use on our number variables, int, float, and double. The simplest are the addition and subtraction operators. They are pretty straightforward, we just use the plus (+) and minus symbols (-). Here's an example that shows how they work:

 

float startSpeed = 5.0f;

float currentSpeed= startSpeed + 5.0f;

// currentSpeed has 10.0f in it.

currentSpeed = startSpeed –  5.0f;

// currentSpeed has 5.0f in it

 

The multiplication and division operators work similarly, and for multiplication we use the star symbol * and for division the backslash /.

 

float startSpeed = 6.0f;

float currentSpeed = startSpeed * 3.0f;

// currentSpeed has 18.0f in it.

currentSpeed = startSpeed / 2.0f;

// currentSpeed has 3.0f in it

 

One possibly surprising thing is that when doing division with integers the remainder is ignored (since integers don't store a decimal part, they can't store remainders):

 

int testInt = 17 / 5;

// testInt now equals three, the remainder two is ignored.

 

Another mathematical operator is the modulus operator, which is basically the remainder operator. It performs division on two numbers and then outputs the remainder of them. The symbol for modulus is %: Here is an example:

 

int testInt = 17 % 5;

// testInt now equals 2, the remainder of 17 /5

 

Unary Operators

Notice that whenever we do an operation like adding where we add two numbers and store the result in a third:

 

int testInt = testInt1 + testInt2;

 

the two numbers that were added didn't change; testInt1 and testInt2 have the same value after that line of code as they did before we entered it. Sometimes we need to do this. But sometimes we want to do something like this:

 

testInt = testInt + 5;

 

Where we add 5 to testInt and testInt itself is changed. This happens so often that there are special unary mathematical operators just for this occasion (unary meaning one) They work by putting the math symbol before the equals sign.  The following two lines of code are the same:

 

testInt = testInt +5;

testInt += 5; // Same as the above

 

// This works the same for multiply/divide/subtract

 

testInt -= 5; // Same as testInt = testInt – 5;

testInt *= 5; // Same as testInt = testInt * 5;

testInt /= 5; // Same as testInt = testInt / 5;

 

Another very common thing to do that is even simpler is to add or subtract one from a number. This comes up so much that there are special operators for it. We put ++ to increment, add one to a number, and –- to decrement, to subtract one from a number. These can be put in front of or behind the number (there are some slight technical difference for putting in front of or behind a number but we won't worry about them here) Here's an example:

 

testInt = 5;

testInt--;

// testInt now equals 4

testInt++;

// added one to testInt, now it equals 5 again

 

Example Program

The following program is pretty straightforward; it just a quick example showing a few variables at work. The only new things are the Readline and Convert methods. The Console.Writeline method writes a string of text to the console, and Console.Readline() works the opposite way, pulling a string of text in from the console. When we have a string of text, such as in the example program when the user enters their age, we sometimes want to change the string into a different variable, like changing the age string to an int. To do this we use the Convert method. Typing in Convert period will bring up a list of different types to convert a string to. The instruction:

 

int age = Convert.ToInt32(Console.ReadLine());

 

Reads in a string from the console and converts it to an int (and stores it in the variable age.) The dangerous thing with this code is if the user enters a string that won't convert to an int. This will throw an exception, that is, cause an error (which we won’t worry about for now.) Here is the program:

 

static void Main (string[] args)

{

 

int feet;

int inches;

 

Console.WriteLine("I'm going to ask about you height, feet and inches.");

 

Console.WriteLine("How many feet tall are you?");

feet = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("And how many inches?");

inches = Convert.ToInt32(Console.ReadLine());

 

float cm = ((feet * 12) + inches) * 2.54f;

 

Console.WriteLine("You are " + cm.ToString() + “ centimeters tall.");

 

}

 

A sample output is:

 

I'm going to ask about you height, feet and inches.

How many feet tall are you?

6

And how many inches?

2

You are 187.96 centimeters tall.

Press any key to continue . . .

 

Two more things to know for now (we'll discuss them in more detail later.) Any variable in C# can be converted to a string, you just add the .ToString() to the end of the variable. Second to combine two or more strings into one you can concatenate them, which means to put them together, by using the plus sign. That is how the line:

 

Console.WriteLine("You are " + cm.ToString() + “ centimeters tall.");

 

Becomes

 

You are 187.96 centimeters tall.

 

By using the .ToString() on the cm variable and concatenating all of the strings together for the output.

(Note depending on the context the .ToString() isn’t always necessary, but we’ll always use it here for clarity.)

 

Finding the Gold Game

Next let's take the first steps to make our Console game “Find the Gold.” The concept of this game is pretty simple; we'll have the player make a series of choices to guess which way to find a bag of gold. The first thing we'll do is ask for the player's name and print it out. Then we’ll ask the player to choose a door, 1,2, or 3 and for now just print out the door number. Go ahead and create a new Console project called FindGoldGame. Here is the code:

 

static void Main(string[] args)

{

Console.WriteLine("Welcome to the Find the Gold Game!\n What is your

name?");

 

string name = Console.ReadLine();

 

Console.WriteLine("Hello, " + name + ". Which door do you choose,  1, 2,

or 3?");

 

int door = Convert.ToInt32(Console.ReadLine());

 

Console.WriteLine("You chose door " + door.ToString());

}

  

 

Here's an example output:

Welcome to the Find the Gold Game!

 What is your name?

Curtis

Hello, Curtis. Which door do you choose, 1, 2, or 3?

2

You chose door 2

Press any key to continue . . .

 

This code should be straightforward. We just ask for the player's name and then ask for a door number. The only new thing is the '\n' character in the first WriteLine. The '\n' means newline, and it's our way of telling the text to hit return on the keyboard. That's why when we run the program the “What is your name?” appears on the second line. Then we print out the door number the player chose. In the next part we'll put in switches so the choosing the door will mean something.

 

Summary

This chapter took a look at simple variables in C#. These are the building blocks of all our programs, and in the next chapter we'll add to our programming capability by looking at how to change the direction the code executes in.

NEXT