Refactored Game to follow encapsulation principle

This commit is contained in:
2025-10-29 17:28:43 +01:00
parent 50713c5021
commit 5da0a02cc8
7 changed files with 152 additions and 139 deletions

View File

@@ -254,10 +254,10 @@ public class Connect4Game {
private void updateCanvas() {
canvas.clearAll();
for (int i = 0; i < game.board.length; i++) {
if (game.board[i] == 'X') {
for (int i = 0; i < game.getBoard().length; i++) {
if (game.getBoard()[i] == 'X') {
canvas.drawDot(Color.RED, i);
} else if (game.board[i] == 'O') {
} else if (game.getBoard()[i] == 'O') {
canvas.drawDot(Color.BLUE, i);
}
}

View File

@@ -258,10 +258,10 @@ public final class ReversiGame {
// Todo: this is very inefficient. still very fast but if the grid is bigger it might cause issues. improve.
canvas.clearAll();
for (int i = 0; i < game.board.length; i++) {
if (game.board[i] == 'B') {
for (int i = 0; i < game.getBoard().length; i++) {
if (game.getBoard()[i] == 'B') {
canvas.drawDot(Color.BLACK, i);
} else if (game.board[i] == 'W') {
} else if (game.getBoard()[i] == 'W') {
canvas.drawDot(Color.WHITE, i);
}
}
@@ -321,7 +321,7 @@ public final class ReversiGame {
Move[] moves = null;
if (isLegalMove) {
moves = game.getFlipsForPotentialMove(
new Point(cellEntered%game.columnSize,cellEntered/game.rowSize),
new Point(cellEntered%game.getColumnSize(),cellEntered/game.getRowSize()),
game.makeBoardAGrid(),
game.getCurrentPlayer());
}

View File

@@ -11,7 +11,7 @@ public class Connect4 extends TurnBasedGame {
public Connect4() {
super(6, 7, 2);
movesLeft = board.length;
movesLeft = this.getBoard().length;
}
public Connect4(Connect4 other) {
@@ -24,8 +24,8 @@ public class Connect4 extends TurnBasedGame {
final ArrayList<Move> legalMoves = new ArrayList<>();
final char currentValue = getCurrentValue();
for (int i = 0; i < columnSize; i++) {
if (board[i] == EMPTY) {
for (int i = 0; i < this.getColumnSize(); i++) {
if (this.getBoard()[i] == EMPTY) {
legalMoves.add(new Move(i, currentValue));
}
}
@@ -35,19 +35,19 @@ public class Connect4 extends TurnBasedGame {
@Override
public GameState play(Move move) {
assert move != null;
assert move.position() >= 0 && move.position() < board.length;
assert move.position() >= 0 && move.position() < this.getBoard().length;
assert move.value() == getCurrentValue();
int lowestEmptySpot = move.position();
for (int i = 0; i < rowSize; i++) {
int checkMovePosition = move.position() + columnSize * i;
if (checkMovePosition < board.length) {
if (board[checkMovePosition] == EMPTY) {
for (int i = 0; i < this.getRowSize(); i++) {
int checkMovePosition = move.position() + this.getColumnSize() * i;
if (checkMovePosition < this.getBoard().length) {
if (this.getBoard()[checkMovePosition] == EMPTY) {
lowestEmptySpot = checkMovePosition;
}
}
}
board[lowestEmptySpot] = move.value();
this.getBoard()[lowestEmptySpot] = move.value();
movesLeft--;
if (checkForWin()) {
@@ -63,33 +63,33 @@ public class Connect4 extends TurnBasedGame {
private boolean checkForWin() {
char[][] boardGrid = makeBoardAGrid();
for (int row = 0; row < rowSize; row++) {
for (int col = 0; col < columnSize; col++) {
for (int row = 0; row < this.getRowSize(); row++) {
for (int col = 0; col < this.getColumnSize(); col++) {
char cell = boardGrid[row][col];
if (cell == ' ' || cell == 0) continue;
if (col + 3 < columnSize &&
if (col + 3 < this.getColumnSize() &&
cell == boardGrid[row][col + 1] &&
cell == boardGrid[row][col + 2] &&
cell == boardGrid[row][col + 3]) {
return true;
}
if (row + 3 < rowSize &&
if (row + 3 < this.getRowSize() &&
cell == boardGrid[row + 1][col] &&
cell == boardGrid[row + 2][col] &&
cell == boardGrid[row + 3][col]) {
return true;
}
if (row + 3 < rowSize && col + 3 < columnSize &&
if (row + 3 < this.getRowSize() && col + 3 < this.getColumnSize() &&
cell == boardGrid[row + 1][col + 1] &&
cell == boardGrid[row + 2][col + 2] &&
cell == boardGrid[row + 3][col + 3]) {
return true;
}
if (row + 3 < rowSize && col - 3 >= 0 &&
if (row + 3 < this.getRowSize() && col - 3 >= 0 &&
cell == boardGrid[row + 1][col - 1] &&
cell == boardGrid[row + 2][col - 2] &&
cell == boardGrid[row + 3][col - 3]) {
@@ -101,9 +101,9 @@ public class Connect4 extends TurnBasedGame {
}
public char[][] makeBoardAGrid() {
char[][] boardGrid = new char[rowSize][columnSize];
for (int i = 0; i < rowSize*columnSize; i++) {
boardGrid[i / columnSize][i % columnSize] = board[i]; //boardGrid[y -> row] [x -> column]
char[][] boardGrid = new char[this.getRowSize()][this.getColumnSize()];
for (int i = 0; i < this.getRowSize()*this.getColumnSize(); i++) {
boardGrid[i / this.getColumnSize()][i % this.getColumnSize()] = this.getBoard()[i]; //this.getBoard()Grid[y -> row] [x -> column]
}
return boardGrid;
}

View File

@@ -1,16 +1,17 @@
package org.toop.game;
import org.toop.game.interfaces.IPlayable;
import org.toop.game.records.Move;
import java.util.Arrays;
public abstract class Game implements IPlayable {
public static final char EMPTY = (char)0;
public static final char EMPTY = (char)0; // Constant
public final int rowSize;
public final int columnSize;
public final char[] board;
private final int rowSize;
private final int columnSize;
private final char[] board;
protected Game(int rowSize, int columnSize) {
assert rowSize > 0 && columnSize > 0;
@@ -27,4 +28,13 @@ public abstract class Game implements IPlayable {
columnSize = other.columnSize;
board = Arrays.copyOf(other.board, other.board.length);
}
public int getRowSize() {return this.rowSize;}
public int getColumnSize() {return this.columnSize;}
public char[] getBoard() {return this.board;}
protected void setBoard(Move move){this.board[move.position()] = move.value();}
}

View File

@@ -33,16 +33,16 @@ public final class Reversi extends TurnBasedGame {
private void addStartPieces() {
board[27] = 'W';
board[28] = 'B';
board[35] = 'B';
board[36] = 'W';
this.setBoard(new Move(27, 'W'));
this.setBoard(new Move(28, 'B'));
this.setBoard(new Move(35, 'B'));
this.setBoard(new Move(36, 'W'));
updateFilledCellsSet();
}
private void updateFilledCellsSet() {
for (int i = 0; i < 64; i++) {
if (board[i] == 'W' || board[i] == 'B') {
filledCells.add(new Point(i % columnSize, i / rowSize));
if (this.getBoard()[i] == 'W' || this.getBoard()[i] == 'B') {
filledCells.add(new Point(i % this.getColumnSize(), i / this.getRowSize()));
}
}
}
@@ -57,7 +57,7 @@ public final class Reversi extends TurnBasedGame {
Move[] moves = getFlipsForPotentialMove(point,boardGrid,currentPlayer);
int score = moves.length;
if (score > 0){
legalMoves.add(new Move(point.x + point.y * rowSize, currentPlayer));
legalMoves.add(new Move(point.x + point.y * this.getRowSize(), currentPlayer));
}
}
return legalMoves.toArray(new Move[0]);
@@ -73,7 +73,7 @@ public final class Reversi extends TurnBasedGame {
|| !isOnBoard(newX, newY)) {
continue;
}
if (boardGrid[newY][newX] == Game.EMPTY) { //check if the cell is empty
if (boardGrid[newY][newX] == EMPTY) { //check if the cell is empty
possibleCells.add(new Point(newX, newY)); //and then add it to the set of possible moves
}
}
@@ -110,7 +110,7 @@ public final class Reversi extends TurnBasedGame {
while (isOnBoard(x, y) && boardGrid[y][x] == opponent) {
movesToFlip.add(new Move(x+y*rowSize, currentPlayer));
movesToFlip.add(new Move(x+y*this.getRowSize(), currentPlayer));
x += dirX;
y += dirY;
}
@@ -121,13 +121,13 @@ public final class Reversi extends TurnBasedGame {
}
private boolean isOnBoard(int x, int y) {
return x >= 0 && x < columnSize && y >= 0 && y < rowSize;
return x >= 0 && x < this.getColumnSize() && y >= 0 && y < this.getRowSize();
}
public char[][] makeBoardAGrid() {
char[][] boardGrid = new char[rowSize][columnSize];
char[][] boardGrid = new char[this.getRowSize()][this.getColumnSize()];
for (int i = 0; i < 64; i++) {
boardGrid[i / rowSize][i % columnSize] = board[i]; //boardGrid[y / row] [x / column]
boardGrid[i / this.getRowSize()][i % this.getColumnSize()] = this.getBoard()[i]; //boardGrid[y / row] [x / column]
}
return boardGrid;
}
@@ -142,13 +142,13 @@ public final class Reversi extends TurnBasedGame {
}
}
if (moveIsLegal) {
Move[] moves = sortMovesFromCenter(getFlipsForPotentialMove(new Point(move.position()%columnSize,move.position()/rowSize), makeBoardAGrid(), move.value()),move);
Move[] moves = sortMovesFromCenter(getFlipsForPotentialMove(new Point(move.position()%this.getColumnSize(),move.position()/this.getRowSize()), makeBoardAGrid(), move.value()),move);
mostRecentlyFlippedPieces = moves;
board[move.position()] = move.value();
this.setBoard(move);
for (Move m : moves) {
board[m.position()] = m.value();
this.setBoard(m);
}
filledCells.add(new Point(move.position() % rowSize, move.position() / columnSize));
filledCells.add(new Point(move.position() % this.getRowSize(), move.position() / this.getColumnSize()));
nextTurn();
if (getLegalMoves().length == 0) {
skipMyTurn();
@@ -196,24 +196,24 @@ public final class Reversi extends TurnBasedGame {
public Score getScore(){
int player1Score = 0, player2Score = 0;
for (int count = 0; count < rowSize * columnSize; count++) {
if (board[count] == 'B') {
for (int count = 0; count < this.getRowSize() * this.getColumnSize(); count++) {
if (this.getBoard()[count] == 'B') {
player1Score += 1;
}
if (board[count] == 'W') {
if (this.getBoard()[count] == 'W') {
player2Score += 1;
}
}
return new Score(player1Score, player2Score);
}
public Move[] sortMovesFromCenter(Move[] moves, Move center) {
int centerX = center.position()%columnSize;
int centerY = center.position()/rowSize;
int centerX = center.position()%this.getColumnSize();
int centerY = center.position()/this.getRowSize();
Arrays.sort(moves, (a, b) -> {
int dxA = a.position()%columnSize - centerX;
int dyA = a.position()/rowSize - centerY;
int dxB = b.position()%columnSize - centerX;
int dyB = b.position()/rowSize - centerY;
int dxA = a.position()%this.getColumnSize() - centerX;
int dyA = a.position()/this.getRowSize() - centerY;
int dxB = b.position()%this.getColumnSize() - centerX;
int dyB = b.position()/this.getRowSize() - centerY;
int distA = dxA * dxA + dyA * dyA;
int distB = dxB * dxB + dyB * dyB;

View File

@@ -10,7 +10,7 @@ public final class TicTacToe extends TurnBasedGame {
public TicTacToe() {
super(3, 3, 2);
movesLeft = board.length;
movesLeft = this.getBoard().length;
}
public TicTacToe(TicTacToe other) {
@@ -23,8 +23,8 @@ public final class TicTacToe extends TurnBasedGame {
final ArrayList<Move> legalMoves = new ArrayList<>();
final char currentValue = getCurrentValue();
for (int i = 0; i < board.length; i++) {
if (board[i] == EMPTY) {
for (int i = 0; i < this.getBoard().length; i++) {
if (this.getBoard()[i] == EMPTY) {
legalMoves.add(new Move(i, currentValue));
}
}
@@ -35,10 +35,11 @@ public final class TicTacToe extends TurnBasedGame {
@Override
public GameState play(Move move) {
assert move != null;
assert move.position() >= 0 && move.position() < board.length;
assert move.position() >= 0 && move.position() < this.getBoard().length;
assert move.value() == getCurrentValue();
board[move.position()] = move.value();
// TODO: Make sure this move is allowed, maybe on the board side?
this.setBoard(move);
movesLeft--;
if (checkForWin()) {
@@ -61,27 +62,27 @@ public final class TicTacToe extends TurnBasedGame {
for (int i = 0; i < 3; i++) {
final int index = i * 3;
if (board[index] != EMPTY
&& board[index] == board[index + 1]
&& board[index] == board[index + 2]) {
if (this.getBoard()[index] != EMPTY
&& this.getBoard()[index] == this.getBoard()[index + 1]
&& this.getBoard()[index] == this.getBoard()[index + 2]) {
return true;
}
}
// Vertical
for (int i = 0; i < 3; i++) {
if (board[i] != EMPTY && board[i] == board[i + 3] && board[i] == board[i + 6]) {
if (this.getBoard()[i] != EMPTY && this.getBoard()[i] == this.getBoard()[i + 3] && this.getBoard()[i] == this.getBoard()[i + 6]) {
return true;
}
}
// B-Slash
if (board[0] != EMPTY && board[0] == board[4] && board[0] == board[8]) {
if (this.getBoard()[0] != EMPTY && this.getBoard()[0] == this.getBoard()[4] && this.getBoard()[0] == this.getBoard()[8]) {
return true;
}
// F-Slash
return board[2] != EMPTY && board[2] == board[4] && board[2] == board[6];
return this.getBoard()[2] != EMPTY && this.getBoard()[2] == this.getBoard()[4] && this.getBoard()[2] == this.getBoard()[6];
}
private boolean checkForEarlyDraw(TicTacToe game) {

View File

@@ -6,6 +6,8 @@ import java.util.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.toop.game.enumerators.GameState;
import org.toop.game.records.Move;
import org.toop.game.reversi.Reversi;
import org.toop.game.reversi.ReversiAI;
@@ -25,27 +27,27 @@ class ReversiTest {
@Test
void testCorrectStartPiecesPlaced() {
assertNotNull(game);
assertEquals('W',game.board[27]);
assertEquals('B',game.board[28]);
assertEquals('B',game.board[35]);
assertEquals('W',game.board[36]);
assertEquals('W',game.getBoard()[27]);
assertEquals('B',game.getBoard()[28]);
assertEquals('B',game.getBoard()[35]);
assertEquals('W',game.getBoard()[36]);
}
@Test
void testGetLegalMovesAtStart() {
Game.Move[] moves = game.getLegalMoves();
List<Game.Move> expectedMoves = List.of(
new Game.Move(19,'B'),
new Game.Move(26,'B'),
new Game.Move(37,'B'),
new Game.Move(44,'B')
Move[] moves = game.getLegalMoves();
List<Move> expectedMoves = List.of(
new Move(19,'B'),
new Move(26,'B'),
new Move(37,'B'),
new Move(44,'B')
);
assertNotNull(moves);
assertTrue(moves.length > 0);
assertMovesMatchIgnoreOrder(expectedMoves, Arrays.asList(moves));
}
private void assertMovesMatchIgnoreOrder(List<Game.Move> expected, List<Game.Move> actual) {
private void assertMovesMatchIgnoreOrder(List<Move> expected, List<Move> actual) {
assertEquals(expected.size(), actual.size());
for (int i = 0; i < expected.size(); i++) {
assertTrue(actual.contains(expected.get(i)));
@@ -55,16 +57,16 @@ class ReversiTest {
@Test
void testMakeValidMoveFlipsPieces() {
game.play(new Game.Move(19, 'B'));
assertEquals('B', game.board[19]);
assertEquals('B', game.board[27], "Piece should have flipped to B");
game.play(new Move(19, 'B'));
assertEquals('B', game.getBoard()[19]);
assertEquals('B', game.getBoard()[27], "Piece should have flipped to B");
}
@Test
void testMakeInvalidMoveDoesNothing() {
char[] before = game.board.clone();
game.play(new Game.Move(0, 'B'));
assertArrayEquals(before, game.board, "Board should not change on invalid move");
char[] before = game.getBoard().clone();
game.play(new Move(0, 'B'));
assertArrayEquals(before, game.getBoard(), "Board should not change on invalid move");
}
@Test
@@ -77,7 +79,7 @@ class ReversiTest {
@Test
void testCountScoreCorrectlyAtStart() {
long start = System.nanoTime();
Game.Score score = game.getScore();
Reversi.Score score = game.getScore();
assertEquals(2, score.player1Score()); // Black
assertEquals(2, score.player2Score()); // White
long end = System.nanoTime();
@@ -86,15 +88,15 @@ class ReversiTest {
@Test
void zLegalMovesInCertainPosition() {
game.play(new Game.Move(19, 'B'));
game.play(new Game.Move(20, 'W'));
Game.Move[] moves = game.getLegalMoves();
List<Game.Move> expectedMoves = List.of(
new Game.Move(13,'B'),
new Game.Move(21, 'B'),
new Game.Move(29, 'B'),
new Game.Move(37, 'B'),
new Game.Move(45, 'B'));
game.play(new Move(19, 'B'));
game.play(new Move(20, 'W'));
Move[] moves = game.getLegalMoves();
List<Move> expectedMoves = List.of(
new Move(13,'B'),
new Move(21, 'B'),
new Move(29, 'B'),
new Move(37, 'B'),
new Move(45, 'B'));
assertNotNull(moves);
assertTrue(moves.length > 0);
IO.println(Arrays.toString(moves));
@@ -105,12 +107,12 @@ class ReversiTest {
void testCountScoreCorrectlyAtEnd() {
for (int i = 0; i < 1; i++){
game = new Reversi();
Game.Move[] legalMoves = game.getLegalMoves();
Move[] legalMoves = game.getLegalMoves();
while(legalMoves.length > 0) {
game.play(legalMoves[(int)(Math.random()*legalMoves.length)]);
legalMoves = game.getLegalMoves();
}
Game.Score score = game.getScore();
Reversi.Score score = game.getScore();
IO.println(score.player1Score());
IO.println(score.player2Score());
char[][] grid = game.makeBoardAGrid();
@@ -123,27 +125,27 @@ class ReversiTest {
@Test
void testPlayerMustSkipTurnIfNoValidMoves() {
game.play(new Game.Move(19, 'B'));
game.play(new Game.Move(34, 'W'));
game.play(new Game.Move(45, 'B'));
game.play(new Game.Move(11, 'W'));
game.play(new Game.Move(42, 'B'));
game.play(new Game.Move(54, 'W'));
game.play(new Game.Move(37, 'B'));
game.play(new Game.Move(46, 'W'));
game.play(new Game.Move(63, 'B'));
game.play(new Game.Move(62, 'W'));
game.play(new Game.Move(29, 'B'));
game.play(new Game.Move(50, 'W'));
game.play(new Game.Move(55, 'B'));
game.play(new Game.Move(30, 'W'));
game.play(new Game.Move(53, 'B'));
game.play(new Game.Move(38, 'W'));
game.play(new Game.Move(61, 'B'));
game.play(new Game.Move(52, 'W'));
game.play(new Game.Move(51, 'B'));
game.play(new Game.Move(60, 'W'));
game.play(new Game.Move(59, 'B'));
game.play(new Move(19, 'B'));
game.play(new Move(34, 'W'));
game.play(new Move(45, 'B'));
game.play(new Move(11, 'W'));
game.play(new Move(42, 'B'));
game.play(new Move(54, 'W'));
game.play(new Move(37, 'B'));
game.play(new Move(46, 'W'));
game.play(new Move(63, 'B'));
game.play(new Move(62, 'W'));
game.play(new Move(29, 'B'));
game.play(new Move(50, 'W'));
game.play(new Move(55, 'B'));
game.play(new Move(30, 'W'));
game.play(new Move(53, 'B'));
game.play(new Move(38, 'W'));
game.play(new Move(61, 'B'));
game.play(new Move(52, 'W'));
game.play(new Move(51, 'B'));
game.play(new Move(60, 'W'));
game.play(new Move(59, 'B'));
assertEquals('B', game.getCurrentPlayer());
game.play(ai.findBestMove(game,5));
game.play(ai.findBestMove(game,5));
@@ -152,40 +154,40 @@ class ReversiTest {
@Test
void testGameShouldEndIfNoValidMoves() {
//European Grand Prix Ghent 2017: Replay Hassan - Verstuyft J. (3-17)
game.play(new Game.Move(19, 'B'));
game.play(new Game.Move(20, 'W'));
game.play(new Game.Move(29, 'B'));
game.play(new Game.Move(22, 'W'));
game.play(new Game.Move(21, 'B'));
game.play(new Game.Move(34, 'W'));
game.play(new Game.Move(23, 'B'));
game.play(new Game.Move(13, 'W'));
game.play(new Game.Move(26, 'B'));
game.play(new Game.Move(18, 'W'));
game.play(new Game.Move(12, 'B'));
game.play(new Game.Move(4, 'W'));
game.play(new Game.Move(17, 'B'));
game.play(new Game.Move(31, 'W'));
Game.State stateTurn15 = game.play(new Game.Move(39, 'B'));
assertEquals(Game.State.NORMAL, stateTurn15);
Game.State stateTurn16 = game.play(new Game.Move(16, 'W'));
assertEquals(Game.State.WIN, stateTurn16);
Game.State stateTurn17 = game.play(new Game.Move(5, 'B'));
game.play(new Move(19, 'B'));
game.play(new Move(20, 'W'));
game.play(new Move(29, 'B'));
game.play(new Move(22, 'W'));
game.play(new Move(21, 'B'));
game.play(new Move(34, 'W'));
game.play(new Move(23, 'B'));
game.play(new Move(13, 'W'));
game.play(new Move(26, 'B'));
game.play(new Move(18, 'W'));
game.play(new Move(12, 'B'));
game.play(new Move(4, 'W'));
game.play(new Move(17, 'B'));
game.play(new Move(31, 'W'));
GameState stateTurn15 = game.play(new Move(39, 'B'));
assertEquals(GameState.NORMAL, stateTurn15);
GameState stateTurn16 = game.play(new Move(16, 'W'));
assertEquals(GameState.WIN, stateTurn16);
GameState stateTurn17 = game.play(new Move(5, 'B'));
assertNull(stateTurn17);
Game.Score score = game.getScore();
Reversi.Score score = game.getScore();
assertEquals(3, score.player1Score());
assertEquals(17, score.player2Score());
}
@Test
void testAISelectsLegalMove() {
Game.Move move = ai.findBestMove(game,4);
Move move = ai.findBestMove(game,4);
assertNotNull(move);
assertTrue(containsMove(game.getLegalMoves(),move), "AI should always choose a legal move");
}
private boolean containsMove(Game.Move[] moves, Game.Move move) {
for (Game.Move m : moves) {
private boolean containsMove(Move[] moves, Move move) {
for (Move m : moves) {
if (m.equals(move)) return true;
}
return false;