XNA Game-Themed CS1 Examples ( XGC1 )

Release 2.0 (XNA V3.1)
2/8/2010

Topic: Topic.2.Input_Output_PrimitiveDataTypes
Example: Ex_3.LocalVariableAssignment

Local Variable Assignment


References:

Goals:



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 " ThumbStick: X is 0 Thumbstick: Y is 0 " at the top of the screen. 

If you move the left thumbstick towards the right, you'll see the X value change in response. If you move the left thumbstick towards the left, you'll see the X value changes to a negative value. Similarly, when you move the left thumbstick forwards & backwards (sometimes described as "up and down"), you will see the Y values change appropriately. 



2. Background :  


The output of this tutorial is exactly the same as the output from the last version of the prior tutorial.  Instead of focusing on output, we will focus on variables.  A variable is a block of space in the computer's memory that contains a value of some sort.  In other words, a variable stores data / information.  The value that is stored in the space can be changed; the value stored in the variable can vary.   Because contents of the block can vary, we can use that fact to store information about our program that changes over time.  For example, when the player begins a new game, the player's score might start out at zero.  In our program, we can represent the player's score by creating a variable (a block of space) that we'll name score , and we'll put the value zero into that space to store the player's starting score.  As the game goes on, maybe the player is awarded 10 points for doing something, so our program will take the value currently stored in the score variable (zero), add ten to that value (0 + 10 = 10), then store that new value back into the space named score .  When the program then displays the score on the screen, the player will now see the new value (10), rather than the old value. 

Because different information needs to be kept around for different lengths of time, there are different types of variables.  For example, a player's score should exist throughout the entire game, so we will need to use a long-lived instance variable to keep track of the score (we will explore instance variables in a future tutorial).  Another example is that the game may need to (or want to) store the results of a complex calculation, then output the calculation in the Update function.  In which case, we only need that data to exist until we can output the data, and then we don't need to store it anymore.  As a matter of fact, we want to NOT store that information any more because we don't need it, and it would waste the computer's memory to store unneeded information.  What we would like to have is a variable that will automatically disappear once the Update method is done .  We will use a local variable to store this short-lived data.  In this case, "local" means that the variable only exists within the method that declares (creates) it.


3. Examining The Program:

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

UpdateWorld(), Version #2

UpdateWorld(), Version #3

UpdateWorld(), Version #4

A note on comparing the different versions:


All of these solutions are all equivalent - each one produces the same results on-screen, and ultimately, each one causes the computer to do in the same way.  In one version, we might specifically create storage space for both X and Y, in another, we create storage space for a single thing, which in turn contains a separate X and Y.  Similarly, we might first declare, then later assign values to our variables, or we might do that all in one step.  So in a very real sense, the work that the computer is doing is the same in all the solutions.

In this sense, no one version is "best".   Each one may have advantages over the other (and/or disadvantages relative to the other) in terms of how easy it is for programmers to read and understand the code, or in terms of the personal preferences of individual programmers.  But no one solution is so much better than the others that it's "best".  This sort of situation - multiple, more-or-less equivalent solutions to the same problem - is very common in programming. 

The important skill for you to develop is to be able to clearly understand the advantages/disadvantages of a given solution, and to be able demonstrate that understanding by discussing it, or explaining it.  Ultimately, this skill will enable you to create a great solution for problems that you haven't even seen yet :)


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 referring the tutorial's code.
  2. Using the same project that the above tutorial makes use of, modify the program so that the code does NOT assign a value to a local variable, and yet the code still tries to print the variable using EchoToTop/BottomStatus.  What happens?
  3. When talking about variables, we can discuss their scope .  Loosely put, a variable's scope is the region of source code in which we can use the variable (i.e., no compiler errors and no logical errors result from using the variable).
    In your own words, describe the scope of local variables.  Feel free to further research this idea in your textbook, online, etc.
  4. Let's say that you have a program, which is included in the box below.  For each comment, you should be able to describe whether an instance variable (such as X , which is declared in the UpdateWorld method) is in scope, or not.
    // Location A: Is X in scope here?

    using System;

    using System.Collections.Generic;

    using Microsoft.Xna.Framework;

    using Microsoft.Xna.Framework.Audio;

    using Microsoft.Xna.Framework.Content;

    using Microsoft.Xna.Framework.GamerServices;

    using Microsoft.Xna.Framework.Graphics;

    using Microsoft.Xna.Framework.Input;

    using Microsoft.Xna.Framework.Net;

    using Microsoft.Xna.Framework.Storage;


    using XNACS1Lib;


    // Location B: Is X in scope here?


    namespace LocalVariableAssignment

    {


        // Location C: Is X in scope here?


        public class Game1 : XNACS1Base

        {

            // Location D: Is X in scope here?


            public Game1() : base ( new Vector2 (0, 0), 100.0f)

            {

                // Location E: Is X in scope here?

            }


            protected override void InitializeWorld()

            {

                // Location F: Is X in scope here?

            }


            protected override void UpdateWorld()

            {

                if (GamePad.ButtonBackClicked())

                    this .Exit();


                float X;

                float Y;


                X = GamePad.ThumbSticks.Left.X;

                Y = GamePad.ThumbSticks.Left.Y;

                // Location G: Is X in scope here?


                EchoToTopStatus( "ThumbStick: X is " + X + " Thumbstick: Y is " + Y);

            }



        }

        // Location H: Is X in scope here?

    }

  5. Examine the code given in the box below.  Notice that inside the InitializeWorld method, there's a variable named X, which is a float , and was assigned the floating-point number 3.14159, and inside the UpdateWorld method there's another variable named X, which is also a float ,  and which is assigned a different value.
    1. Is it legal to have these two local variables with the same name?
    2. If the current value of GamePad.ThumbSticks.Left.X is .75 when UpdateWorld is run, what will be displayed at the top of the screen?  Why not 3.14159?
    3. Will 3.14159 ever be displayed at the top of the screen?
    using System;

    using System.Collections.Generic;

    using Microsoft.Xna.Framework;

    using Microsoft.Xna.Framework.Audio;

    using Microsoft.Xna.Framework.Content;

    using Microsoft.Xna.Framework.GamerServices;

    using Microsoft.Xna.Framework.Graphics;

    using Microsoft.Xna.Framework.Input;

    using Microsoft.Xna.Framework.Net;

    using Microsoft.Xna.Framework.Storage;


    using XNACS1Lib;


    namespace LocalVariableAssignment

    {


        public class Game1 : XNACS1Base

        {

            public Game1() : base ( new Vector2 (0, 0), 100.0f)

            {

            }


            protected override void InitializeWorld()

            {

                float X;

                X = 3.14159;

            }


            protected override void UpdateWorld()

            {

                if (GamePad.ButtonBackClicked())

                    this .Exit();


                float X;

                float Y;


                X = GamePad.ThumbSticks.Left.X;

                Y = GamePad.ThumbSticks.Left.Y;


                EchoToTopStatus( "ThumbStick: X is " + X + " Thumbstick: Y is " + Y);

            }



        }

    }

  6. Using the same project that the above tutorial makes use of, modify the program so that Version #2 is uncommented (i.e., it's active), but you DO NOT COMMENT OUT Version #1.  What happens when you try to compile your program? In your own words, what do those errors mean?
  7. Using the same project that the above tutorial makes use of, modify the program so that Version #3 is uncommented (comment out everything else).  Compile and run your program, in order to make sure that everything works.
    Once you've done that, try removing the .X / .Y when printing?  What happens when you try to compile your program? In your own words, what do those errors mean?
  8. List some differences between of Version #1 (or #2)  vs. #3 (or #4).  Specifically, focus on the advantages, and disadvantages, that #1 (or #2) has over #3 (or #4).
  9. Writing Code On Your Own: The Right Thumbstick

    Start this exercise using Exercise_ 9 's starter project , which is a nearly identical copy of the project that was used in the above tutorial.  Change the program so that instead of updating the top status bar based on the right thumbstick, instead of the left thumbstick.  You can access the right thumbstick using the phrase , GamePad.ThumbSticks.Right in the appropriate places.

    The default keyboard to controller mapping assigned the Left Arrow key to mean "push the thumbstick to the left", the Right key to mean "push the thumbstick to the right", the Up Arrow key to mean "push the thumbstick up", and the Down Arrow key to mean "push the thumbstick to the down".


Project home page : The Game-Themed Introductory Programming Project.
Kelvin Sung
Computing and Software Systems
University of Washington, Bothell
ksung@u.washington.edu
Michael Panitz
Business And Information Technology
Cascadia Community College
mpanitz@cascadia.eduu

Microsoft Logo This work is supported in part by a grant from Microsoft Research under the Computer Gaming Curriculum in Computer Science RFP, Award Number 15871 and 16531.
2/8/2010