I want to check the diagonal lines and horizontal lines of my 2D-enum-array.
The 2D-enum-array looks like this:
private Zelle[][] board = new Zelle[width][height];
My enum looks like this:
public enum Zelle {
RED("RED "),
YELLOW("YELLOW"),
Empty("EMPTY ");
}
The function isConnect4() can already check the vertical lines.
public void isConnect4(int col) {
for (int i = 0; i < height; i++) {
//vertical
switch (board[col][i]) {
case RED -> --counter;
case YELLOW -> ++counter;
case Empty -> counter = 0;
}
}
if (Math.abs(counter) == 4 ) {
System.out.println("Es liegt ein Gewinner vor");
winner = true;
}
}
I fill my 2d array with the makeMove(int col) method and always check if there is a winning line:
public void makeMove(int col) {
if (start && !winner && (IntStream.rangeClosed(0, 6).boxed().toList().contains(col))
&& board[col][0].equals(Zelle.Empty)) {
board[col][IntStream.rangeClosed(0, 6).map(i -> 5 - i).
filter(i -> board[col][i].equals(Zelle.Empty)).findFirst().getAsInt()] = currentPlayer();
next();
System.out.println(printBoard());
} else if (!(board[col][0].equals(Zelle.Empty))) {
System.out.println("You cannot move there, please pick another Column");
} else if (!start){
System.out.println("Game has not started yet");
}
else {
System.out.println("Game Over! Winner is: " + currentplayer );
}
isConnect4(col);
}
For the horizontal, I need to get the current position and look 3 to the left and 3 to the right. For the diagonal, I need to look into 4 different position: left top, left bottom, right top and right bottom. Maybe something like this:
//pseudocode
//this for 4 different directions(left top, left bottom, right top and right bottom.)
for(int i = 0; i <3; i++){
switch (board[col+i][currentPosition]) {
case RED -> --counter;
case YELLOW -> ++counter;
case Empty -> counter = 0;
}
What is the best approach for this? It would also be nice to use Streams (if that's possible).