19.04.2017 Views

Learn to Program with Small Basic

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Listing 9-4 shows an example of using the Or opera<strong>to</strong>r. The goal is <strong>to</strong><br />

end the game if there’s no more time <strong>to</strong> play (timeLeft = 0) or if the player<br />

has lost all their energy (energyLevel = 0).<br />

1 ' OrDemo.sb<br />

2 TextWindow.Write("Time left: ")<br />

3 timeLeft = TextWindow.ReadNumber()<br />

4<br />

5 TextWindow.Write("Energy level: ")<br />

6 energyLevel = TextWindow.ReadNumber()<br />

7<br />

8 If ((timeLeft = 0) Or (energyLevel = 0)) Then<br />

9 TextWindow.WriteLine("Game Over!")<br />

10 EndIf<br />

Listing 9-4: The Or opera<strong>to</strong>r<br />

If timeLeft is 0 or energyLevel is 0, <strong>Small</strong> <strong>Basic</strong> runs the command inside<br />

the If block (line 9). Run this program several times using different inputs<br />

<strong>to</strong> make sure you understand how the Or opera<strong>to</strong>r works.<br />

You could use nested If statements <strong>to</strong> do the same thing. For example,<br />

you could replace lines 8–10 <strong>with</strong> the following code:<br />

If (timeLeft = 0) Then<br />

TextWindow.WriteLine("Game Over!")<br />

Else<br />

If (energyLevel = 0) Then<br />

TextWindow.WriteLine("Game Over!")<br />

EndIf<br />

EndIf<br />

However, as you can see, using nested If statements takes up seven lines<br />

of code, but using Or <strong>to</strong>ok only three! Using the Or opera<strong>to</strong>r is a more concise<br />

way <strong>to</strong> test multiple conditions.<br />

The Cosmic Order of Evaluation<br />

Look at the following condition. How does <strong>Small</strong> <strong>Basic</strong> evaluate this<br />

expression?<br />

If (A = 1 Or B = 1 And C = 1) Then<br />

As it turns out, <strong>Small</strong> <strong>Basic</strong> gives And a higher priority than Or. This<br />

means it finds B = 1 And C = 1 first, and then the result is used as the right<br />

operand for the Or expression. To change the order, you can use parentheses,<br />

like this:<br />

If ((A = 1 Or B = 1) And C = 1) Then<br />

Using Decisions <strong>to</strong> Make Games 119

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!