Created
December 12, 2019 02:18
-
-
Save okalachev/77a256244ea72f283a5c08519a94340f to your computer and use it in GitHub Desktop.
Tree game implemented in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
using namespace std; | |
struct Node | |
{ | |
public: | |
// Answer constructor | |
Node(string answer) : | |
is_question(false), | |
text(answer) | |
{} | |
// Question constructor | |
Node(string question, shared_ptr<Node> yes, shared_ptr<Node> no) : | |
is_question(true), | |
text(question), | |
yes(yes), | |
no(no) | |
{} | |
bool is_question; | |
string text; | |
shared_ptr<Node> yes{nullptr}; | |
shared_ptr<Node> no{nullptr}; | |
}; | |
shared_ptr<Node> get_initial_tree() | |
{ | |
return make_shared<Node>("Это млекопитающее?", | |
make_shared<Node>("кошка"), | |
make_shared<Node>("таракан")); | |
} | |
bool ask_user() | |
{ | |
ask: | |
string input; | |
getline(cin, input); | |
if (input == "y" || input == "д") { | |
return true; | |
} else if (input == "n" || input == "н") { | |
return false; | |
} else { | |
cout << "Пожалуйста, введите д или н. "; | |
goto ask; | |
} | |
} | |
int main() | |
{ | |
auto game_tree = get_initial_tree(); | |
start: | |
string user_input; | |
cout << "Загадайте животное и нажмите Enter. "; | |
cin.get(); | |
auto current_node = game_tree; | |
bool decision; | |
process_node: | |
if (current_node->is_question) { | |
cout << current_node->text << " "; | |
decision = ask_user(); | |
current_node = decision ? current_node->yes : current_node->no; | |
goto process_node; | |
} else { | |
cout << "Это " << current_node->text << "? "; | |
decision = ask_user(); | |
if (decision) { | |
cout << "Обожаю играть с вами!" << endl << endl; | |
cout << "Сыграем еще раз? "; | |
decision = ask_user(); | |
if (decision) { | |
goto start; | |
} else { | |
return 0; | |
} | |
} else { | |
string user_answer, user_question, wrong_answer; | |
cout << "Сдаюсь. Какое животное вы загадали? "; | |
getline(cin, user_answer); | |
cout << "Введите вопрос, который позволит отличить " << current_node->text << " и " << user_answer << ": "; | |
getline(cin, user_question); | |
cout << "Каков ответ на этот вопрос для " << user_answer << "? "; | |
decision = ask_user(); | |
wrong_answer = current_node->text; | |
current_node->is_question = true; | |
current_node->text = user_question; | |
(decision ? current_node->yes : current_node->no) = make_shared<Node>(user_answer); | |
(!decision ? current_node->yes : current_node->no) = make_shared<Node>(wrong_answer); | |
cout << endl; | |
goto start; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment