Duplo W
Duplo W

Reputation: 623

How to randomize a different number for each dice?

I'm trying to make a mini version of a yatzy game, just to learn some loops and if statements. This is how far I've gotten. Now I'm kind of stuck though because:

1) When I click the roll dices button it displays the same number on all 6 dices. How do I make it so that a different number is randomized for each dice?

2) I can only click the roll dices button once, if I want to roll it another time I have to reload the page in order to do so. Why is that?

Here is my HTML:

<!DOCTYPE html>
<html>
<head>
<title></title>

<link rel="stylesheet" type="text/css" href="mycss.css">
<script src="myjavascript2.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

</head>

<body>


<button id="button" onclick="rolldices()">Roll dices</button>

<span id="dice1">0</span>
<span id="dice2">0</span>
<span id="dice3">0</span>
<span id="dice4">0</span>
<span id="dice5">0</span>
<span id="dice6">0</span>


<br><br><br>
<div id="container">
<div id="one">1</div>           <span>0</span>
<div id="two">2</div>           <span>0</span>
<div id="three">3</div>         <span>0</span>
<div id="four">4</div>          <span>0</span>
<div id="five">5</div>          <span>0</span>
<div id="six">6</div>           <span>0</span>
<div id="total">Total</div>     <span>0</span>
</div>


</body>
</html>

Here is my javascript:

var numbers = [ '1', '2', '3', '4', '5', '6' ];

var dices = [ 'dice1', 'dice2', 'dice3', 'dice4', 'dice5', 'dice6' ];

var dice_value = Math.floor((Math.random()*numbers.length));

function rolldices() {

for (var diceindex=0; diceindex<dices.length; diceindex++) {

document.getElementById("dice" + (diceindex + 1)).innerHTML=numbers[dice_value];

}

} // end of rolldices()

I created a fiddle here: http://jsfiddle.net/h26DD/

Upvotes: 0

Views: 126

Answers (1)

Grim...
Grim...

Reputation: 16953

You need to put var dice_value = Math.floor((Math.random()*numbers.length)); inside the loop, or it will be the same all the time.

Upvotes: 2

Related Questions