我正在努力为用户定义的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 :(得分:0)
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