BASIC Programming/Random Number Generation

One useful thing for games are random numbers.

Random numbers in BASIC are implemented by RND. For example:

PRINT "Wikibooks' coolness quotient: ", RND, "%"

You will get "Wikibooks' coolness quotient: .7055475%". That decimal looks random. Run it again and you still get it! That makes a game boring. What do you do? Initialize the random number generator! That's done with RANDOMIZE, which takes a seed as its first parameter. You should use something that changes for the seed. TIMER does, so it is a great seed. The above program evolves to:

RANDOMIZE TIMER
PRINT "Wikibooks' coolness quotient: ", RND, "%"

which will print "Wikibooks' coolness quotient: .8532526%" and another time will print "Wikibooks' coolness quotient: .3582422%". Better, right?

But decimal numbers are boring. If you want a whole number, you must get a random number, multiply by max - min and add min to the result.

The above program morphs to:

RANDOMIZE TIMER
DIM PER AS INTEGER
PER = RND * 99 + 1
PRINT "Wikibooks' coolness quotient: ", PER, "%"

which will print "Wikibooks' coolness quotient: 85%".

Last modified on 20 July 2010, at 01:14