java - How should I implement a horizontal win algorithm for my Connect 4 program?
问题描述
I am making a connect 4 board game and I implemented this horizontal win algorithm. It doesn't seem to work for some reason. Based on the code I assumed the conditions I set in the algorithm would look over the values assigned to the array in generateBoard method but it did not.
What could a possible solution be? Any help is appreciated.
public static String[][] generateBoard(){
String[][] board = new String[6][7]; //[row][column] 6 by 7
for(int i = 0; i<board.length; i++) {
for(int j = 0; j<board[i].length; j++) {
if(j == 0)
board[i][j] = "| |";
else
board[i][j] = " |";
}
}
return board;
}
Horizontal Win Algorithm:
//Checks to see which player's turn it is
String color = (redPlayerTurn) ? "R" : "Y";
int pattern = 0; //Used as a flag for detecting a winner
//HORIZONTAL Check
for(int i = 1; i < board.length; i++) {
String columnIndex = board[i][0];
pattern = 1;
for(int j = 1; j < board[i].length; j++) {
if(!(board[i][j].contains("| |") || board[i][j].contains(" |"))) {
if(columnIndex == board[j][i] && pattern != 0)
pattern++;
}else
columnIndex = board[i][j];
pattern = 0;
}if(pattern == 4) {
return true;
}
}
解决方案
//Checks to see which player's turn it is
String color = (redPlayerTurn) ? "R" : "Y";
int pattern = 0; //Used as a flag for detecting a winner
//HORIZONTAL Check
for(int i = 1; i < board.length; i++) {
String columnIndex = board[i][0];
pattern = 1;
for(int j = 1; j < board[i].length; j++) {
if(!board[i][j].contains("|")) {
if(columnIndex == board[j][i] && pattern != 0) {
pattern++;
} else {
columnIndex = board[i][j];
pattern = 0; // <- missing {} will assign pattern to 0
}
}
}
if(pattern >= 4) {
return true;
}
}
推荐阅读
- algorithm - 机器人和容器最小化问题,需要的方法
- reactjs - 避免在 React 渲染循环中进行每次迭代绑定
- java - 在 dynamodb 中获取地图字符串
- php - 有没有办法减少 PHP Mail() 的电子邮件延迟
- google-cloud-platform - 查找 GCP 平台的项目、存储桶、计算实例详细信息
- javascript - 如何在提示之前 console.log
- spss - 运行频率以查看一个变量的值组合
- algorithm - 查找树可以通过添加或相乘节点生成的所有数字
- forms - 将参考 ID 从 url 栏传递到其他内部页面
- svg - SvgPicture.asset 未正确调整图像大小