Loops

[ LiB ]

Loops

A loop is a block of code that is repeated over and over until a condition is met. For example, the main game loop is repeated over and over until either the player quits or wins the game. Goto, a command you learned in the previous chapter, can be used as a loop. If you remember the demo02-10.bb program, a set of commands was repeated until the user wanted them to stop. Loops work exactly like this: a set of commands are repeated over and over and over until a condition is meteither the user wants to exit the loop or the loop is executed a specific number of times. Figure 3.1 shows a sketch of a loop.

Figure 3.1. The loop.


Loops are used for many repetitive tasks in computer programs. If you want to have a space shooter game, you will have to use a loop to check every bullet against the enemy ships. You will also use loops to update the artificial intelligence (AI) for each of the ships.

There are three different types of loops, and although they all can be used in place of each other, each has a specific style and it is best if they are used in the proper situation. The three types of loops are

  • For Next

  • While Wend

  • Repeat Until

For Next

The For Next loop is used to step through a block of code a set number of times. In other words, you know how many times the loop should iterate. You might use this loop when you want the player to move up exactly 10 spaces. Because you know the number of times you want him to move up, you might have each iteration of the loop move him up one space and have the loop go through its commands 10 times. This loop is also used to update the info of a set of types (types will be explained later in this chapter).

NOTE

Before we move any further, I want to discuss the concept of iterations. As you know, a loop processes a number of commands over and over again, starting at the top, going to the bot tom, and moving back to the top again. An iteration occurs when all of the commands have been processed one full time. When the loop finishes the last statement of the loop, but before it returns to the top of the loop, one iteration has completed. When it returns to the top, the sec ond iteration begins, and so on.

 For loops are always used as follows: For  variable  =  beginning_number  To  ending_number  [Step  step_amount  ]     ;Perform actions Next 

As you can see, a for loop begins with For and ends with Next . The To command defines how many times the loop performs its actions. Step_amount , which is optional, defines how much is added to beginning_number each time. If you omit Step , beginning_number is incremented by 1 each time the loop is traversed.

Let's examine a code example:

 ;demo03-01.bb - counts from 1 to 10 For counter = 1 To 10     Print counter Next WaitKey 

Figure 3.2 shows the output.

Figure 3.2. The demo03-01.bb program.


This program simply prints the numbers 1 to 10 on the screen. The first line after the entry comment begins the For Next loop. It declares counter and initializes it to 1. The To command tells the compiler how many iterations the loop will go through. Here, it says it will count from 1 to 10.

The next line simply prints the value of Counter which, adds 1 to its count every iteration of the loop. The final line of the loop returns the code to the beginning of the loop and raises counter by 1. You can change the step amount of the loop if you wish. The step amount is how much is added to the variable on each iteration of the loop. By default, the step amount is 1.

To change the step amount, simply add the command Step after the To command like this:

 ;demo03-02.bb - Counts backwards using step amounts For counter# = 5.0 To 0.0 Step -1.2     Print counter Next WaitKey 

The output is shown in Figure 3.3.

Figure 3.3. The demo03-02.bb program.


NOTE

CAUTION

Make sure to double-check your loops in case you've made them never-ending . If this program had been written with the step value as 1.2 (as opposed to 1.2), the program would have looped forever and never ended. Fortunately, Blitz Basic will usually catch this error and simply skip the loop.

This program might seem a little strange , but I wrote it as such in order to make a few points. First, the counter variable is a floating-point variable (a variable with decimal places). The starting value is 5.0 and the ending value is 0.0. The step value is 1.2.

The Step value causes the program to count down instead of counting up. On the first iter-ation of the loop, the counter variable is 5.0. Then it is decreased to 3.8, and so on.

Let's look at the values for this loop. Table 3.1 explains the values of the counter variable, the Step amount, and the output throughout the program. As you can see, the first itera-tion of the For Next loop does not decrease the Step amount; instead, the Step amount is taken out beginning with the second iteration.

Table 3.1. Demo02-02.bb's Variable Values

Iteration

Counter#/Output

Step

1

5.0

1.2

2

3.8

1.2

3

2.6

1.2

4

1.4

1.2

5

0.2

1.2


Now is a good time to introduce float trimming. If you look at the output of the demo03-02.bb sample (Figure 3.3), you will notice that there are six digits after the decimal place. Six digits after the decimal is the default value. Because only one of the digits is significant, why leave the extra five sitting there? Trimming in this context means removing the trailing zeroes from a float value.

NOTE

Notice that we use 3 as the length variable. The reason is because the number is converted to a string, and the decimal is part of it. We are keeping the number before the deci mal, the decimal, and one number after the decimal.

In order to trim the trailing zeroes, we have to follow two steps. First, we must convert the floating variable (which has decimal places) into a string. Next, we remove all the digits that are unnecessary. Then, we are free to display the string.

Let's try it out:

 ;demo03-03.bb - Counts using step amounts For counter# = 5.0 To 0.0 Step -1.2     Print Left$(Str counter, 3) Next WaitKey 

Figure 3.4 shows the output.

Figure 3.4. The demo03-03.bb program.


This program begins the same way as the previous program did. It creates a For Next loop that begins with 5.0 and decreases by 1.2 until it reaches 0.0. The next line prints out the newly trimmed version of counter's value. Let's examine this statement.

The Print statement writes out each float value with one digit after the decimal place. The first thing it does is call the Left$() function. Left$() is declared as

 Left$ (string$, length) 

In this case, we used

 Str counter 

as our string$ variable. The Str function takes an integer or float and converts it to a string. It then returns the created string. Because the return value is a string, we can use it in place of the string$ variable. The length variable is set to 3 to include the number and only one decimal point. Table 3.2 describes the parameters.

Table 3.2. Left$'s Parameters

Parameter

Description

string$

The number you want to trim

length

The number of letters you want to remain


While Wend

The next type of loop is the While Wend loop. This loop is very much like the For Next loop, but it is usually used to test variable conditions. In other words, the While Wend loop is usually used when you aren't sure when it will be time to exit the loop.

While loops are the most common main loops in games . The main loop (also known as the game loop) is a loop that runs over and over until the game is over. Because you cannot determine exactly when to end a game, the While Wend loop is a perfect choice.

 ;demo03-04.bb - Waits for a key and then exits Print "This program is worthless." Print "Press escape to exit." While Not KeyDown(1) ;1 = Esc Wend End 

Figure 3.5 shows the output of this program.

Figure 3.5. The demo03-04.bb program.


This program simply displays some text and asks you to quit. Almost a waste of time, huh? Well, at least it demonstrates While Wend and it introduces a new function, KeyDown() .

 The WhileWend loop begins like this: 

 While Not KeyDown(1) 

This line of code sets up a while loop that exits only when the Esc key has been pressed. The loop continues until the Esc key is pressed. KeyDown() , which is declared as

 KeyDown(scancode) 

checks to see whether Esc has been pressed.

Here, the number 1 is used as the scan code. A scan code is a code generated by pressing any key on a keyboard. Each key has its own separate scan code. Esc has the scan code 1. KeyDown returns 1 (true) if the key has been pressed and 0 (false) if the key has not been pressed. Because we want the While Wend loop to continue until the key has been pressed, we invert the return value by including NOT . Therefore, if the player does not hit Esc, the KeyDown returns 0, the NOT command inverts it to 1, and the While Wend loop continues to the next iteration.

Now is a good time to introduce the basic game loop. This loop only ends when the user presses Esc. If the user loses, a function is called that will end the program. Note that this code WILL NOT work. It will only call functions that don't exist (functions will be introduced later in this chapter).

 ;Basic Game loop  While Not KeyDown(1)     PerformLogic()     Animation()     If playerlost Then       GameOver()     EndIf Wend 

This game loop is basically the most simplified version possible. Unless the player loses or presses Esc, the loop continues to iterate. The PerformLogic() function updates the AI for the game, and Animation() draws and animates everything on screen. If the playerlost variable is set to 1 (most likely by the PerformLogic() function), then the GameOver() function is called and the game is over.

You should always strive to keep your main loop as simple as possible. It should not perform more operations than necessary. You will learn how to delegate operations to smaller and more efficient functions later in this chapter.

Repeat Until

The final Blitz Basic loop is the Repeat Until loop. This loop is almost exactly like the While Wend loop, except that the condition is written after the closing statement ( Until ) instead of the opening statement ( Repeat ).

Doesn't seem like a big difference, huh? The only time you would use this type of loop is when you know for sure that the loop should be executed at least once. This is evident in situations that involve displaying menus and testing for keys.

 ;demo03-05.bb - Closes program after player presses ESC. Print "Why did you open this program?" Repeat     Print "Press Esc to exit."     Delay 1000 ;Wait for a sec Until KeyHit(1) Print "Program is ending." 

The output is shown in Figure 3.6.

Figure 3.6. The demo03-05.bb program.


This program simply writes "Press Esc to exit" to the screen until the user hits Esc. Two new functions are introduced: Delay and KeyHit() .

Delay pauses the program's execution for a set number of milliseconds . Delay is declared as

 Delay milliseconds 

where milliseconds is the number of milliseconds you want to delay the program. In this program, we delay the execution for one second.

The other new function introduced is KeyHit()

 KeyHit(scancode) 

NOTE

You might wonder about the differ ence between the new function KeyHit() and the previously intro duced function KeyDown() . The fact is, there is very little difference. KeyDown() checks to see if the button is down at the time of the test, whereas KeyHit() checks to see if it has been down since the last KeyHit() was checked.You can see the difference in any game. If you use KeyDown() , you can hold down a key to make it work repeatedly; if you use KeyHit() , you will have to press the button every time you use it.

where scancode is the code for the hit key. This function checks to see if the key was hit. If the key was hit, it returns True ; if not, it returns False .

The condition for exiting the Repeat Until loop is the opposite of While Wend and For Next loops. Instead of continuing to iterate the loop only as long as the condition is true, the Repeat Until loop continues only when the condition is false. Take extra precautions to make sure you do not create a never-ending loop.

Because we used Repeat Until , the "Press Esc to exit" line will always be shown, even if you press Esc before the loop begins. If you ever write a program that utilizes menus (most RPG [ R ole- P laying G ame] games do), you should use a Repeat Until loop.

Okay, we have now thoroughly discussed each of the loops. I hope that you are now an expert on how, as well as when, to use all three of the types of loops. Now on to an extremely important subject: functions.

[ LiB ]


Game Programming for Teens
Game Programming for Teens
ISBN: 1598635182
EAN: 2147483647
Year: 2004
Pages: 94
Authors: Maneesh Sethi

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net