Learning Loops in VB.NET for Game Development
(Page 1 of 4 )
This is the fourth article of a nine part series that teaches VB.NET via the development of a text-based game. The last article discussed variables, conditionals, and Console input. This article will commence the discussion of loops, starting with the While loop and the Do loop. Join us as we continue on our journey.
Loops
So far, we know how to write information to the console, read information from the console, and work with conditionals. Before we can get started though, we're missing one key concept: loops. Obviously, a game involves repeating a set of instructions over and over again until the user quits. This repetition is, of course, made possible through loops. Visual Basic has four loops, each designed with a particular use in mind. They are the While loop (While ...End), the Do loop (Do ...Loop), the For loop (For ...Next), and the For Each loop (For Each ...Next). We'll cover them all here in the order that I've listed them.
While...End
The first loop is the While loop, and it's probably the most basic loop available. It loops over a set of instructions as long as a given condition comes out True. This loop will be particularly useful in our game because we simply need to follow a regular pattern of accepting user input, acting on that input, accepting more input, acting on the new input, etc. This pattern is repeated any number of times until the user quits the game.
One of the simplest loops we can create is one that runs forever without terminating—in other words, an infinite loop. Let's create a loop that accepts user input, echoes the input to the user, and then repeats the process over and over again:
Dim input As String
While True
input = Console.ReadLine()
Console.WriteLine(input)
End While
(Note: in Visual Studio, you can force the program to exit by pressing the “Stop Debugging” button or by pressing Control+Alt+Break. This is particularly useful in cases where the program gets stuck in a loop, as in the above example.)
Notice how the expression is simply True. Since this condition is, obviously, True , then the loop will continue forever (in theory, that is), accepting user input and then echoing the input. Of course, this behavior is seldom what we want in a loop. We want the loop to terminate at some point. There are two ways of doing this. The first is to manually break out of the loop using the Exit statement, which will immediately transfer control to the first statement outside of the loop. Let's stick an Exit statement in our loop:
Dim input As String
While True
input = Console.ReadLine()
Console.WriteLine(input)
Exit While
End While
Notice how we must specify exactly what we're exiting out of. This way, we can exit out of multiple layers of loops, and we can even exit out of the subroutine entirely (Exit Sub).
Next: While...End continued >>
More Visual Basic.NET Articles
More By Peyton McCullough