滚动多个骰子并保持最佳3

时间:2015-03-18 18:17:50

标签: javascript

我正在研制一种可以掷3个或更多骰子的骰子滚轮。

我需要做的就是这样做,无论掷多少骰子,只保留3个最好的骰子。 这是我到目前为止: (有一个下拉框让玩家选择掷骰子的数量,这就是diceMethod.selectedIndex的用途)

function roll3d6() {
  d1=Math.floor(Math.random() * 6) + 1;
  d2=Math.floor(Math.random() * 6) + 1;
  d3=Math.floor(Math.random() * 6) + 1;
  return d1 + d2 + d3;
}

function roll4d6() {
  d1=Math.floor(Math.random() * 6) + 1;
  d2=Math.floor(Math.random() * 6) + 1;
  d3=Math.floor(Math.random() * 6) + 1;
  d4=Math.floor(Math.random() * 6) + 1;
  if ((d4<=d3)&(d4<=d2)&(d4<=d1)) { return d1 + d2 + d3; }
  else if ((d3<=d4)&(d3<=d2)&(d3<=d1)) { return d1 + d2 + d4; }
  else if ((d2<=d4)&(d2<=d3)&(d2<=d1)) { return d1 + d3 + d4; }
  else { return d2 + d3 + d4; }
}

function roll5d6() {
  d1=Math.floor(Math.random() * 6) + 1;
  d2=Math.floor(Math.random() * 6) + 1;
  d3=Math.floor(Math.random() * 6) + 1;
  d4=Math.floor(Math.random() * 6) + 1;
  d5=Math.floor(Math.random() * 6) + 1;
  if () {
    // Run check here
  }
}

function RollTheDice(){
  // roll 3d6
  if (document.form1.diceMethod.selectedIndex === 0) {
    score1=roll3d6();
  }
  // roll 4d6 best 3
  if (document.form1.diceMethod.selectedIndex === 1) {
    score1=roll4d6();
  }
  // roll 5d6 best 3
  if (document.form1.diceMethod.selectedIndex === 2) {
    score1=roll5d6();        
  }
}

我的roll4d6效果很好但是如果可能的话我想缩短它,我希望有一种简化的方法来进行滚动,所以如果我在滚动中添加更多骰子我就不会# 39; t必须向骰子检查添加更多代码。

1 个答案:

答案 0 :(得分:4)

您可以使用以下通用功能:

function roll(n) {
    var a = Array(n);
    for (var i = 0; i < n; i++)
        a[i] = Math.floor(Math.random() * 6) + 1;
    a = a.sort().slice(n - 3, n);
    return a[0] + a[1] + a[2];
}

其中n是我们要抛出的骰子数。有了这个功能:

  • 我们为骰子生成所有随机数。
  • 我们对它们进行排序。
  • 我们采用最后三个元素,这些元素必须是最大的值。
  • 我们归还他们的金额。