| XNA Game-Themed CS1 Examples (XGC1) | |
|
Release 2.0 (XNA V3.1) |
|
References:
Goals:
1. Obtain the example code
When the game starts, you'll see a screen that
looks similar to this:

For this tutorial, we're going to go back and revisit a program that we examined earlier - the 'Pong Soccer' game that we looked at throughout the Chapter on decision structures, culminating in the finished game in tutorial 4000.900 (Pong Soccer). The game plays exactly the same as before, although the appearance of the blocks has changed slightly (they're now numbered, instead of being labeled with letters).
2. Examining The Program:
Let's examine the
C# source code that produces the behavior we see on-screen
|
private
const
int
NUM_BLOCKS = 5; // new representation of all the blocks private XNACS1Rectangle[] m_Blocks; |
|
// Allocate memory and initialize the blocks m_Blocks = new XNACS1Rectangle[NUM_BLOCKS];float blockXPos = BLOCK_A_X_POSITION; for (int i = 0; i<m_Blocks.Length; i++) { m_Blocks[i] = InitializeRectangle( blockXPos, RandomFloat(BLOCK_POSITION_MIN_Y, BLOCK_POSITION_MAX_Y), BLOCK_WIDTH, BLOCK_HEIGHT); m_Blocks[i].Label = "Block-" + i; blockXPos = blockXPos + BLOCK_X_OFFSET; } |
In C#, each array knows how many elements it stores, and you can ask for this number using the .Length property, as you see above. Since the array was declared to have five elements, then m_Blocks.Length has the value 5. Remember that since the elements are numbered 0, 1, 2, 3, and 4 (NOT 5!), the loop will run correctly when we use the 'strictly less than' operator ( < ), rather than 'less than or equal to'.
m_EBlock = InitializeRectangle(blockXPos,
RandomFloat(BLOCK_POSITION_MIN_Y, BLOCK_POSITION_MAX_Y),
BLOCK_WIDTH, BLOCK_HEIGHT);
m_EBlock.Label =
"E";|
//
notice, we only really need to find the first colliding block // there is no reason for further test after one collision has been // detected: physically impossible to collide with two blocks! for (int i=0; i< m_Blocks.Length; i++) { if (m_Blocks[i].Collided(m_TheSoccer)) { m_TheSoccer.VelocityX = -m_TheSoccer.VelocityX; EchoToTopStatus( "Last block collision:" + i + "-Block");PlayACue( "Break");} } |
The first time through
the loop, i has the value zero, so during the first iteration of the loop,
we're really asking if the rectangle object referred to by element #0 has
collided with the soccer ball. The next time through the loop, i has
the value 1, so the code is then equivalent to:
if
(m_Blocks[0].Collided(m_TheSoccer))
{
m_TheSoccer.VelocityX = -m_TheSoccer.VelocityX;
EchoToTopStatus(
"Last block collision: E-Block");PlayACue(
"Break");}
We've managed to both minimize the amount of repeated code, as well as set things up so that our code will automatically check for a collision with all the blocks (should we choose to add more) without us needing to change anything.
FURTHER EXERCISES: