1

I'm working on a game for my kids and I may end up posting this game online at a later date if it's fully functional. But I'm working on a math deal. Basically it generates 2 random numbers 0-4 and they have to subtract and choose the correct answer. How do I go about making sure the first number is always bigger?

Here's my HTML:

<header>
    <div class="container">
        <h1>Math 4 KIDS</h1>
        <ul>
            <li class=""><a href="add.html">Add +</a></li>
            <li class="current"><a href="subtract.html">Subtract -</a></li>
        </ul>
    </div>
</header>
<div class="wrapper">
    <div class="equation">
        <h1 id="num1">1</h1>
        <h1 style="color: #2ab7ca;">-</h1>
        <h1 id="num2">1</h1>
        <h1 style="color: #fe4a49;">=</h1>
        <h1 style="color: gray;">?</h1>
    </div>
    <div class="answer-options">
        <h1 id="option1">1</h1>
        <h1 id="option2">2</h1>
        <h1 id="option3">3</h1>
    </div>
</div>

And my JS:

const option1 = document.getElementById('option1');
const option2 = document.getElementById('option2');
const option3 = document.getElementById('option3');
const audio = document.getElementById('myAudio');
var answer = 0;

function generate_equation() {
    var num1 = Math.floor(Math.random() * 5);
    var num2 = Math.floor(Math.random() * 5);
    var dummyAnswer1 = Math.floor(Math.random() * 6);
    var dummyAnswer2 = Math.floor(Math.random() * 6);
    var allAnswers = [];
    var switchAnswers = [];

    answer = num1 - num2;


    document.getElementById('num1').innerHTML = num1;
    document.getElementById('num2').innerHTML = num2;

    allAnswers = [answer, dummyAnswer1, dummyAnswer2]

    for(i = allAnswers.length; i--;) {

switchAnswers.push(allAnswers.splice(Math.floor(Math.random() * (i + 1)), 1)[0]);
}

option1.innerHTML = switchAnswers[0];
option2.innerHTML = switchAnswers[1];
option3.innerHTML = switchAnswers[2];
}

option1.addEventListener("click", function() {
    if(option1.innerHTML == answer) {
    generate_equation();
    } else {
    audio.play();
    }
});

option2.addEventListener("click", function() {
    if(option2.innerHTML == answer) {
        generate_equation();
    } else {
        audio.play();
    }
});

option3.addEventListener("click", function() {
    if(option3.innerHTML == answer) {
        generate_equation();
    } else {
        audio.play();
    }
});

generate_equation()
  • 3
    Switch them around when the second one is bigger (hint: if statement and a temporary variable). – kelsny Sep 11 '22 at 03:01

1 Answers1

0

Use a conditional statement to check whether num1 is smaller than num2, if yes, switch them around

So insert the following

if (num1 < num2){
  var tnum=num1;
  num1=num2;
  num2=tnum;
}

after the line

    var num2 = Math.floor(Math.random() * 5);
Ken Lee
  • 6,985
  • 3
  • 10
  • 29