添加事件监听器以掷骰子javascript

时间:2017-10-25 18:24:38

标签: javascript

我目前正在为课程开发一个初学JavaScript程序。

程序应向用户显示两个输入字段。第一个输入字段将接受一个整数,该整数将确定骰子将具有多少边。第二个输入将接受一个整数,该整数将决定掷出骰子的次数。

必须将这些输入验证为仅为正数。输入输入后,用户点击输入字段,addEventListener('blur')将触发,骰子将被“抛出”。例如,应显示You rolled: 6, 2, 3, 5 for a total roll of 16

建议我们使用一个循环来执行骰子的“掷骰子”。当模糊事件发生时,循环应该根据需要执行多次,并且应该显示单个滚动加上总和。

我的问题是:

如何将骰子投入数组的次数存储输入值,然后循环遍历该数组以显示每次掷骰子的随机数,以及总投掷量?每次两个输入字段发生模糊事件时都会发生这种情况。

目前,我的程序只显示骰侧输入的随机数和投掷量的输入。我尝试过使用for或while循环来完成此任务,但没有成功。这就是我现在所拥有的。

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

5 个答案:

答案 0 :(得分:2)

要将骰子投掷到数组中的次数存储输入值,请声明Array并使用.push方法。

// 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);

要遍历数组,请使用.forEach方法或迭代值:

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

要获得投掷总数,您只需访问数组的.length属性(因为您要在数组中存储每个投掷):

var totalThrows = dieThrows.length;

答案 1 :(得分:0)

var numRolls = 6;
var numRollTotal = 0;

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

我故意留下一些空白;)看看你的代码,你很聪明,可以搞清楚。这个上不需要数组。

答案 2 :(得分:0)

您已正确识别子问题!您可以参考以下内容:

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>

答案 3 :(得分:0)

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>"
})

我希望这会有所帮助。所需位置是您希望显示结果的标记的ID。

答案 4 :(得分:0)

有一些乐趣。这应该是你所要求的:

  • 我使用“oninput”而不是“onblur”,因为在这种情况下似乎更好。但是如果优先使用“onchanged”可以使用
  • 更改了代码的格式,因此更容易阅读
  • 使用“regExp”检查逗号

// 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>