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 18-9 shows the main part of the program. Open Unscramble.sb<br />

from this chapter’s folder for the full list of words.<br />

1 ' Unscramble.sb<br />

2 words = "1=mountain;2=valley;...;22=animation;" ' See file for full list<br />

3<br />

4 While ("True")<br />

5 strIn = words[Math.GetRandomNumber(Array.GetItemCount(words))]<br />

6 Scramble() ' Returns strOut (a scrambled version of strIn)<br />

7<br />

8 TextWindow.Write("Unscramble [" + strOut + "]: ")<br />

9 ans = TextWindow.Read()<br />

10 ans = Text.ConvertToLowerCase(ans)<br />

11<br />

12 If (ans = strIn) Then<br />

13 TextWindow.WriteLine("Good Job!")<br />

14 Else<br />

15 TextWindow.WriteLine("No. It is " + strIn + ".")<br />

16 EndIf<br />

17 TextWindow.WriteLine("")<br />

18 EndWhile<br />

Listing 18-9: Scrambling words and asking the player <strong>to</strong> unscramble them<br />

The words array contains the words for this game (line 2). The program<br />

randomly picks a word from this array and saves that word as strIn<br />

(line 5). It then makes a call <strong>to</strong> Scramble() <strong>to</strong> produce strOut, a scrambled<br />

version of strIn (line 6): we’ll add the Scramble() subroutine in a moment.<br />

Next, the program asks the player <strong>to</strong> unscramble strOut (line 8). It reads<br />

their answer (line 9) and converts it <strong>to</strong> lowercase (line 10). It then compares<br />

the player’s answer <strong>with</strong> the correct word (line 12). If the player’s<br />

answer matches the original word, the game displays Good Job! (line 13).<br />

Otherwise, the game displays the correct word (line 15). In both cases,<br />

the program ends by displaying an empty line (line 17) <strong>to</strong> separate the<br />

rounds and the loop repeats.<br />

Now let’s look at the Scramble() subroutine, which shuffles the characters<br />

of a string in<strong>to</strong> a random order. The caller sets the input string (strIn),<br />

and the subroutine returns a new string (strOut) that contains the characters<br />

of strIn shuffled around. Listing 18-10 shows this subroutine.<br />

1 Sub Scramble ' Scramble subroutine<br />

2 len = Text.GetLength(strIn)<br />

3 For N = 1 To len ' Loops up <strong>to</strong> length of word<br />

4 char[N] = Text.GetSubText(strIn, N, 1) ' Saves each letter in<strong>to</strong> an array<br />

5 EndFor<br />

6<br />

7 strout = "" ' Empties the output string<br />

8 While (Text.GetLength(strout) < len)<br />

Advanced Text Magic 279

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

Saved successfully!

Ooh no, something went wrong!