BASIC Programming/Random Number Generation

From Wikibooks, open books for an open world
Jump to navigation Jump to search

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:

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 and add to the result.

The above program morphs to:

PER = RND * 99 + 1
PRINT "Wikibooks' coolness quotient: ", PER, "%"

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