Search code examples
javascripthtmlarraysresetdice

Reset Function for dice rolling game


I have worked for a while on this code for learning purposes. I finally got the program to work, however when you "roll the dice", it only allows the dice to be rolled 1 time; If you wish to roll the dice a second time you must refresh the screen.

I am trying to build a reset function for this program so that I can roll the dice as many times as I wish without a screen-refresh.

I have built the reset function, but It is not working... It clear's the DIV's, but doesn't allow the program to be executed again.

Can someone please help me out?

*I am a semi-noobie at Javascript, I am making programs like this to practice my skills.

HTML:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Dice Rolling</title>
  <link rel="stylesheet" href="css/styles.css">
</head>

<body>
  <header>
    <h1>Roll the Dice!</h1>
    <h2>By: Jeff Ward</h2>
  </header>
  <h3>Setup your Dice!</h3>
  <div id="left">
    <form id="numberOfDiceSelection">
      Number Of Dice Used:
      <br>
      <input id="numberOfDice" type="text" name="numberOfDice">
    </form>
  </div>
  <div id="right">
    <form id="diceSidesSelection">
      Number of sides on each dice:
      <br>
      <input id="diceSides" type="text" name="diceSides">
    </form>
  </div>
  <button type="button" onclick="roll()">Roll the Dice!</button>
  <button type="button" onclick="reset()">Reset Roll</button>


  <div id="output">

  </div>
  <div id="output1">

  </div>
  <script src="js/script.js"></script>

</body>

</html>

JavaScript:

function roll() {
  var text = "";
  var sides = +document.getElementById("diceSides").value;
  var dice = +document.getElementById("numberOfDice").value;
  var rolls = [];

  //  --------Ensures both Numbers are Intergers-----------

  if (isNaN(sides) || isNaN(dice)) {
    alert("Both arguments must be numbers.");
  }
  //  --------Loop to Print out Rolls-----------
  var counter = 1;
  do {
    roll = Math.floor(Math.random() * sides) + 1;
    text += "<h4>You rolled a " + roll + "! ----- with dice number " + counter + "</h4>";
    counter++;
    rolls.push(roll);

  }
  while (counter <= dice)
  document.getElementById("output").innerHTML = text;

  //  --------Double Determination-----------
  var cache = {};
  var results = [];
  for (var i = 0, len = rolls.length; i < len; i++) {
    if (cache[rolls[i]] === true) {
      results.push(rolls[i]);
    } else {
      cache[rolls[i]] = true;
    }
    //  --------Print amount of Doubles to Document-----------
  }
  if (results.length === 0) {} else {
    document.getElementById("output1").innerHTML = "<h5> You rolled " + results.length + " doubles</h5>";
  }
}

//  --------RESET FUNCTION-----------
function reset() {
  document.getElementById("output1").innerHTML = "";
  document.getElementById("output").innerHTML = "";
  document.getElementById("diceSides").value = "";
  document.getElementById("numberOfDice").value = "";
  text = "";
  rolls = [];
}

Thank you!!

JSFiddle Link = https://jsfiddle.net/kkc6tpxs/


Solution

  • I rewrote and did what you were trying to do:

    https://jsfiddle.net/n8oesvoo/

    var log = logger('output'),
        rollBtn = getById('roll'),
        resetBtn = getById('reset'),
        nDices = getById('numofdices'),
        nSides = getById('numofsides'),
        dices = null,
        sides = null,
        rolls = [],
        doubles=0;
    
    rollBtn.addEventListener('click',rollHandler);
    resetBtn.addEventListener('click', resetHandler);
    
    
    function rollHandler() {
        resetView();
        sides = nSides.value;
        dices = nDices.value;
        doubles=0;
        rolls=[];
    
        if(validateInput()) {
            log('invalid input');
            return;
        }
        //rolling simulation
        var rolled;
        while (dices--) {
            rolled = Math.ceil(Math.random()*sides);
            log('For Dice #'+(dices+1)+' Your Rolled: '+ rolled  +'!');
            rolls.push(rolled);
        }
    
        //finding doubles
        //first sort: you can use any way to sort doesnt matter
        rolls.sort(function(a,b){
          return (a>b?1:(a<b)?0:-1);
        });
    
        for (var i =0; i < rolls.length; i++) {
            if (rolls[i] == rolls[i+1]) {
                doubles++;
                i++;
            }
        }
        if (doubles>0) log("You rolled " + doubles + " doubles");
    
    }
    
    function resetHandler(){
        resetView();
        nDices.value = nSides.value = '';
    }
    
    
    function resetView() {
        getById('output').innerText = '';
    }
    
    
    function validateInput(){
        return (isNaN(sides) || sides == '' || isNaN(dices) || dices == '');
    }
    
    
    function logger(x) { var output = getById(x); 
        return function(text){
            output.innerText += text + '\n';
    };}
    
    function getById(x){ return document.getElementById(x); }