【发布时间】:2015-02-20 14:28:56
【问题描述】:
我正在创建一个可扩展的井字游戏程序,但在尝试检查字符串的对角线时遇到了问题。
我可以使用这种方法检查行:
public boolean checkRowsForWin(String b){
//Check all the rows for a winner
for(int y = 0; y < size; y++){
for (int x = 0; x < size; x++){
if (globalGrid[y][x].equals(b)){
inRow++;
if (inRow >= neededToWin){
return true;
}
}else{
inRow = 0;
}
}
inRow = 0;
}
inRow = 0;
return false;
}
我尝试了 for 循环和 if 语句的组合,我最后的修改如下。如果对角线仅包含右上角,则此方法有效,当我需要它来检查即使对角线不在角落时也是如此。
public boolean checkDiagForWin(String b, int c, int d){
for (int x = c, y = d; x < size && y < size; x++, y++){
if (globalGrid[y][x].equals(b)){
inRow++;
if (inRow >= neededToWin){
return true;
}
}
else{
inRow = 0;
}
inRow = 0;
for (int x2 = size - 1, y2 = 0; x2 >=0 && y2 < size; x2--, y2++){
if (globalGrid[y2][x2].equals(b)){
inRow++;
if (inRow >= neededToWin){
return true;
}
}
else{
inRow = 0;
}
}
inRow = 0;
}
inRow = 0;
return false;
}
一行的数量和棋盘的大小是可以变化的,所以不是只检查两个相邻的位置那么简单。
【问题讨论】: