我正在研究掷骰子程序。
到目前为止,一切都奏效了,直到我明白了
到目前为止的代码:
function randomNum(max) {
return Math.floor(Math.random() * (max - 1 + 1)) + 1;
}
var names = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty'];
function rollDice(number, sides) {
return("Rolled "+ names[number] +" "+ names[sides] +" sided dice");
}
function randomDice(number, sides) {
function repeat(number) {
randomNum(sides);
if(sides > 20) sides==20;
}}
问题在于:
function randomDice(number, sides) {
function repeat(number) {
randomNum(sides);
if(sides > 20) sides==20;
}}
我要说的是这样的话
randomDice(2, 20)
应该掷出2个20面骰子,但是如果我希望它能滚动多次,我将无法使randomNum函数重复两次。
编辑:问题已经得到解决,谢谢大家的帮助:)
答案 0 :(得分:1)
尝试for循环
for (i=0; i<2; i++){
repeat(20);
}
//move this function out of the randomDice function
function repeat(number) {
randomNum(sides);
if(sides > 20) sides==20;
}
答案 1 :(得分:0)
只需将您的function repeat(number)
声明更改为for循环:for( var n = 0; n < number; n++)
。这将获得您想要的重复:
function randomNum(max) {
return Math.floor(Math.random() * max) + 1; // No reason to do max+1-1
}
var names = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty'];
function rollDice(number, sides) {
return "Rolled " + names[number] + " " + names[sides] + " sided dice";
}
function randomDice(number, sides) {
var results = [] // Create array to store results
if (sides > 20) // Limit sides, but only needs to be done once (outside loop)
sides == 20;
for (var n = 0; n < number; n++) {
var name = names[randomNum(sides)]; // Translate the number to a word
results.push(name); // Add the word to the array
}
console.log(rollDice(number, sides)); // Display the context
return results; // Return the results as an array
}
console.log(randomDice(2, 20).join(', ')); // Display the values chosen as comma-separated values
我添加了一些其他内容,假设这是您要查找的实现类型。请根据需要进行调整。
答案 2 :(得分:-6)
您要使用setInterval
方法:MDN Documentation