0

I'm new to Web development and trying to learn things by making my own ideas to real. Now I was trying to make a quiz which contain questions from multiple subjects like mathematics, science, language etc. My quiz contains 50 questions and 10 questions from 5 different sections. I'm trying to add my questions in 5 different arrays and try to pick 10 random questions from each section. I don't know how to do that. I hope any one of you can help. I'm following a YouTube tutorial to build this.

game.html

<!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>Let's Play</title>
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="game.css">
</head>
<body>
    <div class="container">
        <div id="game" class="justify-center flex-column">
            <div id="hud">
                <div id="hud-item">
                    <p class="hud-prefix">
                        Question
                    </p>
                    <h1 class="hud-main-text" id="questionCounter">
                        
                    </h1>
                </div>

                <div id="hud-item">
                    <p class="hud-prefix">
                        Score
                    </p>
                    <h1 class="hud-main-text" id="score">
                        0
                    </h1>
                </div>
            </div>
            <h2 id="question">What is the answer to this question?</h2>
            <div class="choice-container">
                <p class="choice-prefix">A</p>
                <p class="choice-text" data-number="1">Choice 1</p>
            </div>
            <div class="choice-container">
                <p class="choice-prefix">B</p>
                <p class="choice-text" data-number="2">Choice 2</p>
            </div>
            <div class="choice-container">
                <p class="choice-prefix">C</p>
                <p class="choice-text" data-number="3">Choice 3</p>
            </div>
            <div class="choice-container">
                <p class="choice-prefix">D</p>
                <p class="choice-text" data-number="4">Choice 4</p>
            </div>
        </div>
    </div>
    <script src="game.js"></script>
</body>
</html>

game.js


const question = document.getElementById("question");
const choices = Array.from(document.getElementsByClassName("choice-text"));
const questionCounterText = document.getElementById('questionCounter');
const scoreText = document.getElementById('score');

let currentQuestion = {};
let acceptingAnswers = false;
let score = 0;
let questionCounter = 0;
let availableQuestions = [];

let questions = [
    {
        question: 'Inside which HTML element do we put the JavaScript??',
        choice1: '<script>',
        choice2: '<javascript>',
        choice3: '<js>',
        choice4: '<scripting>',
        answer: 1,
    },
    {
        question:
            "What is the correct syntax for referring to an external script called 'xxx.js'?",
        choice1: "<script href='xxx.js'>",
        choice2: "<script name='xxx.js'>",
        choice3: "<script src='xxx.js'>",
        choice4: "<script file='xxx.js'>",
        answer: 3,
    },
    {
        question: " How do you write 'Hello World' in an alert box?",
        choice1: "msgBox('Hello World');",
        choice2: "alertBox('Hello World');",
        choice3: "msg('Hello World');",
        choice4: "alert('Hello World');",
        answer: 4,
    },
];

///CONSTANTS

const CORRECT_BONUS = 1;
const MAX_QUESTIONS = 3;

startGame = () =>{
    questionCounter = 0;
    score = 0;
    availableQuestions = [...questions];
    getNewQuestion();
};

getNewQuestion = () =>{

    if(availableQuestions.length === 0 || questionCounter >= MAX_QUESTIONS){
        localStorage.setItem('mostRecentScore', score);
        //go to end page
        return window.location.assign('/end.html');
    }

    questionCounter++;
    
    questionCounterText.innerText = `${questionCounter}/${MAX_QUESTIONS}`;    
    const questionIndex = Math.floor(Math.random() * availableQuestions.length);
    currentQuestion = availableQuestions[questionIndex];
    question.innerText = currentQuestion.question;
    choices.forEach(choice => {
        const number = choice.dataset['number'];
        choice.innerText = currentQuestion['choice' + number];
    });

    availableQuestions.splice(questionIndex, 1);
    acceptingAnswers = true;
};

choices.forEach(choice =>{

    choice.addEventListener('click', e =>{
        if(!acceptingAnswers) return;
        acceptingAnswers = false;

        const selectedChoice = e.target;
        const selectedAnswer = selectedChoice.dataset['number'];


        const classToApply = 
        selectedAnswer == currentQuestion.answer ? "correct" : "incorrect";

        if(classToApply === 'correct'){
            incrementScore(CORRECT_BONUS);
        }
        
        selectedChoice.parentElement.classList.add(classToApply);

        setTimeout (() => {
            selectedChoice.parentElement.classList.remove(classToApply);
            getNewQuestion();
        }, 1000);

    });

});

incrementScore = num =>{
    score += num;
    scoreText.innerText = score;
}

startGame();

1 Answers1

0

Here's a JavaScript function that solves your problem:

// Declare 5 arrays with 20 strings in each array
let array1 = ["apple", "orange", "banana", "grape", "strawberry", "peach", "lemon", "lime", "mango", "pineapple", "watermelon", "kiwi", "blueberry", "raspberry", "blackberry", "cherry", "papaya", "pear", "coconut", "fig"];
let array2 = ["dog", "cat", "bird", "fish", "lizard", "turtle", "snake", "hamster", "rabbit", "mouse", "rat", "gerbil", "ferret", "hedgehog", "guinea pig", "chinchilla", "prairie dog", "parakeet", "finch", "canary"];
let array3 = ["car", "truck", "bus", "van", "motorcycle", "bicycle", "skateboard", "rollerblades", "scooter", "snowmobile", "golf cart", "ATV", "SUV", "boat", "jet ski", "speedboat", "sailboat", "canoe", "kayak", "paddleboard"];
let array4 = ["red", "orange", "yellow", "green", "blue", "purple", "pink", "brown", "black", "white", "gray", "gold", "silver", "bronze", "copper", "platinum", "bronze", "silver", "gold", "platinum"];
let array5 = ["pencil", "pen", "marker", "crayon", "colored pencil", "highlighter", "sharpie", "chalk", "pencil sharpener", "eraser", "paper clip", "stapler", "tape dispenser", "glue stick", "scissors", "hole punch", "ruler", "tape measure", "compass", "protractor"];

// Create a function that picks 10 random items from each array and stores them in 5 new arrays
function pickRandomItems() {
  // Create 5 new arrays
  let newArray1 = [];
  let newArray2 = [];
  let newArray3 = [];
  let newArray4 = [];
  let newArray5 = [];

  // Pick 10 random items from each array and store them in the new arrays
  for (let i = 0; i < 10; i++) {
    newArray1.push(array1[Math.floor(Math.random() * array1.length)]);
    newArray2.push(array2[Math.floor(Math.random() * array2.length)]);
    newArray3.push(array3[Math.floor(Math.random() * array3.length)]);
    newArray4.push(array4[Math.floor(Math.random() * array4.length)]);
    newArray5.push(array5[Math.floor(Math.random() * array5.length)]);
  }

  // Return the new arrays
  newArrayList = [newArray1, newArray2, newArray3, newArray4, newArray5];
  return newArrayList;
}