better user output/error handlin when game cannot be initialized

This commit is contained in:
Maximilian Keßler 2023-08-12 18:58:12 +02:00
parent b1c1f41c6e
commit 4e860f49cc
Signed by: max
GPG key ID: BCC5A619923C0BA5
2 changed files with 13 additions and 7 deletions

View file

@ -88,20 +88,19 @@ namespace Download {
return boost::json::value_to<std::vector<Action>>(action_json);
}
boost::json::object download_game_json(int game_id) {
std::optional<boost::json::object> download_game_json(int game_id) {
std::string request_str = "https://hanab.live/export/" + std::to_string(game_id);
cpr::Response r = cpr::Get(cpr::Url(request_str));
if (r.header["content-type"] != "application/json; charset=utf-8") {
return {};
return std::nullopt;
}
return boost::json::parse(r.text).as_object();
}
boost::json::object open_game_json(const char *filename) {
std::optional<boost::json::object> open_game_json(const char *filename) {
std::ifstream file(filename);
if (!file.is_open()) {
std::cout << "Failed to open " << filename << "." << std::endl;
return {};
return std::nullopt;
}
std::string game_json((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
return boost::json::parse(game_json).as_object();
@ -145,7 +144,7 @@ namespace Download {
}
std::unique_ptr<Hanabi::HanabiStateIF> get_game(std::variant<int, const char*> game_spec, unsigned turn, size_t draw_pile_break = 0) {
const boost::json::object game_json = [&game_spec]() {
const std::optional<boost::json::object> game_json_opt = [&game_spec]() {
if (game_spec.index() == 0) {
return download_game_json(std::get<int>(game_spec));
} else {
@ -153,10 +152,12 @@ namespace Download {
}
}();
if(game_json.empty()) {
if (!game_json_opt.has_value() or game_json_opt.value().empty()) {
return nullptr;
}
const boost::json::object& game_json = game_json_opt.value();
const auto [deck, num_suits] = parse_deck(game_json.at("deck"));
const std::vector<Action> actions = parse_actions(game_json.at("actions"));
const size_t num_players = game_json.at("players").as_array().size();

View file

@ -18,6 +18,11 @@ namespace Hanabi {
void analyze_game_and_start_cli(std::variant<int, const char*> game_id, int turn) {
auto game = Download::get_game(game_id, turn - 1);
if (game == nullptr) {
if(game_id.index() == 0) {
std::cout << "Failed to download game " << std::get<int>(game_id) << " from hanab.live." << std::endl;
} else {
std::cout << "Failed to open file " << std::get<const char*>(game_id) << "." << std::endl;
}
return;
}