This lesson introduces the concepts of arrays and loops and how their use can simplify your code, especially when dealing with larger numbers of objects.
This lesson picks up where Lesson 14 left off.
Source code for Lesson 15 Completed: http://www.bluerosegames.com/xna101/lessons/XnaTutorial15.zip
When it came time to add a second ball to our game, it became clear that just copying and pasting the code and changing the variable names was going to be a problem. So by encapsulating the bouncing ball logic in a BouncingBall class, we were able to reduce dramatically the complexity and the lines of code of our game.
Now what if we want to have 3 balls, or 10, or 100? Should we declare 100 separate BouncingBall objects in the Game1 class initialize them in the Game1 constructor, and have 100 Update and Draw statements? Again, this would get out of control pretty quickly. Fortunately C# provides an alternative.
An array is a fixed size list of objects or primitives of the same data type. Items in the array are accesed via an index. An index is a value that "points" to an element in the array. Typically array indexes are integers. In C# array indexes start at 0, so the first element has an index of 0.
Often when writing code, you get to a point where the code in unmanageable and it's necessary to add classes, move code into new methods, or make other changes. The term refactoring refers to a restructuring of the code while preserving all or most of the current functionality. Ideally after a refactoring, the program should work exactly the same as it did before. In the "Double Trouble" lessons, we refactored the code by creating a BouncingBall class and moving the bouncing ball logic and data into that class. In this lesson, we will refactor the code to use an array to store the BouncingBall information.
The format for declaring an array is as follows:
datatype [] fieldName;
Where the data type can be a primitive, such as float, or a class, such as BouncingBall. In our case, in the Game1 class, replace the ball1 and ball2 declarations in the Game1 class with the following:
BouncingBall [] balls;
int ballCount = 2;
The ballCount Field will help us later when we want to change how many elements are in our array. This is a best practice, try not to use constant values all over your code because it makes changes harder later.
The next step for an array is to initialize the array. At the top of the Game1.Initialize() method, add the following:
balls = new BouncingBall[ballCount];
This initializes the array to a size of 2 (since ballCount is 2). Now that the array itself is initialized, we need to initialize each object in the array. We can, as we had before, have a single "new" statement for each object we want to create, but again this can be an issue if you have a lot of objects. So in order to reduce the amount of code, we can use something called a loop. A loop is a block of code that is run multiple times based on conditions. In this case, we will use a "for" loop. Typically a "for" loop is used when you want to start at one number and end at another number. Our loop will start at the smallest index in our array, and end at the largest index. Replace all of the rest of the the ball1 and ball2 code which initializes the objects and sets values in the Game1.Initialize() method with the following:
for (int index = 0; index < ballCount; index++)
{
balls[index] = new BouncingBall();
balls[index].Velocity =
new Vector2(rand.Next(2, 11), rand.Next(2, 11));
byte r = (byte)rand.Next(64, 256); // Red value
byte g = (byte)rand.Next(64, 256); // Green value
byte b = (byte)rand.Next(64, 256); // Blue value
byte a = (byte)rand.Next(64, 256); // Alpha value
balls[index].DrawingColor = new Color(r, g, b, a);
}
The structure of a for statement has 3 semicolon delimited satements inside the parentheses. The first is executed the first time through the loop and typically initializes the loop index. The second statement is a condition that once false, program execution continues with the next statement after the loop block. The condition is checked every time through the loop, including the first time. If the condition is false on the first time through the loop, the code inside the loop block will not get executed at all. The third statement updates the loop index and is executed at the end of each time through the loop, before the condition is checked again.
Notice the index++ syntax. The "++" operator is a more efficient way of adding 1 to the value in the variable. It is very common in C# and C++ programming (which incidentally is how C++ got its name) and is the preferred way to increment a variable. There is a corresponding "--" operator which subtracts 1 from a variable.
So this loop set index to 0, adding 1 each time through the loop, and will execute as long as index is less than 2. Why less than 2? Because as stated above, arrays in C# start at 0, so an array with 2 elements in it has indexes of 0 and 1. Again this is a boundary condition and as discussed in a previous lesson, you need to be very careful around boundary conditions and it's very easy to get them wrong if you're not careful.
Another type of loop is the "foreach" loop. The "foreach" loop is specifically for looping through an array or list of objects. Though not as flexible as a "for" loop, it is easier to use. For our Update and Draw method changes, let's use the "foreach" loop. First in the Game1.Update() method, remove the ball1 and ball2 Update calls and replace them with the following:
foreach (BouncingBall ball in balls)
{
ball.Update();
}
As you can see, you don't have to access the array element by index, or do the initialization of the loop variable or checking a condition, that's all handled for you. Similarly in the Game1.Draw() method, replace the ball1 and ball2 calls with this:
foreach (BouncingBall ball in balls)
{
ball.Draw(spriteBatch);
}
Run the program again. You should see 2 balls of random color, opacity, and velocity bouncing around. Run it again, and you will see other combinations of colors and velocities.
Now for the fun part. Change the ballCount initializer to set ballCount to 10. Run it again. Now set it to 50. As you can see, arrays and loops are very powerful and a key concept in programming.

Be the first to rate this post
- Currently 0/5 Stars.
- 1
- 2
- 3
- 4
- 5