[Add] command line number guessing game
This commit is contained in:
parent
ad9f742773
commit
dd777cd440
79
game.cpp
Normal file
79
game.cpp
Normal file
@ -0,0 +1,79 @@
|
||||
#include <iostream>
|
||||
#include <cstring>
|
||||
#include <cstdlib>
|
||||
#include <ctime>
|
||||
|
||||
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;
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user