diff --git a/api/AIEngine.java b/api/AIEngine.java index 3490ec4..26101ca 100644 --- a/api/AIEngine.java +++ b/api/AIEngine.java @@ -23,7 +23,7 @@ public Move getSmartMove(Player player, TicTacToeBoard board){ for (int j = 0; j < 3; j++) { if (board.getSymbol(i,j)==null){ Move move = new Move(player, new Cell(i,j)); - Board boardCopy = board.copy(); + Board boardCopy = board.clone(); boardCopy.move(move); if(ruleEngine.getState(boardCopy).isOver()){ return move; @@ -38,7 +38,7 @@ public Move getSmartMove(Player player, TicTacToeBoard board){ if (board.getSymbol(i,j)==null){ Move move = new Move(player.flip(), new Cell(i,j)); - Board boardCopy = board.copy(); + Board boardCopy = board.clone(); boardCopy.move(move); if(ruleEngine.getState(boardCopy).isOver()){ return new Move(player, new Cell(i,j)); diff --git a/boards/TicTacToeBoard.java b/boards/TicTacToeBoard.java index 38ac14a..35c2855 100644 --- a/boards/TicTacToeBoard.java +++ b/boards/TicTacToeBoard.java @@ -6,9 +6,17 @@ import java.util.Arrays; -public class TicTacToeBoard implements Board { +public class TicTacToeBoard implements Board, Cloneable { String[][] cells = new String[3][3]; + public TicTacToeBoard() { + } + + private TicTacToeBoard(TicTacToeBoard board) { + for (int i = 0; i < 3; i++) { + this.cells[i] = Arrays.copyOf(board.cells[i], 3); // Deep copy of each row + } + } public String getSymbol(int i,int j){ return this.cells[i][j]; } @@ -21,21 +29,6 @@ public void setCell(Cell cell, String symbol) { } } - @Override - public TicTacToeBoard copy(){ - TicTacToeBoard ticTacToeBoard = new TicTacToeBoard(); - - for(int i=0;i<3;i++){ - ticTacToeBoard.cells[i] = Arrays.copyOf(this.cells[i], 3); // This the deep copy, no reference to other cells -/* - for(int j=0;j<3;j++){ This is the shallow copy and contains the reference of original board - ticTacToeBoard.cells[i][j] = cells[i][j]; - } -*/ - } - return ticTacToeBoard; - } - @Override public void move(Move move){ setCell(move.getCell(),move.getPlayer().symbol()); @@ -53,4 +46,9 @@ public String toString(){ } return result.toString(); } + + @Override + public TicTacToeBoard clone() { + return new TicTacToeBoard(this); + } } diff --git a/game/Board.java b/game/Board.java index e464f29..4b3416a 100644 --- a/game/Board.java +++ b/game/Board.java @@ -2,5 +2,5 @@ public interface Board { public abstract void move(Move move); - public abstract Board copy(); +// public abstract Board copy(); } diff --git a/test/GamePlayTest.java b/test/GamePlayTest.java index 2bf95f2..c4adbf6 100644 --- a/test/GamePlayTest.java +++ b/test/GamePlayTest.java @@ -8,7 +8,6 @@ import game.Move; import game.Player; -import java.util.Scanner; import org.junit.Assert; import org.junit.Before;