JS Dice Roller - 我如何计算所有骰子的总和?

JS Dice Roller - How can I total all dice?

问题

好久没编程了。我正在设计一款游戏,并首先在 JS/HTML/CSS 中对其进行编程,因为这是我所熟悉的。这是我正在建造的骰子滚筒。到目前为止它正确地掷骰子,但我似乎无法在掷骰子时抓住所有骰子。我假设 total 的变量定义不正确或超出范围。

HTML

<body>
  <div id="dice" class="dice">
  </div>
  <div id="diceTotal"></div>
  <button id="button">Roll Die</button>
</body>

CSS

* {
  font-family: Helvetica, Arial, sans-serif;
  text-align: center;
  font-size: 8 vw;
}

button {
  background-color: #000;
  border-radius: 1vw;
  border: none;
  color: #fff;
  padding: 1vw;
  text-transform: uppercase;
  font-size: 6vw;
  width: 40vw;
  cursor: pointer;
  margin-top: .5vw;
}

.die {
  height: 10vw;
  width: 10vw;
  padding: 0vw;
  margin: .5vw;
  border: .1vw solid gray;
  border-radius: 2vw;
  font-size: 9vw;
  display: inline-block;
}

JS

var tot;
do {
  var sides = parseInt(prompt("How many sides are on your die? ", "6"), 10);
} while (isNaN(sides) || sides < 1);
var dice = {
  sides: sides,
  roll: function() {
    var randomNumber = Math.floor(Math.random() * this.sides) + 1;
    return randomNumber;
  }
}

//Prints dice roll to the page

function printNumber(number) {
  var span = document.createElement("span");
  span.className = "die";
  var diceroll = document.createTextNode(number);
  span.appendChild(diceroll);
  document.getElementById('dice').appendChild(span);
}

var button = document.getElementById('button');

button.onclick = function() {
  var result = dice.roll();
  printNumber(result);
  var tot = result + tot;
  var printDiceTotal = "Total: " + tot;
  document.getElementById('diceTotal').innerHTML = printDiceTotal;
};

这是 JSFiddle。

https://jsfiddle.net/itmadsen/pkgej3uh/2/

我知道我遗漏了一些基本的东西,在有人想出解决方案后我会努力克服它。

首先,您需要将零作为初始值分配给tot

var tot = 0;

其次,你定义了两次 tot

var tot = result + tot;

应该变成

tot = result + tot;

这是工作 fiddle:https://jsfiddle.net/entio/pkgej3uh/5/

谢谢!

我修好了。完美!

https://jsfiddle.net/itmadsen/pkgej3uh/7/

JS

var tot = 0;
do {
  var sides = parseInt(prompt("How many sides are on your die? ", "6"), 10);
} while (isNaN(sides) || sides < 1);
var dice = {
  sides: sides,
  roll: function() {
    var randomNumber = Math.floor(Math.random() * this.sides) + 1;
    return randomNumber;
  }
}

//Prints dice roll to the page

function printNumber(number) {
  var span = document.createElement("span");
  span.className = "die";
  var diceroll = document.createTextNode(number);
  span.appendChild(diceroll);
  document.getElementById('dice').appendChild(span);
}

var button = document.getElementById('button');

button.onclick = function() {
  var result = dice.roll();
  printNumber(result);
  tot = result + tot;
  var printDiceTotal = "Total: " + tot;
  document.getElementById('diceTotal').innerHTML = printDiceTotal;
};