Ogh*_*hli 2 java arrays algorithm multidimensional-array
我正在努力在Java上实现connect 4 Game.我差不多完成了模拟游戏的程序.
我使用2D角色数组char [][] board = new char[6][7];来表示游戏的网格.
我已经实现了checkHorizontal方法来查找是否有4个连续的相同水平元素来检查win条件.我还实现了checkVertical方法来查找是否有4个连续相同的垂直元素来检查win条件.
我在编写checkDiagonal方法算法时有点困惑,该方法检查2D阵列中4个连续相同对角线元素的所有可能性.
以下是游戏中对角线胜利案例的2个例子
情况1:
* * * * * * *
* * * * * * *
Y * * * * * *
R Y * * Y * *
Y R Y R Y R R
R Y R Y R Y R
Run Code Online (Sandbox Code Playgroud)
案例2:
* * * * * * *
* * * * * * *
* * * * * R *
* * * * R Y *
* * * R Y R *
Y Y R Y R Y R
Run Code Online (Sandbox Code Playgroud)
我该如何检查rows并columns解决这些案件?
您只需要检查放置新类型的type位置,因为游戏区域的其余部分保持不变.在那里,你可以这样做:
/**
* Counts pieces of the given type, starting at (y, x),
* in the direction denoted by (dy, dx).
* Stops at field boundaries or when a different field type is encountered.
*/
int count(char type, int x, int y, int dx, int dy) {
int count = 0;
x += dx; // Skip the piece at (y, x) to avoid counting it twice
y += dy; // when looking in both directions on a line.
while (x >= 0 && x < 7 && y >= 0 && y < 6 && board[x][y] == type) {
count++;
x += dx; // Move in the direction denoted by (dy, dx)
y += dy;
}
return count;
}
/**
* Main entry point after a new piece of type `type` was added at (y, x).
* Returns true if this connects 4 or more in any direction.
*/
boolean check(char type, int x, int y) {
return count(type, x, y, -1, 0) + 1 + count(type, x, y, 1, 0) >= 4 // horizontal
|| count(type, x, y, 0, -1) + 1 + count(type, x, y, 0, 1) >= 4 // vertical
|| count(type, x, y, -1, -1) + 1 + count(type, x, y, 1, 1) >= 4 // diagonal
|| count(type, x, y, -1, 1) + 1 + count(type, x, y, 1, -1) >= 4);
}
Run Code Online (Sandbox Code Playgroud)
dx和dy检查参数用于在不同方向上移动,而无需为每个方向分别设置方法.
在你的水平校验码中,你可能通过在循环中将x加1来保持下一个(保持y不变,即将0加到y).在垂直检查代码中,通过向y(和0到x)添加1来移动到下一个部分.要沿对角线移动,您需要为x和y坐标添加1.
为了能够使用单一方法检查所有方向,check()使用移动方向的参数:dx = 1和dy = 0在每个步骤中将1添加到x和0到y,因此您要进行水平检查.使用dx = 0和dy = 1,您可以进行垂直检查.
编辑:摆脱了检查助手,因为它只是在一个地方真的需要