98 lines
2.9 KiB
Java
98 lines
2.9 KiB
Java
package domain;
|
|
|
|
import java.io.Serializable;
|
|
import java.util.*;
|
|
|
|
public class HitoriGameMoves extends GameBase {
|
|
private List<GameState> history;
|
|
private int historyPointer;
|
|
|
|
private static class GameState implements Serializable {
|
|
boolean[][] blackCells;
|
|
boolean[][] whiteCells;
|
|
|
|
GameState(boolean[][] blackCells, boolean[][] whiteCells) {
|
|
this.blackCells = new boolean[blackCells.length][blackCells[0].length];
|
|
this.whiteCells = new boolean[whiteCells.length][whiteCells[0].length];
|
|
for (int i = 0; i < blackCells.length; i++) {
|
|
this.blackCells[i] = Arrays.copyOf(blackCells[i], blackCells[i].length);
|
|
this.whiteCells[i] = Arrays.copyOf(whiteCells[i], whiteCells[i].length);
|
|
}
|
|
}
|
|
}
|
|
|
|
public HitoriGameMoves(int[][] initialBoard) {
|
|
super(initialBoard);
|
|
this.history = new ArrayList<>();
|
|
this.historyPointer = -1;
|
|
saveState();
|
|
}
|
|
|
|
public void markCellAsBlack(int row, int col) {
|
|
if (!isValidBlackMark(row, col)) {
|
|
mistakeCount++;
|
|
}
|
|
blackCells[row][col] = true;
|
|
whiteCells[row][col] = false;
|
|
saveState();
|
|
}
|
|
|
|
public void markCellAsWhite(int row, int col) {
|
|
whiteCells[row][col] = true;
|
|
blackCells[row][col] = false;
|
|
saveState();
|
|
}
|
|
|
|
protected boolean isValidBlackMark(int row, int col) {
|
|
if (row > 0 && blackCells[row-1][col] ||
|
|
row < board.length-1 && blackCells[row+1][col] ||
|
|
col > 0 && blackCells[row][col-1] ||
|
|
col < board[0].length-1 && blackCells[row][col+1]) {
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
private void saveState() {
|
|
while (history.size() > historyPointer + 1) {
|
|
history.remove(history.size() - 1);
|
|
}
|
|
history.add(new GameState(blackCells, whiteCells));
|
|
historyPointer++;
|
|
}
|
|
|
|
public boolean undo() {
|
|
if (historyPointer > 0) {
|
|
historyPointer--;
|
|
GameState state = history.get(historyPointer);
|
|
restoreState(state);
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
public boolean redo() {
|
|
if (historyPointer < history.size() - 1) {
|
|
historyPointer++;
|
|
GameState state = history.get(historyPointer);
|
|
restoreState(state);
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
private void restoreState(GameState state) {
|
|
for (int i = 0; i < board.length; i++) {
|
|
blackCells[i] = Arrays.copyOf(state.blackCells[i], state.blackCells[i].length);
|
|
whiteCells[i] = Arrays.copyOf(state.whiteCells[i], state.whiteCells[i].length);
|
|
}
|
|
}
|
|
|
|
@Override
|
|
public void reset() {
|
|
super.reset();
|
|
history.clear();
|
|
historyPointer = -1;
|
|
saveState();
|
|
}
|
|
} |