#include #include #include #include #include #include "Trivia.h" #include "Question.h" Trivia::Trivia() { } Trivia::~Trivia() { for ( size_t index = 0; index < this->questions.size(); ++index ) delete this->questions[index]; } int Trivia::run() { if ( int result = this->loadQuestions() ) return result; std::srand( std::time(nullptr) + std::clock() ); while ( this->askQuestion() ) ; this->printStatistics(); return 0; } int Trivia::loadQuestions() { const char* const filename = "trivia3.txt"; std::ifstream input(filename); if ( ! input ) return std::cerr << "trivia: could not open " << filename << std::endl, 2; std::string type; while ( std::getline( input, type ) ) { Question* question = createQuestion(type); if ( question ) { input >> *question; this->questions.push_back( question ); } else return std::cerr << "trivia: invalid question type " << type << std::endl, 3; } return 0; } #if 0 for ( size_t index = 0; index < questions.size(); ++index ) std::cout << questions[index] << std::endl; std::cerr << questions.size() << " questions loaded\n"; long seed = std::time(nullptr) + std::clock(); std::default_random_engine generator(seed); std::uniform_int_distribution distribution( 0, this->questions.size() ); auto dice = std::bind(distribution, generator); //size_t index = dice(); for (int i = 0; i < 10; ++i) std::cout << dice() << std::endl; return false; #endif bool Trivia::askQuestion() { size_t index = std::rand() % this->questions.size(); if ( (*this->questions[index]).ask() ) ++this->score; return std::cin.good(); } void Trivia::printStatistics() { std::cout << "You won " << this->score << " points\n"; } #include "NumericQuestion.h" #include "TextualQuestion.h" #include "SingleChoiceQuestion.h" // Factory method Question* Trivia::createQuestion(const std::string& type) { // new Question(); // abstract classes could not be instanced if ( type == "numeric" ) return new NumericQuestion(); if ( type == "textual" ) return new TextualQuestion(); if ( type == "single_choice" ) return new SingleChoiceQuestion(); return nullptr; }