From 0b4f33c123e487ae6c906bc83fdc066675683f57 Mon Sep 17 00:00:00 2001 From: Bart Moyaers Date: Mon, 16 Dec 2019 21:08:56 +0100 Subject: [PATCH] another kata --- Snakes and ladders/main.cpp | 109 ++++++++++++++++++++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 Snakes and ladders/main.cpp diff --git a/Snakes and ladders/main.cpp b/Snakes and ladders/main.cpp new file mode 100644 index 0000000..04f4b8c --- /dev/null +++ b/Snakes and ladders/main.cpp @@ -0,0 +1,109 @@ +#include +#include +#include + +class SnakesLadders +{ + bool player_1_turn = true; + bool game_over = false; + int player_1_pos = 0; + int player_2_pos = 0; + // Map all the ladders and snakes! + std::map ladders_snakes{ + {2, 38}, + {7, 14}, + {8, 31}, + {15, 26}, + {16, 6}, + {21, 42}, + {28, 84}, + {36, 44}, + {46, 25}, + {49, 11}, + {51, 67}, + {62, 19}, + {64, 60}, + {71, 91}, + {74, 53}, + {78, 98}, + {87, 94}, + {89, 68}, + {92, 88}, + {95, 75}, + {99, 80} + }; + private: + void update_pos(bool firstplayer, int die_sum); + int update_pos(int old_pos, int die_sum); + std::string generate_game_string(bool firstplayer); + void init_map(std::map &map); + public: + SnakesLadders(){}; + std::string play(int die1, int die2); +}; + +std::string SnakesLadders::play(int die1, int die2){ + // Update player position + update_pos(player_1_turn, die1+die2); + + // Write output string + std::string result = generate_game_string(player_1_turn); + + // Update next turn + if(die1 != die2) + player_1_turn = !player_1_turn; + + return result; +} + +void SnakesLadders::update_pos(bool firstplayer, int die_sum){ + if(!game_over){ + if(firstplayer){ + player_1_pos = this->update_pos(player_1_pos, die_sum); + } else { + player_2_pos = this->update_pos(player_2_pos, die_sum); + } + } +} + +int SnakesLadders::update_pos(int old_pos, int die_sum){ + int new_pos = old_pos + die_sum; + // Move back if not exactly at end square + if(new_pos > 100) + new_pos = 200 - new_pos; + + // Check for ladders and snakes + auto it = this->ladders_snakes.find(new_pos); + if(it != this->ladders_snakes.end()) + new_pos = it->second; + + return new_pos; +} + +std::string SnakesLadders::generate_game_string(bool firstplayer){ + int position; + int player_number; + if(firstplayer){ + position = player_1_pos; + player_number = 1; + } else { + position = player_2_pos; + player_number = 2; + } + + if(position == 100 && !game_over){ + game_over = true; + return "Player " + std::to_string(player_number) + " Wins!"; + } + + if(game_over){ + return "Game over!"; + } else { + return "Player " + std::to_string(player_number) + " is on square " + std::to_string(position); + } +} + +int main(){ + SnakesLadders game; + std::cout << game.play(1,1); +} \ No newline at end of file