我正在用JavaFX创建一个Connect4游戏,这是我的checkWin方法。我的游戏的工作方式是,board中的每个单元格都有一个空白圆圈,只有当用户选择一列时,它才会有setFill(Color.RED) (或蓝色,取决于玩家)。除了这个方法之外,所有的东西都工作得很好。
public void checkWin(int row, int column, GridPane board) {
Circle piece = ((Circle)getNodeByRowColumnIndex(row, column, board));
// Horizontal check
if (column - 3 <= 0) {
for(int i = 1; piece.equals((Circle)getNodeByRowColumnIndex(row, column + i, board)) ; i++) {
System.out.println("Checking : (" + (row) + " , " + (column + i) + ")");
if(i == 4) hasWon = true;
}
} else if (column + 3 > Columns) {
for(int i = 1; piece.equals((Circle)getNodeByRowColumnIndex(row, column - i, board)) ; i++) {
System.out.println("Checking : (" + (row) + " , " + (column - i) + ")");
if(i == 4) hasWon = true;
}
}
// Vertical check
if (row - 3 <= 0) {
for(int i = 1; piece.equals((Circle)getNodeByRowColumnIndex(row + i, column, board)) ; i++) {
System.out.println("Checking : (" + (row + i) + " , " + (column) + ")");
if(i == 4) hasWon = true;
System.out.println(i);
}
} else if (row + 3 > Rows) {
for(int i = 1; piece.equals((Circle)getNodeByRowColumnIndex(row - i, column, board)) ; i++) {
System.out.println("Checking : (" + (row - i) + " , " + (column) + ")");
if(i == 4) hasWon = true;
}
}
// Ascending diagonal check
if (row - 3 <= 0 && column - 3 <= 0) {
for(int i = 1; piece.equals((Circle)getNodeByRowColumnIndex(row + i, column + i, board)) ; i++) {
System.out.println("Checking : (" + (row + i) + " , " + (column + i) + ")");
if(i == 4) hasWon = true;
}
} else if (row + 3 > Rows && column + 3 > Columns) {
for(int i = 1; piece.equals((Circle)getNodeByRowColumnIndex(row - i, column - i, board)) ; i++) {
System.out.println("Checking : (" + (row - i) + " , " + (column - i) + ")");
if(i == 4) hasWon = true;
}
}
// Descending diagonal check
if (row + 3 > Rows && column - 3 <= 0) {
for(int i = 1; piece.equals((Circle)getNodeByRowColumnIndex(row - i, column + i, board)); i++) {
System.out.println("Checking : (" + (row - i) + " , " + (column + i) + ")");
if(i == 4) hasWon = true;
}
} else if (row - 3 <= 0 && column + 3 > Columns) {
for(int i = 1; piece.equals((Circle)getNodeByRowColumnIndex(row + i, column - i, board)); i++) {
System.out.println("Checking : (" + (row + i) + " , " + (column - i) + ")");
if(i == 4) hasWon = true;
}
}
}发布于 2020-03-12 04:39:21
首先,通常情况下,试着将你的数据从你的表示中分离出来。因此,保留一些数组或其他数据结构,其中只存储是否有一块石头或其他东西。不存储圆
第二。实际问题是密切相关的,并说明了为什么要这样做:您只想比较圆的颜色。而不是圆圈本身。(我只是猜测这些是JavaFX圆,因为您没有显示完整的代码……)因为每个圆都有半径和圆心。而且每个中心都很可能是不同的,你的equals方法将总是返回false。
所以只比较颜色。或者更好:将数据从表示中分离出来。
https://stackoverflow.com/questions/60643811
复制相似问题