From dd777cd4409e8a92abe7612682195c40d2320135 Mon Sep 17 00:00:00 2001 From: Tony Yang Date: Sun, 26 Dec 2021 02:22:34 +0800 Subject: [PATCH] [Add] command line number guessing game --- game.cpp | 79 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 game.cpp diff --git a/game.cpp b/game.cpp new file mode 100644 index 0000000..1d12d50 --- /dev/null +++ b/game.cpp @@ -0,0 +1,79 @@ +#include +#include +#include +#include + +using namespace std; + +class Game { + private: + unsigned int upper; + unsigned int lower; + unsigned int count; + unsigned int answer; + public: + Game(void) { + this->reset(); + } + + unsigned int get_upper() { + return this->upper; + } + + unsigned int get_lower() { + return this->lower; + } + + unsigned int get_count() { + return this->count; + } + + unsigned int get_answer() { + return this->answer; + } + + void reset() { + this->upper = 999; + this->lower = 0; + this->count = 0; + this->answer = rand() % 1000; + } + + bool guess(int num) { + this->count++; + if (num == answer) return true; + + if (num > answer) this->upper = num; + else if (num < answer) this->lower = num; + + return false; + } +}; + +int main(int argc, char const *argv[]) { + srand(time(nullptr)); + + Game game; + + for (int i = 0; i < argc; i++) { + if (strcmp("-debug", argv[i]) == 0) { + cout << "[Debug] " << game.get_answer() << endl; + } + } + + while (true) { + int guess; + cout << "Guess: "; + cin >> guess; + if (game.guess(guess)) { + cout << "Answer correct. You have guessed for " << game.get_count() << " times." << endl; + break; + } else { + cout << "Answer is fewer than " << game.get_upper() << endl; + cout << "Answer is more than " << game.get_lower() << endl; + cout << "------------------------" << endl; + } + } + + return 0; +}