Right now I have a school assignment where I have to create a connect 4 game in java without a gui using arrays. So far I have been able to get the game to detect a horizontal four in a row but I can’t seem to get a vertical four in a row. Originally my array was a 6×7 but I have changed it to a 5×5 just to test the concept of swapping the arrays dementions. Just to make less clutter, I only included the part of the code with the vertical detection.
for (column = 0; column < board.length; column++) {
count_piece = 0;
max = 0;
for (row = 0; row < board.length; row++) {
if (max < count_piece) {
max = count_piece;
}
if (board[column][row] == 'X') {
count_piece++;
} else {
count_piece = 0;
}
}
}
System.out.println(max);
if (max == 4) {
System.out.println("\nYou Win!");
break;
}
If you need more information or if anything is not clear please let me know and i’ll be glad to provide some more info.
EDIT:
Here is the one with the inverted loop.
for (row = 0; row < board.length; row++) {
count_piece = 0;
max = 0;
for (column = 0; column < board.length; column++) {
if (max < count_piece) {
max = count_piece;
}
if (board[column][row] == 'X') {
count_piece++;
} else {
count_piece = 0;
}
}
}
How about inverting your loop that way your inner loop changing will be the column instead of the row?
Also make your inner loop take the length of the single array you are in.
So instead of using
board.lengthuse something likeboard[i].lengthEdit
I think your logic inside your inner loop is wrong…
Try this:
Here is both checks Horizontal and Vertical with any size array