Right now I am creating a connect 4 game in swing. I did not post all the GUI components since it is not important. The game detects horizontal wins for all rows except the bottom row. Here is the code for the win detection.
boolean CheckForWin()
{
for (int row = 1; row < gameBoard.length; row++) //Plus 1 is added to prepare for dimension swap.
{
//Player 1 horizontal count
int max=0;
//Player 2 horrizontal count
int max2=0;
int count_piece=0;
for(int column=1; column<gameBoard.length; column++)
{
// check for horizontal
if(row==6)
{
break;
}
if(count_piece<max || count_piece<max2)
{
count_piece=max;
count_piece=max2;
}
if(gameBoard[row][column]=='r')
{
max++;
}
else
{
max=0;
}
if(gameBoard[row][column]=='b')
{
max2++;
}
else
{
max2=0;
}
if(max==4 || max2==4)
{
return true;
}
// check for vertical
}
}
// check for diagonal up
// check for diagonal down
return false;
}
I’m assuming gameboard is an array of arrays? You are starting rows and columns at 1 in your loops but they are 0 based in java. Do you also not detect a win in the furthest left column?
You should change your loops to
for int row = 0;...andfor int column = 0...