This is a pretty general question about programming patterns for a game I'm making. I want to get this right before I start writing chunks of code so that I don't code myself into a hole, so to speak. Let's say I'm making a video game, and the player-controlled "Character" class has a move function that looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
class Character
{
public:
Character();
void move();
}
void Character::move()
{
if(leftbuttonpressed)
{
if(tilemap.lefttile == wall)
{
moveleft();
}
else
{
stay();
}
//and so on, for up, down, right, etc.
return;
}
|
The move() function requires knowledge of the Character's surroundings, which are contained in a vector called "tilemap". In the above example the character can only move left if there is not a wall in the position he is trying to move in to.
My question is, how should I allow the Character class to access tilemap? There are four ways I thought about doing this, and I was wondering if one of these implementation is better than the others.
1) Declare a global variable.
Pro: Conceptually the easiest to grasp
Con: Everyone says global pointers are a bad practice, and I tend to defer to the experience of the experts...
2) Give Character a pointer to tilemap.
Pro: Easy to implement and use afterwards
Cons: Logically not the most straight forward. Why does a Character have ownership of the level map? With one class and one pointer it's not bad, but if I extend this concept to every interaction between objects it will get messy fast.
3) Pass a tilemap pointer to Character's move function as a parameter. Something like:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
class Character
{
move(std::vector<tile*> tilemap_);
}
Character character;
std::vector<tile*> tilemap;
void update_game_state()
{
character.move(tilemap);
//update other entities
}
|
Pro: Easy to implement
Con: Can't really think of a negative; parameters may add up making code more difficult to parse?
4) Have some mediator external to Character that checks if a given movement is allowed. Implement something like this:
1 2 3 4 5 6
|
void update_game_state()
{
character.trymove();
check_move();
character.respond_to_movement_check();
}
|
Obviously the above code is kind of ugly, but I'm just trying to get the idea across.
Pro: Logically it makes sense to have some class responsible for regulating the movement of all entities.
Con: Seems like the most difficult to implement.
Any insight on the best/a preferable way of doing this would be awesome. Thanks!