A-level Computing/AQA/Problem Solving, Programming, Data Representation and Practical Exercise/Skeleton code/2011 Exam/Random functions
When we are making the cricket game we are allow the user to use their own die or a random number die built into the program. We are now going to look how the random number feature works:
To start using random numbers are need to set up the randomize function. This is a little like throwing a million dice in the air at once and storing all their results, we can then use these 'random' results in our program
The next thing we need to do is to allocate a number from one to six for the dice role. Remember we have two dice, one for the bowler and once for the batter:
Assigning a random number
To get a random number we use the Rnd() function (remember a function returns a value). Unfortunately the Rnd() function returns a value between 0.000000 and 0.9999999. So we need to convert this to a number between 1 and 6.
To do this, we can multiply the number by 6, this will give us values between 0.00000 and 5.99999. These are obviously not whole numbers so we need to round them off to be integers Using the Int() function. Giving us a number between 0 and 5. Still not perfect as we need something between 1 and 6. So we need to be a little smarter and add 1. This will now give us a number between 1and 6.
BowlDieResult = Int(Rnd() * 6) + 1