简体   繁体   中英

adding an event listener to roll dice javascript

I am currently working on a beginner JavaScript program for class.

The program should display two input fields to the user. The first input field will accept an integer that will determine how many sides the die will have. The second input will accept an integer that will determine the amount of times the die is thrown.

These inputs must be validated to only be positive numbers. When the inputs have been entered, and the user clicks out of the input fields, an addEventListener('blur') will fire and the die will be "thrown". This should display, for example, You rolled: 6, 2, 3, 5 for a total roll of 16 .

It was advised that we use a loop that will perform the "roll" of the dice. The loop should be performed as many times as necessary when the blur event occurs and should display the individual roll plus the sum.

My question is:

How would I go about storing the input values from the number of times the die is thrown into an array, then loop through that array to display the random numbers for each die throw, as well as the total throw? This will happen every time the blur event occurs for the two input fields.

At the moment, my program only displays a random number from the die side input and the input for throw amount. I have tried using a for or while loop for this task, but no success. This is what I currently have.

 function dieInfo() { // temporary label to display # of sides var dieSideNum = document.getElementById('die-side-num'); // convert string input into floating integer, // if this doesnt create a number use 0 instead var getDieSide = parseFloat(dieSideQuant.value) || 0; // temporary label to display throw total var throwTotal = document.getElementById('throw-total'); //convert string input into floating integer // if this doesnt create a number use 0 instead var getThrowTotal = parseFloat(throwQuant.value) || 0; // if die sides input or throw amount input is <= 0 if (getDieSide <= 0 || getThrowTotal <= 0) { // display error for improper number of sides for die input dieSideNum.textContent = "Please enter valid Die sides"; // display error for improper throw amount input throwTotal.textContent = "Please enter valid throw amount"; } else { // use random function to store random number from die sides input throwRand = Math.floor(Math.random() * (1 + (getDieSide) - 1)) + 1; // test- display random number of sides for die dieSideNum.textContent = "Number of Sides on Die: " + throwRand; // test - display throw count throwTotal.textContent = " You threw " + getThrowTotal + "times"; } } // retrieve id for for amount of sides on die var dieSideQuant = document.getElementById('die-side-quant'); // fire the dieInfo function when the input element loses focus dieSideQuant.addEventListener('blur', dieInfo); // retrieve id for throw amount input var throwQuant = document.getElementById('throw-quant'); // fire the dieInfo function when the input element loses focus throwQuant.addEventListener('blur', dieInfo); 
 <h1 id="info-die"> How many sides on die? </h1> <input type="number" min="0" id="die-side-quant" placeholder="# sides on die"> <h3 id="die-side-num"></h3> <h1 id="info-throw-die"> Throw Amount? </h1> <input type="number" min="0" id="throw-quant" placeholder="throw amount"> <h3 id="throw-total"></h3> 

a reference picture of what I currently have

To store the input values from the number of times the die is thrown into an array, declare an Array and use the .push method.

// declare an Array variable
var dieThrows = [];

// use .push to store the value in the Array.
dieThrows.push(throwRand);

// or don't bother with the extra throwRand variable by doing it this way
dieThrows.push(Math.floor(Math.random() * (1 + (getDieSide) - 1)) + 1);

To loop through the array, use the .forEach method or just iterate over the values:

// doing it ES5-style:
dieThrows.forEach(function (throwResult, index, array) {
    console.log(throwResult); // display the random numbers for each die throw in the dev tools console
});

// doing it ES6-style:
dieThrows.forEach( (throwResult, index, array) => (console.log(throwResult)) );

// doing it old-school:
for (var i = 0; i < dieThrows.length; i += 1) {
    console.log(throwResult); // display the random numbers for each die throw in the dev tools console
}

To get the total number of throws, you can just access the .length property of the Array (because you're storing each throw in the Array):

var totalThrows = dieThrows.length;
var numRolls = 6;
var numRollTotal = 0;

for(var i = 0; i < numRolls; i++) //Here happens the for magic.
{
    //Write and store
}
//Write again

I left some blanks on purpose ;) Looking at your code you're smart enough to figure it out. No need for arrays on this one.

You've identified the subproblems correctly! You can refer to the following:

 window.onload = function() { document.getElementById('numThrows') .addEventListener('blur', function() { var numSides = parseInt(document.getElementById('numSides').value); var numThrows = parseInt(document.getElementById('numThrows').value); var randArr = []; for (var i = 0; i < numThrows; i++) // On each repetition, store a result into `randArr` randArr.push(1 + Math.floor(Math.random() * numSides)); // Now display the results var results = document.getElementById('results'); results.innerHTML = randArr.map(function(randNum, throwNum) { // Generate HTML markup for each result return '<div class="result">' + 'Throw #' + (throwNum + 1) + '; ' + 'result: ' + randNum + '</div>'; }).join(''); }); }; 
 <div>Note this example has no validation</div> <input id="numSides" placeholder="sides" type="text"/> <input id="numThrows" placeholder="throws" type="text"/> <div id="results"> </div> 

document.getElementById('throw-quant')
  .addEventListener('blur', function(){
  var numSides = parseInt(document.getElementId('die-side-quant').value);
  var numThrows = parseInt(document.getElementId('throw-quant').value);

  var outputString="You rolled:";
  var total=0;
  for(var i=0; i<numThrows; i++){
    var n = Math.floor(Math.random() * (1 + (getDieSide) - 1)) + 1;
    total+=n;
    outputString+=" "+String(n);         
  }
  outputString+=" for a total roll of "+String(total);

  document.getElementById("desired location").innerHTML = "<p>"+outputString+"</p>"
})

I hope this helps. desired location is the ID of the tag that you want your result to be displayed.

Had some fun. This should do exactly what you ask about:

  • I used "oninput" instead of "onblur", because it seems better in this situation. But "onchanged" can be used if preferred
  • Changed the formatting of your code, so it is easier to read
  • Uses "regExp" to check for comma

 // Global variables // var id_dieSideQuant = document.getElementById('id_dieSideQuant'), // retrieve id for for amount of sides on die id_throwQuant = document.getElementById('id_throwQuant'); // retrieve id for throw amount input var id_throwTotal = document.getElementById('id_throwTotal'), // local varible to function only for displaying the throw total id_dieSideNum = document.getElementById('id_dieSideNum'); // local varible to function only for displaying number of sides // Functions // function dieInfo() { // Hide and clear up the text-fields // id_dieSideNum.parentElement.classList.remove("container1"); document.getElementById('id_throwTotal').innerHTML = ""; document.getElementById('id_dieSideNum').innerHTML = ""; // // Local variables /* convert string input into floating integer, if this doesnt create a number use 0 instead */ var getDieSide = parseFloat(id_dieSideQuant.value) || 0, getTotalThrows = parseFloat(id_throwQuant.value) || 0, randThrow, allDieThrows = []; // // Errors if (getDieSide < 2 && id_dieSideQuant.value.length !== 0) { // if die sides input < 2 id_dieSideNum.innerHTML = "<span style='color: red'>Please enter a valid total of die sides; min. 2.</span>"; // display error for improper number of sides for die input } if (getTotalThrows < 1 && id_throwQuant.value.length !== 0) { // if die throw amount input is < 1 id_throwTotal.innerHTML = "<span style='color: red'>Please enter a valid throw amount.</span>"; // display error for improper throw amount input } if (getDieSide < 2 || getTotalThrows < 1 || (new RegExp(/\\d+(?!\\.)/).exec(getDieSide.toString())["index"] !== 0 || new RegExp(/\\d+(?!\\.)/).exec(getTotalThrows.toString())["index"] !== 0)) return false; // Exit if there is something wrong. "/\\d+(?!\\.)/" checks that there is no comma // // if (id_dieSideQuant.value.length !== 0 && id_throwQuant.value.length !== 0) { // Throw the die // for (var i = 0; i < getTotalThrows; i++) { // throw the dice the total amount of throws using a standard for-loop randThrow = Math.floor(Math.random() * getDieSide) + 1; // use random function to store random number from die sides input allDieThrows.push(randThrow); } // Display result // id_throwTotal.innerHTML = `Total throws: ${getTotalThrows}`; // test- display random number of sides for die id_dieSideNum.innerHTML = "Your die landed on:<br><br>"; // test - display throw count for (var i = 0; i < allDieThrows.length; i++) { id_dieSideNum.innerHTML += "Throw #" + (i + 1) + ": " + allDieThrows[i] + "<br>"; } id_dieSideNum.parentElement.classList.add("container1"); } } // Event Listeners // id_dieSideQuant.addEventListener('input', dieInfo); // fire the 'dieInfo' function when the input element is changed (use: 'input' || 'change') id_throwQuant.addEventListener('input', dieInfo); // fire the 'dieInfo' function when the input element is changed (use: 'input' || 'change') id_button0.addEventListener('click', dieInfo); // fire the 'dieInfo' function when the input element is changed 
 body { color: olivedrab; font-family: sans-serif; background-color: #222; } .container0 { padding: 10px; border: 1px solid orange; border-radius: 10px; margin-left: 20px; } .container1 { padding: 5px; border: 2px solid orangered; border-radius: 5px; margin-left: 20px; margin-top: 10px; } 
 <h1>Die-roller</h1> <div class="container0"> <h2 id="id_infoThrowDie">Throw Amount? <button id="id_button0">Update throw</button></h2> <input id="id_throwQuant" type="number" min="1" step="1" placeholder="Throw amount"> (min. 1 throw) <h3 id="id_throwTotal"></h3> <h2 id="id_infoDie">How many sides on die?</h2> <input id="id_dieSideQuant" type="number" min="2" step="1" placeholder="Sides on die"> (min. 2 sides) <div> <h3 id="id_dieSideNum"></h3> </div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM