functions

icon picker
random game

make a lucky dice game using the random function

program requirement

The program should allow the user to play a dice game.
The program should allow the user to enter the number of throws required. The program should then "throw" a dice and report the score for the number of throws requested. A total dice score should be calculated and if the score is 21 or below the player wins, otherwise the player loses.

sample output

How many throws:
3
roll: 1 is: 5

roll: 2 is: 3

roll: 3 is: 2

Total score: 10
Win

learning point

a random number means that the program creates an integer value which cannot be predicted, usually between a minimum and maximum limit
Java uses a special Random object to make random numbers, one object can make an unlimited number of random number values
The Random object uses a parameter to set the upper limit (exclusive), the lower limit is always 0 (inclusive)
duplicate values may appear

introducing the code

1 Random randomMaker = new Random();

2 score = randomMaker.nextInt(6) + 1;
in java a random number is produced by a special program feature called an object, think of it like a little gadget that can make a random number
on line 1 a single Random object is created and it’s been called randomMaker
randomMaker can now make the random number values that are needed
on line 2 randomMaker is set up to make another random number with the parameter set to 6, so a value in the range 0-5 are created and stored in the integer variable score
the result of randomMaker is incremented (+1) to adjust the range 0-5 to become 1-6 which are the values produced by throwing a die
the code in line 2 can be nested within a loop to produce a series of random numbers

developer task

Run the lucky dice roll program a few times and experiment with what kind of scores and totals are produced with different numbers of throws.
What is the highest number of throws you can make without losing?
Notice that the output is random. Sometimes this makes games difficult to test and debug since you the program will produce different results every time it is run.
You could experiment by changing the limit for the random number and the threshold score for winning/losing. Perhaps you can code a bonus win if a player gets exactly 21.

PRIMM assignment
Create code to play a coin-flip game. The player should be able to choose how many flips they want to try. On every turn of the game the player should predict the result and then the program should report if the player guessed correctly.
Create some rules about winning or losing the game.
Can you check to see if all the guesses are correct?
Can you calculate a percentage of correct scores and round the result?

program code

Loading…
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.