Skip to content

Instantly share code, notes, and snippets.

@twhite96 twhite96/app.js
Created Apr 30, 2016

Embed
What would you like to do?
Quiz app
//Create Questions
var questions = [
new Question("Who was the first President of the United States?", [ "George Washington", "Thomas Jefferson" ], "George Washington"),
new Question("What is the answer to the Ultimate Question of Life, the Universe, and Everything?", ["Pi","42"], "42")
];
//Create Quiz
var quiz = new Quiz(questions);
//Display Quiz
QuizUI.displayNext();
function Question(text, choices, answer) {
this.text = text;
this.choices = choices;
this.answer = answer;
}
Question.prototype.isCorrectAnswer = function (choice) {
return this.answer === choice;
};
function Quiz(questions) {
this.score = 0;
this.questions = questions;
this.currentQuestionIndex = 0;
}
Quiz.prototype.guess = function(answer) {
if(this.getCurrentQuestion().isCorrectAnswer(answer)) {
this.score++;
}
this.currentQuestionIndex++;
};
Quiz.prototype.getCurrentQuestion = function() {
return this.questions[this.currentQuestionIndex];
};
Quiz.prototype.hasEnded = function() {
return this.currentQuestionIndex >= this.questions.length;
};
ar QuizUI = {
displayNext: function () {
if (quiz.hasEnded()) {
this.displayScore();
} else {
this.displayQuestion();
this.displayChoices();
this.displayProgress();
}
},
displayQuestion: function() {
this.populateIdWithHTML("question", quiz.getCurrentQuestion().text);
},
displayChoices: function() {
var choices = quiz.getCurrentQuestion().choices;
for(var i = 0; i < choices.length; i++) {
this.populateIdWithHTML("choice" + i, choices[i]);
this.guessHandler("guess" + i, choices[i]);
}
},
displayScore: function() {
var gameOverHTML = "<h1>Game Over</h1>";
gameOverHTML += "<h2> Your score is: " + quiz.score + "</h2>";
this.populateIdWithHTML("quiz", gameOverHTML);
},
populateIdWithHTML: function(id, text) {
var element = document.getElementById(id);
element.innerHTML = text;
},
guessHandler: function(id, guess) {
var button = document.getElementById(id);
button.onclick = function() {
quiz.guess(guess);
QuizUI.displayNext();
}
},
displayProgress: function() {
var currentQuestionNumber = quiz.currentQuestionIndex + 1;
this.populateIdWithHTML("progress", "Question " + currentQuestionNumber + " of " + quiz.questions.length);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.