いくつかの特定の開始点(x、y)があり、この時点で開始する行に3つの等しい番号がある場合は、好奇心が強いとします。あなたが水平方向を見ている場合だけを考えてみましょう。そして、この(無視境界チェック)を行うための一つの方法は、次のようになります:
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;
}
そして対角線のための最後に、1 :
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;
}
これは機能しますが、それほどエレガントではありません。これら3つの機能はすべて非常によく似ています!幸いにも、あなたは単一の統合機能の点でそれらすべてを書き換えることができます。アイデアはこれです。あなたが気付くなら、3つの機能はすべて、どの方向に移動するかを示す「ステップサイズ」を定義することで機能します。水平の場合、ステップは(+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
}
を書き込むことができます。これを考えると、次の3つの値が行に一致するかどうかを確認するために、1つの関数を書くことができますすべての可能な出発点を超えて。
希望すると便利です。
編集:私の愚かなバグを修正するのを手伝ってくれたコメント者のおかげです。 :-)
この宿題はありますか?何を試しましたか? – marcog
宿題ではありませんが、基本的には、50行以上のif文でrow [0] == row [1] && row [2]と言っていますが、まだすべての組み合わせがありません。より良い方法です。 – FrozenWasteland