XNA Game-Themed CS1 Examples ( XGC1 ) Release 2.0 (XNA V3.1) 2/8/2010
Topic: Topic.2.Input_Output_PrimitiveDataTypes

# Math Operators: Addition (using Local Variables)

References:
• Pre-requisite: it is assumed that you have read through the prior tutorials, and are familiar with the concepts covered in those tutorials.
• It may be useful to refer to refer to the diagram illustrating the Draw-Update loop (which explains that your initialization code will be called once, and then the XNACS1Lib will repeatedly call your Update method (after which it will Draw the screen) ), in order to have a clear picture of how your game executes.

Goals:

• In this tutorial, we will:
• Examine the mathematical addition operator
• Examine how to update and change on-screen shapes in response to the player's input

1. Obtain the example code

Download and unzip the zip file and you will see an ExampleProgram folder. Open the ExampleProgram folder, the EXE folder contains the compiled program and you can double click on the .sln file to work with the source code.

Once we compile and run this project, the program displays three rectangles in the screen, labeled with each rectangle's current height.  At the bottom of the screen are instructions for playing game: by using the left thumbstick, you can control the current height of the left-most rectangle (rectangle "A"), by using the right thumbstick, you can control the current height of the middle rectangle (rectangle "B").  The height of the right-most rectangle is automatically set to be the sum of the heights of the other two rectangles, as pictured below.

Additionally, when player presses the 'Back' button (or the keyboard equivalent), the program will exit.

2. Examining The Program:

Let's examine the C# source code that produces the behavior we see on-screen

• Declaring the instance variables

We need to declare our instance variables before we can use them.

 public class Game1 : XNACS1Base {         // The rectangles:     private XNACS1Rectangle aRec; // Rectangle "A"     private XNACS1Rectangle bRec; // Rectangle "B"     private XNACS1Rectangle addRec; // Rectangle that will be "A+B"
• We'll need to keep track of each of the three rectangles that we see on-screen, so we declare each of them here.
• Notice that we give each variable a meaningful name, including addRec, which will display the result of adding the two other rectangles.
• Because what we're doing is sufficiently simple, we can use local variables for everything else that we want to calculate.  As a result, we don't need to declare anything else here.  In particular, we don't need to declare an instance variable to hold the sum of the heights of the two variables.
• InitializeWorld():

We told C# to create instance variables for our Game1.  It's important that we give our variables well-defined values before we use them, like so:

 protected override void   InitializeWorld() {     World. SetWorldCoordinate( new Vector2 (0,0), 100.0f);     aRec = new XNACS1Rectangle ();     aRec.LowerLeft = new Vector2 (10.0f, 20.0f);     aRec.Height = 10.0f;     aRec.Width = 20.0f;     bRec = new XNACS1Rectangle ();     bRec.LowerLeft = new Vector2 (40.0f, 20.0f);     bRec.Height = 5.5f;     bRec.Width = 20.0f;     addRec = new XNACS1Rectangle ();     addRec.LowerLeft = new Vector2 (70.0f, 20.0f);     addRec.Width = 20.0f;     addRec.Height = aRec.Height + bRec.Height;     // Since 10f + 5.5f = 15.5, we could replace the above line with this one:     // addRec.Height = 15.5f; }
• Again, we have the exact same sequence of steps that we used in previous tutorials, repeated here, in order to set up the first two rectangles.
• Simply repeating the code we've previously used works well here, since we can pretty much pick any starting height for the rectangles that we want.  As long as all three rectangles fit on-screen, it will be easy for the player to figure out what's going on.
• Note that we need to be very careful, especially when cutting and pasting , to make sure that we're using the variable name(s) that are correct within this program !
• Looking at the third rectangle ('addRec' - the one whose height we get from adding up the heights of the other two), you'll notice that the addRec object is created in the normal way, and the location and width are set the same way, but that the Height is actually set up to be the sum of the other two:

If we look at this part by part, we see that it breaks down into a series of simple steps, based on the order of operations for the various operators that are here:

1. There are two operators: the addition operator (as indicated by the + symbol), and the assignment operator (as indicated by the = symbol).  The assignment operator is executed last, so addition therefore goes first.  Assignment operators normally go last, so that all the other math can happen, and then the results of that math can be assigned to a variable.
2. In order to do the addition, C# needs to know what the values of aRec.Height and bRec.Height are.  Let's assume that C# will work from left to right.
3. addRec.Height = aRec.Height + bRec.Height;
C# will retrieve the value of the aRec's height, which is 10.0f.  So, mentally, we can think about the line being transformed into:
4. addRec.Height = 10.0f + bRec.Height ;
C# will retrieve the value of the bRec's height, which is 5.5f.  So, mentally, we can think about the line being transformed into:
addRec.Height = 10.0f + 5.5f ;
5. addRec.Height = 10.0f + 5.5f;
Having retrieved the two values, C# can now do the addition operation, which will yield the value 15.5f.
15.5f ;
Once the addition operator has finished, all that's left is to do the assignment operation, which will put the floating-point number 15.5 into the Height property of the addRec rectangle.
• We could have also done this with the code that's been commented out ( addRec.Height = 15.5f; ).  The advantage of this second approach is that we don't have to know how to do addition in C# to do it.  The major disadvantage is that if we were to change the starting height for aRec, then we would have to remember to change this line, too.  While this isn't too tough in this small program, we want to build up the skills, techniques, and mind-set that will help us avoid making errors in the future.  So we prefer to use the first approach, wherein C# will automatically calculate the correct height for us.
• You should go through each of these lines, and make sure that you're clear on what each and every line does.
• As per normal, our game will check if the user presses the 'Back' button.  If we're going to exit, there's no sense in doing any work prior to exiting, so we check if we need to exit as the first two lines in the method
• Since most textbooks present arithmetic ("math") operators using local variables, we'll be using local variables here, too.  The hope is that your textbook will provide a solid background explanation, and this tutorial will explain the video-game specific stuff, and that what's left will be just a couple lines of code that are both explained in your textbook and shown here.
• In order to make our program look more like what you're seeing in your textbook, we will use the basic strategy of copying all the numbers that we need into local variables, then doing the math (like you're seeing in your textbook), then copy the numbers out of the local variables and back into the rectangle(s), in order to update the rectangles.
• We start by creating copies (in local variables) of all the numbers that we'll need.  We basically need to know two things: the current height of rectangles A and B, and how much the thumbsticks are being pushed.  From that, we can figure out what the new heights of the rectangles should be, and once we've got the new heights of rectangles A and B, we can figure out what the height of the addRec should be.
• Let's start by creating local variables that will hold copies of the numbers in the thumbsticks:

// copy the thumbstick values into local variables with shorter names:

• Notice how this is (almost) all stuff that you've seen before: you've seen how to create a local variable that is a float , you've seen how to copy the value of the left thumbstick into that variable, you've seen how to do this all in one line.  The only thing that's slightly new is the way in which we access the right thumbstick ( GamePad.ThumbSticks .Right , on the second line).
• Since we're only interested in how far forwards or backwards the thumbsticks have been pushed, we only copy the Y values, not the X values.
• Next, let's create local variables that will hold copies of the numbers in the rectangles:

// Copy the current rectangle heights into local variables with shorter names:

float aHeight = aRec.Height; // Height of A and B Rectangles

float bHeight = bRec.Height;

• Notice how this is (almost) all stuff that you've seen before: you've seen how to create a local variable that is a float , you've seen how to access the Height property of a rectangle (above), and you've seen how to do this all in one line.  The exact way in which we're combining (composing) a new program out of these older, known pieces is new, but each part should be familiar.
• Once we've got our local copies of the data, we can now do the addition, much like in your textbook:
// Accumulate height for A and B

aHeight = aHeight + leftThumbY;

bHeight = bHeight + rightThumbY;

For both lines, we do the same sequence of actions, so let's step through 1 line in detail, in order to fully understand how it works.

• Pay particular attention to what happens when we have the same variable (aHeight) on both the left and right side of the equation!
1. There are again two operators: the addition operator (as indicated by the + symbol), and the assignment operator (as indicated by the = symbol).  The addition operator goes first, followed by the assignment operator.
2. In order to do the addition, we need to know what the values of aHeight and leftThumbY are.  C# actually knows this already (since both variables are simple variables / value type variables, and therefore C# is actually storing the value immediately inside the variables), but we'll walk through what's going on, so that we're clear about how things are evaluated.
3. aHeight = aHeight + leftThumbY ;
C# will do the addition first, and so we can imagine that C# will substitute the values stored in the variable, then do the addition.  So C# will look up the value of the two variables that are next to the + symbol - leftThumbY, and the right-most aHeight .  For the purposes of this example, let's assume that leftThumbY has the value +0.75:
aHeight = 10.0f + 0.75f ;
4. aHeight = 10.0f + 0.75f;
C# now adds the two numbers together.  Notice that up until now, we haven't even thought about what's going on with the other aHeight, because the assignment operator goes second, according to the order of operations.
aHeight = 10.75f ;
5. aHeight = 10.75f;
The only thing left for C# to do is to assign the value 10.75f into the aHeight variable.
• The above can be summed as: get the current value of aHeight, add the leftThumbY to it, and store that result back into the variable aHeight. If you think about the assignment operator (the single-equals sign) as being like an array (and NOT indicating equality), it may be easiser to think about.  This picture may help make the relationship more clear:

Make sure that you're very comfortable with this sort of reasoning, since this pattern will be used often in programming.
• The same sequence of actions is also done for bHeight and rightThumbY
• Now that we've calculated the new heights for the A and B rectangles, we can calculate the sum of the two, again using the addition and assignment operators:

float addHeight = aHeight + bHeight;

You'll notice that we are, once again, composing a slightly different line out of parts we already know: adding two numbers, assigning the results of addition to a variable, and declaring a variable (with immediate initialization).

• You should able to trace out the execution of this line, in the same sort of style that was used for the previous two lines.
• At this point, we've done all the calculations that we wanted to do. However, all the calculations ended up putting their results into local variables.  So before the method ends, we need to copy all these values back into the rectangles that we see on the screen.

// Update the rectangles with the new heights

aRec.Height = aHeight;

bRec.Height = bHeight;

These should all be fairly straightforward - we simply take the local variable that is storing the new height of a rectangle, and then assign that value to the Height property of the appropriate rectangle.  When the XNACS1Lib next draws the rectangles on the screen, they will be drawn with their new heights.

• The one last thing we need to do is to update the labels on the rectangles, so that they accurately reflect the new height of the rectangles.

// Update the labels, so they also have the new heights

aRec.Label = "A Height=" + aRec.Height;

bRec.Label = "B Height=" + bRec.Height;

• In order to try and be helpful, we also echo a brief message to the bottom status bar, telling the user how to play the game.

FURTHER EXERCISES::

1. Start from a blank starter project (1000.201, if you need it), and re-do the code from memory as much as possible.  On your first try, do what you can, and keep the above code open so that when you get stuck, you can quickly look up what you forgot (and that after you finish a line, so that you can compare your line to the 'correct' line).  On the next try, do the same thing, but try to use the finished code less.  Repeat this until you can type everything, without refering the tutorial's code.
• Repeat this exercise daily for several days, so that you really get the hang of this.  As you go on, periodically review this by re-doing this exercise.
2. Understanding The Code
Using the program that the above tutorial discusses, can you make the height of A (or B) negative?  When you do this, what happens?  Why?
3. Program Tracing:
Trace out the execution of the float addHeight = aHeight + bHeight; line, similar to how the tutorial does this, above.
• For this, and all other tutorials, you should go through this exercise for all new expressions/statements, so that you've gotten some good, solid review on how to evaluate statements in the way that C# does.
4. Understanding The Program
What happens if you leave out the lines that update the labels?  You should first think about what you believe will happen, then run the program to confirm that your predictions were correct.