another kata

This commit is contained in:
2019-12-16 21:08:56 +01:00
parent 97c0e43874
commit 0b4f33c123

109
Snakes and ladders/main.cpp Normal file
View File

@@ -0,0 +1,109 @@
#include <string>
#include <map>
#include <iostream>
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<int, int> 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<int, int> &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);
}