简体   繁体   English

Java Script:为“n”卷添加两个骰子的随机卷

[英]Java Script: Add the random rolls of two dice for "n" rolls

I am working on adding together the random rolls of a pair of dice for n rolls as defined by user.我正在将一对骰子的随机卷加在一起,用于用户定义的n卷。 Here is the code:这是代码:

<!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>

 function roll(repeat) { var repeat = repeat || 1; var Total = 0; for(var i = 0; i < repeat; i++){ var x = Math.floor(Math.random() * ((6 - 1) + 1) + 1); var y = Math.floor(Math.random() * ((6 - 1) + 1) + 1); Total += x + y; } document.getElementById('total').innerHTML = Total; } document.getElementById('rollTrigger').addEventListener('click',function(){ 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>

Add an argument to your roll() function and wrap your var x, y into a for loop.向 roll() 函数添加一个参数并将 var x, y 包装到 for 循环中。 Then pass the value of the input to the roll function :)然后将输入的值传递给 roll 函数:)

See the jsfiddle for more details有关更多详细信息,请参阅 jsfiddle

https://jsfiddle.net/bzdgz6ac/ https://jsfiddle.net/bzdgz6ac/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM