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.

9 pos = Math.GetRandomNumber(len) ' Picks where <strong>to</strong> place the letter<br />

10 If (char[pos] "") Then<br />

11 strout = strout + char[pos] ' Adds in the extra letter<br />

12 char[pos] = "" ' Empties the element<br />

13 EndIf<br />

14 EndWhile<br />

15 EndSub<br />

Listing 18-10: Word-scrambling subroutine<br />

The subroutine saves the length of the input string in<strong>to</strong> len (line 2).<br />

It then uses a For loop <strong>to</strong> save the individual letters of strIn in<strong>to</strong> an array<br />

named char (lines 3–5). It empties the output string, strOut, and starts a<br />

While loop <strong>to</strong> assemble strOut letter by letter (lines 7–14). The While loop<br />

runs until strOut has the same length as strIn (which means that we’ve<br />

added all the letters of strIn). Each iteration of the loop picks a random<br />

element from the char array (line 9). If that element is empty, we loop again<br />

<strong>to</strong> pick another one. Otherwise, we append the selected letter <strong>to</strong> strOut<br />

(line 11) and empty that element <strong>to</strong> indicate that we’ve used it (<strong>to</strong> prevent<br />

using it again) in line 12. Ouy fishendi eth egma!<br />

Here’s a sample run of this program:<br />

Unscramble [lalvey]: lovely<br />

No. It is valley.<br />

TRY IT OUT 18-9<br />

Try <strong>to</strong> update the word-scrambling game using the skills you learned in previous<br />

chapters. Make the game last 10 rounds and then display the user’s score: how<br />

many words were unscrambled correctly out of the 10? Next, add 28 more words<br />

<strong>to</strong> unscramble so you have a <strong>to</strong>tal of 50. Then show the game <strong>to</strong> your friends and<br />

see who can get the best score!<br />

Rhyme Time: The House That Jack Built<br />

Let’s finish this chapter <strong>with</strong> a program that displays a popular British<br />

nursery rhyme and cumulative tale. In a cumulative tale, an action repeats<br />

and builds up as the tale progresses. Figure 18-7 shows this program<br />

in progress; more rhyme lines appear each time a user clicks the Next<br />

but<strong>to</strong>n.<br />

280 Chapter 18

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

Saved successfully!

Ooh no, something went wrong!