Files
Text-Adventure/Engine/src/CommandParser.cpp
T

77 lines
1.6 KiB
C++
Raw Normal View History

2026-08-07 13:10:07 -05:00
#include "CommandParser.h"
#include <algorithm>
#include <cstring>
#include <iostream>
#include <sstream>
CommandParser::CommandParser() {}
bool CommandParser::AddCommand(std::string c, FUNCTION f) {
commands.emplace(c, f);
return true;
}
void CommandParser::RemoveCommand(std::string c) { commands.erase(c); }
std::vector<std::string> CommandParser::Verb(std::stringstream &sentences) {
std::string word;
std::vector<std::string> verbs = {};
while (sentences >> word) {
if (std::find(Verbs.begin(), Verbs.end(), word) != Verbs.end()) {
verbs.push_back(word);
}
}
if (verbs.empty()) {
CommandUnrecognized();
}
return verbs;
}
std::vector<std::string> CommandParser::Noun(std::stringstream &sentences) {
std::string word;
std::vector<std::string> nouns = {};
while (sentences >> word) {
if (std::find(Nouns.begin(), Nouns.end(), word) != Nouns.end()) {
nouns.push_back(word);
}
}
return nouns;
}
int CommandParser::Parse() {
std::string cmd;
std::string word;
std::string noun;
std::vector<std::string> verbs;
std::vector<std::string> nouns;
printf("Please Enter a command \n");
printf("> ");
getline(std::cin, cmd);
cmd[0] = toupper(cmd[0]);
std::stringstream c(cmd);
verbs = Verb(c);
nouns = Noun(c);
for (const auto &verb: verbs) {
2026-08-21 08:02:22 -05:00
if (!commands[verb]) {
printf("Sorry kid, can't understand ya! \n");
break;
}
2026-08-07 13:10:07 -05:00
commands[verb]("");
}
return 0;
}