lundi 31 mai 2021

Generate random answers for each button in Javascript / JQuery

I have been pouring over answers on stack overflow for my problem. All of them have resulted in infinite loops which have caused my code to crash several times. Let me start by saying I am a beginner. I'd also like to iterate that for my current project I have to use Javascript/JQuery as requested. I am creating a math quiz game that generates random equations. Along with the random equations I would like to generate random answers. I have the random equations and answers generated, but for some reason I can't get my quiz app to generate unique random answers without crashing. I have tried populating the array first, then sorting the array, and splicing out duplicates and reiterating through the array. I have also tried to check for duplicates before the random number is populated in the array. None seem to work. I know there are similar questions to mine, and they work when NOT incorporated in my code. I think I'm going about it the wrong way, in which case I'd love for a second pair of eyes. Thanks!

let a, b, op, correctAnswer, ansb;

const novice = () => {
    const num = () => ~~(Math.random() * 10) + 1
    a = num()
    b = num()
    op = ["*", "+", "/", "-"][Math.floor(Math.random() * 4)];
    $("#question").text(`${a} ${op} ${b}`).show()
    correctAnswer = (() => {
        switch (op) {
            case "*": return a * b
            case "+": return a + b
            case "/": return a / b
            case "-": return a - b
        }
    })()
    if (!Number.isInteger(correctAnswer)) {
        novice()
        // equations.pop()
    }
    let randomAnswers = [correctAnswer]
    for (let x = 0; randomAnswers.length < 4; x++) {
        // ! i need to sort the array after its already pushed in there??
        let rand = Math.floor(Math.random() * correctAnswer + 20)
        // randomAnswers.push(rand)
        // console.log(randomAnswers.indexOf(x), randomAnswers.lastIndexOf(x))
        // if (randomAnswers.indexOf(rand) !== randomAnswers.indexOf(x)) {
        randomAnswers.push(rand)
        // }
    }
    let randAnsw = randomAnswers.sort(() => Math.random() - 0.5)
    $("#a0").text(randAnsw[0]).attr("value", `${randAnsw[0]}`)
    $("#a1").text(randAnsw[1]).attr("value", `${randAnsw[1]}`)
    $("#a2").text(randAnsw[2]).attr("value", `${randAnsw[2]}`)
    $("#a3").text(randAnsw[3]).attr("value", `${randAnsw[3]}`)
}

// const nextNov = () => {
//     novice()
//     selectNovAnswer()
// }
// const selectNovAnswer = () => {
//     $('#answer-buttons .btn').each(function () {
//         $(this).unbind("click").on("click", function () {
//             if ($(this).attr("value") == correctAnswer) {
//                 NextNov()
//             } else {
//                 // startOver()
//                 // $(".answ").attr("disabled", 'disabled')
//                 $("#question").append(`<span class="text-danger"> = ${correctAnswer}</span>`)

//             }
//         })
//     })
// }

$("#start").on("click", function () {
    novice()
    // selectNovAnswer()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fast Math Example</title>
    <link rel="stylesheet" href="bootstrap-4.5.3-dist/css/bootstrap.min.css">
</head>

<body>
    <button id="start" type="button">Start</button>
    <h1 id="question"></h1>
    <div id="answer-buttons">
        <button id="a0" class="btn" type="button"></button>
        <button id="a1" class="btn" type="button"></button>
        <button id="a2" class="btn" type="button"></button>
        <button id="a3" class="btn" type="button"></button>
    </div>


    <script src="jquery-3.6.0.min.js"></script>
    <script src="bootstrap-4.5.3-dist/js/bootstrap.min.js"></script>
    <script src="index.js"></script>
</body>

</html>



Aucun commentaire:

Enregistrer un commentaire