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.

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

18 Else<br />

19 TextWindow.WriteLine("Incorrect. It is " + strIn + ".")<br />

20 EndIf<br />

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

22 EndWhile<br />

Listing 18-8: Creating misspelled words and asking the player <strong>to</strong> fix them<br />

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

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

(line 5). Note how we used the array’s item count <strong>to</strong> set the upper limit of<br />

the random number. The program then selects a random letter, randChar,<br />

from the alphabet (line 6). It does that by getting a random number from 1<br />

<strong>to</strong> 26 and adding 96 <strong>to</strong> it; this gives you a random number between 97 (the<br />

code point for letter a) and 122 (the code point for letter z). Next, the program<br />

picks a random position, charPos, in strIn (line 7): this is the position<br />

where the random character is inserted. Then the program creates the misspelled<br />

word and s<strong>to</strong>res it in strOut (lines 9–11).<br />

In line 13, the program asks the player <strong>to</strong> enter the correct spelling. It<br />

reads the user’s answer (line 14) and converts it <strong>to</strong> lowercase (line 15). It<br />

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

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

Otherwise, the game displays an error message and shows the correct spelling<br />

(line 19). In both cases, the program ends by displaying an empty line<br />

(line 21), and the loop repeats <strong>to</strong> give the user a new misspelled word.<br />

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

Enter correct spelling for [mairror]: miror<br />

Incorrect. It is mirror.<br />

Enter correct spelling for [inteorface]: interface<br />

Good Job!<br />

TRY IT OUT 18-8<br />

Update the program in Listing 18-8 so the misspelled word contains two additional<br />

random letters instead of just one random letter. Also, add more words <strong>to</strong> the list<br />

for more variety.<br />

Unscramble<br />

Now we’ll create a word scramble game. The program starts <strong>with</strong> an English<br />

word, scrambles the letters, displays the scrambled word <strong>to</strong> the player, and<br />

asks them <strong>to</strong> guess the original word.<br />

278 Chapter 18

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

Saved successfully!

Ooh no, something went wrong!