< BASIC Programming

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 and add 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%".

This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.