Jump to content

Random generator


rahagnok

Recommended Posts

Hey everybody, I'm really new to javascript and I'm trying to make a simple game. I am having trouble with writing a random generator that will randomly generate a different die face each time the user clicks. I plan on showing five different die and each one needs to be able to generate a random image. Any help is greatly appreciated, thank you.

Link to comment
Share on other sites

Math.floor(Math.random()*5) + 1

That will generate a random number between 1 and 6.

Link to comment
Share on other sites

Oh cool, thanks. What could I use to generate random images to represent the actual faces of the dice. Like if I had 7 different images, how could I make it so when the person clicks "roll", five seperate die faces are generated. Again thanks for all the help! :)

Link to comment
Share on other sites

You can't "generate" images through JavaScript, but if you had six images (one for each face) then you could do something like this:

<script type="text/javascript">	function roll() {		diebox = document.getElementById("diebox");		for (i = 1; i <=5; i++) {			//The dice are called die_1.gif, die_2.gif, die_3.gif, etc			roll = Math.floor(Math.random()*5) + 1;			diebox.innerHTML += "<img src=\"die_" + roll + ".gif\" alt=\"" + roll + "\" /> ";		}	}</script><div id="diebox">	<!-- This division will contain the dice images --></div><input type="button" value="roll" onclick="roll()" />

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...