views:

41

answers:

3

I'm creating a game in C++ (speaking of which, does the code I use matter?), which coudl be loosely described as a board game, and I'm wondering which of these two "check if character is out of bounds" functions is more efficient:

ONE:

int main()
{
    //display board
    //get player input
    //move player
    //if player is out of bounds,
      //force player back into bounds
}

TWO

//int main()
{
    //same thing, except without last two lines.
}
void move(char input)
{
    //if input does not place player out of bounds
      //move player according to input
}

Essentially, the first one moves every entity, then checks all of the entities positions and resets them accordingly, and the second one makes sure that the players move does not move him out of bounds, reather than waiting until the end of the loop.

I would like to know which of these two (systems?) is more efficient or faster than the other, or, if they're both equal, which one of these would be a better coding style?

A: 

The latter is faster (Not doing AND undoing). I would also think that it is the cleaner, but that's a matter of opinion.

C. Ross
A: 

I would make sure that ever move is legal before moving it. That way you keep a sane state instead of trying something and leaving the "board" in an invalid state. It also makes more sense in an object oriented way. The object can not make an invalid move therefore the move can be trusted.

Craig
A: 

Checking before moving would be faster, save, I suppose, the odds of a person going out of bounds being remarkably low.

Regarding style, I recommend not checking the boundaries from within the move() method, even if that check is extracted into its own method, as that gives you two "reasons to change" the move() method down the line (thus breaking Single Responsibility; some people only enforce this at the class level, but I recommend it for methods when you can get away with it).

lance