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

Math Operators: Percent and Multiplication

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 multiplication operator
• Examine how the multiplication operator can be used to calculate a percentage
• 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 on the screen, each labeled with each rectangle's current height (and how that height was calculated)  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").

The middle rectangle's height is set to be 20% of rectangle A.  The right-most rectangle's height is set to be equal to rectangle A's height, minus 20% of A's height.  All numbers are calculated using floating-point numbers (instead of integer numbers).

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 {         private XNACS1Rectangle aRec;        // left-most rectangle     private XNACS1Rectangle percentRec; // middle rectangle     private XNACS1Rectangle subRec;     // right-most rectangle
• We'll need to keep track of each of the rectangles that we see on-screen, so we declare each of them here.
• 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.
• InitializeWorld():

We told C# to create instance variables for our Game1 in the code that's described above.  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);     float aHeight;        // Height of rectangle-A     float percentHeight;  // 20% of rectangle-A height     float subHeight;      // Subtracted height: the height of A - (20% of the height of A)     aHeight = 15.2f;     percentHeight = aHeight * 0.2f;     subHeight = aHeight - percentHeight;     aRec = new XNACS1Rectangle ();     aRec.LowerLeft= new Vector2 (20.0f, 20.0f);     aRec.Height = aHeight;     aRec.Width = 20.0f;     percentRec = new XNACS1Rectangle ();     percentRec.LowerLeft = new Vector2 (40.0f, 20.0f);     percentRec.Height = percentHeight;     percentRec.Width = 20.0f;     subRec = new XNACS1Rectangle ();     subRec.LowerLeft = new Vector2 (60.0f, 20.0f);     subRec.Height = percentHeight;     subRec.Width = 20.0f; }
• For this program we'll use the following strategy to initialize the game:  declare and initialize a number of local variables that will hold some of the values that we want to calculate, then initialize the rectangles like we've done previously, making sure to copy the height values from the local variables into the rectangles.
• The first thing that we do is declare the local variables that we'll make use of:
float aHeight;        // Height of rectangle-A

float percentHeight;  // 20% of rectangle-A height

float subHeight;      // Subtracted height: the height of A - (20% of the height of A)

Technically, we could probably get away with not creating the aHeight variable, but we will do so anyways, as it will look slightly nicer when we use it to calculate the other values we need.  The comments next to each variable are there to indicate what value the variable is intended to hold.

• Next, we decide what the height of rectangle A should be, and then calculate 20% of that height (which we then assign to the percentHeight variable), then we calculate 20% less than the height of A (which we then assign to the subHeight variable)
aHeight = 15.2f;

percentHeight = aHeight * 0.2f;

subHeight = aHeight - percentHeight;

Let's examine how the multiplication operator works, in detail, on the line percentHeight = aHeight * 0.2f;

1. There are two operators: the multiplication operator (as indicated by the * symbol - note that this is called an asterisk , and is located above the 8 key on the keyboard), and the assignment operator (as indicated by the = symbol).  The assignment operator is executed last, so multiplication 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 multiplication, we need to know what the value of aHeight is.  C# actually knows this already (since the variables is a simple variable / value type variable, and therefore C# is actually storing the value immediately inside the variable), but we'll walk through what's going on, so that we're clear about how things are evaluated.
3. percentHeight = aHeight * 0 .2f ;
C# will do the multiplication first, and so we can imagine that C# will substitute the values stored in the variable, then do the operation.  So C# will look up the value of the variable that is next to the * symbol - aHeight (the other value, 0.2f, is written directly into the source code already)
percentHeight = 15.2f * 0 .2f ;
4. percentHeight = 15.2f * 0.2f;
Now that all the values are known, the multiplication operation can be carried out, resulting in 3.04
percentHeight = 3.04f ;
5. percentHeight = 3.04f;
Once the multiplication operator has finished, all that's left is to do the assignment operation, which will put the floating-point number 3.04 into percentHeight local variable
• Next, the program will compute the value of subRec using the subtraction operator, as you've previously seen.
• Having calculated the various numbers that we'll use, we then use our familiar code to initialize the three rectangle objects.
• The only thing to take careful note of are the three lines where we copy the values from the local variables into the rectangles.  These lines will ensure that the calculations we've done are assigned to the height properties of the rectangles.
aRec.Height = aHeight;

percentRec.Height = percentHeight;

subRec.Height = percentHeight;

• UpdateWorld():  protected override void UpdateWorld() {     if (GamePad.ButtonBackClicked())         this .Exit();     float leftThumbY = GamePad.ThumbSticks.Left.Y;     float aHeight = aRec.Height; // Height of rectangle-A     float percentHeight; // 20% of rectangle-A height     float subHeight; // Substracted height     // accumuate rectangle-A's height     aHeight = aHeight + leftThumbY;     // compute 20% of rectangle-A's height     percentHeight = aHeight * 0.2f;     // compute the subtraction     subHeight = aHeight - percentHeight;     // Assign the heights and labels to the corresponding rectangles     aRec.Height = aHeight;     aRec.Label = "A Height=" + aRec.Height;     percentRec.Height = percentHeight;     percentRec.Label = "20% of A Height=" + percentRec.Height;     subRec.Height = subHeight;     subRec.Label = "A - 20% of A=" + subRec.Height;     EchoToBottomStatus( "LeftThumb-Y adjust A-Height" ); }
• 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 the numbers that we'll need.  We basically need to know two things: the current height of rectangle A, and how much the left thumbstick is being pushed.  From that, we can figure out what the new heights of the other two rectangles should be.
• Let's start by creating local variables that will hold copies of the numbers in the thumbsticks and the rectangles' heights::

float aHeight = aRec.Height; // Height of rectangle-A

float percentHeight; // 20% of rectangle-A height

float subHeight; // Substracted height

• Since the first two pairs of lines are pretty much identical to what was done in the previous tutorial, you should understand all this.  Notice that we're keeping all of these variables in floating-point number form.  The comments explain what the variables are intended to hold.
• You'll notice that we're duplicating the names of the local variables: these variables names are exactly identical to the names of the variables in the InitializeWorld method.  This is ok, because all the variables are local variables: even though they have the same names, these variables are completely separate from the variables that were declared in the other method.
• Once we've got our local copies of the data, we can now calculate the new heights of the rectangles.  The height of rectangle A will be adjusted based on the thumbstick.  20% of that new height will then be stored into the percentHeight variable.  Finally, we'll figure out what is 20% less than A's height is by subtracting percentHeight from A's height.

// accumuate rectangle-A's height

aHeight = aHeight + leftThumbY;

// compute 20% of rectangle-A's height

percentHeight = aHeight * 0.2f;

// compute the subtraction

subHeight = aHeight - percentHeight;

These should all be familiar from previously covered material.

• Lastly, we copy all the values back into the rectangles, so that the rectangles will be drawn on the screen correctly:

// Assign the heights and labels to the corresponding rectangles

aRec.Height = aHeight;

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

percentRec.Height = percentHeight;

percentRec.Label = "20% of A Height=" + percentRec.Height;

subRec.Height = subHeight;

subRec.Label = "A - 20% of A=" + subRec.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. Changing the Percentage
Start this exercise using Exercise_ 2 's starter project , which is a nearly identical copy of the project that was used in the above tutorial.
You should modify the project so that the middle rectangle is 50% of the height of the left one.
Once you've got that done, keep the middle rectangle at 50% height, and then modify the right-most one so that it's 70% less than the height of the left one (i.e., so that the formula you'll use will be (height of left) - (70% of height of left)
• You are not allowed to simply set the height of the right rectangle to be 30% of the left one.  The goal here is to make sure you set the height of the middle rectangle to be 125% of the left-most one, and still find a way to do the math to calculate (height of left) - (70% of height of left)
3. Changing the Percentage: Greater than 100%
Start this exercise using Exercise_ 3 's starter project , which is a nearly identical copy of the project that was used in the above tutorial.
You should modify the project so that the middle rectangle is 125% of the height of the left one.
Keep the formula that you're using to set the right-most rectangle as (height of left) - (70% of height of left)
• You are not allowed to simply set the height of the right rectangle to be 30% of the left one.  The goal here is to make sure you set the height of the middle rectangle to be 125% of the left-most one, and still find a way to do the math to calculate (height of left) - (70% of height of left)
4. Scaling Input
Start this exercise using Exercise_ 4 's starter project , which is a nearly identical copy of the project that was used in the PRIOR tutorial (the one about integer and floating point substraction)
For this exercise, we want to scale the input that we're getting from the thumbsticks.  This means that if the user is pushing the thumbstick enough so that we get the value +0.75, we want to multiply that number by another number, say, 0.1f, in order to scale down the input to 0.075.  That way, the number we use is 10% of the value of the 'raw' input value.
The reason for doing this (in addition to demonstrating how to scale a number) is to slow down the rate at which the rectangles change their height.  You'll notice, now that things are moving much slower, that the integer subtraction is much easier to see.  If you hold the left thumbstick up, you can see the floating point subtraction rectangle changing it's height very smoothly, while the integer division rectangle's height 'pops' as it crosses the round-off threshold, and changes by an entire, whole, integer value.