Skip to content

Instantly share code, notes, and snippets.

@twhite96
Created April 30, 2016 23:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save twhite96/42aaf04d874630e4c733236392dc23f7 to your computer and use it in GitHub Desktop.
Save twhite96/42aaf04d874630e4c733236392dc23f7 to your computer and use it in GitHub Desktop.
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