1

I'm doing a little game based on question-answers with 3 options. First of all, I was trying to just randomize the position of the right answer. But, after a long time trying, I decided to just add the value after the randomization of the buttons and give the right value for the right button. But, while I'm doing it, the other 2 wrong answers have the same value. The code:

<main>
   <p>Number pi</p>
   <input type="submit" value="" id='btn1'>
   <input type="submit" value="" id='btn2'>
   <input type="submit" value="" id='btn3'>
</main>
var random = Math.floor(Math.random() * (3 - 1 + 1)) + 1;

for(var i=1;i<=3;i++) {
console.log(i);
var button = document.getElementById('btn' + i);
if(random == i) {
        button.addEventListener('click', acerto);
        button.value = '3.14';
}
else {
        button.addEventListener('click', erro);
        button.value = '2.14';
}
}

So, how can I give 2 different values for the 2 wrong buttons? Like, '3.14' is the right one and the 2 others are '2.14' or '4.14'

Hugo Folloni
  • 317
  • 1
  • 2
  • 10
  • Use an array with three values, shuffle it, assign it to the buttons in a loop. Don't use `random` to determine which one is the correct answer, but just compare the current shuffled value against the correct value to determine whether to assign `acerto` or `erro`. – Bergi May 20 '21 at 00:30
  • Ok, I'll try it. Thanks! But, I'm a very beginner. Could you help me some more? If you can't, no problem at all! – Hugo Folloni May 20 '21 at 00:33
  • I already got it. Thanks for the help anyway! – Hugo Folloni May 20 '21 at 01:06
  • 1
    @decpk gave an example implementing exactly what I had suggested :-) – Bergi May 20 '21 at 01:13

1 Answers1

2

Just create an array with answers and shuffle it. Then assign the button its value and match the text right answer with button text.

const btns = document.querySelectorAll(".btn");

function shuffle(array) {
  var currentIndex = array.length,
    temporaryValue,
    randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {
    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

const answers = [2.14, 3.14, 4.14];
shuffle(answers);

btns.forEach((btn, i) => {
  btn.textContent = answers[i];
  btn.addEventListener("click", (e) => {
    if (+e.target.textContent === 3.14) {
      alert("Equal");
    } else {
      alert("Not equal");
    }
  });
});
<main>
  <p>Number pi</p>
  <button class="btn"></button>
  <button class="btn"></button>
  <button class="btn"></button>
</main>
DecPK
  • 24,537
  • 6
  • 26
  • 42