【发布时间】:2015-12-22 14:04:05
【问题描述】:
我知道有很多关于连接 4 检查是否获胜的问题。问题是大多数其他算法使我的程序出现运行时错误,因为它们试图访问我的数组之外的索引。 我的算法是这样的:
private int checkWin(int[][] gridTable,int rowNum,int colNum, int maxRow, int maxCol)
{
// For checking whether any win or lose condition is reached. Returns 1 if win or lose is reached. else returns 0
// gridTable[][] is the game matrix(can be any number of rows and columns between 4 and 40)
// colNum is the column number where the last token was placed
// rowNum is the row number where the last token was placed
// maxRow is the number of rows in my grid
// maxCol is the number of columns in my grid
int player = gridTable[rowNum][colNum]; //player ID
int count=0;
// Horizontal check
for (int i=0;i<maxCol;i++)
{
if (gridTable[rowNum][i]==player)
count++;
else
count=0;
if (count>=4)
return 1;
}
//Vertical check
for (int i=0;i<maxRow;i++)
{
if (gridTable[i][colNum]==player)
count++;
else
count=0;
if (count>=4)
return 1;
}
count=0;
// 4 in a row diagonally
for(int i=colNum+1,j=rowNum+1;i<maxRow && j<maxCol;i++,j++)
{
if(gridTable[j][i]!=player)
{
count=1;
break;
}
count++;
}
// 4 in a row diagonally
for(int i=colNum-1,j=rowNum-1;i>=0 && j>=0;i--,j--)
{
if(gridTable[j][i]!=player)
{
count=1;
break;
}
count++;
}
// 4 in a row diagonally
for(int i=colNum+1,j=rowNum-1;i<maxRow && j>=0;i++,j--)
{
if(gridTable[j][i]!=player)
{
count=1;
break;
}
count++;
}
for(int i=colNum-1,j=rowNum+1;i>=0 && j<maxCol;i--,j++)
{ // 4 in a row diagonally
if(gridTable[j][i]!=player)
{
count=1;
break;
}
count++;
}
if(count>=4)
return 1;
return 0;
}
count 是检查是否获胜的变量,如果 count 等于或大于 4 意味着它们应该是同一玩家的 4 个或更多连续令牌。
问题:有时该方法在没有按顺序排列 4 个令牌的情况下检查获胜,而其他时候在按顺序排列 4 个令牌时不检查获胜。
【问题讨论】:
-
那么索引边界错误发生在哪一行?
-
@MarcB 这个算法不返回任何绑定错误,这个问题更多的是一个逻辑错误,因为有时当 4 个元素连续时不返回胜利,有时当更少时返回胜利连续超过 3 个元素。
-
基本上你有一个二维矩阵,在这个矩阵中,你需要能够从给定的点开始,向给定的方向移动,检查它们是否是四个匹配的元素。我为tic tac toe 做了类似的事情,但从概念上讲,这是同一件事
-
@MadProgrammer 我试着那样做,但是当我有 3 个令牌、一个空白令牌和另一个令牌时发生了一些事情,当我丢弃生成 5 个直接令牌的令牌时它没有返回胜利
-
我可以看到的一个问题是,当您检查一个单元格时,您要么增加计数,要么将其重置为 0 并继续检查。您可能应该跳出循环并改为检查下一个方向(如果您没有找到四个匹配项)。但是随后您开始做一些不同的事情,在某些情况下,如果检查失败,您甚至不会重置计数...
标签: java arrays algorithm netbeans