2016-03-08 55 views
-2

我的工作增加了對骰子爲n輥的隨機輥一起由用戶所定義的。下面是代碼:Java腳本:添加兩個骰子的隨機輥爲「n」個輥

<!DOCTYPE html> 
<html> 
    <head> 
     <link rel="stylesheet" type="text/css" href="dice.css"> 
     <script> 
//supposed to give 2 random numbers 
function roll() { 
    var x = Math.floor(Math.random() * ((6 - 1) + 1) + 1); 
    var y = Math.floor(Math.random() * ((6 - 1) + 1) + 1); 
    var Total = x + y; 
} 

// ask for user to put how many times they want to roll the two dice 
function myinput() { 
    var NumRoll = prompt("Please enter the number of times you wish to roll"); 

    if (NumRoll <= 0) 
     document.getElementById("wrong").innerHTML = "You entered an invalid number enter number between 1-100"; 
    else if (NumRoll >100) 
     document.getElementById("wrong").innerHTML = "You enter an invalid number enter number between 1-100"; 
    else 
     document.getElementById("right").innerHTML = "Rolling the dice " + NumRoll + " times"; 
} 
     </script> 
    </head> 
    <body> 
     <p id="wrong"> </p> 
     <p1 id="right"></p1> 
     <p>Click to roll dice</p> 

     <button onclick="myinput(); roll()">Press</button> 
    </body> 
</html> 
+0

的的jsfiddle因此用戶要求擲骰子23次,骰子將推出23倍addingall的它捲起來的數字我不surehow連接兩個 – Michele

回答

0

function roll(repeat) { 
 
\t var repeat = repeat || 1; 
 
\t var Total = 0; 
 
    for(var i = 0; i < repeat; i++){ 
 
\t \t var x = Math.floor(Math.random() * ((6 - 1) + 1) + 1); 
 
\t \t var y = Math.floor(Math.random() * ((6 - 1) + 1) + 1); 
 
    Total += x + y; 
 
\t } 
 
    document.getElementById('total').innerHTML = Total; 
 
} 
 

 
document.getElementById('rollTrigger').addEventListener('click',function(){ 
 
\t roll(document.getElementById('numRoll').value); 
 
});
<input id="numRoll" type="text" placeholder="Number of time to roll the dice"> 
 
<br><a href="#" id="rollTrigger">Roll the dice!</a> 
 
<br> 
 
<span id="total"></span>

添加參數傳遞給您的卷()函數和包裝你的VAR的x,y爲一個循環。然後輸入的值傳遞給側傾功能:)

詳情參見

https://jsfiddle.net/bzdgz6ac/