【发布时间】:2017-07-24 23:16:59
【问题描述】:
我正在尝试创建一个包含从 3 到 18 的 6 个数字的数组变量,生成方式与我们为 D&D 第 5 版生成能力分数的方式相同。 对于不熟悉游戏的人来说,这个概念是掷出 6 个骰子,并将最高的 3 个结果相加,以获得 3 到 18 之间的能力值。
我的问题是,即使它的范围应该在 3-18 之间,它有时也会产生 0 分,而且似乎从来没有真正高于 14... 另外,如果我尝试做一个 do/while 循环直到结果高于 17,只是为了检查是否有可能,我会得到一些 24 甚至 34 的分数......所以实际上,我做错了什么?我尝试了很多东西,但仍然不起作用......如果有人能帮助我,我将非常感激!
这是我目前的代码:
function generation() {
var abilities = [0,0,0,0,0,0];
var i, k, c, n, p;
//for each ability (there is 6)
for (c = 0; c <= 5; c++){
var scores = [0,0,0,0,0,0]
var nb = [-1,-2,-3]
var diffMax = 0;
var iDiff = 0;
var diff = 0;
//roll 6 die
for (i = 0; i <= 5; i++){
scores[i] = Math.ceil(Math.random() * 6);
}
//for each die rolled
for (k = 0; k <= 5; k++){
//compare to each score slot (there is 3)
for (n = 0; n <= 2; n++){
//determine difference
diff = scores[k] - nb[n];
//if the difference is higher than the previously determined difference
if (diff >= diffMax){
//note the difference and the position
iDiff = n;
diffMax = diff;
}
}
//replace the lowest score slot by the result if this result is higher than the score slot
if (diffMax >= 0){
nb[iDiff] = scores[k];
}
}
//add up each score slot
for (p = 0; p <= 2; p++){
abilities[c] = abilities[c] + nb[p];
}
}
return abilities;
}
【问题讨论】:
-
我想说这是基本的“javascript 中的随机整数”问题,答案是“function ( min, max ) { return Math.floor ( Math.random () * ( max - min + 1 )) + min; }"
-
(你输入“3, 18”)。顺便说一句,在最初的红盒基本规则之前几年,我一直是 D&D 的粉丝 :)
-
是的,这将完成 nb1 和 nb2 之间的随机数的工作,但这种类型的生成不是线性的,获得 10 左右的数字更容易,获得 1 或18,因为它的生成方式,所以使用简单的 max/min 不会成功:/
-
啊,如果您正在寻找“非常先进的随机数生成器”,那么您的问题就显得力不从心了。或者,您可以在 1、6 之间生成三个随机数(因此使用该随机数函数 3 次)。
-
好吧,我想我描述了我在问题中生成数字的方式,即 6 个骰子,3 个最好的结果加在一起:P
标签: javascript variables for-loop random