掷多个骰子,保持最好的3个

Roll Multiple Dice and keep the best 3

本文关键字:3个      更新时间:2023-09-26

我正在开发一个骰子滚筒,它可以滚动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工作得很好,但如果可能的话,我想把它缩短,我希望有一种简化的方法来进行掷骰子,所以如果我在掷骰子中添加更多的骰子,我就不必在骰子检查中添加更多代码。

您可以使用以下通用函数:

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是我们想要投掷的骰子的数量。具有此功能:

  • 我们为骰子生成所有随机数
  • 我们对它们进行分类
  • 我们考虑最后三个要素,它们必须是最大的价值
  • 我们退还他们的款项