【问题标题】:Java Script: Add the random rolls of two dice for "n" rollsJava Script:为“n”个掷骰添加两个骰子的随机掷骰
【发布时间】:2016-03-08 23:59:37
【问题描述】:

我正在努力将一对骰子的随机掷骰相加,以根据用户定义的 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>

【问题讨论】:

  • 所以用户要求掷骰子 23 次,骰子将掷 23 次,将所有掷出的数字加在一起我不知道如何将两者联系起来

标签: javascript random


【解决方案1】:

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>

为你的 roll() 函数添加一个参数,并将你的 var x, y 包装到一个 for 循环中。然后将输入的值传递给roll函数:)

查看 jsfiddle 了解更多详情

https://jsfiddle.net/bzdgz6ac/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-08
    • 2013-10-30
    • 1970-01-01
    • 2015-05-10
    • 2012-02-29
    • 2014-10-07
    • 1970-01-01
    相关资源
    最近更新 更多