BASIC Programming/Random Number Generation
One useful thing for games is random numbers. This is a sequence of numbers that appears randomly distributed, so they can be used to simulate things like shuffling a deck of cards or producing different behaviours every time a program runs.
Different dialects might require a parameter for the function, so RND(), RND(0) and RND(1) are commonly seen. The parameter is normally ignored. |
Random numbers in BASIC are generated by the RND function. This returns a number between 0 and 1. For example:
PRINT "Wikibooks' coolness quotient: ", RND, "%"
You will get "Wikibooks' coolness quotient: .7055475%".
The sequence is normally produced in one of two ways, depending on the dialect of BASIC. For early mainframe and minicomputer BASICs, as well as most modern versions, the numbers are generated using a mathematical formula applied to the last number generated. The same sequence will be returned every time, so to produce different numbers the starting value has to be changed. This is known as "seeding the random number generator", or simply "seeding". BASICs from the home computer era used a different method that was based on the internal clock, which produced a sequence that was never the same and did not require seeding. |
That result looks random. Run it again and you get the same value! That makes a game boring. This is the purpose of seeding, which is normally accomplished with the RANDOMIZE statement. In modern dialects, this can be tied to the clock using the TIMER keyword:
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 not always useful. If you want a whole number, you must get a random number and then convert it to a whole number. Normally you want that number to be between two limits, say 0 and 100. One solution is to take the number, multiply by the maximum desired value, add half to round it, and then take the whole number part. Some slight variation on the following code is very common:
PER = INT(RND() * 99 + 0.5)
Modern dialects like QBASIC offer more control. We can state the variable is an integer, and BASIC will force it to that format and slightly simplify the code:
RANDOMIZE TIMER
DIM PER AS INTEGER
PER = RND * 100 + 0.5
PRINT "Wikibooks' coolness quotient: ", PER, "%"
which will print "Wikibooks' coolness quotient: 85%".