XNA Game-Themed CS1 Examples (XGC1)

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

Topic: Topic.4.DecisionStructures
Example: Ex_4.IfThenElse

Decision Statements: "If / Else" Statements and More Functions


Need (library reference):

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.

When the game starts, you'll see a screen that looks similar to this:


The game behaves in a manner that is identical to the what was described for the previous tutorial, with three new features:

  1. The ball now bounces off all edges of the screen, so that the ball can never leave the screen

  2. The ball now bounces off both paddles

  3. The game now keeps track of the total number of times that the ball has bounced off a paddle (either left or right, it doesn't matter which).  Once that total exceeds a certain threshold, then the game changes into Expert mode.  At this point, the only thing that differentiates Novice mode and Expert mode is a message at the bottom of the screen, but we'll add more stuff in later on.

Let's examine the source code, feature by feature


2. Ball Bouncing Off The Screen Edges:

Let's examine the C# source code that produces the behavior we see on-screen.  Since the code is nearly identical to the program that was presented in the previous tutorial, we'll leave out everything, except for code that has changed, or code that is new.  Further, we'll move through the changes feature by feature, staring with the feature that makes the ball bounce off all the edges of the screen.  This will ensure that the ball will never leave the screen.  There are two changes that make this happen.


3. Ball Bouncing Off The Paddles:

Let's move on to making the ball bounce of the paddles.  This is an important step towards taking the game towards it's final form.

There are two changes that make this happen:


4. Going To Expert Mode By Counting Bounces

Let's move on to keeping track of how many times the ball has bounced off the paddles, and once the player has bounced the ball at least 5 times, moving the game to expert mode. The basic strategy that we'll use is to create a variable to hold the current number of bounces, which starts at zero.  Each time the ball hits a paddle, we will increase that number by 1. In the UpdateWorld function, we'll check to see if the current number of bounces is above or below the threshold for being in expert mode, and display the appropriate message to the user based on that. Let's go through the changes, one by one:


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.
  2. Working with WorldMin and WorldMax
    Calculate the width of the screen, given:
    1. WorldMin = (0,0)
      WorldMax = (100,56)
    2. WorldMin = (10,10)
      WorldMax = (100,56)
    3. WorldMin = (-5,-5)
      WorldMax = (20,56)
  3. Working with WorldMin and WorldMax; Math Formulas In Programs
    For this exercise, you should use the same project that was explained in the above tutorial.
    What is the formula that you use to calculate the screen's width?  Write up your formula in C#, echo the answer to the top status bar, and check your code against your answers to the previous question by adjusting the values that you use in the constructor.
  4. Chained if/else's
    Let's start by examining the following code:
    private void CheckWorldBound()

    {

        if (m_TheSoccer.CenterX > World.WorldMax.X)

            m_TheSoccer.VelocityX = -m_TheSoccer.VelocityX;

        else if (m_TheSoccer.CenterX < World.WorldMin.X)

            m_TheSoccer.VelocityX = -m_TheSoccer.VelocityX;


        if (m_TheSoccer.CenterY > World.WorldMax.Y)<

            m_TheSoccer.VelocityY = -m_TheSoccer.VelocityY;


        if (m_TheSoccer.CenterY < World.WorldMin.Y)

            m_TheSoccer.VelocityY = -m_TheSoccer.VelocityY;

    }


    You'll notice that we've added in an extra else, which now connects the first two if statements.  Pictorially, we can represent these four lines with the following chart:

    1. First, change the code in your project to match what's given above.  Make sure that it compiles, and that the program continues to behave correctly.
    2. Why does it make sense to chain these first two if statements?  How is this more efficient than having two, separate statements?  Does this clarify the programmer's intentions here?
    3. Make a similar change so that the vertical edges are checked using this sort of approach, too.
    4. Does the following code cause the program to run correctly?  Is it more efficient than the original version?  Is it more clear?
      private void CheckWorldBound()

      {

          if (m_TheSoccer.CenterX > World.WorldMax.X)

              m_TheSoccer.VelocityX = -m_TheSoccer.VelocityX;

          else if (m_TheSoccer.CenterX < World.WorldMin.X)

              m_TheSoccer.VelocityX = -m_TheSoccer.VelocityX;

          else if (m_TheSoccer.CenterY > World.WorldMax.Y)

              m_TheSoccer.VelocityY = -m_TheSoccer.VelocityY;

          else if (m_TheSoccer.CenterY < World.WorldMin.Y)

              m_TheSoccer.VelocityY = -m_TheSoccer.VelocityY;

      }

  5. Sequencing:
    Currently, the part of UpdateWorld that checks for the ball bouncing off the paddles, and updating the Novice/Expert message, looks like this:
        // paddle colliding with the soccer

        BounceOffPaddles();


       
    // the if then else

        if (m_NumBounces > EXPERT_LEVEL_BOUNCES)

            EchoToBottomStatus("EXPERT: bounces=" + m_NumBounces);

        else

            EchoToBottomStatus("NOVICE: bounces=" + m_NumBounces);

    The sequencing (the ordering) is important here because if the player currently has bounced the ball, say, 5 times, and the ball is about to bounce of a paddle, then by FIRST checking for bounces, then NEXT updating the message, we will immediately update the message after detecting the latest bounce.
    What if we change the code to look like this:

        // the if then else

        if (m_NumBounces > EXPERT_LEVEL_BOUNCES)

            EchoToBottomStatus("EXPERT: bounces=" + m_NumBounces);

        else

            EchoToBottomStatus("NOVICE: bounces=" + m_NumBounces);


        // paddle colliding with the soccer

        BounceOffPaddles();

     

    1. Why does the second sequence appear to work, even though the message at the bottom is being set before figuring out if the ball has collided with a paddle?
    2. The lesson to learn here is that in many cases, you can get things wrong, and yet have things work out ok because of something else in the program.  The most important thing to do is to make sure that you have a clear understanding of why things are happening, so that you can modify your program in the future (if you want) correctly.

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