Wednesday, April 18, 2018

Arrays, Loops, and Racing Horses

One of the things I like about using Visual Studio and C# (and Visual Basic for that matter) is the ability to easily create some fun graphical projects. I’ve been using variations of the horse race program for years now. I though it might be fun to share my latest use.

image

Students sometimes have trouble seeing the benefits of arrays because they are used to small projects that can get by without them. I want them to see how the combination of loops and arrays make expanding programs easier.

My students were given a mostly empty project with the objects you see in the image above already part of the project. I don’t want them to get lost in setting up the GUI. There is a “Race” button, a “Reset” button, four picture boxes, and the finish line (a nicely formatted label.) No code though. We’ll create that as a class.

The first thing we do is allocate an array of three picture boxes. Next we assign the value of the existing picture boxes to the array. We talk about how the picture boxes now have two names or two ways of addressing them. This is related to people’s names – formal name, nickname, etc.

public Form1()
{
     InitializeComponent();
     Horses[0] = picHorse0;
     Horses[1] = picHorse1;
     Horses[2] = picHorse2

}

The naming I use (I hope) drives home how identifiers that differ only by a number at the end leads one naturally to thinking about arrays.

We write code to move the “horses” random distances each time a timer fires. Using timers is not absolutely necessary and I have used while loops but timers open some ideas for interesting projects. The “Race” button enables the timer and the horses start moving by changing the Left properties by random numbers of pixels..

for (int index = 0; index < Horses.Length; index++)
{
     Horses[index].Left += r.Next(3, 8);
}

Next we add the code to check to see if the Left property plus the width of the box crosses past the left property of the finish line.

Students are asked to figure out the Reset button on their own and most do so easily. At this point we’ve had a lot of discussion about the code we’ve written so far. Next I ask them to add more horses to the problem. They soon discover that this is a fairly trivial task because of the way we have designed the program.

Since we get to work with interesting arrays and see how setting up loops we cover some important topics. Best of all, students seem to like this project.

There is room for student creativity as well. Some add only a few horses, some add many. Some get fancy with reporting winners. Some explore other images from what I provide. Others decided they wanted that last place horse to disappear before the next race. That involved a lot more work then they expected but they were motivated to try things. But no one, including me, get bored.

No comments:

Post a Comment