LOG320_Lab4/src/main/java/laboratoire4/MovingBoard.java
2023-03-25 19:28:12 -04:00

91 lines
2.5 KiB
Java

package laboratoire4;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Stack;
import java.util.function.Predicate;
public class MovingBoard {
private final MovingPawn[][] board;
private final Player player;
private final Stack<MovingPawn> removedPawns = new Stack<>();
private final Stack<MovingPawn> previousMovedPawns = new Stack<>();
public MovingBoard(Pawn[][] board, Player player) {
this.board = asMovingPawns(board);
this.player = player;
}
public void move(MovingPawn pawn, Pawn.PawnMovement movement) {
int toRow = pawn.getRow() + pawn.getDirection();
int toCol = pawn.getCol() + movement.getMove();
MovingPawn capturedPawn = board[toRow][toCol];
previousMovedPawns.push(pawn);
removedPawns.push(capturedPawn);
board[pawn.getRow()][pawn.getCol()] = null;
board[toRow][toCol] = pawn;
pawn.move(movement);
}
public void revertMove() {
MovingPawn pawn = previousMovedPawns.pop();
MovingPawn capturedPawn = removedPawns.pop();
board[pawn.getRow()][pawn.getCol()] = capturedPawn;
pawn.revertMove();
board[pawn.getRow()][pawn.getCol()] = pawn;
}
public MovingPawn[][] getBoard() {
return board;
}
public Player getPlayer() {
return player;
}
public boolean hasCaptured() {
return removedPawns.peek() != null;
}
public Collection<MovingPawn> getMaxPawns() {
return getPawns(p -> p.getPlayer() == player);
}
public Collection<MovingPawn> getMinPawns() {
return getPawns(p -> p.getPlayer() != player);
}
private Collection<MovingPawn> getPawns(Predicate<MovingPawn> predicate) {
List<MovingPawn> pawns = new ArrayList<>();
for (MovingPawn[] row : board) {
for (MovingPawn pawn : row) {
if (pawn != null && predicate.test(pawn)) {
pawns.add(pawn);
}
}
}
return pawns;
}
public static MovingPawn[][] asMovingPawns(Pawn[][] board) {
MovingPawn[][] to = new MovingPawn[board.length][board.length];
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board.length; col++) {
if (board[row][col] == null) {
continue;
}
MovingPawn pawn = MovingPawn.from(board[row][col]);
to[row][col] = pawn;
}
}
return to;
}
}