From e9693380d952552319b2cdd3f183e2e676676f95 Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Mon, 23 Oct 2017 22:01:18 +0100 Subject: Add deal file parsing and verifying --- CMakeLists.txt | 16 ++-- resources/input-file-schema.json | 35 ++++++++ src/main/card.cpp | 52 ++++++++++++ src/main/card.h | 23 ++++++ src/main/deal_parser.cpp | 101 +++++++++++++++++++++++ src/main/deal_parser.h | 27 ++++++ src/main/legacy_card.cpp | 25 ------ src/main/legacy_card.h | 19 ----- src/main/main.cpp | 173 +++++++++++++++++++++++++++++++++++++-- 9 files changed, 410 insertions(+), 61 deletions(-) create mode 100644 resources/input-file-schema.json create mode 100644 src/main/card.cpp create mode 100644 src/main/card.h create mode 100644 src/main/deal_parser.cpp create mode 100644 src/main/deal_parser.h delete mode 100644 src/main/legacy_card.cpp delete mode 100644 src/main/legacy_card.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 86d5232..d34c1e3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10,9 +10,15 @@ set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) ## source files ############################################################### ############################################################################### -set(sources src/main/main.cpp src/main/command_line_helper.cpp src/main/command_line_helper.h src/main/log_helper.h) +set(sources src/main/main.cpp src/main/command_line_helper.cpp src/main/command_line_helper.h src/main/log_helper.h src/main/card.h src/main/card.cpp src/main/deal_parser.cpp src/main/deal_parser.h) set(sources_test src/test/main_test.cpp) +############################################################################### +## Rapid JSON setup ########################################################### +############################################################################### + +find_package(RapidJSON) + ############################################################################### ## Boost setup ################################################################ ############################################################################### @@ -91,10 +97,6 @@ target_include_directories(solvitaire PUBLIC src/main) target_link_libraries(solvitaire LINK_PUBLIC ${Boost_LIBRARIES}) -# this copies all resource files in the build directory -# we need this, because we want to work with paths relative to the executable -file(COPY ${data} DESTINATION resources) - ############################################################################### ## testing #################################################################### ############################################################################### @@ -119,10 +121,6 @@ ADD_TEST(NAME unit_tests # all install commands get the same destination. this allows us to use paths # relative to the executable. install(TARGETS solvitaire DESTINATION solvitaire) -# this is basically a repeat of the file copy instruction that copies the -# resources in the build directory, but here we tell cmake that we want it -# in the package -install(DIRECTORY resources DESTINATION solvitaire) set(CPACK_OUTPUT_FILE_PREFIX installer) set(CPACK_PACKAGE_VERSION "1.0.0") diff --git a/resources/input-file-schema.json b/resources/input-file-schema.json new file mode 100644 index 0000000..2086eb0 --- /dev/null +++ b/resources/input-file-schema.json @@ -0,0 +1,35 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "definitions": { + "card": { + "type": "string", + "pattern": "^(?i)([A|[1-9]|1[0-3]|J|Q|K])([C|D|H|S])$" + } + }, + "type": "object", + "properties": { + "tableau piles": { + "type": "array", + "items": { + "type": "array", + "items": { + "$ref": "#/definitions/card" + } + } + }, + "hole cards": { + "type": "array", + "items": { + "$ref": "#/definitions/card" + } + } + }, + "additionalProperties": false, + "anyOf": [ + { + "required": [ + "tableau piles" + ] + } + ] +} \ No newline at end of file diff --git a/src/main/card.cpp b/src/main/card.cpp new file mode 100644 index 0000000..98459a3 --- /dev/null +++ b/src/main/card.cpp @@ -0,0 +1,52 @@ +// +// Created by thecharlesblake on 10/11/17. +// + +#include + +#include "card.h" + +using namespace std; + +card::card(const char* c) { + switch(tolower(c[0])) { + case 'a': rank = 1; + break; + case 'j': rank = 11; + break; + case 'q': rank = 12; + break; + case 'k': rank = 13; + break; + default: rank = c[0] - '0'; + } + + suit = c[1]; +} + +int card::get_rank() const { + return rank; +} + +char card::get_suit() const { + return suit; +} + +std::ostream & operator<<(std::ostream & Str, card const & c) { + std::string r; + if (c.get_rank() == 1) { + r = "A"; + } else if (c.get_rank() <= 10) { + r = std::to_string(c.get_rank()); + } else if (c.get_rank() == 11) { + r = "J"; + } else if (c.get_rank() == 12) { + r = "Q"; + } else if (c.get_rank() == 13) { + r = "K"; + } + + r += c.get_suit(); + + return Str << r; +} \ No newline at end of file diff --git a/src/main/card.h b/src/main/card.h new file mode 100644 index 0000000..8397931 --- /dev/null +++ b/src/main/card.h @@ -0,0 +1,23 @@ +// +// Created by thecharlesblake on 10/11/17. +// + +#ifndef SOLITAIRE_PIP_CARD_H +#define SOLITAIRE_PIP_CARD_H + +#include + +class card { +public: + card(const char*); + int get_rank() const; + char get_suit() const; +private: + int rank; + char suit; +}; + +std::ostream & operator<<(std::ostream &, card const &); + + +#endif //SOLITAIRE_PIP_CARD_H diff --git a/src/main/deal_parser.cpp b/src/main/deal_parser.cpp new file mode 100644 index 0000000..6a02d51 --- /dev/null +++ b/src/main/deal_parser.cpp @@ -0,0 +1,101 @@ +// +// Created by thecharlesblake on 10/21/17. +// + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "deal_parser.h" + +using namespace std; +using namespace rapidjson; +using namespace boost; + +void deal_parser::parse(Document& doc, const std::string filename) { + const optional in_json = read_file(filename); + + if (!in_json) { + throw runtime_error("could not read file " + filename); + } + + Document sd; + gen_schema_doc(sd); + SchemaDocument schema(sd); + SchemaValidator validator(schema); + + if(!to_json(doc, *in_json)) { + throw runtime_error(filename + " not valid json"); + } + + if (!doc.Accept(validator)) { + throw runtime_error(schema_err_str(validator)); + } +} + +const optional deal_parser::read_file(const string filename) { + // Reads the file into a string + std::ifstream ifstr(filename); + std::stringstream buf; + buf << ifstr.rdbuf(); + + if (ifstr.fail()) { + return none; + } + + return buf.str(); +} + +void deal_parser::gen_schema_doc(Document& d) { + const char* schema_json = "{\"$schema\":\"http://json-schema.org/draft-04/sc" + "hema#\",\"definitions\":{\"card\":{\"type\":\"string\",\"pattern" + "\":\"^(?i)([A|[1-9]|1[0-3]|J|Q|K])([C|D|H|S])$\"}},\"type\":\"" + "object\",\"properties\":{\"tableau piles\":{\"type\":\"array\"" + ",\"items\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/definit" + "ions/card\"}}},\"hole cards\":{\"type\":\"array\",\"items\":{" + "\"$ref\":\"#/definitions/card\"}}},\"additionalProperties\":fa" + "lse,\"anyOf\":[{\"required\":[\"tableau piles\"]}]}"; + + bool success = to_json(d, schema_json); + assert(success); +} + +bool deal_parser::to_json(rapidjson::Document& d, const char* in) { + d.Parse(in); + return !d.HasParseError(); +} + +bool deal_parser::to_json(rapidjson::Document& d, const string in) { + return to_json(d, in.c_str()); +} + +const string deal_parser::schema_err_str(const SchemaValidator& validator) { + // Input JSON is invalid according to the schema + // Output diagnostic information + string ret = "input JSON failed to match the required schema.\n"; + + StringBuffer sb; + validator.GetInvalidSchemaPointer().StringifyUriFragment(sb); + ret += "Invalid schema: "; + ret += sb.GetString(); + ret += "\n"; + + ret += "Invalid schema keyword: "; + ret += validator.GetInvalidSchemaKeyword(); + ret += "\n"; + + sb.Clear(); + validator.GetInvalidDocumentPointer().StringifyUriFragment(sb); + + ret += "Invalid document: "; + ret += sb.GetString(); + ret += "\n"; + + return ret; +} \ No newline at end of file diff --git a/src/main/deal_parser.h b/src/main/deal_parser.h new file mode 100644 index 0000000..99523f6 --- /dev/null +++ b/src/main/deal_parser.h @@ -0,0 +1,27 @@ +// +// Created by thecharlesblake on 10/21/17. +// + +#ifndef SOLVITAIRE_DEAL_PARSER_H +#define SOLVITAIRE_DEAL_PARSER_H + +#include + +#include +#include +#include + +#include "card.h" + +class deal_parser { +public: + static void parse(rapidjson::Document&, const std::string); +private: + static const boost::optional read_file(const std::string); + static void gen_schema_doc(rapidjson::Document&); + static bool to_json(rapidjson::Document&, const char*); + static bool to_json(rapidjson::Document&, const std::string); + static const std::string schema_err_str(const rapidjson::SchemaValidator&); +}; + +#endif //SOLVITAIRE_DEAL_PARSER_H diff --git a/src/main/legacy_card.cpp b/src/main/legacy_card.cpp deleted file mode 100644 index 9481ecc..0000000 --- a/src/main/legacy_card.cpp +++ /dev/null @@ -1,25 +0,0 @@ -// -// Created by thecharlesblake on 10/11/17. -// - -#include "legacy_card.h" -#include - -legacy_card::legacy_card(const int r, const std::string s): rank(r), suit(s) {} - -std::ostream & operator<<(std::ostream & Str, legacy_card const & c) { - std::string r; - if (c.rank == 1) { - r = "A"; - } else if (c.rank <= 10) { - r = std::to_string(c.rank); - } else if (c.rank == 11) { - r = "J"; - } else if (c.rank == 12) { - r = "Q"; - } else if (c.rank == 13) { - r = "K"; - } - - return Str << r << c.suit; -} \ No newline at end of file diff --git a/src/main/legacy_card.h b/src/main/legacy_card.h deleted file mode 100644 index 215e510..0000000 --- a/src/main/legacy_card.h +++ /dev/null @@ -1,19 +0,0 @@ -// -// Created by thecharlesblake on 10/11/17. -// - -#ifndef SOLITAIRE_PIP_CARD_H -#define SOLITAIRE_PIP_CARD_H - -#include - -struct legacy_card { - legacy_card(const int, const std::string); - const int rank; - const std::string suit; -}; - -std::ostream & operator<<(std::ostream &, legacy_card const &); - - -#endif //SOLITAIRE_PIP_CARD_H diff --git a/src/main/main.cpp b/src/main/main.cpp index 642b27c..4d1c60f 100644 --- a/src/main/main.cpp +++ b/src/main/main.cpp @@ -1,27 +1,184 @@ +#include +#include + #include +#include + #include "command_line_helper.h" -#include +#include "card.h" +#include "deal_parser.h" + +using namespace rapidjson; using namespace std; namespace po = boost::program_options; +bool search(vector* >, card* hole); + int main(int argc, const char* argv[]) { // Parses the command-line options command_line_helper clh; - bool success = clh.parse(argc, argv); - if (!success) { + if (!clh.parse(argc, argv)) { return 1; } - cout << "Random deal: " << clh.get_random_deal() << "\n"; - cout << "Solitaire type: " << clh.get_solitaire_type() << "\n"; - cout << "Filenames: "; for (auto filename : clh.get_input_files()) { - cout << filename << ", "; + try { + Document d; + deal_parser::parse(d, filename); + + vector* > tableaux; + const Value& json_tabx = d["tableau piles"]; + assert(json_tabx.IsArray()); + + for (auto& json_tab : json_tabx.GetArray()) { + vector* tab = new vector(); + + for (auto& json_card : json_tab.GetArray()) { + card* c = new card(json_card.GetString()); + tab->push_back(c); + } + + tableaux.push_back(tab); + } + + bool sol = search(tableaux, new card("AS")); + + cout << (sol ? "Solution Found" : "No Solution"); + + for (vector* tab : tableaux) { + for (card* c : *tab) { + delete c; + } + delete tab; + } + } catch (runtime_error& e) { + cerr << "Error: " << e.what() << "\n"; + } + + + /* + // Reads the file into a string + std::ifstream ifstr(filename); + std::stringstream buf; + buf << ifstr.rdbuf(); + string in_json = buf.str(); + + if (ifstr.fail()) { + cerr << "Error: could not read file '" << filename << "'\n"; + //return 1; + } + + Document sd; + const char* schema_json = "{\"$schema\":\"http://json-schema.org/draft-04/sc" + "hema#\",\"definitions\":{\"card\":{\"type\":\"string\",\"pattern" + "\":\"^(?i)([A|[1-9]|1[0-3]|J|Q|K])([C|D|H|S])$\"}},\"type\":\"" + "object\",\"properties\":{\"tableau piles\":{\"type\":\"array\"" + ",\"items\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/definit" + "ions/card\"}}},\"hole cards\":{\"type\":\"array\",\"items\":{" + "\"$ref\":\"#/definitions/card\"}}},\"additionalProperties\":fa" + "lse,\"anyOf\":[{\"required\":[\"tableau piles\"]}]}"; + if (sd.Parse(schema_json).HasParseError()) { + // the schema is not a valid JSON. + assert(false); + } + SchemaDocument schema(sd); + + Document d; + if (d.Parse(in_json.c_str()).HasParseError()) { + // the input is not a valid JSON. + cerr << "in not valid json\n"; + } + SchemaValidator validator(schema); + if (d.Accept(validator)) { + vector* > tableaux; + const Value& json_tabx = d["tableau piles"]; + assert(json_tabx.IsArray()); + + for (auto& json_tab : json_tabx.GetArray()) { + vector* tab = new vector(); + + for (auto& json_card : json_tab.GetArray()) { + card* c = new card(json_card.GetString()); + tab->push_back(c); + } + + tableaux.push_back(tab); + } + + cout << (search(tableaux, new card("AS")) ? "Solution Found" : "No Solution"); + + for (vector* tab : tableaux) { + for (card* c : *tab) { + delete c; + } + delete tab; + } + + } else { + // Input JSON is invalid according to the schema + // Output diagnostic information + StringBuffer sb; + validator.GetInvalidSchemaPointer().StringifyUriFragment(sb); + printf("Invalid schema: %s\n", sb.GetString()); + printf("Invalid keyword: %s\n", validator.GetInvalidSchemaKeyword()); + sb.Clear(); + validator.GetInvalidDocumentPointer().StringifyUriFragment(sb); + printf("Invalid document: %s\n", sb.GetString()); + }*/ } - cout << "\n"; return 0; } +bool search(vector* > tableaux, card* hole) { + // If the tableaux are all empty, return true + + // Seaches through each tableau. If the top card is one away from + // the hole card, puts it in the hole and recurses. + // If that fails then put the card back and repeat for the next foundation + // If it succeeds, return true + + // If we get to the end of the function, return false + +#ifndef NDEBUG + string stateRep; + for (unsigned int i = 0; i < 2; i++) { + for (vector* tableau : tableaux) { + if (tableau->size() > i) { + cout << *((*tableau)[i]); + } + cout << "\t"; + } + cout << "\n"; + } + cout << "Hole: " << *hole << "\n"; +#endif + + bool allTableauxEmpty = true; + for (unsigned int i = 0; i < tableaux.size(); i++) { + auto tableau = tableaux[i]; + + if (tableau->empty()) { + continue; + } else { + allTableauxEmpty = false; + } + + card* topCard = tableau->back(); + if (topCard->get_rank() == hole->get_rank() + 1 || topCard->get_rank() == hole->get_rank() - 1) { + tableau->pop_back(); + + bool success = search(tableaux, topCard); + + if (success) { + return true; + } else { + tableau->push_back(topCard); + } + } + } + + return allTableauxEmpty; +} -- cgit v1.2.1