Home > Back-end >  end game after last question has been answered
end game after last question has been answered

Time:08-25

I am building a simple quiz with JavaScript, when the game starts everything works fine timer counts down, the score and questions both receive the correct values, but when the last question is answered the game will not end until the timer hits 0. I have moved where the timer starts and the game ends when time hits zero still to no success.

please check out the deployed page for a better view of the issue.

https://brycebann.github.io/The-Coding-Quiz/

//calling in id/class from HTML 
const questionEl = document.getElementById("question")
const checkers = document.getElementById("right-wrong")
const timerEl = document.getElementsByClassName("timeSpan")
const answerOne = document.getElementById("answer1")
const answerTwo = document.getElementById("answer2")
const answerThree = document.getElementById("answer3")
const answerFour = document.getElementById("answer4")
const finalScoreEl = document.getElementById("pointScore")
const nameEl = document.getElementById("initials")
const highScoreEl = document.getElementById("highScoreList")
//const randomQuestionMix = mixedQ(); comment out to address later
//test question 
var questionKey = [

  {
    question: "which variable has the value of a string.",
    choiceOne: "x = 6",
    choiceTwo: "x = \"87\"",
    choiceThree: "x = true",
    choiceFour: "x;",
    answer: "x = \"87\""
  },

  {
    question: "choose the operator that checks for value and type.",
    choiceOne: "=",
    choiceTwo: " =",
    choiceThree: "===",
    choiceFour: "<=;",
    answer: "==="
  },

  {
    question: "choose  the true statement.",
    choiceOne: "4 != 4",
    choiceTwo: "4 > 85",
    choiceThree: "7 === \"7\"",
    choiceFour: "7.6 == \"7.6\"",
    answer: "7.6 == \"7.6\""
  },

  {
    question: "which data type is not primitive.",
    choiceOne: "boolean",
    choiceTwo: "array",
    choiceThree: "number",
    choiceFour: "string",
    answer: "array"
  },

  {
    question: "Which one is the Increment operator.",
    choiceOne: "**",
    choiceTwo: "/",
    choiceThree: "  ",
    choiceFour: " =",
    answer: "  "
  }
];

//starting positions
let timeLeft = 60;
let score = 0;
let currentQuestion = -1
let finalScore;

//change div to start the test
function changeDiv(curr, next) {
  document.getElementById(curr).classList.add('hide');
  document.getElementById(next).removeAttribute('class')
};

//button to start the game, this button will start the functions to change the on screen div and start the count down timer
document.querySelector('#startButton').addEventListener('click', gameStart);

function gameStart() {
  changeDiv('start', 'questionHolder');
  currentQuestion = 0;
  displayQuestion();
  startTimer();
};

//timer function/Count down
function startTimer() {

  let timeInterval = setInterval(
    () => {
      timeLeft--;
      document.getElementById("timeSpan").innerHTML = timeLeft
      if (timeLeft <= 0) {
        clearInterval(timeInterval);
        gameOver();
      }

    }, 1000);
};

function displayQuestion() {
  questionEl.textContent = questionKey[currentQuestion].question
  answerOne.textContent = questionKey[currentQuestion].choiceOne
  answerTwo.textContent = questionKey[currentQuestion].choiceTwo
  answerThree.textContent = questionKey[currentQuestion].choiceThree
  answerFour.textContent = questionKey[currentQuestion].choiceFour
}
//will end game when all questions are completed as well as populate the next question
document.querySelector('#questionHolder').addEventListener('click', nextquestion);

function nextquestion(event) {
  //console.log(event)
  //console.log(event.target.className)
  //console.log(event.target.textContent)

  if (event.target.className === "btn") {
    console.log(event.target.textContent, questionKey[currentQuestion].answer)
    if (event.target.textContent === questionKey[currentQuestion].answer) {
      score  = 10
      console.log("correct")
      console.log(score)
    } else {
      if (timeLeft >= 10) {
        console.log(timeLeft)
        timeLeft = timeLeft - 10;
        document.getElementById("timeSpan").innerHTML = timeLeft
        console.log("not correct")
      } else {
        timeLeft = 0;
        gameOver();
      }
    }
    currentQuestion  ;
    displayQuestion();
  }

};

//the game is over and logs your  current score
function gameOver() {
  timerEl.textContent = 0;
  changeDiv('questionHolder', 'finishedPage');
  finalScore = score;
  finalScoreEl.textContent = finalScore;
};
<!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>The coding quiz</title>
  <link rel="stylesheet" a href="./Main/style.css">

</head>

<body>


  <!--Top of page-->
  <header>
    <div id="pageTop">
      <h1>The coding quiz</h1>
    </div>
  </header>

  <!--High score and timer div -->
  <div id="scoreTime">
    <p ><a href="./highscore/index.html">View highscores</a></p>
    <p >Time left: <span id="timeSpan">60</span></p>
  </div>

  <!--Main quiz portion of the page-->
  <div id="quizHolder">
    <div id="start">
      <h2>Basic Code Quiz</h2>
      <p>Welcome to the basic coding quiz, this quiz will test you knoweledge on basic javascript.</p>
      <button id="startButton" >Start</button>
    </div>
    <div id="questionHolder" >
      <h2 id="question"></h2>
      <button id="answer1" ></button>
      <button id="answer2" ></button>
      <button id="answer3" ></button>
      <button id="answer4" ></button>
    </div>
    <!--Results and high score-->
    <div id="finishedPage" >
      <h2>Quiz Complete</h2>
      <p>Your final score is <span id="pointScore"></span>/50</p>
      <label>Enter your initials:</label>
      <input type="text" id="initials">
      <button id="sendScore" >Submit score</button>
    </div>
  </div>
  <script src="Main/script.js"></script>
</body>

</html>

CodePudding user response:

After you increment the "current question" counter, here currentQuestion ; check if the counter reached the length of your questions array questionKey:

// IF THERE ARE NO MORE QUESTIONS, CALL gameOver
if (currentQuestion == questionKey.length) {
  gameOver();
} else {
  displayQuestion();
}

//calling in id/class from HTML 
const questionEl = document.getElementById("question")
const checkers = document.getElementById("right-wrong")
const timerEl = document.getElementsByClassName("timeSpan")
const answerOne = document.getElementById("answer1")
const answerTwo = document.getElementById("answer2")
const answerThree = document.getElementById("answer3")
const answerFour = document.getElementById("answer4")
const finalScoreEl = document.getElementById("pointScore")
const nameEl = document.getElementById("initials")
const highScoreEl = document.getElementById("highScoreList")
//const randomQuestionMix = mixedQ(); comment out to address later
//test question 
var questionKey = [

  {
    question: "which variable has the value of a string.",
    choiceOne: "x = 6",
    choiceTwo: "x = \"87\"",
    choiceThree: "x = true",
    choiceFour: "x;",
    answer: "x = \"87\""
  },

  {
    question: "choose the operator that checks for value and type.",
    choiceOne: "=",
    choiceTwo: " =",
    choiceThree: "===",
    choiceFour: "<=;",
    answer: "==="
  },

  {
    question: "choose  the true statment.",
    choiceOne: "4 != 4",
    choiceTwo: "4 > 85",
    choiceThree: "7 === \"7\"",
    choiceFour: "7.6 == \"7.6\"",
    answer: "7.6 == \"7.6\""
  },

  {
    question: "which data type is not primitive.",
    choiceOne: "boolean",
    choiceTwo: "array",
    choiceThree: "number",
    choiceFour: "string",
    answer: "array"
  },

  {
    question: "Wich one is the Increment operator.",
    choiceOne: "**",
    choiceTwo: "/",
    choiceThree: "  ",
    choiceFour: " =",
    answer: "  "
  }
];

//starting postions
let timeLeft = 60;
let score = 0;
let currentQuestion = -1
let finalScore;
let timeInterval;

//change div to start the test
function changeDiv(curr, next) {
  document.getElementById(curr).classList.add('hide');
  document.getElementById(next).removeAttribute('class')
};

//button to start the game, this button will start the functions to cnage the on screen div and start the count down timer
document.querySelector('#startButton').addEventListener('click', gameStart);

function gameStart() {
  changeDiv('start', 'questionHolder');
  currentQuestion = 0;
  displayQuestion();
  startTimer();
};

//timer function/Count down
function startTimer() {

  timeInterval = setInterval(
    () => {
      timeLeft--;
      document.getElementById("timeSpan").innerHTML = timeLeft
      if (timeLeft <= 0) {
        clearInterval(timeInterval);
        gameOver();
      }

    }, 1000);
};

function displayQuestion() {
  questionEl.textContent = questionKey[currentQuestion].question
  answerOne.textContent = questionKey[currentQuestion].choiceOne
  answerTwo.textContent = questionKey[currentQuestion].choiceTwo
  answerThree.textContent = questionKey[currentQuestion].choiceThree
  answerFour.textContent = questionKey[currentQuestion].choiceFour
}
//will end game when all questions are completed as well as populate the next question
document.querySelector('#questionHolder').addEventListener('click', nextquestion);

function nextquestion(event) {
  //console.log(event)
  //console.log(event.target.className)
  //console.log(event.target.textContent)

  if (event.target.className === "btn") {
    console.log(event.target.textContent, questionKey[currentQuestion].answer)
    if (event.target.textContent === questionKey[currentQuestion].answer) {
      score  = 10
      console.log("correct")
      console.log(score)
    } else {
      if (timeLeft >= 10) {
        console.log(timeLeft)
        timeLeft = timeLeft - 10;
        document.getElementById("timeSpan").innerHTML = timeLeft
        console.log("not correct")
      } else {
        timeLeft = 0;
        gameOver();
      }
    }
    currentQuestion  ;
    
    // IF THERE ARE NO MORE QUESTIONS, CALL gameOver
    if (currentQuestion == questionKey.length) {
      clearInterval(timeInterval);
      gameOver();
    } else {
      displayQuestion();
    }
  }

};

//the game is over and logs your  current score
function gameOver() {
  timerEl.textContent = 0;
  changeDiv('questionHolder', 'finishedPage');
  finalScore = score;
  finalScoreEl.textContent = finalScore;
};
<!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>The coding quiz</title>
  <link rel="stylesheet" a href="./Main/style.css">

</head>

<body>


  <!--Top of page-->
  <header>
    <div id="pageTop">
      <h1>The coding quiz</h1>
    </div>
  </header>

  <!--High score and timer div -->
  <div id="scoreTime">
    <p ><a href="./highscore/index.html">View highscores</a></p>
    <p >Time left: <span id="timeSpan">60</span></p>
  </div>

  <!--Main quiz portion of the page-->
  <div id="quizHolder">
    <div id="start">
      <h2>Basic Code Quiz</h2>
      <p>Welcome to the basic coding quiz, this quiz will test you knoweledge on basic javascript.</p>
      <button id="startButton" >Start</button>
    </div>
    <div id="questionHolder" >
      <h2 id="question"></h2>
      <button id="answer1" ></button>
      <button id="answer2" ></button>
      <button id="answer3" ></button>
      <button id="answer4" ></button>
    </div>
    <!--Results and high score-->
    <div id="finishedPage" >
      <h2>Quiz Complete</h2>
      <p>Your final score is <span id="pointScore"></span>/50</p>
      <label>Enter your initials:</label>
      <input type="text" id="initials">
      <button id="sendScore" >Submit score</button>
    </div>
  </div>
  <script src="Main/script.js"></script>
</body>

</html>

  • Related