From db208b38d78571d68a5f92b7221175d2e67d09ed Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Mon, 16 Oct 2017 12:53:14 +0100 Subject: Move setup classes to legacy --- src/main/Card.cpp | 25 ---------- src/main/Card.h | 19 -------- src/main/legacy_card.cpp | 25 ++++++++++ src/main/legacy_card.h | 19 ++++++++ src/main/legacy_main.cpp | 121 +++++++++++++++++++++++++++++++++++++++++++++++ src/main/main.cpp | 121 ----------------------------------------------- 6 files changed, 165 insertions(+), 165 deletions(-) delete mode 100644 src/main/Card.cpp delete mode 100644 src/main/Card.h create mode 100644 src/main/legacy_card.cpp create mode 100644 src/main/legacy_card.h create mode 100644 src/main/legacy_main.cpp (limited to 'src') diff --git a/src/main/Card.cpp b/src/main/Card.cpp deleted file mode 100644 index ead2fd5..0000000 --- a/src/main/Card.cpp +++ /dev/null @@ -1,25 +0,0 @@ -// -// Created by thecharlesblake on 10/11/17. -// - -#include "Card.h" -#include - -Card::Card(const int r, const std::string s): rank(r), suit(s) {} - -std::ostream & operator<<(std::ostream & Str, 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/Card.h b/src/main/Card.h deleted file mode 100644 index 651df71..0000000 --- a/src/main/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 Card { - Card(const int, const std::string); - const int rank; - const std::string suit; -}; - -std::ostream & operator<<(std::ostream &, Card const &); - - -#endif //SOLITAIRE_PIP_CARD_H diff --git a/src/main/legacy_card.cpp b/src/main/legacy_card.cpp new file mode 100644 index 0000000..9481ecc --- /dev/null +++ b/src/main/legacy_card.cpp @@ -0,0 +1,25 @@ +// +// 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 new file mode 100644 index 0000000..215e510 --- /dev/null +++ b/src/main/legacy_card.h @@ -0,0 +1,19 @@ +// +// 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/legacy_main.cpp b/src/main/legacy_main.cpp new file mode 100644 index 0000000..76940df --- /dev/null +++ b/src/main/legacy_main.cpp @@ -0,0 +1,121 @@ +#include +#include +#include +#include +#include +#include +#include "legacy_card.h" +#include + +#if defined NDEBUG + #define LOG_DEBUG(msg) +#else + #define LOG_DEBUG(msg) BOOST_LOG_TRIVIAL(debug) << msg +#endif +#define LOG_INFO(msg) BOOST_LOG_TRIVIAL(info) << msg +#define LOG_WARNING(msg) BOOST_LOG_TRIVIAL(warning) << msg +#define LOG_ERROR(msg) BOOST_LOG_ERROR(error) << msg + +using namespace std; + +bool search(vector* >, legacy_card* hole); + +int main() +{ + const int topRank = 4; + + vector* > tableaux; + + vector shuffleCards; + for (int r = 1; r <= topRank; r++) { + for (int s = 0; s < 4; s++) { + string suit; + if (s == 0) { + suit = "D"; + } else if (s == 1) { + suit = "S"; + } else if (s == 2) { + suit = "H"; + } else { + suit = "C"; + } + + legacy_card* c = new legacy_card(r, suit); + shuffleCards.push_back(c); + } + } + + auto rng = std::default_random_engine(2); // 3 has solution + std::shuffle(std::begin(shuffleCards), std::end(shuffleCards), rng); + + for (int i = 0; i < topRank * 2; i++) { + vector* tab = new vector(); + for (int j = 0; j < 2; j++) { + int idx = i + (topRank * 2 * j); + if (shuffleCards[idx]->suit == "S" && shuffleCards[idx]->rank == 1) { + continue; + } else { + tab->push_back(shuffleCards[idx]); + } + } + tableaux.push_back(tab); + } + + legacy_card c(2, string("H")); + LOG_DEBUG(c); + + cout << (search(tableaux, new legacy_card(1, "S")) ? "Solution Found" : "No Solution"); + + return 0; +} + +bool search(vector* > tableaux, legacy_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 (auto 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; + } + + legacy_card* topCard = tableau->back(); + if (topCard->rank == hole->rank + 1 || topCard->rank == hole->rank - 1) { + tableau->pop_back(); + + bool success = search(tableaux, topCard); + + if (success) { + return true; + } else { + tableau->push_back(topCard); + } + } + } + + return allTableauxEmpty; +} \ No newline at end of file diff --git a/src/main/main.cpp b/src/main/main.cpp index 1b75252..e69de29 100644 --- a/src/main/main.cpp +++ b/src/main/main.cpp @@ -1,121 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include "Card.h" -#include - -#if defined NDEBUG - #define LOG_DEBUG(msg) -#else - #define LOG_DEBUG(msg) BOOST_LOG_TRIVIAL(debug) << msg -#endif -#define LOG_INFO(msg) BOOST_LOG_TRIVIAL(info) << msg -#define LOG_WARNING(msg) BOOST_LOG_TRIVIAL(warning) << msg -#define LOG_ERROR(msg) BOOST_LOG_ERROR(error) << msg - -using namespace std; - -bool search(vector* >, Card* hole); - -int main() -{ - const int topRank = 4; - - vector* > tableaux; - - vector shuffleCards; - for (int r = 1; r <= topRank; r++) { - for (int s = 0; s < 4; s++) { - string suit; - if (s == 0) { - suit = "D"; - } else if (s == 1) { - suit = "S"; - } else if (s == 2) { - suit = "H"; - } else { - suit = "C"; - } - - Card* c = new Card(r, suit); - shuffleCards.push_back(c); - } - } - - auto rng = std::default_random_engine(2); // 3 has solution - std::shuffle(std::begin(shuffleCards), std::end(shuffleCards), rng); - - for (int i = 0; i < topRank * 2; i++) { - vector* tab = new vector(); - for (int j = 0; j < 2; j++) { - int idx = i + (topRank * 2 * j); - if (shuffleCards[idx]->suit == "S" && shuffleCards[idx]->rank == 1) { - continue; - } else { - tab->push_back(shuffleCards[idx]); - } - } - tableaux.push_back(tab); - } - - Card c(2, string("H")); - LOG_DEBUG(c); - - cout << (search(tableaux, new Card(1, "S")) ? "Solution Found" : "No Solution"); - - 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 (auto 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->rank == hole->rank + 1 || topCard->rank == hole->rank - 1) { - tableau->pop_back(); - - bool success = search(tableaux, topCard); - - if (success) { - return true; - } else { - tableau->push_back(topCard); - } - } - } - - return allTableauxEmpty; -} \ No newline at end of file -- cgit v1.2.1 From 9101c98f951e7b104e6969fd5984379ca04745ea Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Mon, 16 Oct 2017 14:15:25 +0100 Subject: Add demo command line parsing --- src/main/command_line_helper.cpp | 18 ++++++++++++++++++ src/main/command_line_helper.h | 12 ++++++++++++ src/main/main.cpp | 29 +++++++++++++++++++++++++++++ 3 files changed, 59 insertions(+) create mode 100644 src/main/command_line_helper.cpp create mode 100644 src/main/command_line_helper.h (limited to 'src') diff --git a/src/main/command_line_helper.cpp b/src/main/command_line_helper.cpp new file mode 100644 index 0000000..38b9af0 --- /dev/null +++ b/src/main/command_line_helper.cpp @@ -0,0 +1,18 @@ +// +// Created by thecharlesblake on 10/16/17. +// + +#include "command_line_helper.h" +#include + +namespace po = boost::program_options; + +po::options_description get_options_desc() { + // Creates the command line options + po::options_description desc("Allowed options"); + desc.add_options() + ("help", "produce help message") + ("compression", po::value(), "set compression level"); + + return desc; +} \ No newline at end of file diff --git a/src/main/command_line_helper.h b/src/main/command_line_helper.h new file mode 100644 index 0000000..dc3b2b6 --- /dev/null +++ b/src/main/command_line_helper.h @@ -0,0 +1,12 @@ +// +// Created by thecharlesblake on 10/16/17. +// + +#ifndef SOLVITAIRE_COMMAND_LINE_HELPER_H +#define SOLVITAIRE_COMMAND_LINE_HELPER_H + +#include + +boost::program_options::options_description get_options_desc(); + +#endif //SOLVITAIRE_COMMAND_LINE_HELPER_H diff --git a/src/main/main.cpp b/src/main/main.cpp index e69de29..8c07d1f 100644 --- a/src/main/main.cpp +++ b/src/main/main.cpp @@ -0,0 +1,29 @@ +#include +#include +#include "command_line_helper.h" + +using namespace std; + +namespace po = boost::program_options; + +int main(int argc, const char* argv[]) { + // Creates the command line options + po::options_description desc = get_options_desc(); + + po::variables_map vm; + po::store(po::parse_command_line(argc, argv, desc), vm); + po::notify(vm); + + if (vm.count("help")) { + cout << desc << "\n"; + return 1; + } + + if (vm.count("compression")) { + cout << "Compression level was set to " + << vm["compression"].as() << ".\n"; + } else { + cout << "Compression level was not set.\n"; + } +} + -- cgit v1.2.1 From dc01ab729c749fbfd2421943198a038d126aa66c Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Mon, 16 Oct 2017 22:56:16 +0100 Subject: Add simple black hole cmdline parse & err handling --- src/main/command_line_helper.cpp | 121 ++++++++++++++++++++++++++++++++++++--- src/main/command_line_helper.h | 24 +++++++- src/main/log_helper.h | 17 ++++++ src/main/main.cpp | 28 +++++---- 4 files changed, 166 insertions(+), 24 deletions(-) create mode 100644 src/main/log_helper.h (limited to 'src') diff --git a/src/main/command_line_helper.cpp b/src/main/command_line_helper.cpp index 38b9af0..9e389fd 100644 --- a/src/main/command_line_helper.cpp +++ b/src/main/command_line_helper.cpp @@ -2,17 +2,122 @@ // Created by thecharlesblake on 10/16/17. // -#include "command_line_helper.h" +#include +#include +#include + #include +#include "command_line_helper.h" + +using namespace std; + namespace po = boost::program_options; -po::options_description get_options_desc() { - // Creates the command line options - po::options_description desc("Allowed options"); - desc.add_options() +command_line_helper::command_line_helper() + : main_options("options") { + + main_options.add_options() ("help", "produce help message") - ("compression", po::value(), "set compression level"); + ("type", po::value(), + "specify the type of the solitaire game to be solved (REQUIRED)") + ("random", "create and solve a random solitaire deal"); + + po::options_description hidden_options("Hidden options"); + hidden_options.add_options() + ("input-files", po::value>(), + "the file containing the deal to be solved"); + + cmdline_options.add(main_options).add(hidden_options); + + p.add("input-files", -1); +} + +bool command_line_helper::parse(int argc, const char* argv[]) { + po::variables_map vm; + try { + store(po::command_line_parser(argc, argv).options(cmdline_options) + .positional(p).run(), vm); + } catch(po::error& e) { + cerr << "Error: " << e.what() << "\n"; + return false; + } + + notify(vm); + + help = vm.count("help"); + + if (vm.count("input-files")) { + input_files = vm["input-files"].as>(); + } + + if (vm.count("type")) { + solitaire_type = vm["type"].as(); + } + + random_deal = vm.count("random"); + + // Handle logic error scenarios + return assess_errors(); +} + +bool command_line_helper::assess_errors() { + if (help) { + print_help(); + return false; + } + + if (solitaire_type.empty()) { + print_no_sol_type_error(); + return false; + } + + if (random_deal && !input_files.empty()) { + print_rand_plus_input_err(); + return false; + } + + if (input_files.empty() && !random_deal) { + print_no_input_error(); + return false; + } + return true; +} + +void command_line_helper::print_help() { + cout << "Usage: solvitaire [options] input-file1 input-file2 ...\n" + << main_options << "\n"; +} + +void command_line_helper::print_no_input_error() { + cerr << "Error: User must supply input file(s) or the '--random' " + "option\n"; + print_help(); +} + +void command_line_helper::print_no_sol_type_error() { + cerr << "Error: User must supply a solitaire type\n"; + print_help(); +} + +void command_line_helper::print_rand_plus_input_err() { + cerr << "Error: User must supply input file(s) or the '--random' option, " + "not both\n"; + print_help(); +} + +const vector command_line_helper::get_input_files() { + return input_files; +} + +const string command_line_helper::get_solitaire_type() { + return solitaire_type; +} + +bool command_line_helper::get_random_deal() { + return random_deal; +} - return desc; -} \ No newline at end of file +bool command_line_helper::get_help() { + return help; +} diff --git a/src/main/command_line_helper.h b/src/main/command_line_helper.h index dc3b2b6..53a5a5e 100644 --- a/src/main/command_line_helper.h +++ b/src/main/command_line_helper.h @@ -7,6 +7,28 @@ #include -boost::program_options::options_description get_options_desc(); +class command_line_helper { +public: + command_line_helper(); + bool parse(int argc, const char* argv[]); + void print_help(); + void print_no_input_error(); + void print_no_sol_type_error(); + void print_rand_plus_input_err(); + const std::vector get_input_files(); + const std::string get_solitaire_type(); + bool get_random_deal(); + bool get_help(); + bool assess_errors(); +private: + boost::program_options::options_description cmdline_options; + boost::program_options::options_description main_options; + boost::program_options::positional_options_description p; + + std::vector input_files; + std::string solitaire_type; + bool random_deal; + bool help; +}; #endif //SOLVITAIRE_COMMAND_LINE_HELPER_H diff --git a/src/main/log_helper.h b/src/main/log_helper.h new file mode 100644 index 0000000..8e634a7 --- /dev/null +++ b/src/main/log_helper.h @@ -0,0 +1,17 @@ +// +// Created by thecharlesblake on 10/16/17. +// + +#ifndef SOLVITAIRE_LOG_HELPER_H +#define SOLVITAIRE_LOG_HELPER_H + +#if defined NDEBUG + #define LOG_DEBUG(msg) +#else + #define LOG_DEBUG(msg) BOOST_LOG_TRIVIAL(debug) << msg +#endif +#define LOG_INFO(msg) BOOST_LOG_TRIVIAL(info) << msg +#define LOG_WARNING(msg) BOOST_LOG_TRIVIAL(warning) << msg +#define LOG_ERROR(msg) BOOST_LOG_ERROR(error) << msg + +#endif //SOLVITAIRE_LOG_HELPER_H diff --git a/src/main/main.cpp b/src/main/main.cpp index 8c07d1f..642b27c 100644 --- a/src/main/main.cpp +++ b/src/main/main.cpp @@ -1,29 +1,27 @@ #include -#include #include "command_line_helper.h" +#include using namespace std; namespace po = boost::program_options; int main(int argc, const char* argv[]) { - // Creates the command line options - po::options_description desc = get_options_desc(); - - po::variables_map vm; - po::store(po::parse_command_line(argc, argv, desc), vm); - po::notify(vm); - - if (vm.count("help")) { - cout << desc << "\n"; + // Parses the command-line options + command_line_helper clh; + bool success = clh.parse(argc, argv); + if (!success) { return 1; } - if (vm.count("compression")) { - cout << "Compression level was set to " - << vm["compression"].as() << ".\n"; - } else { - cout << "Compression level was not set.\n"; + 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 << ", "; } + cout << "\n"; + + return 0; } -- cgit v1.2.1 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 --- 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 ++++++++++++++++++++++++++++++++++++++++++++--- 7 files changed, 368 insertions(+), 52 deletions(-) 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 (limited to 'src') 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 From c5e5d9d6bbd7d7d2a6c6463505e7b7031e846ebf Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Tue, 24 Oct 2017 01:23:00 +0100 Subject: Draft of OO game logic --- src/main/black_hole_state.cpp | 74 +++++++++++++++++++++++++++++++ src/main/black_hole_state.h | 36 +++++++++++++++ src/main/card.cpp | 2 + src/main/card.h | 3 ++ src/main/deal_parser.cpp | 101 ------------------------------------------ src/main/deal_parser.h | 27 ----------- src/main/game_state.cpp | 51 +++++++++++++++++++++ src/main/game_state.h | 28 ++++++++++++ src/main/io_utils.cpp | 101 ++++++++++++++++++++++++++++++++++++++++++ src/main/io_utils.h | 27 +++++++++++ src/main/main.cpp | 4 +- 11 files changed, 324 insertions(+), 130 deletions(-) create mode 100644 src/main/black_hole_state.cpp create mode 100644 src/main/black_hole_state.h delete mode 100644 src/main/deal_parser.cpp delete mode 100644 src/main/deal_parser.h create mode 100644 src/main/game_state.cpp create mode 100644 src/main/game_state.h create mode 100644 src/main/io_utils.cpp create mode 100644 src/main/io_utils.h (limited to 'src') diff --git a/src/main/black_hole_state.cpp b/src/main/black_hole_state.cpp new file mode 100644 index 0000000..4b54bc6 --- /dev/null +++ b/src/main/black_hole_state.cpp @@ -0,0 +1,74 @@ +// +// Created by thecharlesblake on 10/23/17. +// + +#include + +#include + +#include "card.h +#include "game_state.h" +#include "black_hole_state.h" + +using namespace std; +using namespace rapidjson; + + +black_hole_state::black_hole_state(const Document& doc) + : game_state(doc), solved(false) { + // Assign hole card + assert(doc.HasMember("hole card")); + const Value& json_h_card = doc["hole card"]; + assert(json_h_card.IsArray()); + hole_card = doc["hole card"].GetString(); +}; + +vector black_hole_state::get_next_legal_states() const { + vector next; + + bool all_tableaux_empty = true; + for (int i = 0; i < tableau_piles.size(); i++) { + vector tableau_pile = tableau_piles[i]; + card top_card = tableau_pile.back(); + + if (tableau_pile.empty()) { + continue; + } else { + all_tableaux_empty = false; + } + + if (adjacent(top_card, hole_card)) { + black_hole_state s = *this; + s.move_to_hole(i); + next.push_back(s); + } + } + + // If there are no cards left in play, deal solved + solved = all_tableaux_empty; + + return next; +} + +void black_hole_state::move_to_hole(int tab_idx) { + hole_card = tableau_piles[tab_idx].back(); + tableau_piles[tab_idx].pop_back(); +} + +bool black_hole_state::is_solved() const { + return solved; +} + +ostream& black_hole_state::print(ostream& stream) const { + return game_state::print(stream) << "Hole: " << hole_card << "\n"; +} + +bool black_hole_state::adjacent(const card& a, const card& b) { + int x = a.get_rank(); + int y = b.get_rank(); + + return x == y + 1 + || x + 1 == y + || x == 1 && y == MAX_RANK + || x == MAX_RANK && y == 1; +} \ No newline at end of file diff --git a/src/main/black_hole_state.h b/src/main/black_hole_state.h new file mode 100644 index 0000000..75fda71 --- /dev/null +++ b/src/main/black_hole_state.h @@ -0,0 +1,36 @@ +// +// Created by thecharlesblake on 10/23/17. +// + +#ifndef SOLVITAIRE_BLACK_HOLE_STATE_H +#define SOLVITAIRE_BLACK_HOLE_STATE_H + +#include +#include + +#include + +#include "card.h +#include "game_state.h" + +class black_hole_state : public game_state { +public: + black_hole_state(const rapidjson::Document& doc); + std::vector get_next_legal_states() const override; + bool is_solved() const override; + std::ostream& print(std::ostream&) const override; + + friend std::ostream& operator<< (std::ostream&, const black_hole_state&); + +protected: + virtual static const int MAX_RANK = 13; + +private: + void move_to_hole(int); + static bool adjacent(const card& a, const card& b); + + card hole_card; + mutable bool solved; +}; + +#endif //SOLVITAIRE_BLACK_HOLE_STATE_H diff --git a/src/main/card.cpp b/src/main/card.cpp index 98459a3..266d675 100644 --- a/src/main/card.cpp +++ b/src/main/card.cpp @@ -8,6 +8,8 @@ using namespace std; +card::card() {} + card::card(const char* c) { switch(tolower(c[0])) { case 'a': rank = 1; diff --git a/src/main/card.h b/src/main/card.h index 8397931..c6fbd8e 100644 --- a/src/main/card.h +++ b/src/main/card.h @@ -9,9 +9,12 @@ class card { public: + card(); card(const char*); int get_rank() const; char get_suit() const; + + friend std::string& operator+= (std::ostream&, const game_state&); private: int rank; char suit; diff --git a/src/main/deal_parser.cpp b/src/main/deal_parser.cpp deleted file mode 100644 index 6a02d51..0000000 --- a/src/main/deal_parser.cpp +++ /dev/null @@ -1,101 +0,0 @@ -// -// 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 deleted file mode 100644 index 99523f6..0000000 --- a/src/main/deal_parser.h +++ /dev/null @@ -1,27 +0,0 @@ -// -// 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/game_state.cpp b/src/main/game_state.cpp new file mode 100644 index 0000000..c6278e2 --- /dev/null +++ b/src/main/game_state.cpp @@ -0,0 +1,51 @@ +// +// Created by thecharlesblake on 10/23/17. +// + +#include +#include + +#include + +#include "game_state.h" + +using namespace std; +using namespace rapidjson; + +game_state::game_state(const Document& doc) { + const Value& json_tab_piles = doc["tableau piles"]; + assert(json_tab_piles.IsArray()); + + for (auto& json_tab : json_tab_piles.GetArray()) { + vector tableau_pile; + + for (auto& json_card : json_tab.GetArray()) { + tableau_pile.push_back(card(json_card.GetString())); + } + + tableau_piles.push_back(tableau_pile); + } +} + +ostream& game_state::print(ostream& stream) const { + bool empty_row = false; + int row_idx = 0; + + while (!empty_row) { + empty_row = true; + for (auto tableau_pile : tableau_piles) { + if (tableau_pile.size() > row_idx) { + empty_row = false; + stream << tableau_pile[row_idx]; + } + stream << "\t"; + } + stream << "\n"; + row_idx++; + } + return stream; +} + +ostream& operator <<(ostream& stream, const game_state& gs) { + return gs.print(stream); +} \ No newline at end of file diff --git a/src/main/game_state.h b/src/main/game_state.h new file mode 100644 index 0000000..693b127 --- /dev/null +++ b/src/main/game_state.h @@ -0,0 +1,28 @@ +// +// Created by thecharlesblake on 10/23/17. +// + +#ifndef SOLVITAIRE_GAME_STATE_H +#define SOLVITAIRE_GAME_STATE_H + +#include +#include + +#include + +#include "card.h + +class game_state { +public: + game_state(const rapidjson::Document&); + virtual std::vector get_next_legal_states() const = 0; + virtual bool is_solved() const = 0; + virtual std::ostream& print(std::ostream&) const; + + friend std::ostream& operator<< (std::ostream&, const game_state&); + +protected: + std::vector> tableau_piles; +}; + +#endif //SOLVITAIRE_GAME_STATE_H diff --git a/src/main/io_utils.cpp b/src/main/io_utils.cpp new file mode 100644 index 0000000..4239c78 --- /dev/null +++ b/src/main/io_utils.cpp @@ -0,0 +1,101 @@ +// +// Created by thecharlesblake on 10/21/17. +// + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "io_utils.h" + +using namespace std; +using namespace rapidjson; +using namespace boost; + +void io_utils::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 io_utils::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 io_utils::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 card\":{\"$ref\":\"#/definitions/card\"}}" + ",\"additionalProperties\":false,\"anyOf\":[{\"required\":[\"tableau" + " piles\"]}]}"; + + bool success = to_json(d, schema_json); + assert(success); +} + +bool io_utils::to_json(rapidjson::Document& d, const char* in) { + d.Parse(in); + return !d.HasParseError(); +} + +bool io_utils::to_json(rapidjson::Document& d, const string in) { + return to_json(d, in.c_str()); +} + +const string io_utils::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/io_utils.h b/src/main/io_utils.h new file mode 100644 index 0000000..659a0c4 --- /dev/null +++ b/src/main/io_utils.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 io_utils { +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/main.cpp b/src/main/main.cpp index 4d1c60f..7e9d132 100644 --- a/src/main/main.cpp +++ b/src/main/main.cpp @@ -6,7 +6,7 @@ #include "command_line_helper.h" #include "card.h" -#include "deal_parser.h" +#include "io_utils.h" using namespace rapidjson; @@ -26,7 +26,7 @@ int main(int argc, const char* argv[]) { for (auto filename : clh.get_input_files()) { try { Document d; - deal_parser::parse(d, filename); + io_utils::parse(d, filename); vector* > tableaux; const Value& json_tabx = d["tableau piles"]; -- cgit v1.2.1 From 3eff79ed14f1fda1f148a9a4c5c3a1ae4edbee37 Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Thu, 26 Oct 2017 14:51:13 +0100 Subject: BH Solver with path outputted, based on user input --- src/main/black_hole_state.cpp | 74 ------------------ src/main/black_hole_state.h | 36 --------- src/main/card.cpp | 18 ++--- src/main/card.h | 1 - src/main/command_line_helper.h | 11 +-- src/main/deal_parser.cpp | 96 ++++++++++++++++++++++++ src/main/deal_parser.h | 27 +++++++ src/main/game_state.cpp | 81 ++++++++++++++++++-- src/main/game_state.h | 21 ++++-- src/main/io_utils.cpp | 101 ------------------------- src/main/io_utils.h | 27 ------- src/main/legacy_main.cpp | 121 ------------------------------ src/main/log_helper.h | 12 +-- src/main/main.cpp | 165 ++++------------------------------------- src/main/solver.cpp | 68 +++++++++++++++++ src/main/solver.h | 36 +++++++++ 16 files changed, 351 insertions(+), 544 deletions(-) delete mode 100644 src/main/black_hole_state.cpp delete mode 100644 src/main/black_hole_state.h create mode 100644 src/main/deal_parser.cpp create mode 100644 src/main/deal_parser.h delete mode 100644 src/main/io_utils.cpp delete mode 100644 src/main/io_utils.h delete mode 100644 src/main/legacy_main.cpp create mode 100644 src/main/solver.cpp create mode 100644 src/main/solver.h (limited to 'src') diff --git a/src/main/black_hole_state.cpp b/src/main/black_hole_state.cpp deleted file mode 100644 index 4b54bc6..0000000 --- a/src/main/black_hole_state.cpp +++ /dev/null @@ -1,74 +0,0 @@ -// -// Created by thecharlesblake on 10/23/17. -// - -#include - -#include - -#include "card.h -#include "game_state.h" -#include "black_hole_state.h" - -using namespace std; -using namespace rapidjson; - - -black_hole_state::black_hole_state(const Document& doc) - : game_state(doc), solved(false) { - // Assign hole card - assert(doc.HasMember("hole card")); - const Value& json_h_card = doc["hole card"]; - assert(json_h_card.IsArray()); - hole_card = doc["hole card"].GetString(); -}; - -vector black_hole_state::get_next_legal_states() const { - vector next; - - bool all_tableaux_empty = true; - for (int i = 0; i < tableau_piles.size(); i++) { - vector tableau_pile = tableau_piles[i]; - card top_card = tableau_pile.back(); - - if (tableau_pile.empty()) { - continue; - } else { - all_tableaux_empty = false; - } - - if (adjacent(top_card, hole_card)) { - black_hole_state s = *this; - s.move_to_hole(i); - next.push_back(s); - } - } - - // If there are no cards left in play, deal solved - solved = all_tableaux_empty; - - return next; -} - -void black_hole_state::move_to_hole(int tab_idx) { - hole_card = tableau_piles[tab_idx].back(); - tableau_piles[tab_idx].pop_back(); -} - -bool black_hole_state::is_solved() const { - return solved; -} - -ostream& black_hole_state::print(ostream& stream) const { - return game_state::print(stream) << "Hole: " << hole_card << "\n"; -} - -bool black_hole_state::adjacent(const card& a, const card& b) { - int x = a.get_rank(); - int y = b.get_rank(); - - return x == y + 1 - || x + 1 == y - || x == 1 && y == MAX_RANK - || x == MAX_RANK && y == 1; -} \ No newline at end of file diff --git a/src/main/black_hole_state.h b/src/main/black_hole_state.h deleted file mode 100644 index 75fda71..0000000 --- a/src/main/black_hole_state.h +++ /dev/null @@ -1,36 +0,0 @@ -// -// Created by thecharlesblake on 10/23/17. -// - -#ifndef SOLVITAIRE_BLACK_HOLE_STATE_H -#define SOLVITAIRE_BLACK_HOLE_STATE_H - -#include -#include - -#include - -#include "card.h -#include "game_state.h" - -class black_hole_state : public game_state { -public: - black_hole_state(const rapidjson::Document& doc); - std::vector get_next_legal_states() const override; - bool is_solved() const override; - std::ostream& print(std::ostream&) const override; - - friend std::ostream& operator<< (std::ostream&, const black_hole_state&); - -protected: - virtual static const int MAX_RANK = 13; - -private: - void move_to_hole(int); - static bool adjacent(const card& a, const card& b); - - card hole_card; - mutable bool solved; -}; - -#endif //SOLVITAIRE_BLACK_HOLE_STATE_H diff --git a/src/main/card.cpp b/src/main/card.cpp index 266d675..45de1d1 100644 --- a/src/main/card.cpp +++ b/src/main/card.cpp @@ -3,6 +3,7 @@ // #include +#include #include "card.h" @@ -34,21 +35,20 @@ char card::get_suit() const { return suit; } -std::ostream & operator<<(std::ostream & Str, card const & c) { +std::ostream & operator<<(std::ostream & s, card const & c) { std::string r; if (c.get_rank() == 1) { - r = "A"; + s << "A"; } else if (c.get_rank() <= 10) { - r = std::to_string(c.get_rank()); + s << c.get_rank(); } else if (c.get_rank() == 11) { - r = "J"; + s << "J"; } else if (c.get_rank() == 12) { - r = "Q"; + s << "Q"; } else if (c.get_rank() == 13) { - r = "K"; + s << "K"; } - r += c.get_suit(); - - return Str << r; + s << c.get_suit(); + return s; } \ No newline at end of file diff --git a/src/main/card.h b/src/main/card.h index c6fbd8e..2d9635f 100644 --- a/src/main/card.h +++ b/src/main/card.h @@ -14,7 +14,6 @@ public: int get_rank() const; char get_suit() const; - friend std::string& operator+= (std::ostream&, const game_state&); private: int rank; char suit; diff --git a/src/main/command_line_helper.h b/src/main/command_line_helper.h index 53a5a5e..3454bfb 100644 --- a/src/main/command_line_helper.h +++ b/src/main/command_line_helper.h @@ -11,16 +11,17 @@ class command_line_helper { public: command_line_helper(); bool parse(int argc, const char* argv[]); - void print_help(); - void print_no_input_error(); - void print_no_sol_type_error(); - void print_rand_plus_input_err(); const std::vector get_input_files(); const std::string get_solitaire_type(); bool get_random_deal(); bool get_help(); - bool assess_errors(); private: + bool assess_errors(); + void print_help(); + void print_no_input_error(); + void print_no_sol_type_error(); + void print_rand_plus_input_err(); + boost::program_options::options_description cmdline_options; boost::program_options::options_description main_options; boost::program_options::positional_options_description p; diff --git a/src/main/deal_parser.cpp b/src/main/deal_parser.cpp new file mode 100644 index 0000000..8a9cef1 --- /dev/null +++ b/src/main/deal_parser.cpp @@ -0,0 +1,96 @@ +// +// 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 card\":{\"$ref\":\"#/definitions/card\"}}" + ",\"additionalProperties\":false,\"anyOf\":[{\"required\":[\"tableau" + " piles\"]}]}"; + + to_json(d, schema_json); +} + +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 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/game_state.cpp b/src/main/game_state.cpp index c6278e2..0e4f210 100644 --- a/src/main/game_state.cpp +++ b/src/main/game_state.cpp @@ -1,5 +1,5 @@ // -// Created by thecharlesblake on 10/23/17. +// Created by thecharlesblake on 10/24/17. // #include @@ -9,10 +9,13 @@ #include "game_state.h" -using namespace std; using namespace rapidjson; +using namespace std; -game_state::game_state(const Document& doc) { +// Construct an initial game state from a JSON doc +game_state::game_state(const Document& doc) : max_rank(1) { + // Construct tableau piles + assert(doc.HasMember("tableau piles")); const Value& json_tab_piles = doc["tableau piles"]; assert(json_tab_piles.IsArray()); @@ -20,29 +23,95 @@ game_state::game_state(const Document& doc) { vector tableau_pile; for (auto& json_card : json_tab.GetArray()) { - tableau_pile.push_back(card(json_card.GetString())); + card c(json_card.GetString()); + if (c.get_rank() > max_rank) max_rank = c.get_rank(); + tableau_pile.push_back(c); } tableau_piles.push_back(tableau_pile); } + + // Assign hole card + assert(doc.HasMember("hole card")); + const Value& json_h_card = doc["hole card"]; + assert(json_h_card.IsString()); + hole_card = json_h_card.GetString(); +} + +vector game_state::get_next_legal_states() const { + vector next; + + // Searches through each column for a top card that can be moved to the hole + bool all_tableaux_empty = true; + for (vector>::size_type i = 0; i < tableau_piles.size(); i++) { + vector tableau_pile = tableau_piles[i]; + + // Ignore empty piles + if (tableau_pile.empty()) { + continue; + } else { + all_tableaux_empty = false; + } + card top_card = tableau_pile.back(); + + // If a card at the top of a tableau pile is adjacent to the hole card, + // move it to the hole and add that state + if (adjacent(top_card, hole_card)) { + game_state s = *this; + s.move_to_hole(i); + next.push_back(s); + } + } + + // If there are no cards left in play, deal solved + solved = all_tableaux_empty; + + return next; +} + +bool game_state::adjacent(const card& a, const card& b) const { + int x = a.get_rank(); + int y = b.get_rank(); + + return x == y + 1 + || x + 1 == y + || (x == 1 && y == max_rank) + || (x == max_rank && y == 1); +} + +void game_state::move_to_hole(int tab_idx) { + hole_card = tableau_piles[tab_idx].back(); + tableau_piles[tab_idx].pop_back(); +} + +bool game_state::is_solved() const { + return solved; } ostream& game_state::print(ostream& stream) const { bool empty_row = false; - int row_idx = 0; + vector::size_type row_idx = 0; while (!empty_row) { empty_row = true; - for (auto tableau_pile : tableau_piles) { + + for (vector tableau_pile : tableau_piles) { if (tableau_pile.size() > row_idx) { empty_row = false; stream << tableau_pile[row_idx]; } stream << "\t"; } + + if (!empty_row) stream << "|"; + if (row_idx == 0) { + stream << " Hole card: " << hole_card; + } + stream << "\n"; row_idx++; } + return stream; } diff --git a/src/main/game_state.h b/src/main/game_state.h index 693b127..3d0d38f 100644 --- a/src/main/game_state.h +++ b/src/main/game_state.h @@ -1,5 +1,5 @@ // -// Created by thecharlesblake on 10/23/17. +// Created by thecharlesblake on 10/24/17. // #ifndef SOLVITAIRE_GAME_STATE_H @@ -10,19 +10,26 @@ #include -#include "card.h +#include "card.h" class game_state { public: game_state(const rapidjson::Document&); - virtual std::vector get_next_legal_states() const = 0; - virtual bool is_solved() const = 0; - virtual std::ostream& print(std::ostream&) const; + std::vector get_next_legal_states() const; + bool is_solved() const; + std::ostream& print(std::ostream&) const; friend std::ostream& operator<< (std::ostream&, const game_state&); -protected: - std::vector> tableau_piles; +private: + void move_to_hole(int); + bool adjacent(const card& a, const card& b) const; + + std::vector > tableau_piles; + int max_rank; + card hole_card; + mutable bool solved; }; + #endif //SOLVITAIRE_GAME_STATE_H diff --git a/src/main/io_utils.cpp b/src/main/io_utils.cpp deleted file mode 100644 index 4239c78..0000000 --- a/src/main/io_utils.cpp +++ /dev/null @@ -1,101 +0,0 @@ -// -// Created by thecharlesblake on 10/21/17. -// - -#include -#include -#include -#include - -#include -#include -#include -#include - -#include "io_utils.h" - -using namespace std; -using namespace rapidjson; -using namespace boost; - -void io_utils::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 io_utils::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 io_utils::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 card\":{\"$ref\":\"#/definitions/card\"}}" - ",\"additionalProperties\":false,\"anyOf\":[{\"required\":[\"tableau" - " piles\"]}]}"; - - bool success = to_json(d, schema_json); - assert(success); -} - -bool io_utils::to_json(rapidjson::Document& d, const char* in) { - d.Parse(in); - return !d.HasParseError(); -} - -bool io_utils::to_json(rapidjson::Document& d, const string in) { - return to_json(d, in.c_str()); -} - -const string io_utils::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/io_utils.h b/src/main/io_utils.h deleted file mode 100644 index 659a0c4..0000000 --- a/src/main/io_utils.h +++ /dev/null @@ -1,27 +0,0 @@ -// -// 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 io_utils { -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_main.cpp b/src/main/legacy_main.cpp deleted file mode 100644 index 76940df..0000000 --- a/src/main/legacy_main.cpp +++ /dev/null @@ -1,121 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include "legacy_card.h" -#include - -#if defined NDEBUG - #define LOG_DEBUG(msg) -#else - #define LOG_DEBUG(msg) BOOST_LOG_TRIVIAL(debug) << msg -#endif -#define LOG_INFO(msg) BOOST_LOG_TRIVIAL(info) << msg -#define LOG_WARNING(msg) BOOST_LOG_TRIVIAL(warning) << msg -#define LOG_ERROR(msg) BOOST_LOG_ERROR(error) << msg - -using namespace std; - -bool search(vector* >, legacy_card* hole); - -int main() -{ - const int topRank = 4; - - vector* > tableaux; - - vector shuffleCards; - for (int r = 1; r <= topRank; r++) { - for (int s = 0; s < 4; s++) { - string suit; - if (s == 0) { - suit = "D"; - } else if (s == 1) { - suit = "S"; - } else if (s == 2) { - suit = "H"; - } else { - suit = "C"; - } - - legacy_card* c = new legacy_card(r, suit); - shuffleCards.push_back(c); - } - } - - auto rng = std::default_random_engine(2); // 3 has solution - std::shuffle(std::begin(shuffleCards), std::end(shuffleCards), rng); - - for (int i = 0; i < topRank * 2; i++) { - vector* tab = new vector(); - for (int j = 0; j < 2; j++) { - int idx = i + (topRank * 2 * j); - if (shuffleCards[idx]->suit == "S" && shuffleCards[idx]->rank == 1) { - continue; - } else { - tab->push_back(shuffleCards[idx]); - } - } - tableaux.push_back(tab); - } - - legacy_card c(2, string("H")); - LOG_DEBUG(c); - - cout << (search(tableaux, new legacy_card(1, "S")) ? "Solution Found" : "No Solution"); - - return 0; -} - -bool search(vector* > tableaux, legacy_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 (auto 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; - } - - legacy_card* topCard = tableau->back(); - if (topCard->rank == hole->rank + 1 || topCard->rank == hole->rank - 1) { - tableau->pop_back(); - - bool success = search(tableaux, topCard); - - if (success) { - return true; - } else { - tableau->push_back(topCard); - } - } - } - - return allTableauxEmpty; -} \ No newline at end of file diff --git a/src/main/log_helper.h b/src/main/log_helper.h index 8e634a7..9ac1351 100644 --- a/src/main/log_helper.h +++ b/src/main/log_helper.h @@ -5,13 +5,15 @@ #ifndef SOLVITAIRE_LOG_HELPER_H #define SOLVITAIRE_LOG_HELPER_H +#include + #if defined NDEBUG - #define LOG_DEBUG(msg) + #define LOG_DEBUG #else - #define LOG_DEBUG(msg) BOOST_LOG_TRIVIAL(debug) << msg + #define LOG_DEBUG clog << "[debug]\n" #endif -#define LOG_INFO(msg) BOOST_LOG_TRIVIAL(info) << msg -#define LOG_WARNING(msg) BOOST_LOG_TRIVIAL(warning) << msg -#define LOG_ERROR(msg) BOOST_LOG_ERROR(error) << msg +#define LOG_INFO(msg) clog << "[info]\n" +#define LOG_WARNING(msg) clog << "[warning]\n" +#define LOG_ERROR(msg) cerr << "[error]\n" #endif //SOLVITAIRE_LOG_HELPER_H diff --git a/src/main/main.cpp b/src/main/main.cpp index 7e9d132..a7e5871 100644 --- a/src/main/main.cpp +++ b/src/main/main.cpp @@ -1,12 +1,13 @@ #include -#include #include #include #include "command_line_helper.h" #include "card.h" -#include "io_utils.h" +#include "deal_parser.h" +#include "game_state.h" +#include "solver.h" using namespace rapidjson; @@ -14,8 +15,6 @@ 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; @@ -23,162 +22,24 @@ int main(int argc, const char* argv[]) { return 1; } - for (auto filename : clh.get_input_files()) { + for (auto input_json : clh.get_input_files()) { try { - Document d; - io_utils::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); - } + // Attempts to read the user's json into a document + Document doc; + deal_parser::parse(doc, input_json); - bool sol = search(tableaux, new card("AS")); + // Creates a game state object from the json, plus a solver + game_state gs(doc); + solver sol(gs); - cout << (sol ? "Solution Found" : "No Solution"); + cout << "Attempting to solve " << input_json << "...\n"; + sol.run(); + cout << sol; - 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()); - }*/ } 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; -} diff --git a/src/main/solver.cpp b/src/main/solver.cpp new file mode 100644 index 0000000..7e7155a --- /dev/null +++ b/src/main/solver.cpp @@ -0,0 +1,68 @@ +// +// Created by thecharlesblake on 10/24/17. +// + +#include +#include +#include + +#include "solver.h" +#include "log_helper.h" +#include "game_state.h" +#include +using namespace std; + +solver::solver(const game_state gs) : root(gs), solution(gs), + solution_found(false) {} + +solver::node::node(const game_state gs) : state(gs) {} + +bool solver::run() { + been_run = true; + + // Iteratively run a depth-first search. Nodes in the frontier are yet to + // be explored + vector frontier; + frontier.push_back(root); + while (!frontier.empty()) { + // Pop the element at the top of the stack + node current = frontier.back(); + frontier.pop_back(); + + LOG_DEBUG << current.state; + + // Create new nodes for each of the children + vector new_children = current.state.get_next_legal_states(); + for (auto it = new_children.rbegin(); it != new_children.rend(); it++) { + node n = current; + n.history.push_back(n.state); + n.state = *it; + + frontier.push_back(n); + } + + if (current.state.is_solved()) { + solution = current; + solution_found = true; + break; + } + } + + return solution_found; +} + +std::ostream& operator<< (std::ostream& stream, const solver& sol) { + if (sol.solution_found) { + stream << "Solution:\n"; + for (auto state : sol.solution.history) { + stream << state << "\n"; + } + stream << sol.solution.state << "\n"; + + } else if (sol.been_run) { + stream << "No Possible Solution\n"; + } else { + stream << "Solver has not been run yet\n"; + } + return stream; +} \ No newline at end of file diff --git a/src/main/solver.h b/src/main/solver.h new file mode 100644 index 0000000..0520cc7 --- /dev/null +++ b/src/main/solver.h @@ -0,0 +1,36 @@ +// +// Created by thecharlesblake on 10/24/17. +// + +#ifndef SOLVITAIRE_SOLVER_H +#define SOLVITAIRE_SOLVER_H + +#include +#include + +#include + +#include "game_state.h" + +class solver { +public: + solver(const game_state); + bool run(); + + friend std::ostream& operator<< (std::ostream&, const solver&); + +private: + struct node { + node(const game_state); + std::vector history; + game_state state; + }; + + const node root; + bool been_run; + node solution; + bool solution_found; +}; + + +#endif //SOLVITAIRE_SOLVER_H -- cgit v1.2.1 From a841befd0ecdc0b469d6bc46b209f259358778ec Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Fri, 27 Oct 2017 23:25:50 +0100 Subject: Add random game generation to bh --- src/main/card.cpp | 42 ++++++++++++++++++++++++++++++++++------ src/main/card.h | 3 ++- src/main/command_line_helper.cpp | 11 +++++++---- src/main/command_line_helper.h | 4 ++-- src/main/game_state.cpp | 35 +++++++++++++++++++++++++++++++++ src/main/game_state.h | 1 + src/main/log_helper.h | 8 ++++---- src/main/main.cpp | 10 ++++++++++ src/main/solver.cpp | 2 +- 9 files changed, 98 insertions(+), 18 deletions(-) (limited to 'src') diff --git a/src/main/card.cpp b/src/main/card.cpp index 45de1d1..0b7c0b8 100644 --- a/src/main/card.cpp +++ b/src/main/card.cpp @@ -2,29 +2,53 @@ // Created by thecharlesblake on 10/11/17. // -#include #include +#include #include "card.h" using namespace std; -card::card() {} +card::card() : rank(-1), suit(-1) {} -card::card(const char* c) { +card::card(int r, int s) : rank(r), suit(s) {} + +card::card(const char* c) : rank(-1), suit(-1) { + bool letter = false; switch(tolower(c[0])) { case 'a': rank = 1; + letter = true; break; case 'j': rank = 11; + letter = true; break; case 'q': rank = 12; + letter = true; break; case 'k': rank = 13; + letter = true; break; - default: rank = c[0] - '0'; + default: rank = atoi(c); + } + + char s; + if (rank >= 10 && !letter) { + s = c[2]; + } else { + s = c[1]; } - suit = c[1]; + s = tolower(s); + + if (s == 's') { + suit = 0; + } else if (s == 'h') { + suit = 1; + } else if (s == 'd') { + suit = 2; + } else if (s == 'c') { + suit = 3; + } } int card::get_rank() const { @@ -32,7 +56,13 @@ int card::get_rank() const { } char card::get_suit() const { - return suit; + switch (suit) { + case 0: return 'S'; + case 1: return 'H'; + case 2: return 'D'; + case 3: return 'C'; + default: return 'X'; + } } std::ostream & operator<<(std::ostream & s, card const & c) { diff --git a/src/main/card.h b/src/main/card.h index 2d9635f..13507f0 100644 --- a/src/main/card.h +++ b/src/main/card.h @@ -10,13 +10,14 @@ class card { public: card(); + card(int, int); card(const char*); int get_rank() const; char get_suit() const; private: int rank; - char suit; + int suit; }; std::ostream & operator<<(std::ostream &, card const &); diff --git a/src/main/command_line_helper.cpp b/src/main/command_line_helper.cpp index 9e389fd..67bf7ff 100644 --- a/src/main/command_line_helper.cpp +++ b/src/main/command_line_helper.cpp @@ -15,13 +15,14 @@ using namespace std; namespace po = boost::program_options; command_line_helper::command_line_helper() - : main_options("options") { + : main_options("options"), random_deal(-1) { main_options.add_options() ("help", "produce help message") ("type", po::value(), "specify the type of the solitaire game to be solved (REQUIRED)") - ("random", "create and solve a random solitaire deal"); + ("random", po::value(), "create and solve a random solitaire " + "deal based on a seed"); po::options_description hidden_options("Hidden options"); hidden_options.add_options() @@ -55,7 +56,9 @@ bool command_line_helper::parse(int argc, const char* argv[]) { solitaire_type = vm["type"].as(); } - random_deal = vm.count("random"); + if (vm.count("random")) { + random_deal = vm["random"].as(); + } // Handle logic error scenarios return assess_errors(); @@ -114,7 +117,7 @@ const string command_line_helper::get_solitaire_type() { return solitaire_type; } -bool command_line_helper::get_random_deal() { +int command_line_helper::get_random_deal() { return random_deal; } diff --git a/src/main/command_line_helper.h b/src/main/command_line_helper.h index 3454bfb..97c522a 100644 --- a/src/main/command_line_helper.h +++ b/src/main/command_line_helper.h @@ -13,7 +13,7 @@ public: bool parse(int argc, const char* argv[]); const std::vector get_input_files(); const std::string get_solitaire_type(); - bool get_random_deal(); + int get_random_deal(); bool get_help(); private: bool assess_errors(); @@ -28,7 +28,7 @@ private: std::vector input_files; std::string solitaire_type; - bool random_deal; + int random_deal; bool help; }; diff --git a/src/main/game_state.cpp b/src/main/game_state.cpp index 0e4f210..527f080 100644 --- a/src/main/game_state.cpp +++ b/src/main/game_state.cpp @@ -4,6 +4,9 @@ #include #include +#include +#include +#include #include @@ -38,6 +41,38 @@ game_state::game_state(const Document& doc) : max_rank(1) { hole_card = json_h_card.GetString(); } +// Construct an initial game state from a seed +game_state::game_state(int seed) : max_rank(7) { + int start = 1; // Ignore the first (hole) card + int end = max_rank * 4; + + // Create a vector of pointers to ints from [start, end) + vector v; + for (int i = start; i < end; i++) { + v.push_back(new int(i)); + } + + // Randomly shuffle the pointers + auto rng = std::default_random_engine(seed); + std::shuffle(std::begin(v), std::end(v), rng); + + for (vector::size_type i = 0; i < v.size(); i++) { + int r = ((*v[i]) % max_rank); + int s = (*v[i]) / max_rank; + + // Add the randomly generated card to the tableau piles + if (i % 3 == 0) tableau_piles.push_back(vector()); + tableau_piles[i / 3].push_back(card(r + 1, s)); + } + + hole_card = "AS"; + + // release memory + for (int i = start; i < max_rank; i++) { + delete v[i]; + } +} + vector game_state::get_next_legal_states() const { vector next; diff --git a/src/main/game_state.h b/src/main/game_state.h index 3d0d38f..d7a396f 100644 --- a/src/main/game_state.h +++ b/src/main/game_state.h @@ -15,6 +15,7 @@ class game_state { public: game_state(const rapidjson::Document&); + game_state(int seed); std::vector get_next_legal_states() const; bool is_solved() const; std::ostream& print(std::ostream&) const; diff --git a/src/main/log_helper.h b/src/main/log_helper.h index 9ac1351..889a5ae 100644 --- a/src/main/log_helper.h +++ b/src/main/log_helper.h @@ -10,10 +10,10 @@ #if defined NDEBUG #define LOG_DEBUG #else - #define LOG_DEBUG clog << "[debug]\n" + #define LOG_DEBUG(msg) clog << "[debug]\n" << msg #endif -#define LOG_INFO(msg) clog << "[info]\n" -#define LOG_WARNING(msg) clog << "[warning]\n" -#define LOG_ERROR(msg) cerr << "[error]\n" +#define LOG_INFO(msg) clog << "[info]\n" << msg +#define LOG_WARNING(msg) clog << "[warning]\n" << msg +#define LOG_ERROR(msg) cerr << "[error]\n" << msg #endif //SOLVITAIRE_LOG_HELPER_H diff --git a/src/main/main.cpp b/src/main/main.cpp index a7e5871..ae5e00b 100644 --- a/src/main/main.cpp +++ b/src/main/main.cpp @@ -22,6 +22,16 @@ int main(int argc, const char* argv[]) { return 1; } + int seed = clh.get_random_deal(); + if (seed >= 0) { + game_state gs(seed); + solver sol(gs); + + cout << "Attempting to solve with seed: " << seed << "...\n"; + sol.run(); + cout << sol; + } + for (auto input_json : clh.get_input_files()) { try { // Attempts to read the user's json into a document diff --git a/src/main/solver.cpp b/src/main/solver.cpp index 7e7155a..396a9dc 100644 --- a/src/main/solver.cpp +++ b/src/main/solver.cpp @@ -29,7 +29,7 @@ bool solver::run() { node current = frontier.back(); frontier.pop_back(); - LOG_DEBUG << current.state; + LOG_DEBUG(current.state); // Create new nodes for each of the children vector new_children = current.state.get_next_legal_states(); -- cgit v1.2.1 From 70522b28586ba117ff9e1e27c8f4b183f8414fd1 Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Sat, 28 Oct 2017 10:13:13 +0100 Subject: Add simple and regular bh types --- src/main/command_line_helper.cpp | 21 +++++++++++++++++++-- src/main/command_line_helper.h | 1 + src/main/game_state.cpp | 12 +++++++++--- src/main/game_state.h | 6 ++++-- src/main/main.cpp | 4 ++-- 5 files changed, 35 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/main/command_line_helper.cpp b/src/main/command_line_helper.cpp index 67bf7ff..fdf6c9c 100644 --- a/src/main/command_line_helper.cpp +++ b/src/main/command_line_helper.cpp @@ -75,18 +75,35 @@ bool command_line_helper::assess_errors() { return false; } - if (random_deal && !input_files.empty()) { + bool valid_sol_type = assess_sol_type(); + if (!valid_sol_type) return false; + + if (random_deal >= 0 && !input_files.empty()) { print_rand_plus_input_err(); return false; } - if (input_files.empty() && !random_deal) { + if (input_files.empty() && random_deal >= 0) { print_no_input_error(); return false; } return true; } +bool command_line_helper::assess_sol_type() { + if (solitaire_type == "black-hole") { + return true; + } else if (solitaire_type == "simple-black-hole") { + return true; + } else { + cerr << "Error: Solitaire type is not valid: " << solitaire_type + << "\nValid solitaire types are: 'black-hole' and " + "'simple-black-hole'"; + print_help(); + return false; + } +} + void command_line_helper::print_help() { cout << "Usage: solvitaire [options] input-file1 input-file2 ...\n" << main_options << "\n"; diff --git a/src/main/command_line_helper.h b/src/main/command_line_helper.h index 97c522a..5694830 100644 --- a/src/main/command_line_helper.h +++ b/src/main/command_line_helper.h @@ -17,6 +17,7 @@ public: bool get_help(); private: bool assess_errors(); + bool assess_sol_type(); void print_help(); void print_no_input_error(); void print_no_sol_type_error(); diff --git a/src/main/game_state.cpp b/src/main/game_state.cpp index 527f080..ef9db97 100644 --- a/src/main/game_state.cpp +++ b/src/main/game_state.cpp @@ -16,7 +16,10 @@ using namespace rapidjson; using namespace std; // Construct an initial game state from a JSON doc -game_state::game_state(const Document& doc) : max_rank(1) { +game_state::game_state(const Document& doc, string sol_type) + : max_rank(1) { + simple = sol_type == "simple-black-hole"; + // Construct tableau piles assert(doc.HasMember("tableau piles")); const Value& json_tab_piles = doc["tableau piles"]; @@ -42,7 +45,10 @@ game_state::game_state(const Document& doc) : max_rank(1) { } // Construct an initial game state from a seed -game_state::game_state(int seed) : max_rank(7) { +game_state::game_state(int seed, string sol_type) { + simple = sol_type == "simple-black-hole"; + max_rank = simple ? 7 : 13; + int start = 1; // Ignore the first (hole) card int end = max_rank * 4; @@ -51,7 +57,7 @@ game_state::game_state(int seed) : max_rank(7) { for (int i = start; i < end; i++) { v.push_back(new int(i)); } - + // Randomly shuffle the pointers auto rng = std::default_random_engine(seed); std::shuffle(std::begin(v), std::end(v), rng); diff --git a/src/main/game_state.h b/src/main/game_state.h index d7a396f..ff92247 100644 --- a/src/main/game_state.h +++ b/src/main/game_state.h @@ -7,6 +7,7 @@ #include #include +#include #include @@ -14,8 +15,8 @@ class game_state { public: - game_state(const rapidjson::Document&); - game_state(int seed); + game_state(const rapidjson::Document&, std::string); + game_state(int seed, std::string); std::vector get_next_legal_states() const; bool is_solved() const; std::ostream& print(std::ostream&) const; @@ -25,6 +26,7 @@ public: private: void move_to_hole(int); bool adjacent(const card& a, const card& b) const; + bool simple; std::vector > tableau_piles; int max_rank; diff --git a/src/main/main.cpp b/src/main/main.cpp index ae5e00b..cc1df9f 100644 --- a/src/main/main.cpp +++ b/src/main/main.cpp @@ -24,7 +24,7 @@ int main(int argc, const char* argv[]) { int seed = clh.get_random_deal(); if (seed >= 0) { - game_state gs(seed); + game_state gs(seed, clh.get_solitaire_type()); solver sol(gs); cout << "Attempting to solve with seed: " << seed << "...\n"; @@ -39,7 +39,7 @@ int main(int argc, const char* argv[]) { deal_parser::parse(doc, input_json); // Creates a game state object from the json, plus a solver - game_state gs(doc); + game_state gs(doc, clh.get_solitaire_type()); solver sol(gs); cout << "Attempting to solve " << input_json << "...\n"; -- cgit v1.2.1