From bba8775ce7c63783303240470d4a4b8404c9498b Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Sat, 11 Nov 2017 11:36:27 +0000 Subject: Add src file directory structure --- src/main/card.cpp | 90 ------- src/main/card.h | 27 --- src/main/command_line_helper.cpp | 146 ------------ src/main/command_line_helper.h | 36 --- src/main/deal_parser.cpp | 96 -------- src/main/deal_parser.h | 27 --- src/main/game/card.cpp | 90 +++++++ src/main/game/card.h | 27 +++ src/main/game/game_state.cpp | 325 ++++++++++++++++++++++++++ src/main/game/game_state.h | 55 +++++ src/main/game/pile.cpp | 128 ++++++++++ src/main/game/pile.h | 49 ++++ src/main/game/sol_rules.cpp | 116 +++++++++ src/main/game/sol_rules.h | 60 +++++ src/main/game_state.cpp | 325 -------------------------- src/main/game_state.h | 55 ----- src/main/input-output/command_line_helper.cpp | 146 ++++++++++++ src/main/input-output/command_line_helper.h | 36 +++ src/main/input-output/deal_parser.cpp | 96 ++++++++ src/main/input-output/deal_parser.h | 27 +++ src/main/input-output/log_helper.h | 19 ++ src/main/log_helper.h | 19 -- src/main/main.cpp | 8 +- src/main/pile.cpp | 128 ---------- src/main/pile.h | 49 ---- src/main/sol_rules.cpp | 116 --------- src/main/sol_rules.h | 60 ----- src/main/solver.cpp | 82 ------- src/main/solver.h | 39 ---- src/main/solver/solver.cpp | 82 +++++++ src/main/solver/solver.h | 39 ++++ 31 files changed, 1299 insertions(+), 1299 deletions(-) delete mode 100644 src/main/card.cpp delete mode 100644 src/main/card.h delete mode 100644 src/main/command_line_helper.cpp delete mode 100644 src/main/command_line_helper.h delete mode 100644 src/main/deal_parser.cpp delete mode 100644 src/main/deal_parser.h create mode 100644 src/main/game/card.cpp create mode 100644 src/main/game/card.h create mode 100644 src/main/game/game_state.cpp create mode 100644 src/main/game/game_state.h create mode 100644 src/main/game/pile.cpp create mode 100644 src/main/game/pile.h create mode 100644 src/main/game/sol_rules.cpp create mode 100644 src/main/game/sol_rules.h delete mode 100644 src/main/game_state.cpp delete mode 100644 src/main/game_state.h create mode 100644 src/main/input-output/command_line_helper.cpp create mode 100644 src/main/input-output/command_line_helper.h create mode 100644 src/main/input-output/deal_parser.cpp create mode 100644 src/main/input-output/deal_parser.h create mode 100644 src/main/input-output/log_helper.h delete mode 100644 src/main/log_helper.h delete mode 100644 src/main/pile.cpp delete mode 100644 src/main/pile.h delete mode 100644 src/main/sol_rules.cpp delete mode 100644 src/main/sol_rules.h delete mode 100644 src/main/solver.cpp delete mode 100644 src/main/solver.h create mode 100644 src/main/solver/solver.cpp create mode 100644 src/main/solver/solver.h (limited to 'src') diff --git a/src/main/card.cpp b/src/main/card.cpp deleted file mode 100644 index 14ba92d..0000000 --- a/src/main/card.cpp +++ /dev/null @@ -1,90 +0,0 @@ -// -// Created by thecharlesblake on 10/11/17. -// - -#include -#include - -#include "card.h" - -using namespace std; - -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 = atoi(c); - } - - char s; - if (rank >= 10 && !letter) { - s = c[2]; - } else { - s = c[1]; - } - - s = tolower(s); - - if (s == 'c') { - suit = 0; - } else if (s == 'd') { - suit = 1; - } else if (s == 'h') { - suit = 2; - } else if (s == 's') { - suit = 3; - } -} - -bool operator==(const card& l, const card& r) { - return l.get_rank() == r.get_rank() && l.get_suit() == r.get_suit(); -} - -int card::get_rank() const { - return rank; -} - -char card::get_suit() const { - switch (suit) { - case 0: return 'C'; - case 1: return 'D'; - case 2: return 'H'; - case 3: return 'S'; - default: return 'X'; - } -} - -int card::get_suit_val() const { - return suit; -} - -std::ostream & operator<<(std::ostream & s, card const & c) { - std::string r; - if (c.get_rank() == 1) { - s << "A"; - } else if (c.get_rank() <= 10) { - s << c.get_rank(); - } else if (c.get_rank() == 11) { - s << "J"; - } else if (c.get_rank() == 12) { - s << "Q"; - } else if (c.get_rank() == 13) { - s << "K"; - } - - s << c.get_suit(); - return s; -} \ No newline at end of file diff --git a/src/main/card.h b/src/main/card.h deleted file mode 100644 index ef6ae58..0000000 --- a/src/main/card.h +++ /dev/null @@ -1,27 +0,0 @@ -// -// Created by thecharlesblake on 10/11/17. -// - -#ifndef SOLITAIRE_PIP_CARD_H -#define SOLITAIRE_PIP_CARD_H - -#include - -class card { -public: - card(int, int); - card(const char*); - int get_rank() const; - char get_suit() const; - int get_suit_val() const; - -private: - int rank; - int suit; -}; - -std::ostream & operator<<(std::ostream &, card const &); -bool operator==(const card&, const card&); - - -#endif //SOLITAIRE_PIP_CARD_H diff --git a/src/main/command_line_helper.cpp b/src/main/command_line_helper.cpp deleted file mode 100644 index 71eaf43..0000000 --- a/src/main/command_line_helper.cpp +++ /dev/null @@ -1,146 +0,0 @@ -// -// Created by thecharlesblake on 10/16/17. -// - -#include -#include -#include - -#include - -#include "command_line_helper.h" -#include "sol_rules.h" - -using namespace std; - -namespace po = boost::program_options; - -command_line_helper::command_line_helper() - : 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", po::value(), "create and solve a random solitaire " - "deal based on a seed"); - - 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(); - } - - if (vm.count("random")) { - random_deal = vm["random"].as(); - } - - // 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; - } - - bool valid_sol_type = assess_sol_type(); - if (!valid_sol_type) return false; - - if (random_deal != -1 && !input_files.empty()) { - print_rand_plus_input_err(); - return false; - } - - if (input_files.empty() && random_deal == -1) { - print_no_input_error(); - return false; - } - return true; -} - -bool command_line_helper::assess_sol_type() { - if (find(sol_rules::valid_sol_strs.begin(), - sol_rules::valid_sol_strs.end(), - solitaire_type) != sol_rules::valid_sol_strs.end()) { - return true; - } else { - cerr << "Error: Solitaire type is not valid: " << solitaire_type - << "\nValid solitaire types are: "; - copy(begin(sol_rules::valid_sol_strs), end(sol_rules::valid_sol_strs), - ostream_iterator(cerr, ", ")); - cerr << "\n"; - print_help(); - return false; - } -} - -void command_line_helper::print_help() { - cerr << "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; -} - -int command_line_helper::get_random_deal() { - return random_deal; -} - -bool command_line_helper::get_help() { - return help; -} diff --git a/src/main/command_line_helper.h b/src/main/command_line_helper.h deleted file mode 100644 index 8cc67cb..0000000 --- a/src/main/command_line_helper.h +++ /dev/null @@ -1,36 +0,0 @@ -// -// Created by thecharlesblake on 10/16/17. -// - -#ifndef SOLVITAIRE_COMMAND_LINE_HELPER_H -#define SOLVITAIRE_COMMAND_LINE_HELPER_H - -#include - -class command_line_helper { -public: - command_line_helper(); - bool parse(int argc, const char* argv[]); - const std::vector get_input_files(); - const std::string get_solitaire_type(); - int get_random_deal(); - 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(); - 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; - - std::vector input_files; - std::string solitaire_type; - int random_deal; - bool help; -}; - -#endif //SOLVITAIRE_COMMAND_LINE_HELPER_H diff --git a/src/main/deal_parser.cpp b/src/main/deal_parser.cpp deleted file mode 100644 index 8a9cef1..0000000 --- a/src/main/deal_parser.cpp +++ /dev/null @@ -1,96 +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 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 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/card.cpp b/src/main/game/card.cpp new file mode 100644 index 0000000..14ba92d --- /dev/null +++ b/src/main/game/card.cpp @@ -0,0 +1,90 @@ +// +// Created by thecharlesblake on 10/11/17. +// + +#include +#include + +#include "card.h" + +using namespace std; + +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 = atoi(c); + } + + char s; + if (rank >= 10 && !letter) { + s = c[2]; + } else { + s = c[1]; + } + + s = tolower(s); + + if (s == 'c') { + suit = 0; + } else if (s == 'd') { + suit = 1; + } else if (s == 'h') { + suit = 2; + } else if (s == 's') { + suit = 3; + } +} + +bool operator==(const card& l, const card& r) { + return l.get_rank() == r.get_rank() && l.get_suit() == r.get_suit(); +} + +int card::get_rank() const { + return rank; +} + +char card::get_suit() const { + switch (suit) { + case 0: return 'C'; + case 1: return 'D'; + case 2: return 'H'; + case 3: return 'S'; + default: return 'X'; + } +} + +int card::get_suit_val() const { + return suit; +} + +std::ostream & operator<<(std::ostream & s, card const & c) { + std::string r; + if (c.get_rank() == 1) { + s << "A"; + } else if (c.get_rank() <= 10) { + s << c.get_rank(); + } else if (c.get_rank() == 11) { + s << "J"; + } else if (c.get_rank() == 12) { + s << "Q"; + } else if (c.get_rank() == 13) { + s << "K"; + } + + s << c.get_suit(); + return s; +} \ No newline at end of file diff --git a/src/main/game/card.h b/src/main/game/card.h new file mode 100644 index 0000000..ef6ae58 --- /dev/null +++ b/src/main/game/card.h @@ -0,0 +1,27 @@ +// +// Created by thecharlesblake on 10/11/17. +// + +#ifndef SOLITAIRE_PIP_CARD_H +#define SOLITAIRE_PIP_CARD_H + +#include + +class card { +public: + card(int, int); + card(const char*); + int get_rank() const; + char get_suit() const; + int get_suit_val() const; + +private: + int rank; + int suit; +}; + +std::ostream & operator<<(std::ostream &, card const &); +bool operator==(const card&, const card&); + + +#endif //SOLITAIRE_PIP_CARD_H diff --git a/src/main/game/game_state.cpp b/src/main/game/game_state.cpp new file mode 100644 index 0000000..2d6ae2b --- /dev/null +++ b/src/main/game/game_state.cpp @@ -0,0 +1,325 @@ +// +// Created by thecharlesblake on 10/24/17. +// + +#include +#include +#include +#include +#include +#include + +#include + +#include "game_state.h" +#include "pile.h" + +using namespace rapidjson; +using namespace std; + +typedef sol_rules::build_order ord; +typedef sol_rules::build_policy pol; + +// Construct an initial game state from a JSON doc +game_state::game_state(const Document& doc) + : hole(false, ord::BOTH, pol::ANY_SUIT, true, rules.max_rank), + rules("simple-black-hole") { + // Construct tableau piles + assert(doc.HasMember("tableau piles")); + const Value& json_tab_piles = doc["tableau piles"]; + assert(json_tab_piles.IsArray()); + + int max_rank = 1; + for (auto& json_tab : json_tab_piles.GetArray()) { + pile tableau_pile(true, rules.build_ord, pol::ANY_SUIT, false); + + for (auto& json_card : json_tab.GetArray()) { + card c(json_card.GetString()); + if (c.get_rank() > max_rank) max_rank = c.get_rank(); + tableau_pile.place(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.place(json_h_card.GetString()); +} + +// Construct an initial game state from a seed +game_state::game_state(int seed, const sol_rules& s_rules) + : rules(s_rules) { + + vector deck = shuffled_deck(seed, rules.max_rank); + + // If there is a hole, move the ace of spades to it + if (rules.hole) { + deck.erase(find(begin(deck), end(deck), card("AS"))); + hole = pile(false, ord::BOTH, pol::ANY_SUIT, true, rules.max_rank); + hole.place("AS"); + } + + unsigned int deckCardsUsed = 0; + + // If there is a stock, deal to it and set up a waste pile too + if (rules.stock_size > 0) { + stock = pile(true, ord::NO_BUILD, pol::ANY_SUIT, false); + waste = pile(true, ord::NO_BUILD, pol::ANY_SUIT, false); + + for (unsigned int i = 0; i < rules.stock_size; i++) { + stock.place(deck[i + deckCardsUsed]); + } + deckCardsUsed += rules.stock_size; + } + + // If there is a reserve, deal to it + if (rules.reserve_size > 0) { + reserve = pile(true, ord::NO_BUILD, pol::ANY_SUIT, false); + + for (unsigned int i = 0; i < rules.reserve_size; i++) { + reserve.place(deck[i + deckCardsUsed]); + } + deckCardsUsed += rules.reserve_size; + } + + + // Deal to the tableau piles (row-by-row) + vector::size_type remainingCards = deck.size() - deckCardsUsed; + for (vector::size_type i = 0; i < remainingCards; i++) { + card c = deck[i + deckCardsUsed]; + + // For the first row we must create all the tableau pile vectors + if (i / rules.tableau_pile_count == 0) { + pile p(true, rules.build_ord, pol::ANY_SUIT, false); + tableau_piles.push_back(p); + } + + // Add the randomly generated card to the tableau piles + tableau_piles[i % rules.tableau_pile_count].place(c); + } + deckCardsUsed += remainingCards; + assert(deckCardsUsed == deck.size()); + + // If there are foundation piles, create the relevant pile vectors + if (rules.foundations) { + for (int i = 0; i < 4; i++) { + pile p(true, ord::ASCENDING, pol(i), false); + foundations.push_back(p); + } + } + + // If there are cell piles, create the relevant cell vectors + if (rules.cells > 0) { + for (unsigned int i = 0; i < rules.cells; i++) { + pile p(true, ord::SINGLE_CARD, pol::ANY_SUIT, false); + cells.push_back(p); + } + } +} + +// Generate a randomly ordered vector of cards +vector game_state::shuffled_deck(int seed, int max_rank = 13) { + vector v; + for (int i = 0; i < max_rank * 4; 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); + + vector deck; + for (int *i : v) { + int r = ((*i) % max_rank) + 1; + int s = (*i) / max_rank; + + deck.push_back(card(r, s)); + } + + // release memory + for (int i = 0; i < max_rank * 4; i++) { + delete v[i]; + } + + return deck; +} + +vector game_state::get_next_legal_states() { + // Generates vectors of references to all the piles from which + // cards can be removed, and to which they can be added + vector can_remove; + vector can_add; + + for (vector::size_type i = 0; i < tableau_piles.size(); i++) { + can_remove.push_back(&tableau_piles[i]); + if (rules.build_ord != ord::NO_BUILD) { + can_add.push_back(&tableau_piles[i]); + } + } + if (rules.reserve_size > 0) { + can_remove.push_back(&reserve); + } + if (rules.foundations) { + for (vector::size_type i = 0; i < foundations.size(); i++) { + can_remove.push_back(&foundations[i]); + can_add.push_back(&foundations[i]); + } + } + for (vector::size_type i = 0; i < cells.size(); i++) { + can_remove.push_back(&cells[i]); + can_add.push_back(&cells[i]); + } + if (rules.stock_size > 0) { + can_remove.push_back(&waste); + } + if (rules.hole) { + can_add.push_back(&hole); + } + + // The next legal states + vector next; + + // Moving from and to the 'can remove' and 'can add' piles + for (pile *rem_pile : can_remove) { + if (rem_pile->empty()) continue; + + for (pile *add_pile : can_add) { + if (add_pile != rem_pile + && add_pile->can_place(rem_pile->top_card())) { + + move(rem_pile, add_pile); // remove + game_state s = *this; + next.push_back(s); + move(add_pile, rem_pile); // restore + } + } + } + + // Dealing from the stock to the waste + if (!stock.empty()) { + move(&stock, &waste); + game_state s = *this; + next.push_back(s); + move(&waste, &stock); + } + + return next; +} + + +bool game_state::is_solved() const { + for (auto p : foundations) { + if (p.size() != rules.max_rank) { + return false; + } + } + + if (rules.hole && hole.size() != rules.max_rank * 4) { + return false; + } + return true; +} + +ostream& game_state::print(ostream& stream) const { + if (rules.foundations) { + print_header(stream, "Foundations"); + print_foundations(stream); + } + if (rules.cells) { + print_header(stream, "Cells"); + print_cells(stream); + } + if (rules.reserve_size > 0) { + print_header(stream, "Reserve"); + print_pile(stream, reserve); + } + if (rules.tableau_pile_count > 0) { + print_header(stream, "Tableau Piles"); + print_tableau_piles(stream); + } + if (rules.stock_size > 0) { + print_header(stream, "Stock"); + print_pile(stream, stock); + print_header(stream, "Waste"); + print_pile(stream, waste); + } + if (rules.hole) { + print_header(stream, "Hole Card"); + print_hole(stream); + } + return stream << "===================================\n"; +} + +void game_state::print_header(ostream& stream, const char* header) const { + stream << "--- " << header << " "; + int pad = 20 - strlen(header); + for (int i = 0; i < pad; i++) { + stream << '-'; + } + stream << "\n"; +} + +void game_state::print_foundations(ostream& stream) const { + stream << foundations[0] << "\t" + << foundations[1] << "\t" + << foundations[2] << "\t" + << foundations[3] << "\n"; +} + +void game_state::print_cells(ostream& stream) const { + for (pile cell : cells) { + if (cells.empty()) { + stream << "[]" << "\t"; + } else { + stream << cells[0] << "\t"; + } + } + stream << "\n"; +} + +void game_state::print_pile(ostream& stream, const pile &p) const { + if (p.empty()) { + stream << "[]\n"; + } else { + for (unsigned int i = 0; i < p.size(); i++) { + stream << p[i] << "\n"; + } + } +} + +void game_state::print_tableau_piles(ostream& stream) const { + bool empty_row = false; + vector::size_type row_idx = 0; + + while (!empty_row) { + empty_row = true; + + for (pile tableau_pile : tableau_piles) { + if (tableau_pile.size() > row_idx) { + empty_row = false; + stream << tableau_pile[row_idx]; + } + stream << "\t"; + } + + stream << "\n"; + row_idx++; + } +} + +void game_state::print_hole(ostream& stream) const { + stream << hole.top_card() << "\n"; +} + +bool operator==(const game_state& a, const game_state& b) { + return a.tableau_piles == b.tableau_piles + && a.foundations == b.foundations + && a.hole == b.hole; +} + +ostream& operator <<(ostream& stream, const game_state& gs) { + return gs.print(stream); +} \ No newline at end of file diff --git a/src/main/game/game_state.h b/src/main/game/game_state.h new file mode 100644 index 0000000..424c678 --- /dev/null +++ b/src/main/game/game_state.h @@ -0,0 +1,55 @@ +// +// Created by thecharlesblake on 10/24/17. +// + +#ifndef SOLVITAIRE_GAME_STATE_H +#define SOLVITAIRE_GAME_STATE_H + +#include +#include +#include + +#include + +#include "card.h" +#include "sol_rules.h" +#include "pile.h" + +class game_state { +public: + // Create a game state representation from a JSON doc + game_state(const rapidjson::Document&); + // Do the same from a 'rules' object + game_state(int seed, const sol_rules&); + + std::vector get_next_legal_states(); + // NOTE: will only be evaluated after get_next_legal_states() is called + bool is_solved() const; + + std::ostream& print(std::ostream&) const; + + friend bool operator==(const game_state&, const game_state&); + friend std::ostream& operator<< (std::ostream&, const game_state&); + +private: + static std::vector shuffled_deck(int, int); + + void print_header(std::ostream&, const char*) const; + void print_foundations(std::ostream&) const; + void print_cells(std::ostream&) const; + void print_tableau_piles(std::ostream&) const; + void print_hole(std::ostream&) const; + void print_pile(std::ostream&, const pile&) const; + + std::vector tableau_piles; + std::vector cells; + std::vector foundations; + pile waste; + pile reserve; + pile stock; + pile hole; + sol_rules rules; +}; + + +#endif //SOLVITAIRE_GAME_STATE_H diff --git a/src/main/game/pile.cpp b/src/main/game/pile.cpp new file mode 100644 index 0000000..344e56c --- /dev/null +++ b/src/main/game/pile.cpp @@ -0,0 +1,128 @@ +// +// Created by thecharlesblake on 10/28/17. +// + +#include +#include + +#include "pile.h" + +using namespace std; + +pile::pile() { + set_max_rank(13); +} + +pile::pile(bool r, sol_rules::build_order bo, sol_rules::build_policy bp, bool l, + int mr) { + set_remove(r); + set_build_order(bo); + set_build_policy(bp); + set_loops(l); + set_max_rank(mr); +} + +void pile::set_remove(bool r) {remove = r;} +void pile::set_loops(bool l) {build_order_loops = l;} +void pile::set_max_rank(int mr) {max_rank = mr;} +void pile::set_build_order(sol_rules::build_order bo) {build_order = bo;} +void pile::set_build_policy(sol_rules::build_policy bp) {build_policy = bp;} + +bool pile::can_place(const card& c) const { + typedef sol_rules::build_order ord; + typedef sol_rules::build_policy pol; + + if (build_order == ord::NO_BUILD) { + return false; + } else if (build_order == ord::SINGLE_CARD) { + return empty(); + } + + if (empty()) { + if (sol_rules::is_suit(build_policy)) { + return c.get_suit_val() == sol_rules::suit_val(build_policy) + && c.get_rank() == 1; + } else { + return true; + } + } + + card top_c = top_card(); + + // Check suit + if (build_policy == pol::SAME_SUIT && c.get_suit_val() + != top_c.get_suit_val()) { + return false; + } + if (sol_rules::is_suit(build_policy) && c.get_suit_val() + != sol_rules::suit_val(build_policy)) { + return false; + } + + int tc_r = top_c.get_rank(); + int comp_r = c.get_rank(); + + if (build_order == ord::ASCENDING) { + return one_lt(tc_r, comp_r); + } else if (build_order == ord::DESCENDING) { + return one_lt(comp_r, tc_r); + } else if (build_order == ord::BOTH) { + return one_lt(tc_r, comp_r) || one_lt(comp_r, tc_r); + } else { + return false; + } +} + +bool pile::one_lt(int a, int b) const { + return (a == b - 1) || (build_order_loops && a == max_rank && b == 1); +} + +void pile::place(const card& c) { + pile_vec.push_back(c); +} + +card pile::top_card() const { + return pile_vec.back(); +} + +card pile::take() { + card c = top_card(); + pile_vec.pop_back(); + return c; +} + +bool pile::can_remove() const { + return remove; +} + +bool pile::empty() const { + return pile_vec.empty(); +} + +unsigned long pile::size() const { + return pile_vec.size(); +} + +card& pile::operator[] (vector::size_type i) { + return pile_vec[i]; +} +card pile::operator[] (vector::size_type i) const { + return pile_vec[i]; +} + + +void move(pile *a, pile *b) { + b->place(a->take()); +} + +bool operator==(const pile& a, const pile& b) { + return a.pile_vec == b.pile_vec; +} + +ostream & operator<<(ostream & stream, pile const & p) { + if (p.empty()) { + return stream << "[]"; + } else { + return stream << p.top_card(); + } +} diff --git a/src/main/game/pile.h b/src/main/game/pile.h new file mode 100644 index 0000000..4bc6e71 --- /dev/null +++ b/src/main/game/pile.h @@ -0,0 +1,49 @@ +// +// Created by thecharlesblake on 10/28/17. +// + +#ifndef SOLVITAIRE_PILE_H +#define SOLVITAIRE_PILE_H + +#include + +#include "sol_rules.h" +#include "card.h" + +class pile { +public: + pile(); + pile(bool, sol_rules::build_order, sol_rules::build_policy, bool, int m = 13); + + void set_remove(bool); + void set_loops(bool); + void set_max_rank(int); + void set_build_order(sol_rules::build_order); + void set_build_policy(sol_rules::build_policy); + + bool can_place(const card&) const; + void place(const card&); + card take(); + card top_card() const; + bool can_remove() const; + bool empty() const; + unsigned long size() const; + card& operator[] (std::vector::size_type); + card operator[] (std::vector::size_type) const; + + friend bool operator==(const pile&, const pile&); + friend std::ostream & operator<<(std::ostream &, pile const &); +private: + std::vector pile_vec; + bool remove; + bool build_order_loops; + int max_rank; + sol_rules::build_order build_order; + sol_rules::build_policy build_policy; + bool one_lt(int, int) const; +}; + +void move(pile*, pile*); + + +#endif //SOLVITAIRE_PILE_H diff --git a/src/main/game/sol_rules.cpp b/src/main/game/sol_rules.cpp new file mode 100644 index 0000000..f47cf44 --- /dev/null +++ b/src/main/game/sol_rules.cpp @@ -0,0 +1,116 @@ +// +// Created by thecharlesblake on 10/28/17. +// + +#include +#include +#include +#include + +#include "sol_rules.h" + +using namespace std; + +// Static + +typedef sol_rules::build_policy pol; + +vector sol_rules::valid_sol_strs = { + "black-hole", + "simple-black-hole", + "spanish-patience", + "simple-spanish-patience", + "free-cell", + "simple-free-cell", + "canfield", + "simple-canfield" +}; + +bool sol_rules::is_suit(pol bp) { + return suit_val(bp) != -1; +} +int sol_rules::suit_val(pol bp) { + switch (bp) { + case pol::CLUBS: return 0; + case pol::DIAMONDS: return 1; + case pol::HEARTS: return 2; + case pol::SPADES: return 3; + default: return -1; + } +} + +// Non-static + +sol_rules::sol_rules(std::string sol_type) { + valid_sol vs = valid_sol_enum(sol_type); + + // Default game values + build_ord = build_order::DESCENDING; + build_pol = build_policy::ANY_SUIT; + max_rank = 13; + hole = false; + foundations = true; + cells = 0; + reserve_size = 0; + stock_size = 0; + + // Game-specific values + switch(vs) { + case valid_sol::BLACK_HOLE: + tableau_pile_count = 17; + build_ord = build_order::NO_BUILD; + hole = true; + foundations = false; + cells = 0; + break; + case valid_sol::SIMPLE_BLACK_HOLE: + tableau_pile_count = 9; + build_ord = build_order::NO_BUILD; + max_rank = 7; + hole = true; + foundations = false; + break; + case valid_sol::SPANISH_PATIENCE: + tableau_pile_count = 13; + break; + case valid_sol::SIMPLE_SPANISH_PATIENCE: + tableau_pile_count = 5; + max_rank = 5; + break; + case valid_sol::FREE_CELL: + tableau_pile_count = 8; + cells = 4; + break; + case valid_sol::SIMPLE_FREE_CELL: + tableau_pile_count = 3; + max_rank = 3; + cells = 1; + break; + case valid_sol::CANFIELD: + tableau_pile_count = 4; + build_pol = build_policy::RED_BLACK; + reserve_size = 14; + stock_size = 34; + break; + case valid_sol::SIMPLE_CANFIELD: + tableau_pile_count = 3; + build_pol = build_policy::RED_BLACK; + max_rank = 3; + reserve_size = 3; + stock_size = 6; + break; + default: + assert(false); + } +} + +sol_rules::valid_sol sol_rules::valid_sol_enum(const std::string& s) { + auto sol_type_it = + find(valid_sol_strs.begin(), valid_sol_strs.end(), s); + + assert(sol_type_it != valid_sol_strs.end()); + + long idx = sol_type_it - valid_sol_strs.begin(); + + return sol_rules::valid_sol(idx); +} \ No newline at end of file diff --git a/src/main/game/sol_rules.h b/src/main/game/sol_rules.h new file mode 100644 index 0000000..44b83bb --- /dev/null +++ b/src/main/game/sol_rules.h @@ -0,0 +1,60 @@ +// +// Created by thecharlesblake on 10/28/17. +// + +#ifndef SOLVITAIRE_SOL_RULES_H +#define SOLVITAIRE_SOL_RULES_H + +#include +#include + +class sol_rules { +public: + enum class valid_sol { + BLACK_HOLE, + SIMPLE_BLACK_HOLE, + SPANISH_PATIENCE, + SIMPLE_SPANISH_PATIENCE, + FREE_CELL, + SIMPLE_FREE_CELL, + CANFIELD, + SIMPLE_CANFIELD + }; + enum class build_order { + NO_BUILD, + DESCENDING, + ASCENDING, + BOTH, + SINGLE_CARD + }; + enum class build_policy { + CLUBS, + DIAMONDS, + HEARTS, + SPADES, + ANY_SUIT, + SAME_SUIT, + RED_BLACK + }; + + static std::vector valid_sol_strs; + static bool is_suit(build_policy); + static int suit_val(build_policy); + + sol_rules(std::string); + + unsigned int tableau_pile_count; + build_order build_ord; + build_policy build_pol; + unsigned int max_rank; + bool hole; + bool foundations; + unsigned int cells; + unsigned int reserve_size; + unsigned int stock_size; + +private: + static valid_sol valid_sol_enum(const std::string&); +}; + +#endif //SOLVITAIRE_SOL_RULES_H diff --git a/src/main/game_state.cpp b/src/main/game_state.cpp deleted file mode 100644 index 2d6ae2b..0000000 --- a/src/main/game_state.cpp +++ /dev/null @@ -1,325 +0,0 @@ -// -// Created by thecharlesblake on 10/24/17. -// - -#include -#include -#include -#include -#include -#include - -#include - -#include "game_state.h" -#include "pile.h" - -using namespace rapidjson; -using namespace std; - -typedef sol_rules::build_order ord; -typedef sol_rules::build_policy pol; - -// Construct an initial game state from a JSON doc -game_state::game_state(const Document& doc) - : hole(false, ord::BOTH, pol::ANY_SUIT, true, rules.max_rank), - rules("simple-black-hole") { - // Construct tableau piles - assert(doc.HasMember("tableau piles")); - const Value& json_tab_piles = doc["tableau piles"]; - assert(json_tab_piles.IsArray()); - - int max_rank = 1; - for (auto& json_tab : json_tab_piles.GetArray()) { - pile tableau_pile(true, rules.build_ord, pol::ANY_SUIT, false); - - for (auto& json_card : json_tab.GetArray()) { - card c(json_card.GetString()); - if (c.get_rank() > max_rank) max_rank = c.get_rank(); - tableau_pile.place(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.place(json_h_card.GetString()); -} - -// Construct an initial game state from a seed -game_state::game_state(int seed, const sol_rules& s_rules) - : rules(s_rules) { - - vector deck = shuffled_deck(seed, rules.max_rank); - - // If there is a hole, move the ace of spades to it - if (rules.hole) { - deck.erase(find(begin(deck), end(deck), card("AS"))); - hole = pile(false, ord::BOTH, pol::ANY_SUIT, true, rules.max_rank); - hole.place("AS"); - } - - unsigned int deckCardsUsed = 0; - - // If there is a stock, deal to it and set up a waste pile too - if (rules.stock_size > 0) { - stock = pile(true, ord::NO_BUILD, pol::ANY_SUIT, false); - waste = pile(true, ord::NO_BUILD, pol::ANY_SUIT, false); - - for (unsigned int i = 0; i < rules.stock_size; i++) { - stock.place(deck[i + deckCardsUsed]); - } - deckCardsUsed += rules.stock_size; - } - - // If there is a reserve, deal to it - if (rules.reserve_size > 0) { - reserve = pile(true, ord::NO_BUILD, pol::ANY_SUIT, false); - - for (unsigned int i = 0; i < rules.reserve_size; i++) { - reserve.place(deck[i + deckCardsUsed]); - } - deckCardsUsed += rules.reserve_size; - } - - - // Deal to the tableau piles (row-by-row) - vector::size_type remainingCards = deck.size() - deckCardsUsed; - for (vector::size_type i = 0; i < remainingCards; i++) { - card c = deck[i + deckCardsUsed]; - - // For the first row we must create all the tableau pile vectors - if (i / rules.tableau_pile_count == 0) { - pile p(true, rules.build_ord, pol::ANY_SUIT, false); - tableau_piles.push_back(p); - } - - // Add the randomly generated card to the tableau piles - tableau_piles[i % rules.tableau_pile_count].place(c); - } - deckCardsUsed += remainingCards; - assert(deckCardsUsed == deck.size()); - - // If there are foundation piles, create the relevant pile vectors - if (rules.foundations) { - for (int i = 0; i < 4; i++) { - pile p(true, ord::ASCENDING, pol(i), false); - foundations.push_back(p); - } - } - - // If there are cell piles, create the relevant cell vectors - if (rules.cells > 0) { - for (unsigned int i = 0; i < rules.cells; i++) { - pile p(true, ord::SINGLE_CARD, pol::ANY_SUIT, false); - cells.push_back(p); - } - } -} - -// Generate a randomly ordered vector of cards -vector game_state::shuffled_deck(int seed, int max_rank = 13) { - vector v; - for (int i = 0; i < max_rank * 4; 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); - - vector deck; - for (int *i : v) { - int r = ((*i) % max_rank) + 1; - int s = (*i) / max_rank; - - deck.push_back(card(r, s)); - } - - // release memory - for (int i = 0; i < max_rank * 4; i++) { - delete v[i]; - } - - return deck; -} - -vector game_state::get_next_legal_states() { - // Generates vectors of references to all the piles from which - // cards can be removed, and to which they can be added - vector can_remove; - vector can_add; - - for (vector::size_type i = 0; i < tableau_piles.size(); i++) { - can_remove.push_back(&tableau_piles[i]); - if (rules.build_ord != ord::NO_BUILD) { - can_add.push_back(&tableau_piles[i]); - } - } - if (rules.reserve_size > 0) { - can_remove.push_back(&reserve); - } - if (rules.foundations) { - for (vector::size_type i = 0; i < foundations.size(); i++) { - can_remove.push_back(&foundations[i]); - can_add.push_back(&foundations[i]); - } - } - for (vector::size_type i = 0; i < cells.size(); i++) { - can_remove.push_back(&cells[i]); - can_add.push_back(&cells[i]); - } - if (rules.stock_size > 0) { - can_remove.push_back(&waste); - } - if (rules.hole) { - can_add.push_back(&hole); - } - - // The next legal states - vector next; - - // Moving from and to the 'can remove' and 'can add' piles - for (pile *rem_pile : can_remove) { - if (rem_pile->empty()) continue; - - for (pile *add_pile : can_add) { - if (add_pile != rem_pile - && add_pile->can_place(rem_pile->top_card())) { - - move(rem_pile, add_pile); // remove - game_state s = *this; - next.push_back(s); - move(add_pile, rem_pile); // restore - } - } - } - - // Dealing from the stock to the waste - if (!stock.empty()) { - move(&stock, &waste); - game_state s = *this; - next.push_back(s); - move(&waste, &stock); - } - - return next; -} - - -bool game_state::is_solved() const { - for (auto p : foundations) { - if (p.size() != rules.max_rank) { - return false; - } - } - - if (rules.hole && hole.size() != rules.max_rank * 4) { - return false; - } - return true; -} - -ostream& game_state::print(ostream& stream) const { - if (rules.foundations) { - print_header(stream, "Foundations"); - print_foundations(stream); - } - if (rules.cells) { - print_header(stream, "Cells"); - print_cells(stream); - } - if (rules.reserve_size > 0) { - print_header(stream, "Reserve"); - print_pile(stream, reserve); - } - if (rules.tableau_pile_count > 0) { - print_header(stream, "Tableau Piles"); - print_tableau_piles(stream); - } - if (rules.stock_size > 0) { - print_header(stream, "Stock"); - print_pile(stream, stock); - print_header(stream, "Waste"); - print_pile(stream, waste); - } - if (rules.hole) { - print_header(stream, "Hole Card"); - print_hole(stream); - } - return stream << "===================================\n"; -} - -void game_state::print_header(ostream& stream, const char* header) const { - stream << "--- " << header << " "; - int pad = 20 - strlen(header); - for (int i = 0; i < pad; i++) { - stream << '-'; - } - stream << "\n"; -} - -void game_state::print_foundations(ostream& stream) const { - stream << foundations[0] << "\t" - << foundations[1] << "\t" - << foundations[2] << "\t" - << foundations[3] << "\n"; -} - -void game_state::print_cells(ostream& stream) const { - for (pile cell : cells) { - if (cells.empty()) { - stream << "[]" << "\t"; - } else { - stream << cells[0] << "\t"; - } - } - stream << "\n"; -} - -void game_state::print_pile(ostream& stream, const pile &p) const { - if (p.empty()) { - stream << "[]\n"; - } else { - for (unsigned int i = 0; i < p.size(); i++) { - stream << p[i] << "\n"; - } - } -} - -void game_state::print_tableau_piles(ostream& stream) const { - bool empty_row = false; - vector::size_type row_idx = 0; - - while (!empty_row) { - empty_row = true; - - for (pile tableau_pile : tableau_piles) { - if (tableau_pile.size() > row_idx) { - empty_row = false; - stream << tableau_pile[row_idx]; - } - stream << "\t"; - } - - stream << "\n"; - row_idx++; - } -} - -void game_state::print_hole(ostream& stream) const { - stream << hole.top_card() << "\n"; -} - -bool operator==(const game_state& a, const game_state& b) { - return a.tableau_piles == b.tableau_piles - && a.foundations == b.foundations - && a.hole == b.hole; -} - -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 deleted file mode 100644 index 424c678..0000000 --- a/src/main/game_state.h +++ /dev/null @@ -1,55 +0,0 @@ -// -// Created by thecharlesblake on 10/24/17. -// - -#ifndef SOLVITAIRE_GAME_STATE_H -#define SOLVITAIRE_GAME_STATE_H - -#include -#include -#include - -#include - -#include "card.h" -#include "sol_rules.h" -#include "pile.h" - -class game_state { -public: - // Create a game state representation from a JSON doc - game_state(const rapidjson::Document&); - // Do the same from a 'rules' object - game_state(int seed, const sol_rules&); - - std::vector get_next_legal_states(); - // NOTE: will only be evaluated after get_next_legal_states() is called - bool is_solved() const; - - std::ostream& print(std::ostream&) const; - - friend bool operator==(const game_state&, const game_state&); - friend std::ostream& operator<< (std::ostream&, const game_state&); - -private: - static std::vector shuffled_deck(int, int); - - void print_header(std::ostream&, const char*) const; - void print_foundations(std::ostream&) const; - void print_cells(std::ostream&) const; - void print_tableau_piles(std::ostream&) const; - void print_hole(std::ostream&) const; - void print_pile(std::ostream&, const pile&) const; - - std::vector tableau_piles; - std::vector cells; - std::vector foundations; - pile waste; - pile reserve; - pile stock; - pile hole; - sol_rules rules; -}; - - -#endif //SOLVITAIRE_GAME_STATE_H diff --git a/src/main/input-output/command_line_helper.cpp b/src/main/input-output/command_line_helper.cpp new file mode 100644 index 0000000..b31761a --- /dev/null +++ b/src/main/input-output/command_line_helper.cpp @@ -0,0 +1,146 @@ +// +// Created by thecharlesblake on 10/16/17. +// + +#include +#include +#include + +#include + +#include "command_line_helper.h" +#include "game/sol_rules.h" + +using namespace std; + +namespace po = boost::program_options; + +command_line_helper::command_line_helper() + : 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", po::value(), "create and solve a random solitaire " + "deal based on a seed"); + + 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(); + } + + if (vm.count("random")) { + random_deal = vm["random"].as(); + } + + // 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; + } + + bool valid_sol_type = assess_sol_type(); + if (!valid_sol_type) return false; + + if (random_deal != -1 && !input_files.empty()) { + print_rand_plus_input_err(); + return false; + } + + if (input_files.empty() && random_deal == -1) { + print_no_input_error(); + return false; + } + return true; +} + +bool command_line_helper::assess_sol_type() { + if (find(sol_rules::valid_sol_strs.begin(), + sol_rules::valid_sol_strs.end(), + solitaire_type) != sol_rules::valid_sol_strs.end()) { + return true; + } else { + cerr << "Error: Solitaire type is not valid: " << solitaire_type + << "\nValid solitaire types are: "; + copy(begin(sol_rules::valid_sol_strs), end(sol_rules::valid_sol_strs), + ostream_iterator(cerr, ", ")); + cerr << "\n"; + print_help(); + return false; + } +} + +void command_line_helper::print_help() { + cerr << "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; +} + +int command_line_helper::get_random_deal() { + return random_deal; +} + +bool command_line_helper::get_help() { + return help; +} diff --git a/src/main/input-output/command_line_helper.h b/src/main/input-output/command_line_helper.h new file mode 100644 index 0000000..8cc67cb --- /dev/null +++ b/src/main/input-output/command_line_helper.h @@ -0,0 +1,36 @@ +// +// Created by thecharlesblake on 10/16/17. +// + +#ifndef SOLVITAIRE_COMMAND_LINE_HELPER_H +#define SOLVITAIRE_COMMAND_LINE_HELPER_H + +#include + +class command_line_helper { +public: + command_line_helper(); + bool parse(int argc, const char* argv[]); + const std::vector get_input_files(); + const std::string get_solitaire_type(); + int get_random_deal(); + 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(); + 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; + + std::vector input_files; + std::string solitaire_type; + int random_deal; + bool help; +}; + +#endif //SOLVITAIRE_COMMAND_LINE_HELPER_H diff --git a/src/main/input-output/deal_parser.cpp b/src/main/input-output/deal_parser.cpp new file mode 100644 index 0000000..8a9cef1 --- /dev/null +++ b/src/main/input-output/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/input-output/deal_parser.h b/src/main/input-output/deal_parser.h new file mode 100644 index 0000000..60eb8fb --- /dev/null +++ b/src/main/input-output/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 "game/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/input-output/log_helper.h b/src/main/input-output/log_helper.h new file mode 100644 index 0000000..889a5ae --- /dev/null +++ b/src/main/input-output/log_helper.h @@ -0,0 +1,19 @@ +// +// Created by thecharlesblake on 10/16/17. +// + +#ifndef SOLVITAIRE_LOG_HELPER_H +#define SOLVITAIRE_LOG_HELPER_H + +#include + +#if defined NDEBUG + #define LOG_DEBUG +#else + #define LOG_DEBUG(msg) clog << "[debug]\n" << msg +#endif +#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/log_helper.h b/src/main/log_helper.h deleted file mode 100644 index 889a5ae..0000000 --- a/src/main/log_helper.h +++ /dev/null @@ -1,19 +0,0 @@ -// -// Created by thecharlesblake on 10/16/17. -// - -#ifndef SOLVITAIRE_LOG_HELPER_H -#define SOLVITAIRE_LOG_HELPER_H - -#include - -#if defined NDEBUG - #define LOG_DEBUG -#else - #define LOG_DEBUG(msg) clog << "[debug]\n" << msg -#endif -#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 5e11537..7a0d390 100644 --- a/src/main/main.cpp +++ b/src/main/main.cpp @@ -3,10 +3,10 @@ #include #include -#include "command_line_helper.h" -#include "deal_parser.h" -#include "game_state.h" -#include "solver.h" +#include "input-output/command_line_helper.h" +#include "input-output/deal_parser.h" +#include "game/game_state.h" +#include "solver/solver.h" using namespace rapidjson; diff --git a/src/main/pile.cpp b/src/main/pile.cpp deleted file mode 100644 index 344e56c..0000000 --- a/src/main/pile.cpp +++ /dev/null @@ -1,128 +0,0 @@ -// -// Created by thecharlesblake on 10/28/17. -// - -#include -#include - -#include "pile.h" - -using namespace std; - -pile::pile() { - set_max_rank(13); -} - -pile::pile(bool r, sol_rules::build_order bo, sol_rules::build_policy bp, bool l, - int mr) { - set_remove(r); - set_build_order(bo); - set_build_policy(bp); - set_loops(l); - set_max_rank(mr); -} - -void pile::set_remove(bool r) {remove = r;} -void pile::set_loops(bool l) {build_order_loops = l;} -void pile::set_max_rank(int mr) {max_rank = mr;} -void pile::set_build_order(sol_rules::build_order bo) {build_order = bo;} -void pile::set_build_policy(sol_rules::build_policy bp) {build_policy = bp;} - -bool pile::can_place(const card& c) const { - typedef sol_rules::build_order ord; - typedef sol_rules::build_policy pol; - - if (build_order == ord::NO_BUILD) { - return false; - } else if (build_order == ord::SINGLE_CARD) { - return empty(); - } - - if (empty()) { - if (sol_rules::is_suit(build_policy)) { - return c.get_suit_val() == sol_rules::suit_val(build_policy) - && c.get_rank() == 1; - } else { - return true; - } - } - - card top_c = top_card(); - - // Check suit - if (build_policy == pol::SAME_SUIT && c.get_suit_val() - != top_c.get_suit_val()) { - return false; - } - if (sol_rules::is_suit(build_policy) && c.get_suit_val() - != sol_rules::suit_val(build_policy)) { - return false; - } - - int tc_r = top_c.get_rank(); - int comp_r = c.get_rank(); - - if (build_order == ord::ASCENDING) { - return one_lt(tc_r, comp_r); - } else if (build_order == ord::DESCENDING) { - return one_lt(comp_r, tc_r); - } else if (build_order == ord::BOTH) { - return one_lt(tc_r, comp_r) || one_lt(comp_r, tc_r); - } else { - return false; - } -} - -bool pile::one_lt(int a, int b) const { - return (a == b - 1) || (build_order_loops && a == max_rank && b == 1); -} - -void pile::place(const card& c) { - pile_vec.push_back(c); -} - -card pile::top_card() const { - return pile_vec.back(); -} - -card pile::take() { - card c = top_card(); - pile_vec.pop_back(); - return c; -} - -bool pile::can_remove() const { - return remove; -} - -bool pile::empty() const { - return pile_vec.empty(); -} - -unsigned long pile::size() const { - return pile_vec.size(); -} - -card& pile::operator[] (vector::size_type i) { - return pile_vec[i]; -} -card pile::operator[] (vector::size_type i) const { - return pile_vec[i]; -} - - -void move(pile *a, pile *b) { - b->place(a->take()); -} - -bool operator==(const pile& a, const pile& b) { - return a.pile_vec == b.pile_vec; -} - -ostream & operator<<(ostream & stream, pile const & p) { - if (p.empty()) { - return stream << "[]"; - } else { - return stream << p.top_card(); - } -} diff --git a/src/main/pile.h b/src/main/pile.h deleted file mode 100644 index 4bc6e71..0000000 --- a/src/main/pile.h +++ /dev/null @@ -1,49 +0,0 @@ -// -// Created by thecharlesblake on 10/28/17. -// - -#ifndef SOLVITAIRE_PILE_H -#define SOLVITAIRE_PILE_H - -#include - -#include "sol_rules.h" -#include "card.h" - -class pile { -public: - pile(); - pile(bool, sol_rules::build_order, sol_rules::build_policy, bool, int m = 13); - - void set_remove(bool); - void set_loops(bool); - void set_max_rank(int); - void set_build_order(sol_rules::build_order); - void set_build_policy(sol_rules::build_policy); - - bool can_place(const card&) const; - void place(const card&); - card take(); - card top_card() const; - bool can_remove() const; - bool empty() const; - unsigned long size() const; - card& operator[] (std::vector::size_type); - card operator[] (std::vector::size_type) const; - - friend bool operator==(const pile&, const pile&); - friend std::ostream & operator<<(std::ostream &, pile const &); -private: - std::vector pile_vec; - bool remove; - bool build_order_loops; - int max_rank; - sol_rules::build_order build_order; - sol_rules::build_policy build_policy; - bool one_lt(int, int) const; -}; - -void move(pile*, pile*); - - -#endif //SOLVITAIRE_PILE_H diff --git a/src/main/sol_rules.cpp b/src/main/sol_rules.cpp deleted file mode 100644 index f47cf44..0000000 --- a/src/main/sol_rules.cpp +++ /dev/null @@ -1,116 +0,0 @@ -// -// Created by thecharlesblake on 10/28/17. -// - -#include -#include -#include -#include - -#include "sol_rules.h" - -using namespace std; - -// Static - -typedef sol_rules::build_policy pol; - -vector sol_rules::valid_sol_strs = { - "black-hole", - "simple-black-hole", - "spanish-patience", - "simple-spanish-patience", - "free-cell", - "simple-free-cell", - "canfield", - "simple-canfield" -}; - -bool sol_rules::is_suit(pol bp) { - return suit_val(bp) != -1; -} -int sol_rules::suit_val(pol bp) { - switch (bp) { - case pol::CLUBS: return 0; - case pol::DIAMONDS: return 1; - case pol::HEARTS: return 2; - case pol::SPADES: return 3; - default: return -1; - } -} - -// Non-static - -sol_rules::sol_rules(std::string sol_type) { - valid_sol vs = valid_sol_enum(sol_type); - - // Default game values - build_ord = build_order::DESCENDING; - build_pol = build_policy::ANY_SUIT; - max_rank = 13; - hole = false; - foundations = true; - cells = 0; - reserve_size = 0; - stock_size = 0; - - // Game-specific values - switch(vs) { - case valid_sol::BLACK_HOLE: - tableau_pile_count = 17; - build_ord = build_order::NO_BUILD; - hole = true; - foundations = false; - cells = 0; - break; - case valid_sol::SIMPLE_BLACK_HOLE: - tableau_pile_count = 9; - build_ord = build_order::NO_BUILD; - max_rank = 7; - hole = true; - foundations = false; - break; - case valid_sol::SPANISH_PATIENCE: - tableau_pile_count = 13; - break; - case valid_sol::SIMPLE_SPANISH_PATIENCE: - tableau_pile_count = 5; - max_rank = 5; - break; - case valid_sol::FREE_CELL: - tableau_pile_count = 8; - cells = 4; - break; - case valid_sol::SIMPLE_FREE_CELL: - tableau_pile_count = 3; - max_rank = 3; - cells = 1; - break; - case valid_sol::CANFIELD: - tableau_pile_count = 4; - build_pol = build_policy::RED_BLACK; - reserve_size = 14; - stock_size = 34; - break; - case valid_sol::SIMPLE_CANFIELD: - tableau_pile_count = 3; - build_pol = build_policy::RED_BLACK; - max_rank = 3; - reserve_size = 3; - stock_size = 6; - break; - default: - assert(false); - } -} - -sol_rules::valid_sol sol_rules::valid_sol_enum(const std::string& s) { - auto sol_type_it = - find(valid_sol_strs.begin(), valid_sol_strs.end(), s); - - assert(sol_type_it != valid_sol_strs.end()); - - long idx = sol_type_it - valid_sol_strs.begin(); - - return sol_rules::valid_sol(idx); -} \ No newline at end of file diff --git a/src/main/sol_rules.h b/src/main/sol_rules.h deleted file mode 100644 index 44b83bb..0000000 --- a/src/main/sol_rules.h +++ /dev/null @@ -1,60 +0,0 @@ -// -// Created by thecharlesblake on 10/28/17. -// - -#ifndef SOLVITAIRE_SOL_RULES_H -#define SOLVITAIRE_SOL_RULES_H - -#include -#include - -class sol_rules { -public: - enum class valid_sol { - BLACK_HOLE, - SIMPLE_BLACK_HOLE, - SPANISH_PATIENCE, - SIMPLE_SPANISH_PATIENCE, - FREE_CELL, - SIMPLE_FREE_CELL, - CANFIELD, - SIMPLE_CANFIELD - }; - enum class build_order { - NO_BUILD, - DESCENDING, - ASCENDING, - BOTH, - SINGLE_CARD - }; - enum class build_policy { - CLUBS, - DIAMONDS, - HEARTS, - SPADES, - ANY_SUIT, - SAME_SUIT, - RED_BLACK - }; - - static std::vector valid_sol_strs; - static bool is_suit(build_policy); - static int suit_val(build_policy); - - sol_rules(std::string); - - unsigned int tableau_pile_count; - build_order build_ord; - build_policy build_pol; - unsigned int max_rank; - bool hole; - bool foundations; - unsigned int cells; - unsigned int reserve_size; - unsigned int stock_size; - -private: - static valid_sol valid_sol_enum(const std::string&); -}; - -#endif //SOLVITAIRE_SOL_RULES_H diff --git a/src/main/solver.cpp b/src/main/solver.cpp deleted file mode 100644 index 1db92f9..0000000 --- a/src/main/solver.cpp +++ /dev/null @@ -1,82 +0,0 @@ -// -// Created by thecharlesblake on 10/24/17. -// - -#include -#include -#include -#include - -#include "solver.h" -#include "log_helper.h" -#include "game_state.h" -#include -using namespace std; - -solver::solver(const game_state gs, const sol_rules& sr) - : root(gs), rules(sr), solution(gs), solution_found(false), - states_searched(0) {} - -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(); - states_searched++; - - // NOTE: get_next_legal_states() makes the is_solved() function work - if (current.state.is_solved()) { - solution = current; - solution_found = true; - break; - } - - for (auto it = new_children.rbegin(); it != new_children.rend(); it++) { - // If we have seen the state before, ignore it (loop detection)) - if (find(begin(current.history), end(current.history), *it) - != end(current.history)) { - continue; - } - - node n = current; - n.history.push_back(n.state); - n.state = *it; - - frontier.push_back(n); - } - } - - 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 << "\nSolved!\n"; - - } else if (sol.been_run) { - stream << "Deal:\n" << sol.root.state << "\n" - << "No Possible Solution\n"; - } else { - stream << "Solver has not been run yet\n"; - } - stream << "States Searched: " << sol.states_searched << "\n"; - return stream; -} \ No newline at end of file diff --git a/src/main/solver.h b/src/main/solver.h deleted file mode 100644 index 4215989..0000000 --- a/src/main/solver.h +++ /dev/null @@ -1,39 +0,0 @@ -// -// Created by thecharlesblake on 10/24/17. -// - -#ifndef SOLVITAIRE_SOLVER_H -#define SOLVITAIRE_SOLVER_H - -#include -#include - -#include - -#include "game_state.h" -#include "sol_rules.h" - -class solver { -public: - solver(const game_state, const sol_rules&); - 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; - const sol_rules rules; - bool been_run; - node solution; - bool solution_found; - int states_searched; -}; - - -#endif //SOLVITAIRE_SOLVER_H diff --git a/src/main/solver/solver.cpp b/src/main/solver/solver.cpp new file mode 100644 index 0000000..1c03d02 --- /dev/null +++ b/src/main/solver/solver.cpp @@ -0,0 +1,82 @@ +// +// Created by thecharlesblake on 10/24/17. +// + +#include +#include +#include +#include + +#include "solver.h" +#include "input-output/log_helper.h" +#include "game/game_state.h" +#include +using namespace std; + +solver::solver(const game_state gs, const sol_rules& sr) + : root(gs), rules(sr), solution(gs), solution_found(false), + states_searched(0) {} + +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(); + states_searched++; + + // NOTE: get_next_legal_states() makes the is_solved() function work + if (current.state.is_solved()) { + solution = current; + solution_found = true; + break; + } + + for (auto it = new_children.rbegin(); it != new_children.rend(); it++) { + // If we have seen the state before, ignore it (loop detection)) + if (find(begin(current.history), end(current.history), *it) + != end(current.history)) { + continue; + } + + node n = current; + n.history.push_back(n.state); + n.state = *it; + + frontier.push_back(n); + } + } + + 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 << "\nSolved!\n"; + + } else if (sol.been_run) { + stream << "Deal:\n" << sol.root.state << "\n" + << "No Possible Solution\n"; + } else { + stream << "Solver has not been run yet\n"; + } + stream << "States Searched: " << sol.states_searched << "\n"; + return stream; +} \ No newline at end of file diff --git a/src/main/solver/solver.h b/src/main/solver/solver.h new file mode 100644 index 0000000..c1a72d3 --- /dev/null +++ b/src/main/solver/solver.h @@ -0,0 +1,39 @@ +// +// Created by thecharlesblake on 10/24/17. +// + +#ifndef SOLVITAIRE_SOLVER_H +#define SOLVITAIRE_SOLVER_H + +#include +#include + +#include + +#include "game/game_state.h" +#include "game/sol_rules.h" + +class solver { +public: + solver(const game_state, const sol_rules&); + 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; + const sol_rules rules; + bool been_run; + node solution; + bool solution_found; + int states_searched; +}; + + +#endif //SOLVITAIRE_SOLVER_H -- cgit v1.2.1 From 8670a71468d0deb2bcd6d52d27873f9427c42ad9 Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Sat, 11 Nov 2017 11:55:19 +0000 Subject: Refactor main --- src/main/main.cpp | 49 ++++++++++++++++++++++++++++++------------------- 1 file changed, 30 insertions(+), 19 deletions(-) (limited to 'src') diff --git a/src/main/main.cpp b/src/main/main.cpp index 7a0d390..77d5d5b 100644 --- a/src/main/main.cpp +++ b/src/main/main.cpp @@ -14,6 +14,8 @@ using namespace std; namespace po = boost::program_options; +void solve_random_game(int, const sol_rules&); +void solve_input_files(const vector, const sol_rules); void solve_game(const game_state&, const sol_rules&); int main(int argc, const char* argv[]) { @@ -26,31 +28,40 @@ int main(int argc, const char* argv[]) { // Generates the rules of the solitaire from the game type const sol_rules rules(clh.get_solitaire_type()); - int seed = clh.get_random_deal(); - if (seed >= 0) { - cout << "Attempting to solve with seed: " << seed << "...\n"; - game_state gs(seed, rules); - solve_game(gs, rules); + // Retrieves the input files to be solved + const vector input_files = clh.get_input_files(); + + // If there are no input files, solve a random deal based on the + // supplied seed + if (input_files.empty()) { + solve_random_game(clh.get_random_deal(), rules); + } + // Otherwise, solve the input files + else { + solve_input_files(input_files, rules); } - for (auto input_json : clh.get_input_files()) { - try { - // Attempts to read the user's json into a document - Document doc; - deal_parser::parse(doc, input_json); + return 0; +} + +void solve_random_game(int seed, const sol_rules& rules) { + cout << "Attempting to solve with seed: " << seed << "...\n"; + game_state gs(seed, rules); + solve_game(gs, rules); +} - // Creates a game state object from the json, plus a solver - game_state gs(doc); +void solve_input_files(const vector input_files, const sol_rules rules) { + for (const auto &input_json : input_files) { + // Attempts to read the user's json into a document + Document doc; + deal_parser::parse(doc, input_json); - cout << "Attempting to solve " << input_json << "...\n"; - solve_game(gs, rules); + // Creates a game state object from the json, plus a solver + game_state gs(doc); - } catch (runtime_error& e) { - cerr << "Error: " << e.what() << "\n"; - } + cout << "Attempting to solve " << input_json << "...\n"; + solve_game(gs, rules); } - - return 0; } void solve_game(const game_state& gs, const sol_rules& rules) { -- cgit v1.2.1 From 34cc6c6d68728d21d49b639f448030a8c2df58c4 Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Sat, 11 Nov 2017 12:03:35 +0000 Subject: Refactor command line helper --- src/main/input-output/command_line_helper.cpp | 15 +++++++++++++-- src/main/input-output/command_line_helper.h | 1 + 2 files changed, 14 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/main/input-output/command_line_helper.cpp b/src/main/input-output/command_line_helper.cpp index b31761a..2228d51 100644 --- a/src/main/input-output/command_line_helper.cpp +++ b/src/main/input-output/command_line_helper.cpp @@ -16,7 +16,7 @@ using namespace std; namespace po = boost::program_options; command_line_helper::command_line_helper() - : main_options("options"), random_deal(-1) { + : main_options("options") { main_options.add_options() ("help", "produce help message") @@ -35,8 +35,10 @@ command_line_helper::command_line_helper() p.add("input-files", -1); } +// Returns true if we can continue solving the supplied solitaire(s) bool command_line_helper::parse(int argc, const char* argv[]) { po::variables_map vm; + // Attempts to parse cmdln options. Catches basic errors try { store(po::command_line_parser(argc, argv).options(cmdline_options) .positional(p).run(), vm); @@ -45,9 +47,12 @@ bool command_line_helper::parse(int argc, const char* argv[]) { return false; } + // Updates the variables map which the user's options are stored in notify(vm); - help = vm.count("help"); + // Converts the variables map into flags and values + + help = (vm.count("help") != 0); if (vm.count("input-files")) { input_files = vm["input-files"].as>(); @@ -59,6 +64,8 @@ bool command_line_helper::parse(int argc, const char* argv[]) { if (vm.count("random")) { random_deal = vm["random"].as(); + } else { + random_deal = -1; } // Handle logic error scenarios @@ -79,6 +86,8 @@ bool command_line_helper::assess_errors() { bool valid_sol_type = assess_sol_type(); if (!valid_sol_type) return false; + // The user must either supply input files or a random seed + if (random_deal != -1 && !input_files.empty()) { print_rand_plus_input_err(); return false; @@ -91,11 +100,13 @@ bool command_line_helper::assess_errors() { return true; } +// Checks if the supplied solitaire type is in the list of valid solitaires bool command_line_helper::assess_sol_type() { if (find(sol_rules::valid_sol_strs.begin(), sol_rules::valid_sol_strs.end(), solitaire_type) != sol_rules::valid_sol_strs.end()) { return true; + } else { cerr << "Error: Solitaire type is not valid: " << solitaire_type << "\nValid solitaire types are: "; diff --git a/src/main/input-output/command_line_helper.h b/src/main/input-output/command_line_helper.h index 8cc67cb..9cb772b 100644 --- a/src/main/input-output/command_line_helper.h +++ b/src/main/input-output/command_line_helper.h @@ -15,6 +15,7 @@ public: const std::string get_solitaire_type(); int get_random_deal(); bool get_help(); + private: bool assess_errors(); bool assess_sol_type(); -- cgit v1.2.1 From 14f534452ac99913931c0513532dfbad2e277493 Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Sat, 11 Nov 2017 12:20:31 +0000 Subject: Update logging --- src/main/input-output/command_line_helper.cpp | 16 ++++++++-------- src/main/input-output/log_helper.h | 8 ++++---- src/main/main.cpp | 7 +++---- src/main/solver/solver.cpp | 2 +- 4 files changed, 16 insertions(+), 17 deletions(-) (limited to 'src') diff --git a/src/main/input-output/command_line_helper.cpp b/src/main/input-output/command_line_helper.cpp index 2228d51..b66cc39 100644 --- a/src/main/input-output/command_line_helper.cpp +++ b/src/main/input-output/command_line_helper.cpp @@ -4,12 +4,12 @@ #include #include -#include #include #include "command_line_helper.h" #include "game/sol_rules.h" +#include "input-output/log_helper.h" using namespace std; @@ -43,7 +43,7 @@ bool command_line_helper::parse(int argc, const char* argv[]) { store(po::command_line_parser(argc, argv).options(cmdline_options) .positional(p).run(), vm); } catch(po::error& e) { - cerr << "Error: " << e.what() << "\n"; + LOG_ERROR << "Error: " << e.what() << "\n"; return false; } @@ -108,34 +108,34 @@ bool command_line_helper::assess_sol_type() { return true; } else { - cerr << "Error: Solitaire type is not valid: " << solitaire_type + LOG_ERROR << "Error: Solitaire type is not valid: " << solitaire_type << "\nValid solitaire types are: "; copy(begin(sol_rules::valid_sol_strs), end(sol_rules::valid_sol_strs), ostream_iterator(cerr, ", ")); - cerr << "\n"; + LOG_ERROR << "\n"; print_help(); return false; } } void command_line_helper::print_help() { - cerr << "Usage: solvitaire [options] input-file1 input-file2 ...\n" + LOG_ERROR << "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' " + LOG_ERROR << "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"; + LOG_ERROR << "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, " + LOG_ERROR << "Error: User must supply input file(s) or the '--random' option, " "not both\n"; print_help(); } diff --git a/src/main/input-output/log_helper.h b/src/main/input-output/log_helper.h index 889a5ae..441381f 100644 --- a/src/main/input-output/log_helper.h +++ b/src/main/input-output/log_helper.h @@ -10,10 +10,10 @@ #if defined NDEBUG #define LOG_DEBUG #else - #define LOG_DEBUG(msg) clog << "[debug]\n" << msg + #define LOG_DEBUG clog << "[debug]\n" #endif -#define LOG_INFO(msg) clog << "[info]\n" << msg -#define LOG_WARNING(msg) clog << "[warning]\n" << msg -#define LOG_ERROR(msg) cerr << "[error]\n" << msg +#define LOG_INFO clog << "[info] " +#define LOG_WARNING clog << "[warning] " +#define LOG_ERROR cerr << "[ERROR] " #endif //SOLVITAIRE_LOG_HELPER_H diff --git a/src/main/main.cpp b/src/main/main.cpp index 77d5d5b..803b587 100644 --- a/src/main/main.cpp +++ b/src/main/main.cpp @@ -1,5 +1,3 @@ -#include - #include #include @@ -7,6 +5,7 @@ #include "input-output/deal_parser.h" #include "game/game_state.h" #include "solver/solver.h" +#include "input-output/log_helper.h" using namespace rapidjson; @@ -45,7 +44,7 @@ int main(int argc, const char* argv[]) { } void solve_random_game(int seed, const sol_rules& rules) { - cout << "Attempting to solve with seed: " << seed << "...\n"; + LOG_INFO << "Attempting to solve with seed: " << seed << "...\n"; game_state gs(seed, rules); solve_game(gs, rules); } @@ -59,7 +58,7 @@ void solve_input_files(const vector input_files, const sol_rules rules) // Creates a game state object from the json, plus a solver game_state gs(doc); - cout << "Attempting to solve " << input_json << "...\n"; + LOG_INFO << "Attempting to solve " << input_json << "...\n"; solve_game(gs, rules); } } diff --git a/src/main/solver/solver.cpp b/src/main/solver/solver.cpp index 1c03d02..ca60333 100644 --- a/src/main/solver/solver.cpp +++ b/src/main/solver/solver.cpp @@ -31,7 +31,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 df25689ed0d530d3557bc9b5306486ef5d595aa4 Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Sat, 11 Nov 2017 14:51:16 +0000 Subject: refcator card class --- src/main/game/card.cpp | 8 +++++--- src/main/game/card.h | 3 +++ 2 files changed, 8 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/main/game/card.cpp b/src/main/game/card.cpp index 14ba92d..2c7fb58 100644 --- a/src/main/game/card.cpp +++ b/src/main/game/card.cpp @@ -3,12 +3,14 @@ // #include -#include #include "card.h" using namespace std; +// A card can either be created using two int values (rank & suit), or +// using a string (e.g. "AS") + card::card(int r, int s) : rank(r), suit(s) {} card::card(const char* c) : rank(-1), suit(-1) { @@ -26,7 +28,7 @@ card::card(const char* c) : rank(-1), suit(-1) { case 'k': rank = 13; letter = true; break; - default: rank = atoi(c); + default: rank = stoi(c); } char s; @@ -36,7 +38,7 @@ card::card(const char* c) : rank(-1), suit(-1) { s = c[1]; } - s = tolower(s); + s = (char) tolower(s); if (s == 'c') { suit = 0; diff --git a/src/main/game/card.h b/src/main/game/card.h index ef6ae58..d184b45 100644 --- a/src/main/game/card.h +++ b/src/main/game/card.h @@ -6,9 +6,12 @@ #define SOLITAIRE_PIP_CARD_H #include +#include class card { public: + // A card can either be created using two int values (rank & suit), or + // using a string (e.g. "AS") card(int, int); card(const char*); int get_rank() const; -- cgit v1.2.1 From 4b66501286a4e7e87f5a310ff060b5f4ee4c8315 Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Sun, 12 Nov 2017 09:50:25 +0000 Subject: Improve game state gen + run() returns opt --- src/main/solver/solver.cpp | 58 +++++++++++++++++++++++++--------------------- src/main/solver/solver.h | 18 ++++++++------ 2 files changed, 43 insertions(+), 33 deletions(-) (limited to 'src') diff --git a/src/main/solver/solver.cpp b/src/main/solver/solver.cpp index ca60333..160af6f 100644 --- a/src/main/solver/solver.cpp +++ b/src/main/solver/solver.cpp @@ -11,15 +11,29 @@ #include "input-output/log_helper.h" #include "game/game_state.h" #include + using namespace std; +using namespace boost; solver::solver(const game_state gs, const sol_rules& sr) - : root(gs), rules(sr), solution(gs), solution_found(false), + : root(NULL, gs), rules(sr), solution(root), solution_found(false), states_searched(0) {} -solver::node::node(const game_state gs) : state(gs) {} +solver::node::node(const node* parent, const game_state& gs) : + history(solver::node::gen_history(parent)), state(gs) {} + +const vector solver::node::gen_history(const node* parent) { + vector hist; + if (parent != NULL) { + hist = std::vector(parent->history); + hist.push_back(parent->state); + } else { + hist = vector(); + } + return hist; +} -bool solver::run() { +optional solver::run() { been_run = true; // Iteratively run a depth-first search. Nodes in the frontier are yet to @@ -28,10 +42,10 @@ bool solver::run() { frontier.push_back(root); while (!frontier.empty()) { // Pop the element at the top of the stack - node current = frontier.back(); + const 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(); @@ -39,9 +53,7 @@ bool solver::run() { // NOTE: get_next_legal_states() makes the is_solved() function work if (current.state.is_solved()) { - solution = current; - solution_found = true; - break; + return node(current); } for (auto it = new_children.rbegin(); it != new_children.rend(); it++) { @@ -51,32 +63,26 @@ bool solver::run() { continue; } - node n = current; - n.history.push_back(n.state); - n.state = *it; - + const node n(¤t, *it); frontier.push_back(n); } } - return solution_found; + return none; } -std::ostream& operator<< (std::ostream& stream, const solver& sol) { +const solver::node solver::get_root() const { + return root; +} - if (sol.solution_found) { - stream << "Solution:\n"; - for (auto state : sol.solution.history) { - stream << state << "\n"; - } - stream << sol.solution.state << "\nSolved!\n"; +int solver::get_states_searched() const { + return states_searched; +} - } else if (sol.been_run) { - stream << "Deal:\n" << sol.root.state << "\n" - << "No Possible Solution\n"; - } else { - stream << "Solver has not been run yet\n"; +std::ostream& operator<< (std::ostream& stream, const solver::node& solution) { + for (auto state : solution.history) { + stream << state << "\n"; } - stream << "States Searched: " << sol.states_searched << "\n"; + stream << solution.state << "\n"; return stream; } \ No newline at end of file diff --git a/src/main/solver/solver.h b/src/main/solver/solver.h index c1a72d3..6dfccc2 100644 --- a/src/main/solver/solver.h +++ b/src/main/solver/solver.h @@ -15,18 +15,22 @@ class solver { public: - solver(const game_state, const sol_rules&); - bool run(); - - friend std::ostream& operator<< (std::ostream&, const solver&); - -private: struct node { - node(const game_state); + node(const node*, const game_state&); std::vector history; game_state state; + + static const std::vector gen_history(const node* parent); }; + solver(const game_state, const sol_rules&); + boost::optional run(); + const node get_root() const; + int get_states_searched() const; + + friend std::ostream& operator<< (std::ostream&, const solver::node&); + +private: const node root; const sol_rules rules; bool been_run; -- cgit v1.2.1 From 2b6b5d1046c69a43656cc8990426176ad20ed597 Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Sun, 12 Nov 2017 09:51:32 +0000 Subject: Make log macros proper functions --- src/main/input-output/log_helper.h | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/main/input-output/log_helper.h b/src/main/input-output/log_helper.h index 441381f..71cc5f4 100644 --- a/src/main/input-output/log_helper.h +++ b/src/main/input-output/log_helper.h @@ -8,12 +8,12 @@ #include #if defined NDEBUG - #define LOG_DEBUG + #define LOG_DEBUG(msg) #else - #define LOG_DEBUG clog << "[debug]\n" + #define LOG_DEBUG(msg) clog << "[debug]\n" << msg << "\n" #endif -#define LOG_INFO clog << "[info] " -#define LOG_WARNING clog << "[warning] " -#define LOG_ERROR cerr << "[ERROR] " +#define LOG_INFO(msg) clog << "[info] " << msg << "\n" +#define LOG_WARNING clog(msg) << "[warning] " << msg << "\n" +#define LOG_ERROR(msg) cerr << "[ERROR] " << msg << "\n" #endif //SOLVITAIRE_LOG_HELPER_H -- cgit v1.2.1 From b1809820b192fb93e95daa50c5993da0b35fa03d Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Sun, 12 Nov 2017 09:52:23 +0000 Subject: Solution output printing moved to main --- src/main/main.cpp | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/main/main.cpp b/src/main/main.cpp index 803b587..d748c80 100644 --- a/src/main/main.cpp +++ b/src/main/main.cpp @@ -1,4 +1,5 @@ #include +#include #include #include "input-output/command_line_helper.h" @@ -10,6 +11,7 @@ using namespace rapidjson; using namespace std; +using namespace boost; namespace po = boost::program_options; @@ -44,7 +46,7 @@ int main(int argc, const char* argv[]) { } void solve_random_game(int seed, const sol_rules& rules) { - LOG_INFO << "Attempting to solve with seed: " << seed << "...\n"; + LOG_INFO ("Attempting to solve with seed: " << seed << "..."); game_state gs(seed, rules); solve_game(gs, rules); } @@ -58,7 +60,7 @@ void solve_input_files(const vector input_files, const sol_rules rules) // Creates a game state object from the json, plus a solver game_state gs(doc); - LOG_INFO << "Attempting to solve " << input_json << "...\n"; + LOG_INFO ("Attempting to solve " << input_json << "..."); solve_game(gs, rules); } } @@ -66,6 +68,11 @@ void solve_input_files(const vector input_files, const sol_rules rules) void solve_game(const game_state& gs, const sol_rules& rules) { solver sol(gs, rules); - sol.run(); - cout << sol; + optional solution = sol.run(); + if (solution) { + cout << "Solution:\n" << *solution << "States Searched: " + << sol.get_states_searched() << "\n"; + } else { + cout << "Deal:\n" << sol.get_root() << "\nNo Possible Solution\n"; + } } -- cgit v1.2.1 From 6298ad1261c1f398b5f191600ec1efa5cb137a95 Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Sun, 12 Nov 2017 09:53:08 +0000 Subject: Use new logging in command line helper --- src/main/input-output/command_line_helper.cpp | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) (limited to 'src') diff --git a/src/main/input-output/command_line_helper.cpp b/src/main/input-output/command_line_helper.cpp index b66cc39..e61c546 100644 --- a/src/main/input-output/command_line_helper.cpp +++ b/src/main/input-output/command_line_helper.cpp @@ -43,7 +43,7 @@ bool command_line_helper::parse(int argc, const char* argv[]) { store(po::command_line_parser(argc, argv).options(cmdline_options) .positional(p).run(), vm); } catch(po::error& e) { - LOG_ERROR << "Error: " << e.what() << "\n"; + LOG_ERROR ("Error: " << e.what()); return false; } @@ -108,35 +108,35 @@ bool command_line_helper::assess_sol_type() { return true; } else { - LOG_ERROR << "Error: Solitaire type is not valid: " << solitaire_type - << "\nValid solitaire types are: "; + LOG_ERROR ("Error: Solitaire type is not valid: " << solitaire_type + << "\nValid solitaire types are: "); copy(begin(sol_rules::valid_sol_strs), end(sol_rules::valid_sol_strs), ostream_iterator(cerr, ", ")); - LOG_ERROR << "\n"; + cerr << "\n"; print_help(); return false; } } void command_line_helper::print_help() { - LOG_ERROR << "Usage: solvitaire [options] input-file1 input-file2 ...\n" - << main_options << "\n"; + LOG_ERROR ("Usage: solvitaire [options] input-file1 input-file2 ...\n" + << main_options); } void command_line_helper::print_no_input_error() { - LOG_ERROR << "Error: User must supply input file(s) or the '--random' " - "option\n"; + LOG_ERROR ("Error: User must supply input file(s) or the '--random' " + "option"); print_help(); } void command_line_helper::print_no_sol_type_error() { - LOG_ERROR << "Error: User must supply a solitaire type\n"; + LOG_ERROR ("Error: User must supply a solitaire type"); print_help(); } void command_line_helper::print_rand_plus_input_err() { - LOG_ERROR << "Error: User must supply input file(s) or the '--random' option, " - "not both\n"; + LOG_ERROR ("Error: User must supply input file(s) or the '--random' option, " + "not both"); print_help(); } -- cgit v1.2.1 From e52d6f9902023a32058d6563f837a12303c5f909 Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Sun, 12 Nov 2017 09:53:38 +0000 Subject: Remove old style cast from card class --- src/main/game/card.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/main/game/card.cpp b/src/main/game/card.cpp index 2c7fb58..9f7dbdf 100644 --- a/src/main/game/card.cpp +++ b/src/main/game/card.cpp @@ -38,7 +38,7 @@ card::card(const char* c) : rank(-1), suit(-1) { s = c[1]; } - s = (char) tolower(s); + s = static_cast(tolower(s)); if (s == 'c') { suit = 0; -- cgit v1.2.1 From 2953fd4a15675cf0cd59a1a1b589d327e2a74d4c Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Sun, 12 Nov 2017 09:54:17 +0000 Subject: Simplify pile class & make const where possible --- src/main/game/pile.cpp | 26 +++++++------------------- src/main/game/pile.h | 29 +++++++++++++---------------- 2 files changed, 20 insertions(+), 35 deletions(-) (limited to 'src') diff --git a/src/main/game/pile.cpp b/src/main/game/pile.cpp index 344e56c..776c997 100644 --- a/src/main/game/pile.cpp +++ b/src/main/game/pile.cpp @@ -9,24 +9,13 @@ using namespace std; -pile::pile() { - set_max_rank(13); -} - -pile::pile(bool r, sol_rules::build_order bo, sol_rules::build_policy bp, bool l, - int mr) { - set_remove(r); - set_build_order(bo); - set_build_policy(bp); - set_loops(l); - set_max_rank(mr); -} - -void pile::set_remove(bool r) {remove = r;} -void pile::set_loops(bool l) {build_order_loops = l;} -void pile::set_max_rank(int mr) {max_rank = mr;} -void pile::set_build_order(sol_rules::build_order bo) {build_order = bo;} -void pile::set_build_policy(sol_rules::build_policy bp) {build_policy = bp;} +pile::pile(bool r, sol_rules::build_order bo, sol_rules::build_policy bp, + bool l, int mr) : + remove(r), + build_order(bo), + build_policy(bp), + build_order_loops(l), + max_rank(mr) {} bool pile::can_place(const card& c) const { typedef sol_rules::build_order ord; @@ -110,7 +99,6 @@ card pile::operator[] (vector::size_type i) const { return pile_vec[i]; } - void move(pile *a, pile *b) { b->place(a->take()); } diff --git a/src/main/game/pile.h b/src/main/game/pile.h index 4bc6e71..4d2c80d 100644 --- a/src/main/game/pile.h +++ b/src/main/game/pile.h @@ -12,35 +12,32 @@ class pile { public: - pile(); pile(bool, sol_rules::build_order, sol_rules::build_policy, bool, int m = 13); - void set_remove(bool); - void set_loops(bool); - void set_max_rank(int); - void set_build_order(sol_rules::build_order); - void set_build_policy(sol_rules::build_policy); - bool can_place(const card&) const; - void place(const card&); - card take(); - card top_card() const; bool can_remove() const; + card top_card() const; bool empty() const; unsigned long size() const; + + void place(const card&); + card take(); + card& operator[] (std::vector::size_type); card operator[] (std::vector::size_type) const; friend bool operator==(const pile&, const pile&); friend std::ostream & operator<<(std::ostream &, pile const &); private: - std::vector pile_vec; - bool remove; - bool build_order_loops; - int max_rank; - sol_rules::build_order build_order; - sol_rules::build_policy build_policy; bool one_lt(int, int) const; + + std::vector pile_vec; + + const bool remove; + const sol_rules::build_order build_order; + const sol_rules::build_policy build_policy; + const bool build_order_loops; + const int max_rank; }; void move(pile*, pile*); -- cgit v1.2.1 From af1fa0716bbf21ffe6b03694351be85b7457dc2c Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Sun, 12 Nov 2017 09:54:57 +0000 Subject: Init piles in game_state & make get states const --- src/main/game/game_state.cpp | 51 ++++++++++++++++++++++++-------------------- src/main/game/game_state.h | 4 ++-- 2 files changed, 30 insertions(+), 25 deletions(-) (limited to 'src') diff --git a/src/main/game/game_state.cpp b/src/main/game/game_state.cpp index 2d6ae2b..9432239 100644 --- a/src/main/game/game_state.cpp +++ b/src/main/game/game_state.cpp @@ -22,7 +22,10 @@ typedef sol_rules::build_policy pol; // Construct an initial game state from a JSON doc game_state::game_state(const Document& doc) - : hole(false, ord::BOTH, pol::ANY_SUIT, true, rules.max_rank), + : reserve(true, ord::NO_BUILD, pol::ANY_SUIT, false), + stock(true, ord::NO_BUILD, pol::ANY_SUIT, false), + waste(true, ord::NO_BUILD, pol::ANY_SUIT, false), + hole(false, ord::BOTH, pol::ANY_SUIT, true, rules.max_rank), rules("simple-black-hole") { // Construct tableau piles assert(doc.HasMember("tableau piles")); @@ -50,15 +53,18 @@ game_state::game_state(const Document& doc) } // Construct an initial game state from a seed -game_state::game_state(int seed, const sol_rules& s_rules) - : rules(s_rules) { +game_state::game_state(int seed, const sol_rules& s_rules) : + reserve(true, ord::NO_BUILD, pol::ANY_SUIT, false), + stock(true, ord::NO_BUILD, pol::ANY_SUIT, false), + waste(true, ord::NO_BUILD, pol::ANY_SUIT, false), + hole(false, ord::BOTH, pol::ANY_SUIT, true, s_rules.max_rank), + rules(s_rules) { vector deck = shuffled_deck(seed, rules.max_rank); // If there is a hole, move the ace of spades to it if (rules.hole) { deck.erase(find(begin(deck), end(deck), card("AS"))); - hole = pile(false, ord::BOTH, pol::ANY_SUIT, true, rules.max_rank); hole.place("AS"); } @@ -66,9 +72,6 @@ game_state::game_state(int seed, const sol_rules& s_rules) // If there is a stock, deal to it and set up a waste pile too if (rules.stock_size > 0) { - stock = pile(true, ord::NO_BUILD, pol::ANY_SUIT, false); - waste = pile(true, ord::NO_BUILD, pol::ANY_SUIT, false); - for (unsigned int i = 0; i < rules.stock_size; i++) { stock.place(deck[i + deckCardsUsed]); } @@ -77,8 +80,6 @@ game_state::game_state(int seed, const sol_rules& s_rules) // If there is a reserve, deal to it if (rules.reserve_size > 0) { - reserve = pile(true, ord::NO_BUILD, pol::ANY_SUIT, false); - for (unsigned int i = 0; i < rules.reserve_size; i++) { reserve.place(deck[i + deckCardsUsed]); } @@ -147,36 +148,40 @@ vector game_state::shuffled_deck(int seed, int max_rank = 13) { return deck; } -vector game_state::get_next_legal_states() { +vector game_state::get_next_legal_states() const { // Generates vectors of references to all the piles from which // cards can be removed, and to which they can be added vector can_remove; vector can_add; + // A mutable version of the current state, used to create the next legal + // states + game_state mut_state = *this; + for (vector::size_type i = 0; i < tableau_piles.size(); i++) { - can_remove.push_back(&tableau_piles[i]); + can_remove.push_back(&mut_state.tableau_piles[i]); if (rules.build_ord != ord::NO_BUILD) { - can_add.push_back(&tableau_piles[i]); + can_add.push_back(&mut_state.tableau_piles[i]); } } if (rules.reserve_size > 0) { - can_remove.push_back(&reserve); + can_remove.push_back(&mut_state.reserve); } if (rules.foundations) { for (vector::size_type i = 0; i < foundations.size(); i++) { - can_remove.push_back(&foundations[i]); - can_add.push_back(&foundations[i]); + can_remove.push_back(&mut_state.foundations[i]); + can_add.push_back(&mut_state.foundations[i]); } } for (vector::size_type i = 0; i < cells.size(); i++) { - can_remove.push_back(&cells[i]); - can_add.push_back(&cells[i]); + can_remove.push_back(&mut_state.cells[i]); + can_add.push_back(&mut_state.cells[i]); } if (rules.stock_size > 0) { - can_remove.push_back(&waste); + can_remove.push_back(&mut_state.waste); } if (rules.hole) { - can_add.push_back(&hole); + can_add.push_back(&mut_state.hole); } // The next legal states @@ -191,7 +196,7 @@ vector game_state::get_next_legal_states() { && add_pile->can_place(rem_pile->top_card())) { move(rem_pile, add_pile); // remove - game_state s = *this; + game_state s(mut_state); next.push_back(s); move(add_pile, rem_pile); // restore } @@ -200,10 +205,10 @@ vector game_state::get_next_legal_states() { // Dealing from the stock to the waste if (!stock.empty()) { - move(&stock, &waste); - game_state s = *this; + move(&mut_state.stock, &mut_state.waste); + game_state s(mut_state); next.push_back(s); - move(&waste, &stock); + move(&mut_state.waste, &mut_state.stock); } return next; diff --git a/src/main/game/game_state.h b/src/main/game/game_state.h index 424c678..e856056 100644 --- a/src/main/game/game_state.h +++ b/src/main/game/game_state.h @@ -22,7 +22,7 @@ public: // Do the same from a 'rules' object game_state(int seed, const sol_rules&); - std::vector get_next_legal_states(); + std::vector get_next_legal_states() const; // NOTE: will only be evaluated after get_next_legal_states() is called bool is_solved() const; @@ -44,9 +44,9 @@ private: std::vector tableau_piles; std::vector cells; std::vector foundations; - pile waste; pile reserve; pile stock; + pile waste; pile hole; sol_rules rules; }; -- cgit v1.2.1 From dc2e84e3ca0ceda7753f1aaec1e648dbde24e9e3 Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Sun, 12 Nov 2017 10:01:18 +0000 Subject: Tidy up headers for consistency --- src/main/game/card.h | 1 + src/main/game/pile.h | 9 +++++---- src/main/input-output/command_line_helper.h | 1 + 3 files changed, 7 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/main/game/card.h b/src/main/game/card.h index d184b45..1cac344 100644 --- a/src/main/game/card.h +++ b/src/main/game/card.h @@ -14,6 +14,7 @@ public: // using a string (e.g. "AS") card(int, int); card(const char*); + int get_rank() const; char get_suit() const; int get_suit_val() const; diff --git a/src/main/game/pile.h b/src/main/game/pile.h index 4d2c80d..c967cc1 100644 --- a/src/main/game/pile.h +++ b/src/main/game/pile.h @@ -19,25 +19,26 @@ public: card top_card() const; bool empty() const; unsigned long size() const; - + void place(const card&); card take(); - + card& operator[] (std::vector::size_type); card operator[] (std::vector::size_type) const; friend bool operator==(const pile&, const pile&); friend std::ostream & operator<<(std::ostream &, pile const &); + private: bool one_lt(int, int) const; - std::vector pile_vec; - const bool remove; const sol_rules::build_order build_order; const sol_rules::build_policy build_policy; const bool build_order_loops; const int max_rank; + + std::vector pile_vec; }; void move(pile*, pile*); diff --git a/src/main/input-output/command_line_helper.h b/src/main/input-output/command_line_helper.h index 9cb772b..bb2f698 100644 --- a/src/main/input-output/command_line_helper.h +++ b/src/main/input-output/command_line_helper.h @@ -10,6 +10,7 @@ class command_line_helper { public: command_line_helper(); + bool parse(int argc, const char* argv[]); const std::vector get_input_files(); const std::string get_solitaire_type(); -- cgit v1.2.1 From b2173ab5118fb2c5700197ae8b295d1577aca3e9 Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Sun, 12 Nov 2017 10:17:10 +0000 Subject: Clean up sol_rules class --- src/main/game/sol_rules.cpp | 10 ++++++++-- src/main/game/sol_rules.h | 2 +- 2 files changed, 9 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/main/game/sol_rules.cpp b/src/main/game/sol_rules.cpp index f47cf44..df5b939 100644 --- a/src/main/game/sol_rules.cpp +++ b/src/main/game/sol_rules.cpp @@ -11,7 +11,9 @@ using namespace std; -// Static +//////////// +// Static // +//////////// typedef sol_rules::build_policy pol; @@ -39,12 +41,16 @@ int sol_rules::suit_val(pol bp) { } } -// Non-static +//////////////// +// Non-static // +//////////////// sol_rules::sol_rules(std::string sol_type) { valid_sol vs = valid_sol_enum(sol_type); // Default game values + + // tableau_pile_count = no obvious default build_ord = build_order::DESCENDING; build_pol = build_policy::ANY_SUIT; max_rank = 13; diff --git a/src/main/game/sol_rules.h b/src/main/game/sol_rules.h index 44b83bb..b73097d 100644 --- a/src/main/game/sol_rules.h +++ b/src/main/game/sol_rules.h @@ -41,7 +41,7 @@ public: static bool is_suit(build_policy); static int suit_val(build_policy); - sol_rules(std::string); + explicit sol_rules(std::string); unsigned int tableau_pile_count; build_order build_ord; -- cgit v1.2.1 From c651b6894081ba71609249c98f61789ebbe31f0d Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Sun, 12 Nov 2017 10:51:09 +0000 Subject: Add factory to pile class to create std pile types --- src/main/game/game_state.cpp | 18 +++++++----------- src/main/game/game_state.h | 4 ++-- src/main/game/pile.cpp | 38 ++++++++++++++++++++++++++++++++++---- src/main/game/pile.h | 11 ++++++++++- 4 files changed, 53 insertions(+), 18 deletions(-) (limited to 'src') diff --git a/src/main/game/game_state.cpp b/src/main/game/game_state.cpp index 9432239..9d03155 100644 --- a/src/main/game/game_state.cpp +++ b/src/main/game/game_state.cpp @@ -12,7 +12,6 @@ #include #include "game_state.h" -#include "pile.h" using namespace rapidjson; using namespace std; @@ -54,10 +53,10 @@ game_state::game_state(const Document& doc) // Construct an initial game state from a seed game_state::game_state(int seed, const sol_rules& s_rules) : - reserve(true, ord::NO_BUILD, pol::ANY_SUIT, false), - stock(true, ord::NO_BUILD, pol::ANY_SUIT, false), - waste(true, ord::NO_BUILD, pol::ANY_SUIT, false), - hole(false, ord::BOTH, pol::ANY_SUIT, true, s_rules.max_rank), + reserve(pile::reserve_factory()), + stock(pile::stock_factory()), + waste(pile::waste_factory()), + hole(pile::hole_factory(s_rules.max_rank)), rules(s_rules) { vector deck = shuffled_deck(seed, rules.max_rank); @@ -94,8 +93,7 @@ game_state::game_state(int seed, const sol_rules& s_rules) : // For the first row we must create all the tableau pile vectors if (i / rules.tableau_pile_count == 0) { - pile p(true, rules.build_ord, pol::ANY_SUIT, false); - tableau_piles.push_back(p); + tableau_piles.push_back(pile::tableau_factory(rules.build_ord)); } // Add the randomly generated card to the tableau piles @@ -107,16 +105,14 @@ game_state::game_state(int seed, const sol_rules& s_rules) : // If there are foundation piles, create the relevant pile vectors if (rules.foundations) { for (int i = 0; i < 4; i++) { - pile p(true, ord::ASCENDING, pol(i), false); - foundations.push_back(p); + foundations.push_back(pile::foundation_factory(pol(i))); } } // If there are cell piles, create the relevant cell vectors if (rules.cells > 0) { for (unsigned int i = 0; i < rules.cells; i++) { - pile p(true, ord::SINGLE_CARD, pol::ANY_SUIT, false); - cells.push_back(p); + cells.push_back(pile::cell_factory()); } } } diff --git a/src/main/game/game_state.h b/src/main/game/game_state.h index e856056..b985924 100644 --- a/src/main/game/game_state.h +++ b/src/main/game/game_state.h @@ -41,9 +41,9 @@ private: void print_hole(std::ostream&) const; void print_pile(std::ostream&, const pile&) const; - std::vector tableau_piles; - std::vector cells; std::vector foundations; + std::vector cells; + std::vector tableau_piles; pile reserve; pile stock; pile waste; diff --git a/src/main/game/pile.cpp b/src/main/game/pile.cpp index 776c997..84a6046 100644 --- a/src/main/game/pile.cpp +++ b/src/main/game/pile.cpp @@ -9,8 +9,40 @@ using namespace std; -pile::pile(bool r, sol_rules::build_order bo, sol_rules::build_policy bp, - bool l, int mr) : +typedef sol_rules::build_order ord; +typedef sol_rules::build_policy pol; + +//////////// +// Static // +//////////// + +pile pile::foundation_factory(pol p) { + return pile(true, ord::ASCENDING, p, false); +} +pile pile::cell_factory() { + return pile(true, ord::SINGLE_CARD, pol::ANY_SUIT, false); +} +pile pile::tableau_factory(ord o) { + return pile(true, o, pol::ANY_SUIT, false); +} +pile pile::reserve_factory() { + return pile(true, ord::NO_BUILD, pol::ANY_SUIT, false); +} +pile pile::stock_factory() { + return pile(true, ord::NO_BUILD, pol::ANY_SUIT, false); +} +pile pile::waste_factory() { + return pile(true, ord::NO_BUILD, pol::ANY_SUIT, false); +} +pile pile::hole_factory(int max_rank) { + return pile(false, ord::BOTH, pol::ANY_SUIT, true, max_rank); +} + +//////////////// +// Non-static // +//////////////// + +pile::pile(bool r, ord bo, pol bp, bool l, int mr) : remove(r), build_order(bo), build_policy(bp), @@ -18,8 +50,6 @@ pile::pile(bool r, sol_rules::build_order bo, sol_rules::build_policy bp, max_rank(mr) {} bool pile::can_place(const card& c) const { - typedef sol_rules::build_order ord; - typedef sol_rules::build_policy pol; if (build_order == ord::NO_BUILD) { return false; diff --git a/src/main/game/pile.h b/src/main/game/pile.h index c967cc1..807364f 100644 --- a/src/main/game/pile.h +++ b/src/main/game/pile.h @@ -12,7 +12,16 @@ class pile { public: - pile(bool, sol_rules::build_order, sol_rules::build_policy, bool, int m = 13); + static pile foundation_factory(sol_rules::build_policy); + static pile cell_factory(); + static pile tableau_factory(sol_rules::build_order); + static pile reserve_factory(); + static pile stock_factory(); + static pile waste_factory(); + static pile hole_factory(int max_rank = 13); + + pile(bool, sol_rules::build_order, sol_rules::build_policy, bool, + int max_rank = 13); bool can_place(const card&) const; bool can_remove() const; -- cgit v1.2.1 From 5c5afaa42e5f51d5f6d289be2b7d0b13ee80ca10 Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Sun, 12 Nov 2017 10:59:04 +0000 Subject: Remove dynamic mem alloc for random deal gen --- src/main/game/game_state.cpp | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/main/game/game_state.cpp b/src/main/game/game_state.cpp index 9d03155..b38c2d8 100644 --- a/src/main/game/game_state.cpp +++ b/src/main/game/game_state.cpp @@ -119,26 +119,23 @@ game_state::game_state(int seed, const sol_rules& s_rules) : // Generate a randomly ordered vector of cards vector game_state::shuffled_deck(int seed, int max_rank = 13) { - vector v; + vector values; + vector v_ptrs; for (int i = 0; i < max_rank * 4; i++) { - v.push_back(new int(i)); + values.push_back(i); + v_ptrs.push_back(&values[i]); } // Randomly shuffle the pointers auto rng = std::default_random_engine(seed); - std::shuffle(std::begin(v), std::end(v), rng); + std::shuffle(std::begin(v_ptrs), std::end(v_ptrs), rng); vector deck; - for (int *i : v) { + for (int *i : v_ptrs) { int r = ((*i) % max_rank) + 1; int s = (*i) / max_rank; - deck.push_back(card(r, s)); - } - - // release memory - for (int i = 0; i < max_rank * 4; i++) { - delete v[i]; + deck.emplace_back(card(r, s)); } return deck; -- cgit v1.2.1 From 9779d5b9823de8d013c449630e198f16a5c05bf6 Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Sun, 12 Nov 2017 11:18:14 +0000 Subject: Fix random deal bug --- src/main/game/game_state.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/main/game/game_state.cpp b/src/main/game/game_state.cpp index b38c2d8..cd40c53 100644 --- a/src/main/game/game_state.cpp +++ b/src/main/game/game_state.cpp @@ -123,12 +123,14 @@ vector game_state::shuffled_deck(int seed, int max_rank = 13) { vector v_ptrs; for (int i = 0; i < max_rank * 4; i++) { values.push_back(i); + } + for (int i = 0; i < max_rank * 4; i++) { v_ptrs.push_back(&values[i]); } // Randomly shuffle the pointers - auto rng = std::default_random_engine(seed); - std::shuffle(std::begin(v_ptrs), std::end(v_ptrs), rng); + auto rng = default_random_engine(seed); + shuffle(begin(v_ptrs), end(v_ptrs), rng); vector deck; for (int *i : v_ptrs) { -- cgit v1.2.1 From 44f14e06c347db7eea68cad9c4ece8972b89ebed Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Sun, 12 Nov 2017 11:33:59 +0000 Subject: Clean up deal from shuffled deck --- src/main/game/game_state.cpp | 25 +++++++++++-------------- src/main/game/sol_rules.cpp | 4 ++-- 2 files changed, 13 insertions(+), 16 deletions(-) (limited to 'src') diff --git a/src/main/game/game_state.cpp b/src/main/game/game_state.cpp index cd40c53..4caf9d9 100644 --- a/src/main/game/game_state.cpp +++ b/src/main/game/game_state.cpp @@ -67,40 +67,37 @@ game_state::game_state(int seed, const sol_rules& s_rules) : hole.place("AS"); } - unsigned int deckCardsUsed = 0; - // If there is a stock, deal to it and set up a waste pile too if (rules.stock_size > 0) { for (unsigned int i = 0; i < rules.stock_size; i++) { - stock.place(deck[i + deckCardsUsed]); + stock.place(deck.back()); + deck.pop_back(); } - deckCardsUsed += rules.stock_size; } // If there is a reserve, deal to it if (rules.reserve_size > 0) { for (unsigned int i = 0; i < rules.reserve_size; i++) { - reserve.place(deck[i + deckCardsUsed]); + reserve.place(deck.back()); + deck.pop_back(); } - deckCardsUsed += rules.reserve_size; } - // Deal to the tableau piles (row-by-row) - vector::size_type remainingCards = deck.size() - deckCardsUsed; - for (vector::size_type i = 0; i < remainingCards; i++) { - card c = deck[i + deckCardsUsed]; + unsigned int t = 0; + while (!deck.empty()) { + card c = deck.back(); + deck.pop_back(); // For the first row we must create all the tableau pile vectors - if (i / rules.tableau_pile_count == 0) { + if (t / rules.tableau_pile_count == 0) { tableau_piles.push_back(pile::tableau_factory(rules.build_ord)); } // Add the randomly generated card to the tableau piles - tableau_piles[i % rules.tableau_pile_count].place(c); + tableau_piles[t % rules.tableau_pile_count].place(c); + t++; } - deckCardsUsed += remainingCards; - assert(deckCardsUsed == deck.size()); // If there are foundation piles, create the relevant pile vectors if (rules.foundations) { diff --git a/src/main/game/sol_rules.cpp b/src/main/game/sol_rules.cpp index df5b939..fd32c72 100644 --- a/src/main/game/sol_rules.cpp +++ b/src/main/game/sol_rules.cpp @@ -102,8 +102,8 @@ sol_rules::sol_rules(std::string sol_type) { tableau_pile_count = 3; build_pol = build_policy::RED_BLACK; max_rank = 3; - reserve_size = 3; - stock_size = 6; + reserve_size = 2; + stock_size = 2; break; default: assert(false); -- cgit v1.2.1 From 2b3e92a384c2483d88f48c8fcafe8ffcdfb0f3b3 Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Sun, 12 Nov 2017 11:41:28 +0000 Subject: Simplify is_solved() --- src/main/game/game_state.cpp | 5 +---- src/main/game/game_state.h | 1 - 2 files changed, 1 insertion(+), 5 deletions(-) (limited to 'src') diff --git a/src/main/game/game_state.cpp b/src/main/game/game_state.cpp index 4caf9d9..8105cb3 100644 --- a/src/main/game/game_state.cpp +++ b/src/main/game/game_state.cpp @@ -214,10 +214,7 @@ bool game_state::is_solved() const { } } - if (rules.hole && hole.size() != rules.max_rank * 4) { - return false; - } - return true; + return !rules.hole || hole.size() == rules.max_rank * 4; } ostream& game_state::print(ostream& stream) const { diff --git a/src/main/game/game_state.h b/src/main/game/game_state.h index b985924..26d2650 100644 --- a/src/main/game/game_state.h +++ b/src/main/game/game_state.h @@ -23,7 +23,6 @@ public: game_state(int seed, const sol_rules&); std::vector get_next_legal_states() const; - // NOTE: will only be evaluated after get_next_legal_states() is called bool is_solved() const; std::ostream& print(std::ostream&) const; -- cgit v1.2.1 From f6259b5e0ebf20a3da6683d2e5c6c09fe33e1064 Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Sun, 12 Nov 2017 12:26:34 +0000 Subject: Refactor and improve state printing --- src/main/game/game_state.cpp | 91 ++++++++++++++++++++++---------------------- src/main/game/game_state.h | 7 ++-- src/main/game/pile.cpp | 34 ++++++++--------- src/main/game/pile.h | 2 +- 4 files changed, 66 insertions(+), 68 deletions(-) (limited to 'src') diff --git a/src/main/game/game_state.cpp b/src/main/game/game_state.cpp index 8105cb3..4080f3c 100644 --- a/src/main/game/game_state.cpp +++ b/src/main/game/game_state.cpp @@ -220,11 +220,11 @@ bool game_state::is_solved() const { ostream& game_state::print(ostream& stream) const { if (rules.foundations) { print_header(stream, "Foundations"); - print_foundations(stream); + print_top_of_piles(stream, foundations); } if (rules.cells) { print_header(stream, "Cells"); - print_cells(stream); + print_piles(stream, cells); } if (rules.reserve_size > 0) { print_header(stream, "Reserve"); @@ -232,19 +232,17 @@ ostream& game_state::print(ostream& stream) const { } if (rules.tableau_pile_count > 0) { print_header(stream, "Tableau Piles"); - print_tableau_piles(stream); + print_piles(stream, tableau_piles); } if (rules.stock_size > 0) { - print_header(stream, "Stock"); - print_pile(stream, stock); - print_header(stream, "Waste"); - print_pile(stream, waste); + print_header(stream, "Stock | Waste"); + print_piles(stream, {stock, waste}); } if (rules.hole) { print_header(stream, "Hole Card"); - print_hole(stream); + print_top_of_pile(stream, hole); } - return stream << "===================================\n"; + return stream << "==================================="; } void game_state::print_header(ostream& stream, const char* header) const { @@ -256,56 +254,57 @@ void game_state::print_header(ostream& stream, const char* header) const { stream << "\n"; } -void game_state::print_foundations(ostream& stream) const { - stream << foundations[0] << "\t" - << foundations[1] << "\t" - << foundations[2] << "\t" - << foundations[3] << "\n"; -} - -void game_state::print_cells(ostream& stream) const { - for (pile cell : cells) { - if (cells.empty()) { - stream << "[]" << "\t"; - } else { - stream << cells[0] << "\t"; - } - } - stream << "\n"; -} - -void game_state::print_pile(ostream& stream, const pile &p) const { - if (p.empty()) { - stream << "[]\n"; - } else { - for (unsigned int i = 0; i < p.size(); i++) { - stream << p[i] << "\n"; - } - } -} - -void game_state::print_tableau_piles(ostream& stream) const { +void game_state::print_piles(ostream& stream, + const vector& pile_vec) const { bool empty_row = false; vector::size_type row_idx = 0; + // Loops through the rows in each pile, starting from the bottom, until + // one is empty while (!empty_row) { + // Loops throught the current row to determine if it is empty empty_row = true; - - for (pile tableau_pile : tableau_piles) { + for (const pile& tableau_pile : pile_vec) { if (tableau_pile.size() > row_idx) { empty_row = false; - stream << tableau_pile[row_idx]; + break; } - stream << "\t"; } + if (!empty_row || row_idx == 0) { + // Loops through the current (non-empty) row, and outputs the values + for (const pile& tableau_pile : pile_vec) { + if (tableau_pile.size() > row_idx) { + stream << tableau_pile[row_idx]; + } else if (row_idx == 0) { + stream << "[]"; + } + stream << "\t"; + } - stream << "\n"; - row_idx++; + stream << "\n"; + row_idx++; + } + } +} + +void game_state::print_pile(ostream& stream, const pile &p) const { + print_piles(stream, {p}); +} + +void game_state::print_top_of_piles(ostream& stream, const vector& vp) const { + vector top(vp); + for (pile& p : top) { + if (!p.empty()) { + card t = p.top_card(); + p.clear(); + p.place(t); + } } + print_piles(stream, top); } -void game_state::print_hole(ostream& stream) const { - stream << hole.top_card() << "\n"; +void game_state::print_top_of_pile(ostream& stream, const pile& p) const { + print_top_of_piles(stream, {p}); } bool operator==(const game_state& a, const game_state& b) { diff --git a/src/main/game/game_state.h b/src/main/game/game_state.h index 26d2650..6b2af7d 100644 --- a/src/main/game/game_state.h +++ b/src/main/game/game_state.h @@ -34,11 +34,10 @@ private: static std::vector shuffled_deck(int, int); void print_header(std::ostream&, const char*) const; - void print_foundations(std::ostream&) const; - void print_cells(std::ostream&) const; - void print_tableau_piles(std::ostream&) const; - void print_hole(std::ostream&) const; + void print_piles(std::ostream&, const std::vector&) const; void print_pile(std::ostream&, const pile&) const; + void print_top_of_piles(std::ostream&, const std::vector&) const; + void print_top_of_pile(std::ostream&, const pile&) const; std::vector foundations; std::vector cells; diff --git a/src/main/game/pile.cpp b/src/main/game/pile.cpp index 84a6046..5b05661 100644 --- a/src/main/game/pile.cpp +++ b/src/main/game/pile.cpp @@ -96,20 +96,12 @@ bool pile::one_lt(int a, int b) const { return (a == b - 1) || (build_order_loops && a == max_rank && b == 1); } -void pile::place(const card& c) { - pile_vec.push_back(c); -} + card pile::top_card() const { return pile_vec.back(); } -card pile::take() { - card c = top_card(); - pile_vec.pop_back(); - return c; -} - bool pile::can_remove() const { return remove; } @@ -129,6 +121,22 @@ card pile::operator[] (vector::size_type i) const { return pile_vec[i]; } + +void pile::place(const card& c) { + pile_vec.push_back(c); +} + +card pile::take() { + card c = top_card(); + pile_vec.pop_back(); + return c; +} + +void pile::clear() { + pile_vec.clear(); +} + + void move(pile *a, pile *b) { b->place(a->take()); } @@ -136,11 +144,3 @@ void move(pile *a, pile *b) { bool operator==(const pile& a, const pile& b) { return a.pile_vec == b.pile_vec; } - -ostream & operator<<(ostream & stream, pile const & p) { - if (p.empty()) { - return stream << "[]"; - } else { - return stream << p.top_card(); - } -} diff --git a/src/main/game/pile.h b/src/main/game/pile.h index 807364f..1297063 100644 --- a/src/main/game/pile.h +++ b/src/main/game/pile.h @@ -31,12 +31,12 @@ public: void place(const card&); card take(); + void clear(); card& operator[] (std::vector::size_type); card operator[] (std::vector::size_type) const; friend bool operator==(const pile&, const pile&); - friend std::ostream & operator<<(std::ostream &, pile const &); private: bool one_lt(int, int) const; -- cgit v1.2.1 From 076a6b129e6b35779ea946a5738357e9348c7f7e Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Sun, 12 Nov 2017 22:41:27 +0000 Subject: Refactor game state --- src/main/game/game_state.cpp | 80 +++++++++++++++++++++++++------------------- src/main/game/game_state.h | 5 ++- src/main/game/pile.cpp | 9 +++-- src/main/game/pile.h | 3 +- src/main/game/sol_rules.cpp | 4 +-- 5 files changed, 56 insertions(+), 45 deletions(-) (limited to 'src') diff --git a/src/main/game/game_state.cpp b/src/main/game/game_state.cpp index 4080f3c..3336020 100644 --- a/src/main/game/game_state.cpp +++ b/src/main/game/game_state.cpp @@ -4,7 +4,6 @@ #include #include -#include #include #include #include @@ -140,7 +139,7 @@ vector game_state::shuffled_deck(int seed, int max_rank = 13) { return deck; } -vector game_state::get_next_legal_states() const { +const vector game_state::get_next_legal_states() const { // Generates vectors of references to all the piles from which // cards can be removed, and to which they can be added vector can_remove; @@ -150,62 +149,48 @@ vector game_state::get_next_legal_states() const { // states game_state mut_state = *this; - for (vector::size_type i = 0; i < tableau_piles.size(); i++) { - can_remove.push_back(&mut_state.tableau_piles[i]); - if (rules.build_ord != ord::NO_BUILD) { - can_add.push_back(&mut_state.tableau_piles[i]); + for (pile* p : mut_state.get_regular_pile_refs()) { + if (p->can_remove()) { + can_remove.push_back(p); } - } - if (rules.reserve_size > 0) { - can_remove.push_back(&mut_state.reserve); - } - if (rules.foundations) { - for (vector::size_type i = 0; i < foundations.size(); i++) { - can_remove.push_back(&mut_state.foundations[i]); - can_add.push_back(&mut_state.foundations[i]); + if (p->get_build_order() != ord::NO_BUILD) { + can_add.push_back(p); } } - for (vector::size_type i = 0; i < cells.size(); i++) { - can_remove.push_back(&mut_state.cells[i]); - can_add.push_back(&mut_state.cells[i]); - } - if (rules.stock_size > 0) { - can_remove.push_back(&mut_state.waste); - } - if (rules.hole) { - can_add.push_back(&mut_state.hole); - } // The next legal states vector next; // Moving from and to the 'can remove' and 'can add' piles - for (pile *rem_pile : can_remove) { + for (pile* rem_pile : can_remove) { if (rem_pile->empty()) continue; - for (pile *add_pile : can_add) { - if (add_pile != rem_pile + for (pile* add_pile : can_add) { + if (&add_pile != &rem_pile && add_pile->can_place(rem_pile->top_card())) { - move(rem_pile, add_pile); // remove - game_state s(mut_state); - next.push_back(s); - move(add_pile, rem_pile); // restore + game_state new_gs = move(mut_state, rem_pile, add_pile); + next.push_back(new_gs); } } } // Dealing from the stock to the waste if (!stock.empty()) { - move(&mut_state.stock, &mut_state.waste); - game_state s(mut_state); - next.push_back(s); - move(&mut_state.waste, &mut_state.stock); + game_state new_gs = move(mut_state, &mut_state.stock, &mut_state.waste); + next.push_back(new_gs); } return next; } +const game_state game_state::move(game_state& gs, pile* from, pile* to) const { + to->place(from->take()); + const game_state new_gs(gs); + from->place(to->take()); + return new_gs; +} + bool game_state::is_solved() const { for (auto p : foundations) { @@ -217,6 +202,31 @@ bool game_state::is_solved() const { return !rules.hole || hole.size() == rules.max_rank * 4; } +// Not the stock, because cards from it can't be moved to the rest of the piles! +vector game_state::get_regular_pile_refs() { + vector piles; + auto to_ptr = [](pile& p){return &p;}; + + if (rules.foundations) { + transform(begin(foundations), end(foundations), back_inserter(piles), + to_ptr); + } + if (rules.cells) { + transform(begin(cells), end(cells), back_inserter(piles), to_ptr); + } + transform(begin(tableau_piles), end(tableau_piles), back_inserter(piles), to_ptr); + if (rules.reserve_size > 0) { + piles.push_back(&reserve); + } + if (rules.stock_size > 0) { + piles.push_back(&waste); + } + if (rules.hole) { + piles.push_back(&hole); + } + return piles; +} + ostream& game_state::print(ostream& stream) const { if (rules.foundations) { print_header(stream, "Foundations"); diff --git a/src/main/game/game_state.h b/src/main/game/game_state.h index 6b2af7d..12dcda9 100644 --- a/src/main/game/game_state.h +++ b/src/main/game/game_state.h @@ -22,7 +22,7 @@ public: // Do the same from a 'rules' object game_state(int seed, const sol_rules&); - std::vector get_next_legal_states() const; + const std::vector get_next_legal_states() const; bool is_solved() const; std::ostream& print(std::ostream&) const; @@ -33,6 +33,9 @@ public: private: static std::vector shuffled_deck(int, int); + const game_state move(game_state&, pile*, pile*) const; + std::vector get_regular_pile_refs(); + void print_header(std::ostream&, const char*) const; void print_piles(std::ostream&, const std::vector&) const; void print_pile(std::ostream&, const pile&) const; diff --git a/src/main/game/pile.cpp b/src/main/game/pile.cpp index 5b05661..bebd1f6 100644 --- a/src/main/game/pile.cpp +++ b/src/main/game/pile.cpp @@ -114,6 +114,10 @@ unsigned long pile::size() const { return pile_vec.size(); } +ord pile::get_build_order() const { + return build_order; +} + card& pile::operator[] (vector::size_type i) { return pile_vec[i]; } @@ -136,11 +140,6 @@ void pile::clear() { pile_vec.clear(); } - -void move(pile *a, pile *b) { - b->place(a->take()); -} - bool operator==(const pile& a, const pile& b) { return a.pile_vec == b.pile_vec; } diff --git a/src/main/game/pile.h b/src/main/game/pile.h index 1297063..6482e0c 100644 --- a/src/main/game/pile.h +++ b/src/main/game/pile.h @@ -28,6 +28,7 @@ public: card top_card() const; bool empty() const; unsigned long size() const; + sol_rules::build_order get_build_order() const; void place(const card&); card take(); @@ -50,7 +51,5 @@ private: std::vector pile_vec; }; -void move(pile*, pile*); - #endif //SOLVITAIRE_PILE_H diff --git a/src/main/game/sol_rules.cpp b/src/main/game/sol_rules.cpp index fd32c72..003528c 100644 --- a/src/main/game/sol_rules.cpp +++ b/src/main/game/sol_rules.cpp @@ -99,9 +99,9 @@ sol_rules::sol_rules(std::string sol_type) { stock_size = 34; break; case valid_sol::SIMPLE_CANFIELD: - tableau_pile_count = 3; + tableau_pile_count = 2; build_pol = build_policy::RED_BLACK; - max_rank = 3; + max_rank = 2; reserve_size = 2; stock_size = 2; break; -- cgit v1.2.1 From 16556a7f36da4fc8093285392f81409b1cfa7aa7 Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Sun, 12 Nov 2017 22:48:15 +0000 Subject: Refactor solver --- src/main/solver/solver.cpp | 19 ++++++++----------- src/main/solver/solver.h | 6 +++--- 2 files changed, 11 insertions(+), 14 deletions(-) (limited to 'src') diff --git a/src/main/solver/solver.cpp b/src/main/solver/solver.cpp index 160af6f..f412d03 100644 --- a/src/main/solver/solver.cpp +++ b/src/main/solver/solver.cpp @@ -16,8 +16,7 @@ using namespace std; using namespace boost; solver::solver(const game_state gs, const sol_rules& sr) - : root(NULL, gs), rules(sr), solution(root), solution_found(false), - states_searched(0) {} + : root(NULL, gs), rules(sr), solution(root), states_searched(0) {} solver::node::node(const node* parent, const game_state& gs) : history(solver::node::gen_history(parent)), state(gs) {} @@ -33,13 +32,12 @@ const vector solver::node::gen_history(const node* parent) { return hist; } -optional solver::run() { - been_run = true; - +const optional solver::run() { // 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 const node current = frontier.back(); @@ -51,11 +49,6 @@ optional solver::run() { vector new_children = current.state.get_next_legal_states(); states_searched++; - // NOTE: get_next_legal_states() makes the is_solved() function work - if (current.state.is_solved()) { - return node(current); - } - for (auto it = new_children.rbegin(); it != new_children.rend(); it++) { // If we have seen the state before, ignore it (loop detection)) if (find(begin(current.history), end(current.history), *it) @@ -64,7 +57,11 @@ optional solver::run() { } const node n(¤t, *it); - frontier.push_back(n); + if (n.state.is_solved()) { + return n; + } else { + frontier.push_back(n); + } } } diff --git a/src/main/solver/solver.h b/src/main/solver/solver.h index 6dfccc2..91c93d6 100644 --- a/src/main/solver/solver.h +++ b/src/main/solver/solver.h @@ -24,18 +24,18 @@ public: }; solver(const game_state, const sol_rules&); - boost::optional run(); + const node get_root() const; int get_states_searched() const; + const boost::optional run(); + friend std::ostream& operator<< (std::ostream&, const solver::node&); private: const node root; const sol_rules rules; - bool been_run; node solution; - bool solution_found; int states_searched; }; -- cgit v1.2.1