Best class design for game with player moving in a room?

I am trying do implement a player walking inside a room with specific boundaries. However, I dont know how to best specify the class relationships and their responsibilities between the Player class and the Room class.

The player will store a state with its coordinate and move according to input from the keyboard:

1
2
3
4
5
6
7
8
class Player {
// ....

void move(keyboard input...);

private:
Coordinate mCoordinate;
};


When the player moves, we must validate that the move is valid, i.e. that the player dont bump into the wall for example. So my question is, should the Player class have a reference to the Room so that the Player class itself can validate the move? Or is it better to have a superior class, GameHandler maybe, which first verifies that the move is valid and the calls a set method for the new position if the move was valid? For Example:

1
2
3
4
5
6
Coordinate co = player.getNewCoordinate(input);
if(room.validateMovement(co)) {
  player.setNewCoordinate(co);
} else {
 // throw some invalidMovementException
}


But with this design it is not easy to call a method named move() from the Player class. In order to call a move() method it would probably be better if the Player stored a reference to the Room class so that itself could verify the move. But on the other hand the class relationships and responsibilities get messed up as I see it.

This is a very general problem I think so what would be the best design for this specific case?
Are you sure your approach is what you really want?

I think I'd split Player and Room to 2 classes and make a class called game which handles the inputs correctly.
Well that was basically what I proposed (I think???) with a GameHandler class which validates the move.

Can you give a little code example how you meant?
If a player can only move within a room, why don't you pass the room to the move:
1
2
3
4
5
6
7
8
void player::move(const keyboard &input, const room &cur_room)
{
  ... new_coord = ...;
  if(cur_room.is_coord_valid(new_coord))
    ...
  else
    ..
}
Well, whatever, there is no "best design" anyway, just personal preferences
You have 3 different designs now, any of these will do the job ;)

I'd personally try to split my data as good as possible because I'm a huge fan of code reuse but a design like that would require a little bit more work and you'd have to change pieces of the code anyway
Topic archived. No new replies allowed.