Search code examples
javascriptjquerydice

JS Dice Roller - How can I total all dice?


The Problem

It's been a long time since I programmed. I'm designing a game, and first programming it in JS/HTML/CSS since that is what I'm familiar with. Here is a dice roller I'm building. It rolls dice properly so far, but I can't seem to grab a total of dice as they are rolled. I'm assuming the variable for total is improperly defined, or out of scope.

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;
};

Here is the JSFiddle.

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

I know I'm missing something basic, and I'll be kicking myself over it after someone comes up with a solution.


Solution

  • Firstly, you need to assign zero as initial value to tot

    var tot = 0;
    

    Secondly, you're defining tot twice

    var tot = result + tot;
    

    should become

    tot = result + tot;
    

    Here's working fiddle: https://jsfiddle.net/entio/pkgej3uh/5/