在游戏的“移动功能”中或外部作为外部功能中包含“检查位置”功能更有效?

StackOverflow https://stackoverflow.com/questions/958060

我在C ++中创建了一个游戏(说到哪个,我使用的代码很重要?),哪个coudl被松散地描述为棋盘游戏,我想知道这两个“检查字符是否超出范围”中的哪一个中的哪个”功能更有效:

一:

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

//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
}

从本质上讲,第一个人移动每个实体,然后检查所有实体位置并相应地重置它们,第二个实体可以确保玩家的移动不会使他摆脱界限,而不是等到循环结束。

我想知道这两个(系统?)中的哪一个比另一个更有效或更快,或者,如果它们俩平等,那么哪一种将是更好的编码样式?

有帮助吗?

解决方案

我会确保在移动之前曾经进行过移动。这样一来,您就保持了理智的状态,而不是尝试某些东西并将“董事会”留在无效状态。这也以面向对象的方式更有意义。该对象无法采取无效的动作,因此可以信任该动作。

其他提示

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

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).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top