Categories:
Partners
Web Hosting
We've partnered with HostGator for reliable, affordable hosting starting at $3.95/mon. Use coupon code "javascriptkit25" for 25% off any package.

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:

<html>
<head>
<script type="text/javascript">
//preload the six images first
var face0=new Image()
face0.src="d1.gif"
var face1=new Image()
face1.src="d2.gif"
var face2=new Image()
face2.src="d3.gif"
var face3=new Image()
face3.src="d4.gif"
var face4=new Image()
face4.src="d5.gif"
var face5=new Image()
face5.src="d6.gif"
</script>
</head>
<body>
<img src="d1.gif" name="mydice">
<form>
<input type="button" value="Throw dice!" onClick="throwdice()">
</form>
<script>
function throwdice(){
//create a random integer between 0 and 5
var randomdice=Math.round(Math.random()*5)
document.images["mydice"].src=eval("face"+randomdice+".src")
}
</script>
</body>
</html>

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!

Copyright 1997-2014 JavaScript Kit. NO PART may be reproduced without author's permission.