假设你有一些特定的起点(x,y),并且你很好奇这一行中是否有三个相同的数字开始。让我们考虑一下你在水平方向上看的情况。然后有办法做到这一点(忽略边界检查)会是这样的:
bool IsHorizontalMatch(int x, int y) {
/* Get the value of the start position. */
const int startValue = board[x][y];
/* Confirm the two values after it match. */
for (int i = 1; i < 3; ++i)
if (board[x + i][y] != startValue)
return false;
/* If we got here, then they all match! */
return true;
}
你可以同样写这样的功能对于垂直检查:
bool IsVerticalMatch(int x, int y) {
/* Get the value of the start position. */
const int startValue = board[x][y];
/* Confirm the two values after it match. */
for (int i = 1; i < 3; ++i)
if (board[x][y + i] != startValue)
return false;
/* If we got here, then they all match! */
return true;
}
最后,一个对角线:
bool IsDiagonalDownMatch(int x, int y) {
/* Get the value of the start position. */
const int startValue = board[x][y];
/* Confirm the two values after it match. */
for (int i = 1; i < 3; ++i)
if (board[x + i][y + i] != startValue)
return false;
/* If we got here, then they all match! */
return true;
}
bool IsDiagonalUpMatch(int x, int y) {
/* Get the value of the start position. */
const int startValue = board[x][y];
/* Confirm the two values after it match. */
for (int i = 1; i < 3; ++i)
if (board[x + i][y - i] != startValue)
return false;
/* If we got here, then they all match! */
return true;
}
这个工程,但它不是很优雅;所有这三个功能看起来都非常相似!幸运的是,你可以用一个单一的统一函数来重写它们。这个想法是这样的 - 如果你会注意到,所有这三个函数的工作都是通过定义一些“步长”来指示你移动的方向。在水平情况下,步骤为(+1,+0),在垂直情况下为(+0,+1),在对角线中为(+1,+1)或(+1,-1)。鉴于此,您可以编写一个函数来检查,如果三个值中的线匹配:
bool IsLinearMatch(int x, int y, int stepX, int stepY) {
/* Get the value of the start position. */
const int startValue = board[x][y];
/* Confirm the two values after it match. */
for (int i = 1; i < 3; ++i)
if (board[x + i * stepX][y + i * stepY] != startValue)
return false;
/* If we got here, then they all match! */
return true;
}
然后,您可以编写
bool IsLineStartingAt(int x, int y) {
return IsLinearMatch(x, y, 1, 0) || // Horizontal
IsLinearMatch(x, y, 0, 1) || // Vertical
IsLinearMatch(x, y, 1, 1) || // Diagonal Down
IsLinearMatch(x, y, 1, -1) || // Diagonal Up
}
鉴于这种原始的,你可以只遍历检查所有可能的匹配在所有可能的起点上。
希望这会有所帮助!
编辑:感谢评论者帮助解决我的愚蠢的错误。 :-)
这功课吗?你有什么尝试? – marcog 2011-01-08 22:43:50
它不是家庭作业,但基本上我有超过50如果陈述如果行[0] ==行[1] &&行[2],然后...但我仍然没有所有的组合,我知道必须是更好的方法。 – FrozenWasteland 2011-01-08 22:47:29