I know there is a lot of of questions regarding connect 4 check for a win. The issue is that most of other algorithms make my program have runtime errors, because they try to access an index outside of my array.
My algorithm is like this:
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 is the variable that checks for a win if count is equal or more than 4 means they should be 4 or more consecutive tokens of the same player.
THE PROBLEM: sometimes the method checks for a win without being 4 tokens in order and other times does not check for a win when 4 tokens are in order.
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…