#include "Trivia.h" #include "Question.h" #include #include Trivia::Trivia() { } Trivia::~Trivia() { for ( size_t index = 0; index < questions.size(); ++index ) delete questions[index]; } int Trivia::run() { srand( time(nullptr) ); if ( ! loadQuestions() ) return 1; while ( launchQuestion() ) ; showStatistics(); return 0; } bool Trivia::loadQuestions() { #define filename "trivia3.txt" std::ifstream inputFile(filename); if ( ! inputFile ) return std::cerr << "trivia: could not open " filename "\n", false; std::string questionType; while ( std::getline(inputFile, questionType) ) { Question* question = createQuestion(questionType); if ( question == nullptr ) return std::cerr << "trivia: invalid question type: " << questionType << std::endl, 2; inputFile >> *question; questions.push_back(question); } // inputFile destructor closes the file, but we can do it explicitly inputFile.close(); return true; } bool Trivia::launchQuestion() { size_t randomIndex = rand() % questions.size(); Question* selectedQuestion = questions[randomIndex]; std::cout << *selectedQuestion; std::string playerAnswer; if ( ! std::getline( std::cin, playerAnswer ) ) return false; if ( selectedQuestion->isRightAnswer(playerAnswer) ) { std::cout << "Right! You got " << selectedQuestion->getScore() << " points\n\n"; player.increaseScore( selectedQuestion->getScore() ); } else std::cout << "Wrong answer!\n\n"; return true; } void Trivia::showStatistics() { std::cout << "Game over. You got " << player.getScore() << " points! See you soon...\n"; } // Factory method #include "NumericQuestion.h" #include "SingleChoiceQuestion.h" #include "TextualQuestion.h" Question* Trivia::createQuestion(const std::string& questionType) { if ( questionType == "single_choice" ) return new SingleChoiceQuestion(); if ( questionType == "numeric" ) return new NumericQuestion(); if ( questionType == "textual" ) return new TextualQuestion(); return nullptr; }