user966379
user966379

Reputation: 2983

Limiting invoking method of a class

I have faced a problem while designing chess game. There are 2 Player: p1, p2; I want to implement the class in such awy that same player can not call makeMove twice simultaneously.

see the example.

class Move {};
class Player {
    void makeMove(Move *m) {

    }
};

// situation 1:

Player p1;
p1.makeMove(new move());
p1.makeMove(new move());   // it should give error

// situation 2:

Player p1;
p1.makeMove(new move());
Player p2;
p2.makeMove(new move());

p1.makeMove(new move());   // it os ok

Please help me in designing the classes

Upvotes: 3

Views: 50

Answers (2)

Juri Glass
Juri Glass

Reputation: 91533

I imagine that there is a Class called GameOfChess or something like this, which should be aware which Player has the next turn. Why don't you synchronize the moves of the player with the help of this class?

You could for instance do it something like this:

void makeMove(Move *m) {
    if (game.isItMyTurn(this)) {

        // Do the move
        game.move(m);
    }    
    // else ignore moves or throw an exception
}

Upvotes: 1

Denis Biondic
Denis Biondic

Reputation: 8201

First of all, I don't think that Player class should be responsible for that. It would be better of with something like

class ChessEngine
{
   void MovePlayer(Player *player, Move *move)
   {

   }
}

In which ChessEngine could have a list of previous moves and then check if player is allowed to move.

Upvotes: 2

Related Questions