Looking at other uses of a random engine- simulating a dice throw

Remember, a JavaScript random engine can be used to power any script that requires the quality of randomness, although its used mainly by JavaScripters on the net to create random links.

The throw of a dice is another classic example of a random event. Lets use the knowledge obtained thus far to recreate this event. To acheive this, we will first need six images of the same size, each representing one "face" of the dice:

d1.gif (1516 bytes) d2.gif (1560 bytes) d3.gif (1625 bytes) d4.gif (1676 bytes) d5.gif (1719 bytes) d6.gif (1717 bytes)

The idea is to use the random engine to randomly load one of the six faces of the dice each time the dice is "thrown", and display the image in place of the old. The below example illustrates this:

<script type="text/javascript">
//preload the six images first
var face0=new Image()
var face1=new Image()
var face2=new Image()
var face3=new Image()
var face4=new Image()
var face5=new Image()
<img src="d1.gif" name="mydice">
<input type="button" value="Throw dice!" onClick="throwdice()">
function throwdice(){
	//create a random integer between 0 and 5
	var randomdice=Math.round(Math.random()*5)

There really isn't anything new here; we simply used the random() method to first generate a random number between 0 and 5, attached this number to the remaining path of the "face" image, and boom- we have a dice!