Header
Home | Sitemap Set as homepage | Add to favorites
  Search the Site     » Advanced Search
Sections



Random Number Generation(WML)

by

image

Random Number Generation
There is something in the air of a gambling casino that invigorates people, from the highrollers
at the plush mahogany-and-felt craps tables to the quarter-poppers at the one-armed
bandits. It is the element of chance, the possibility that luck will convert a pocketful of money
into a mountain of wealth. The element of chance is introduced through the Lang object’s
random method. Later, in Chapter 18, we’ll show how to use the random method
to create the game of craps.
Many instances occur where generating random numbers is necessary to a program.
For instance, a program may simulate the flip of a coin, a roll of a six-sided die or perhaps
display a random advertisement. WMLScript offers a built-in method, part of the Lang
object, that generates random integers. Method Lang.random generates an integer value
from 0 up to (but not including) a limit set by the programmer (using an argument). Consider
the following statement:
Fig. 16.5 WML listing that calls a programmer-defined function.
Chapter 16 WMLScript: Functions 293
© Copyright 2001 by Deitel & Associates, Inc. All Rights Reserved. review Packet 5/7/01.
randomNumber = Lang.random( 5 );
This statement would generate a random integer from 0 up to but not including 5 and store
that number in the variable randomNumber. If random truly produces values at random,
every value from 0 up to (but not including) the limit has an equal chance (or probability)
of being chosen each time random is called.
The range of values produced directly by random is often different from what is
needed in a specific application. For example, a program that simulates coin tossing might
require only 0 for “heads” and 1 for “tails.” A program that simulates rolling a six-sided die
would require random integers from 1 to 6. A program that randomly predicts the next type
of spaceship (out of four possibilities) that will fly across the horizon in a video game might
require random integers in the range 0 through 3 or 1 through 4.
To demonstrate method random, let us develop a program (Fig.16.6) that generates
a random number between 1 and 100 and allows the user to keep guessing until they reach
the correct number. The program will tell the user whether each guess was high or low. To
generate random numbers beginning with 1, we must shift the value by one. On lines 6–7,
we use the addition operator (+) in conjunction with random as follows:
1 + Lang.random( 100 )
When the Lang object’s random method is invoked on the number 100, a random number
between 0 and 99 will be produced. By adding 1, we achieve our goal of producing random
numbers from 1 to 100. Figure16.6 shows the WMLScript that picks a random number,
obtains a guess from the user and determines whether the user guessed the number correctly.
1 // Fig 16.6: guess.wmls
2 // Using the max function
34
extern function pickNumber()
5 {
6 WMLBrowser.setVar( "secretNumber", (1 +
7 Lang.random( 100 ) ) );
8 WMLBrowser.go( "#guess" );
9 }
10
11 extern function newGuess()
12 {
13 var secret = Lang.parseInt(
14 WMLBrowser.getVar( "secretNumber" ) );
15 var guess = Lang.parseInt(
16 WMLBrowser.getVar( "nextGuess" ) );
17 var guessCount = Lang.parseInt(
18 WMLBrowser.getVar( "tries" ) ) + 1;
19 WMLBrowser.setVar( "tries", guessCount );
20
21 if ( guess<secret ){
22 WMLBrowser.setVar( "reply", "Too Low" );
23 WMLBrowser.go( "#check" );
24 }
Fig. 16.6 Generating random numbers with WMLScript.
294 WMLScript: Functions Chapter 16
© Copyright 2001 by Deitel & Associates, Inc. All Rights Reserved. review Packet 5/7/01.
The pickNumber function which begins on line 4 picks a number at random, stores
it in the browser variable secretNumber and forwards the user to the guess card. This
function is called when the user begins a new game. The random number is generated on
lines 6 and 7.
WMLBrowser.setVar( "secretNumber", (1 +
Lang.random( 100 )) );
This code adds 1 to Lang.random(100) to generate random numbers between 1 and
100. It then stores that value in the browser variable secretNumber using the WMLBrowser
object’s setVar method. Browser variables are accessible by all cards within
the active deck. WMLScript can also access browser variables using the setVar and
getVar methods. After the secret number has been chosen at random and stored, the user
is forwarded to the guess card using the go method on line 8. When the guess card is
loaded, it prompts the user to enter a number. After entering the number the user must press
the Submit soft key to continue. Pressing the soft key stores the guess in a variable and
calls the WMLScript function newGuess, which is found on lines 11-32 of Fig.16.6. The
function sets three variables—secret, guess and guessCount. Lines 13–16
var secret = Lang.parseInt(
WMLBrowser.getVar( "secretNumber" ) );
var guess = Lang.parseInt(
WMLBrowser.getVar( "nextGuess" ) );
declare and initialize the first two variables. On line 13, the WMLBrowser object’s get-
Var method retrieves the value of the browser variable secretNumber that was set earlier.
It then converts it to an integer and stores it in the variable secret. Next, the user’s
guess which was stored in the nextGuess browser variable by the guess card in Fig. 16.7
is retrieved. The guess is then converted to an integer and stored in the variable guess.
Lines 17-19,
var guessCount = Lang.parseInt(
WMLBrowser.getVar( "tries" ) ) + 1;
WMLBrowser.setVar( "tries", guessCount );
initialize the variable guessCount to track the number of guesses the user has made. This
value is set according to the value of the browser variable tries (Fig. 16.7). The browser
variable tries is initialized to 0 when the user begins the game. Each time the
newGuess function is called, the value of tries is retrieved, incremented by 1 and
stored in nextGuess. The value of tries is then updated to reflect the new value of
25 else if (guess>secret)
26 WMLBrowser.setVar( "reply", "Too High" );
27 WMLBrowser.go( "#check" );
28 }
29 else if (guess==secret){
30 WMLBrowser.go( "#winner" );
31 }
32 }
Fig. 16.6 Generating random numbers with WMLScript.
Chapter 16 WMLScript: Functions 295
© Copyright 2001 by Deitel & Associates, Inc. All Rights Reserved. review Packet 5/7/01.
nextGuess. Consequently, each time the user makes a guess the values of both nextGuess
and tries are incremented. When the user guesses correctly, the value of
tries displays to show the user how many guesses were made.
Once the variables have been initialized, checking can be done to see whether the guess
was too high, too low, or correct. The checking is done in lines 21-32 of Fig.16.6 using if/
else statements. We briefly introduced the if structure in Chapter 15, and will explain it
in greater detail in Chapter 17 when we introduce WMLScript control structures. In line 21,
the function checks to see if the guess was less than the secret number. If so, variable
reply is set to the string Too Low, and the user is sent to the check card. The check
card informs the user that the guess was incorrect and displays the value of the variable In
line 25 the first else structure is executed. This condition is only checked if the previous
if condition was not met. In this case the else checks to see if the guess was greater than
the secret number by comparing the values of variables guess and secret. If so, the
value of reply is set to Too High and the user is once again forwarded to the check
card. Storing the result of the comparison of the user’s guess and the secret number in the
browser variable reply allows us to simplify our WML deck. The check card is used to
display all results by dereferencing the value of reply each time. On line 29 we have our
final else statement which checks to see if the user guessed correctly. Remember, the ==
(double equals) operator is used in if/else structures to determine whether two values
are equal. If guess is equal to secret, the reply variable is set to Your Right! and
the user is forwarded to the winner card. This time we did not forward the user to the
check card. Instead, the user is sent to the winner card because we wanted to add a
unique soft key (lines 51–53) that would allow the user to restart. The check card only
allows the user to guess again. The winner card informs the user that they guessed correctly
and displays the value of the browser variable tries. Figure 16.7 shows the WML document
that calls the WMLScript functions that play the guessing game.
1 <?xml version="1.0"?>
2 <!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD
3 WML 1.2//EN" "http://www.wapforum.org/DTD/wml12.dtd">
45
<!-- Fig. 16.7: fig16_7.wml -->
6 <!-- Guessing a secret number -->
78
<wml>
9 <card id="index" title="Max Function">
10 <onevent type="onenterforward">
11 <refresh>
12 <setvar name="tries" value="0"/>
13 </refresh>
14 </onevent>
15
16 <do type="accept" label="Start">
17 <go href="guess.wmls#pickNumber()"/>
18 </do>
19
20 <p>
21
Fig. 16.7 A guessing game using random numbers in WML.
296 WMLScript: Functions Chapter 16
© Copyright 2001 by Deitel & Associates, Inc. All Rights Reserved. review Packet 5/7/01.
22 <b>The Guessing Game.</b>
23 I'll think of a number from 1 to 100.
24 You try to guess it.
25 Press Start to begin.
26 </p>
27 </card>
28
29 <card id="guess" title="Guess The Number">
30 <do type="accept" label="Submit">
31 <go href="guess.wmls#newGuess()"/>
32 </do>
33
34 <p>
35 Enter your guess and press submit:
36 <input name="nextGuess" value="" size="3"/>
37 </p>
38 </card>
39
40 <card id="check" title="Checking">
41 <do type="accept" label="Guess Again">
42 <go href="#guess"/>
43 </do>
44
45 <p>
46 Your guess was $reply. Try again
47 </p>
48 </card>
49
50 <card id="winner" title="You Win">
51 <do type="accept" label="Restart">
52 <go href="#index"/>
53 </do>
54
55 <p>
56 You win! My number was $secretNumber!
57 It only took you $tries guesses!
58 Press Restart and I will pick a new number.
59 </p>
60 </card>
61 </wml>
Fig. 16.7 A guessing game using random numbers in WML.
Chapter 16 WMLScript: Functions 297
© Copyright 2001 by Deitel & Associates, Inc. All Rights Reserved. review Packet 5/7/01.
Fig. 16.7 A guessing game using random numbers in WML.
298 WMLScript: Functions Chapter 16
© Copyright 2001 by Deitel & Associates, Inc. All Rights Reserved. review Packet 5/7/01.
On line 12
<setvar name="tries" value="0"/>
the browser variable tries is initialized to 0. This occurs when the card is entered for the
first time because the setVar element is found within an onEvent element of type
onenterforward. In other words, each time the index card is accessed the value of
tries is reset. In lines 16–18
<do type="accept" label="Start">
<go href="guess.wmls#pickNumber()"/>
</do>
the function pickNumber is called with the go element. The function is called when the
Start soft key if pressed. In line 36, an input element accepts the user’s guess. It’s id
attribute is set to nextGuess. The guess card also features a soft key called Submit,
which calls the newGuess function in Fig. 16.6 when pressed. You may recall that the
newGuess function uses the getVar method to retrieve the value of nextGuess. The
nextGuess function forwards the user to the check card (line 40) if the guess was incorrect
or the winner card (line 50) if it was correct. The check card simply displays the
value of the reply browser variable which is set to either Too Low or Too High by the
nextGuess function. The card also features a soft key which allows the user to guess
again by returning them to the guess card. The winner card (lines 50-60) informs the
user that they guessed correctly and displays the secret number and the total number of
guesses made. It also allows the user to restart by forwarding them to the index card.
1508 times read

Related news

» Scope Rules (WML)
by admin posted on Aug 28,2007
» Function Definitions
by admin posted on Aug 28,2007
» Program Modules in WMLScript
by admin posted on Aug 24,2007
» wml script functions
by admin posted on Aug 28,2007
» Duration of Identifiers(WML)
by admin posted on Aug 28,2007


More Top News
Cisco Wireless Networking
Most Popular
Featured Author