Skip to content

Instantly share code, notes, and snippets.

@yokeshrana
Created April 2, 2021 11:07
Show Gist options
  • Save yokeshrana/9253f4f44b67dc5714fba7e34e101298 to your computer and use it in GitHub Desktop.
Save yokeshrana/9253f4f44b67dc5714fba7e34e101298 to your computer and use it in GitHub Desktop.
Machine Coding Snake and Ladder Game
#include <iostream>
#include <map>
#include <vector>
using namespace std;
class Snake{
int end;
public:
Snake() {}
Snake(int anEnd) : end(anEnd) {}
int getAnEnd() const {
return end;
}
void setAnEnd(int anEnd) {
end = anEnd;
}
};
class Ladder{
int end;
public:
Ladder() {}
Ladder(int anEnd) : end(anEnd) {}
int getAnEnd() const {
return end;
}
void setAnEnd(int anEnd) {
end = anEnd;
}
};
class SnakeBoard{
int boardSize;
map<int,Snake> snakes;
map<int,Ladder> ladders;
public:
SnakeBoard() {}
SnakeBoard(int boardSize, const map<int, Snake> &snakes, const map<int, Ladder> &ladders) : boardSize(boardSize),
snakes(snakes),ladders(ladders) {}
int getBoardSize() const {
return boardSize;
}
void setBoardSize(int boardSize) {
boardSize= boardSize;
}
const map<int, Snake> &getSnakes() const {
return snakes;
}
void setSnakes(const map<int, Snake> &snakes) {
SnakeBoard::snakes = snakes;
}
const map<int, Ladder> &getLadders() const {
return ladders;
}
void setLadders(const map<int, Ladder> &ladders) {
SnakeBoard::ladders = ladders;
}
};
class Player{
int position;
string name;
public:
Player(int position, const string &name) : position(position=0), name(name) {}
const string &getName() const {
return name;
}
void setName(const string &name) {
Player::name = name;
}
Player(int position) : position(position) {}
int getPosition() const {
return position;
}
void setPosition(int position) {
Player::position = position;
}
};
int main() {
map<int,Snake> snakes;
map<int,Ladder> ladders;
snakes.insert({20,Snake(10)});
snakes.insert({99,Snake(1)});
ladders.insert({40,Ladder(95)});
ladders.insert({30,Ladder(45)});
SnakeBoard snakeBoard(100,snakes,ladders);
vector<Player*> players;
players.push_back(new Player(0,"Yokesh"));
players.push_back(new Player(1,"Sagar"));
bool flag=true;
while(1){
for(int i=0;i<players.size();i++) {
auto x=players[i];
int rollNumber = (rand() % 6) + 1;
cout<<rollNumber<<endl;
int new_pos = x->getPosition() + rollNumber;
if (snakes.find(new_pos)!=snakes.end()) {
cout<<"Snakes ";
new_pos -= snakes[new_pos].getAnEnd();
}
else
if (ladders.find(new_pos)!=ladders.end()) {
cout<<"Ladder ";
new_pos += ladders[new_pos].getAnEnd();
}
if (new_pos <= 100 && new_pos>0) {
x->setPosition(new_pos);
cout << x->getName() << " got " << rollNumber << " move to :: " << x->getPosition() << endl;
}
if (new_pos == 100) {
cout << "Player " << x->getName() << " Won";
flag=false;
break;
}
}
if(flag== false)
break;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment