272 remake game framework interfaces to properly represent vmc (#278)

* Cleaned up a lot of old files and renamed/remade interfaces to better suit the framework

* Broken commit

* Fixed online play

* Better file structure and closer to MVC
This commit is contained in:
Stef
2025-12-03 20:35:37 +01:00
committed by GitHub
parent 040287ad70
commit 8d77f51355
68 changed files with 524 additions and 2702 deletions

View File

@@ -1,6 +0,0 @@
package org.toop.game;
import org.toop.game.interfaces.IAIMove;
public abstract class AI<T extends Game> implements IAIMove<T> {
}

View File

@@ -1,116 +0,0 @@
package org.toop.game.Connect4;
import org.toop.game.TurnBasedGame;
import org.toop.framework.gameFramework.GameState;
import org.toop.game.records.Move;
import java.util.ArrayList;
public class Connect4 extends TurnBasedGame {
private int movesLeft;
public Connect4() {
super(6, 7, 2);
movesLeft = this.getBoard().length;
}
public Connect4(Connect4 other) {
super(other);
movesLeft = other.movesLeft;
}
@Override
public Move[] getLegalMoves() {
final ArrayList<Move> legalMoves = new ArrayList<>();
final char currentValue = getCurrentValue();
for (int i = 0; i < this.getColumnSize(); i++) {
if (this.getBoard()[i] == EMPTY) {
legalMoves.add(new Move(i, currentValue));
}
}
return legalMoves.toArray(new Move[0]);
}
@Override
public GameState play(Move move) {
assert move != null;
assert move.position() >= 0 && move.position() < this.getBoard().length;
assert move.value() == getCurrentValue();
int lowestEmptySpot = move.position();
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;
}
}
}
this.getBoard()[lowestEmptySpot] = move.value();
movesLeft--;
if (checkForWin()) {
return GameState.WIN;
}
nextTurn();
return GameState.NORMAL;
}
private boolean checkForWin() {
char[][] boardGrid = makeBoardAGrid();
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 < this.getColumnSize() &&
cell == boardGrid[row][col + 1] &&
cell == boardGrid[row][col + 2] &&
cell == boardGrid[row][col + 3]) {
return true;
}
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 < 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 < this.getRowSize() && col - 3 >= 0 &&
cell == boardGrid[row + 1][col - 1] &&
cell == boardGrid[row + 2][col - 2] &&
cell == boardGrid[row + 3][col - 3]) {
return true;
}
}
}
return false;
}
private char[][] makeBoardAGrid() {
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;
}
private char getCurrentValue() {
return this.getCurrentTurn() == 0 ? 'X' : 'O';
}
}

View File

@@ -1,63 +0,0 @@
package org.toop.game.Connect4;
import org.toop.game.AI;
import org.toop.framework.gameFramework.GameState;
import org.toop.game.records.Move;
public class Connect4AI extends AI<Connect4> {
public Move findBestMove(Connect4 game, int depth) {
assert game != null;
assert depth >= 0;
final Move[] legalMoves = game.getLegalMoves();
if (legalMoves.length <= 0) {
return null;
}
int bestScore = -depth;
Move bestMove = null;
for (final Move move : legalMoves) {
final int score = getMoveScore(game, depth, move, true);
if (score > bestScore) {
bestMove = move;
bestScore = score;
}
}
return bestMove != null? bestMove : legalMoves[(int)(Math.random() * legalMoves.length)];
}
private int getMoveScore(Connect4 game, int depth, Move move, boolean maximizing) {
final Connect4 copy = new Connect4(game);
final GameState state = copy.play(move);
switch (state) {
case GameState.DRAW: return 0;
case GameState.WIN: return maximizing? depth + 1 : -depth - 1;
}
if (depth <= 0) {
return 0;
}
final Move[] legalMoves = copy.getLegalMoves();
int score = maximizing? depth + 1 : -depth - 1;
for (final Move next : legalMoves) {
if (maximizing) {
score = Math.min(score, getMoveScore(copy, depth - 1, next, false));
} else {
score = Math.max(score, getMoveScore(copy, depth - 1, next, true));
}
}
return score;
}
}

View File

@@ -1,40 +0,0 @@
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; // Constant
private final int rowSize;
private final int columnSize;
private final char[] board;
protected Game(int rowSize, int columnSize) {
assert rowSize > 0 && columnSize > 0;
this.rowSize = rowSize;
this.columnSize = columnSize;
board = new char[rowSize * columnSize];
Arrays.fill(board, EMPTY);
}
protected Game(Game other) {
rowSize = other.rowSize;
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

@@ -1,24 +0,0 @@
package org.toop.game.GameThreadBehaviour;
import org.toop.game.players.AbstractPlayer;
/**
* Strategy interface for controlling game thread behavior.
* <p>
* Defines how a game's execution is started, stopped, and which player is active.
*/
public interface GameThreadStrategy {
/** Starts the game loop or execution according to the strategy. */
void start();
/** Stops the game loop or execution according to the strategy. */
void stop();
/**
* Returns the player whose turn it currently is.
*
* @return the current active {@link AbstractPlayer}
*/
AbstractPlayer getCurrentPlayer();
}

View File

@@ -1,57 +0,0 @@
package org.toop.game.GameThreadBehaviour;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.toop.framework.gameFramework.abstractClasses.TurnBasedGameR;
import org.toop.game.players.AbstractPlayer;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Base class for thread-based game behaviours.
* <p>
* Provides common functionality for managing game state and execution:
* a running flag, a game reference, and a logger.
* Subclasses implement the actual game-loop logic.
*/
public abstract class ThreadBehaviourBase implements GameThreadStrategy {
private final AbstractPlayer[] players;
/** Indicates whether the game loop or event processing is active. */
protected final AtomicBoolean isRunning = new AtomicBoolean();
/** The game instance controlled by this behaviour. */
protected final TurnBasedGameR game;
/** Logger for the subclass to report errors or debug info. */
protected final Logger logger = LogManager.getLogger(this.getClass());
/**
* Creates a new base behaviour for the specified game.
*
* @param game the turn-based game to control
*/
public ThreadBehaviourBase(TurnBasedGameR game, AbstractPlayer[] players) {
this.game = game;
this.players = players;
}
/**
* Returns the player whose turn it currently is.
*
* @return the current active player
*/
@Override
public AbstractPlayer getCurrentPlayer() {
return players[game.getCurrentTurn()];
}
public AbstractPlayer getFirstPlayerWithName(String name) {
for (AbstractPlayer player : players){
if (player.getName().equals(name)){
return player;
}
}
return null;
}
}

View File

@@ -0,0 +1,3 @@
package org.toop.game;
// TODO: Remove this, only used in ReversiCanvas. Needs to not
public record Move(int position, char value) {}

View File

@@ -1,25 +0,0 @@
package org.toop.game;
public abstract class TurnBasedGame extends Game {
private final int playerCount; // How many players are playing
private int turn = 0; // What turn it is in the game
protected TurnBasedGame(int rowSize, int columnSize, int playerCount) {
super(rowSize, columnSize);
this.playerCount = playerCount;
}
protected TurnBasedGame(TurnBasedGame other) {
super(other);
playerCount = other.playerCount;
turn = other.turn;
}
protected void nextTurn() {
turn += 1;
}
public int getCurrentTurn() {
return turn % playerCount;
}
}

View File

@@ -1,11 +1,12 @@
package org.toop.game.GameThreadBehaviour;
package org.toop.game.gameThreads;
import org.toop.framework.eventbus.EventFlow;
import org.toop.framework.gameFramework.GameState;
import org.toop.framework.gameFramework.PlayResult;
import org.toop.framework.gameFramework.abstractClasses.TurnBasedGameR;
import org.toop.framework.gameFramework.GUIEvents;
import org.toop.game.players.AbstractPlayer;
import org.toop.framework.gameFramework.model.game.PlayResult;
import org.toop.framework.gameFramework.model.game.threadBehaviour.AbstractThreadBehaviour;
import org.toop.framework.gameFramework.view.GUIEvents;
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
import org.toop.framework.gameFramework.model.player.Player;
/**
* Handles local turn-based game logic at a fixed update rate.
@@ -13,10 +14,10 @@ import org.toop.game.players.AbstractPlayer;
* Runs a separate thread that executes game turns at a fixed frequency (default 60 updates/sec),
* applying player moves, updating the game state, and dispatching UI events.
*/
public class LocalFixedRateThreadBehaviour extends ThreadBehaviourBase implements Runnable {
public class LocalFixedRateThreadBehaviour<T extends TurnBasedGame<T>> extends AbstractThreadBehaviour<T> implements Runnable {
/** All players participating in the game. */
private final AbstractPlayer[] players;
private final Player<T>[] players;
/**
* Creates a fixed-rate behaviour for a local turn-based game.
@@ -24,8 +25,8 @@ public class LocalFixedRateThreadBehaviour extends ThreadBehaviourBase implement
* @param game the game instance
* @param players the list of players in turn order
*/
public LocalFixedRateThreadBehaviour(TurnBasedGameR game, AbstractPlayer[] players) {
super(game, players);
public LocalFixedRateThreadBehaviour(T game, Player<T>[] players) {
super(game);
this.players = players;
}
@@ -60,8 +61,8 @@ public class LocalFixedRateThreadBehaviour extends ThreadBehaviourBase implement
if (now >= nextUpdate) {
nextUpdate += UPDATE_INTERVAL;
AbstractPlayer currentPlayer = getCurrentPlayer();
int move = currentPlayer.getMove(game.clone());
Player<T> currentPlayer = game.getPlayer(game.getCurrentTurn());
int move = currentPlayer.getMove(game.deepCopy());
PlayResult result = game.play(move);
new EventFlow().addPostEvent(GUIEvents.RefreshGameCanvas.class).postEvent();
@@ -85,10 +86,4 @@ public class LocalFixedRateThreadBehaviour extends ThreadBehaviourBase implement
}
}
}
/** Returns the player whose turn it currently is. */
@Override
public AbstractPlayer getCurrentPlayer() {
return players[game.getCurrentTurn()];
}
}

View File

@@ -1,11 +1,12 @@
package org.toop.game.GameThreadBehaviour;
package org.toop.game.gameThreads;
import org.toop.framework.eventbus.EventFlow;
import org.toop.framework.gameFramework.GUIEvents;
import org.toop.framework.gameFramework.PlayResult;
import org.toop.framework.gameFramework.abstractClasses.TurnBasedGameR;
import org.toop.framework.gameFramework.model.game.threadBehaviour.AbstractThreadBehaviour;
import org.toop.framework.gameFramework.view.GUIEvents;
import org.toop.framework.gameFramework.model.game.PlayResult;
import org.toop.framework.gameFramework.GameState;
import org.toop.game.players.AbstractPlayer;
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
import org.toop.framework.gameFramework.model.player.Player;
/**
* Handles local turn-based game logic in its own thread.
@@ -13,7 +14,7 @@ import org.toop.game.players.AbstractPlayer;
* Repeatedly gets the current player's move, applies it to the game,
* updates the UI, and stops when the game ends or {@link #stop()} is called.
*/
public class LocalThreadBehaviour extends ThreadBehaviourBase implements Runnable {
public class LocalThreadBehaviour<T extends TurnBasedGame<T>> extends AbstractThreadBehaviour<T> implements Runnable {
/**
* Creates a new behaviour for a local turn-based game.
@@ -21,8 +22,8 @@ public class LocalThreadBehaviour extends ThreadBehaviourBase implements Runnabl
* @param game the game instance
* @param players the list of players in turn order
*/
public LocalThreadBehaviour(TurnBasedGameR game, AbstractPlayer[] players) {
super(game, players);
public LocalThreadBehaviour(T game, Player<T>[] players) {
super(game);
}
/** Starts the game loop in a new thread. */
@@ -46,8 +47,8 @@ public class LocalThreadBehaviour extends ThreadBehaviourBase implements Runnabl
@Override
public void run() {
while (isRunning.get()) {
AbstractPlayer currentPlayer = getCurrentPlayer();
int move = currentPlayer.getMove(game.clone());
Player<T> currentPlayer = game.getPlayer(game.getCurrentTurn());
int move = currentPlayer.getMove(game.deepCopy());
PlayResult result = game.play(move);
new EventFlow().addPostEvent(GUIEvents.RefreshGameCanvas.class).postEvent();

View File

@@ -1,12 +1,13 @@
package org.toop.game.GameThreadBehaviour;
package org.toop.game.gameThreads;
import org.toop.framework.eventbus.EventFlow;
import org.toop.framework.gameFramework.GUIEvents;
import org.toop.framework.gameFramework.abstractClasses.GameR;
import org.toop.framework.gameFramework.model.game.threadBehaviour.AbstractThreadBehaviour;
import org.toop.framework.gameFramework.view.GUIEvents;
import org.toop.framework.gameFramework.model.game.AbstractGame;
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
import org.toop.framework.networking.events.NetworkEvents;
import org.toop.framework.gameFramework.abstractClasses.TurnBasedGameR;
import org.toop.framework.gameFramework.interfaces.SupportsOnlinePlay;
import org.toop.game.players.AbstractPlayer;
import org.toop.framework.gameFramework.model.game.SupportsOnlinePlay;
import org.toop.framework.gameFramework.model.player.Player;
import org.toop.game.players.OnlinePlayer;
/**
@@ -15,25 +16,27 @@ import org.toop.game.players.OnlinePlayer;
* Reacts to server events, sending moves and updating the game state
* for the local player while receiving moves from other players.
*/
public class OnlineThreadBehaviour extends ThreadBehaviourBase implements SupportsOnlinePlay {
public class OnlineThreadBehaviour<T extends TurnBasedGame<T>> extends AbstractThreadBehaviour<T> implements SupportsOnlinePlay {
/** The local player controlled by this client. */
private AbstractPlayer mainPlayer;
private final Player<T> mainPlayer;
private final int playerTurn;
/**
* Creates behaviour and sets the first local player
* (non-online player) from the given array.
*/
public OnlineThreadBehaviour(TurnBasedGameR game, AbstractPlayer[] players) {
super(game, players);
this.mainPlayer = getFirstNotOnlinePlayer(players);
public OnlineThreadBehaviour(T game, Player<T>[] players) {
super(game);
this.playerTurn = getFirstNotOnlinePlayer(players);
this.mainPlayer = players[this.playerTurn];
}
/** Finds the first non-online player in the array. */
private AbstractPlayer getFirstNotOnlinePlayer(AbstractPlayer[] players) {
for (AbstractPlayer player : players) {
if (!(player instanceof OnlinePlayer)) {
return player;
private int getFirstNotOnlinePlayer(Player<T>[] players) {
for (int i = 0; i < players.length; i++) {
if (!(players[i] instanceof OnlinePlayer)) {
return i;
}
}
throw new RuntimeException("All players are online players");
@@ -56,9 +59,9 @@ public class OnlineThreadBehaviour extends ThreadBehaviourBase implements Suppor
* Sends the generated move back to the server.
*/
@Override
public void yourTurn(NetworkEvents.YourTurnResponse event) {
public void onYourTurn(NetworkEvents.YourTurnResponse event) {
if (!isRunning.get()) return;
int move = mainPlayer.getMove(game.clone());
int move = mainPlayer.getMove(game.deepCopy());
new EventFlow().addPostEvent(NetworkEvents.SendMove.class, event.clientId(), (short) move).postEvent();
}
@@ -67,7 +70,7 @@ public class OnlineThreadBehaviour extends ThreadBehaviourBase implements Suppor
* Updates the game state and triggers a UI refresh.
*/
@Override
public void moveReceived(NetworkEvents.GameMoveResponse event) {
public void onMoveReceived(NetworkEvents.GameMoveResponse event) {
if (!isRunning.get()) return;
game.play(Integer.parseInt(event.move()));
new EventFlow().addPostEvent(GUIEvents.RefreshGameCanvas.class).postEvent();
@@ -80,9 +83,9 @@ public class OnlineThreadBehaviour extends ThreadBehaviourBase implements Suppor
@Override
public void gameFinished(NetworkEvents.GameResultResponse event) {
switch(event.condition().toUpperCase()){
case "WIN" -> new EventFlow().addPostEvent(GUIEvents.GameEnded.class, true, mainPlayer.getPlayerIndex()).postEvent();
case "DRAW" -> new EventFlow().addPostEvent(GUIEvents.GameEnded.class, false, TurnBasedGameR.EMPTY).postEvent();
case "LOSS" -> new EventFlow().addPostEvent(GUIEvents.GameEnded.class, true, (mainPlayer.getPlayerIndex() + 1)%2).postEvent();
case "WIN" -> new EventFlow().addPostEvent(GUIEvents.GameEnded.class, true, playerTurn).postEvent();
case "DRAW" -> new EventFlow().addPostEvent(GUIEvents.GameEnded.class, false, AbstractGame.EMPTY).postEvent();
case "LOSS" -> new EventFlow().addPostEvent(GUIEvents.GameEnded.class, true, (playerTurn + 1)%2).postEvent();
default -> {
logger.error("Invalid condition");
throw new RuntimeException("Unknown condition");

View File

@@ -1,8 +1,8 @@
package org.toop.game.GameThreadBehaviour;
package org.toop.game.gameThreads;
import org.toop.framework.gameFramework.abstractClasses.TurnBasedGameR;
import org.toop.framework.gameFramework.model.game.AbstractGame;
import org.toop.framework.networking.events.NetworkEvents;
import org.toop.game.players.AbstractPlayer;
import org.toop.framework.gameFramework.model.player.AbstractPlayer;
/**
* Online thread behaviour that adds a fixed delay before processing
@@ -19,7 +19,7 @@ public class OnlineWithSleepThreadBehaviour extends OnlineThreadBehaviour {
* @param game the online-capable turn-based game
* @param players the list of local and remote players
*/
public OnlineWithSleepThreadBehaviour(TurnBasedGameR game, AbstractPlayer[] players) {
public OnlineWithSleepThreadBehaviour(AbstractGame game, AbstractPlayer[] players) {
super(game, players);
}
@@ -29,7 +29,7 @@ public class OnlineWithSleepThreadBehaviour extends OnlineThreadBehaviour {
* @param event the network event indicating it's this client's turn
*/
@Override
public void yourTurn(NetworkEvents.YourTurnResponse event) {
public void onYourTurn(NetworkEvents.YourTurnResponse event) {
try {
Thread.sleep(1000);
@@ -37,6 +37,6 @@ public class OnlineWithSleepThreadBehaviour extends OnlineThreadBehaviour {
e.printStackTrace();
}
super.yourTurn(event);
super.onYourTurn(event);
}
}

View File

@@ -0,0 +1,15 @@
package org.toop.game.games.reversi;
import org.toop.framework.gameFramework.model.player.AbstractAI;
import java.util.Random;
public final class ReversiAIR extends AbstractAI<ReversiR> {
public int getMove(ReversiR game) {
int[] moves = game.getLegalMoves();
if (moves.length == 0) return -1;
int inty = new Random().nextInt(0, moves.length);
return moves[inty];
}
}

View File

@@ -1,8 +1,9 @@
package org.toop.game.reversi;
package org.toop.game.games.reversi;
import org.toop.framework.gameFramework.GameState;
import org.toop.framework.gameFramework.PlayResult;
import org.toop.framework.gameFramework.abstractClasses.TurnBasedGameR;
import org.toop.framework.gameFramework.model.game.PlayResult;
import org.toop.framework.gameFramework.model.game.AbstractGame;
import org.toop.framework.gameFramework.model.player.Player;
import java.awt.*;
import java.util.ArrayList;
@@ -11,21 +12,21 @@ import java.util.HashSet;
import java.util.Set;
public final class ReversiR extends TurnBasedGameR {
public final class ReversiR extends AbstractGame<ReversiR> {
private int movesTaken;
private Set<Point> filledCells = new HashSet<>();
private int[] mostRecentlyFlippedPieces;
// TODO: Don't hardcore for two players :)
public record Score(int player1Score, int player2Score) {}
@Override
public ReversiR clone() {
public ReversiR deepCopy() {
return new ReversiR(this);
}
public ReversiR() {
super(8, 8, 2);
// TODO: Don't hardcore for two players :)
public record Score(int player1Score, int player2Score) {}
public ReversiR(Player<ReversiR>[] players) {
super(8, 8, 2, players);
addStartPieces();
}
@@ -38,10 +39,10 @@ public final class ReversiR extends TurnBasedGameR {
private void addStartPieces() {
this.setBoardPosition(27, 1);
this.setBoardPosition(28, 0);
this.setBoardPosition(35, 0);
this.setBoardPosition(36, 1);
this.setBoard(27, 1);
this.setBoard(28, 0);
this.setBoard(35, 0);
this.setBoard(36, 1);
updateFilledCellsSet();
}
private void updateFilledCellsSet() {
@@ -138,7 +139,7 @@ public final class ReversiR extends TurnBasedGameR {
}
private boolean gameOver(){
ReversiR gameCopy = clone();
ReversiR gameCopy = deepCopy();
return gameCopy.getLegalMoves().length == 0 && gameCopy.skipTurn().getLegalMoves().length == 0;
}
@@ -202,7 +203,7 @@ public final class ReversiR extends TurnBasedGameR {
if (getLegalMoves().length == 0){
PlayResult result;
// Check if next turn is also a force skip
if (clone().skipTurn().getLegalMoves().length == 0){
if (deepCopy().skipTurn().getLegalMoves().length == 0){
// Game over
int winner = getWinner();
result = new PlayResult(winner == EMPTY ? GameState.DRAW : GameState.WIN, winner);

View File

@@ -1,7 +1,7 @@
package org.toop.game.tictactoe;
package org.toop.game.games.tictactoe;
import org.toop.framework.gameFramework.abstractClasses.AIR;
import org.toop.framework.gameFramework.PlayResult;
import org.toop.framework.gameFramework.model.player.AbstractAI;
import org.toop.framework.gameFramework.model.game.PlayResult;
import org.toop.framework.gameFramework.GameState;
/**
@@ -13,7 +13,7 @@ import org.toop.framework.gameFramework.GameState;
* opening or when no clear best move is found.
* </p>
*/
public final class TicTacToeAIR extends AIR<TicTacToeR> {
public final class TicTacToeAIR extends AbstractAI<TicTacToeR> {
/**
* Determines the best move for the given Tic-Tac-Toe game state.
@@ -27,10 +27,9 @@ public final class TicTacToeAIR extends AIR<TicTacToeR> {
* @param depth the depth of lookahead for evaluating moves (non-negative)
* @return the index of the best move, or -1 if no moves are available
*/
@Override
public int findBestMove(TicTacToeR game, int depth) {
public int getMove(TicTacToeR game) {
int depth = 9;
assert game != null;
assert depth >= 0;
final int[] legalMoves = game.getLegalMoves();
// If there are no moves, return -1
@@ -73,7 +72,7 @@ public final class TicTacToeAIR extends AIR<TicTacToeR> {
* @return the score of the move
*/
private int getMoveScore(TicTacToeR game, int depth, int move, boolean maximizing) {
final TicTacToeR copy = game.clone();
final TicTacToeR copy = game.deepCopy();
final PlayResult result = copy.play(move);
GameState state = result.state();

View File

@@ -1,17 +1,18 @@
package org.toop.game.tictactoe;
package org.toop.game.games.tictactoe;
import org.toop.framework.gameFramework.PlayResult;
import org.toop.framework.gameFramework.abstractClasses.TurnBasedGameR;
import org.toop.framework.gameFramework.model.game.PlayResult;
import org.toop.framework.gameFramework.model.game.AbstractGame;
import org.toop.framework.gameFramework.GameState;
import org.toop.framework.gameFramework.model.player.Player;
import java.util.ArrayList;
import java.util.Objects;
public final class TicTacToeR extends TurnBasedGameR {
public final class TicTacToeR extends AbstractGame<TicTacToeR> {
private int movesLeft;
public TicTacToeR() {
super(3, 3, 2);
public TicTacToeR(Player<TicTacToeR>[] players) {
super(3, 3, 2, players);
movesLeft = this.getBoard().length;
}
@@ -101,7 +102,7 @@ public final class TicTacToeR extends TurnBasedGameR {
private boolean checkForEarlyDraw() {
for (final int move : this.getLegalMoves()) {
final TicTacToeR copy = this.clone();
final TicTacToeR copy = this.deepCopy();
if (copy.play(move).state() == GameState.WIN || !copy.checkForEarlyDraw()) {
return false;
@@ -111,8 +112,7 @@ public final class TicTacToeR extends TurnBasedGameR {
return true;
}
@Override
public TicTacToeR clone() {
public TicTacToeR deepCopy() {
return new TicTacToeR(this);
}
}

View File

@@ -1,8 +0,0 @@
package org.toop.game.interfaces;
import org.toop.game.Game;
import org.toop.game.records.Move;
public interface IAIMove <T extends Game>{
Move findBestMove(T game, int depth);
}

View File

@@ -1,9 +0,0 @@
package org.toop.game.interfaces;
import org.toop.framework.gameFramework.GameState;
import org.toop.game.records.Move;
public interface IPlayable {
Move[] getLegalMoves();
GameState play(Move move);
}

View File

@@ -1,51 +0,0 @@
package org.toop.game.players;
import org.toop.framework.gameFramework.abstractClasses.GameR;
/**
* Abstract class representing a player in a game.
* <p>
* Players are entities that can make moves based on the current state of a game.
* This class implements {@link MakesMove} and serves as a base for concrete
* player types, such as human players or AI players.
* </p>
* <p>
* Subclasses should override the {@link #getMove(GameR)} method to provide
* specific move logic.
* </p>
*/
public abstract class AbstractPlayer implements MakesMove {
private int playerIndex = -1;
private final String name;
protected AbstractPlayer(String name) {
this.name = name;
}
/**
* Determines the next move based on the provided game state.
* <p>
* The default implementation throws an {@link UnsupportedOperationException},
* indicating that concrete subclasses must override this method to provide
* actual move logic.
* </p>
*
* @param gameCopy a snapshot of the current game state
* @return an integer representing the chosen move
* @throws UnsupportedOperationException if the method is not overridden
*/
@Override
public int getMove(GameR gameCopy) {
throw new UnsupportedOperationException("Not supported yet.");
}
public String getName(){
return this.name;
}
public int getPlayerIndex() {
return playerIndex;
}
public void setPlayerIndex(int playerIndex) {
this.playerIndex = playerIndex;
}
}

View File

@@ -1,28 +1,30 @@
package org.toop.game.players;
import org.toop.framework.gameFramework.abstractClasses.AIR;
import org.toop.framework.gameFramework.abstractClasses.GameR;
import org.toop.framework.gameFramework.model.player.AbstractAI;
import org.toop.framework.gameFramework.model.player.AbstractPlayer;
import org.toop.framework.gameFramework.model.player.MoveProvider;
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
/**
* Represents a player controlled by an AI in a game.
* <p>
* This player uses an {@link AIR} instance to determine its moves. The generic
* This player uses an {@link AbstractAI} instance to determine its moves. The generic
* parameter {@code T} specifies the type of {@link GameR} the AI can handle.
* </p>
*
* @param <T> the specific type of game this AI player can play
*/
public class ArtificialPlayer<T extends GameR> extends AbstractPlayer {
public class ArtificialPlayer<T extends TurnBasedGame<T>> extends AbstractPlayer<T> {
/** The AI instance used to calculate moves. */
private final AIR<T> ai;
private final MoveProvider<T> ai;
/**
* Constructs a new ArtificialPlayer using the specified AI.
*
* @param ai the AI instance that determines moves for this player
*/
public ArtificialPlayer(AIR<T> ai, String name) {
public ArtificialPlayer(MoveProvider<T> ai, String name) {
super(name);
this.ai = ai;
}
@@ -39,8 +41,7 @@ public class ArtificialPlayer<T extends GameR> extends AbstractPlayer {
* @return the integer representing the chosen move
* @throws ClassCastException if {@code gameCopy} is not of type {@code T}
*/
@Override
public int getMove(GameR gameCopy) {
return ai.findBestMove((T) gameCopy, 9); // TODO: Make depth configurable
public int getMove(T gameCopy) {
return ai.getMove(gameCopy);
}
}

View File

@@ -1,11 +1,12 @@
package org.toop.game.players;
import org.toop.framework.gameFramework.abstractClasses.GameR;
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
import org.toop.framework.gameFramework.model.player.AbstractPlayer;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class LocalPlayer extends AbstractPlayer {
public class LocalPlayer<T extends TurnBasedGame<T>> extends AbstractPlayer<T> {
// Future can be used with event system, IF unsubscribeAfterSuccess works...
// private CompletableFuture<Integer> LastMove = new CompletableFuture<>();
@@ -16,7 +17,7 @@ public class LocalPlayer extends AbstractPlayer {
}
@Override
public int getMove(GameR gameCopy) {
public int getMove(T gameCopy) {
return getValidMove(gameCopy);
}
@@ -30,7 +31,7 @@ public class LocalPlayer extends AbstractPlayer {
return false;
}
private int getMove2(GameR gameCopy) {
private int getMove2(T gameCopy) {
LastMove = new CompletableFuture<>();
int move = -1;
try {
@@ -42,16 +43,16 @@ public class LocalPlayer extends AbstractPlayer {
return move;
}
protected int getValidMove(GameR gameCopy){
protected int getValidMove(T gameCopy){
// Get this player's valid moves
int[] validMoves = gameCopy.getLegalMoves();
// Make sure provided move is valid
// TODO: Limit amount of retries?
// TODO: Stop copying game so many times
int move = getMove2(gameCopy.clone());
int move = getMove2(gameCopy.deepCopy());
while (!contains(validMoves, move)) {
System.out.println("Not a valid move, try again");
move = getMove2(gameCopy.clone());
move = getMove2(gameCopy.deepCopy());
}
return move;
}

View File

@@ -1,23 +0,0 @@
package org.toop.game.players;
import org.toop.framework.gameFramework.abstractClasses.GameR;
/**
* Interface representing an entity capable of making a move in a game.
* <p>
* Any class implementing this interface should provide logic to determine
* the next move given a snapshot of the current game state.
* </p>
*/
public interface MakesMove {
/**
* Determines the next move based on the provided game state.
*
* @param gameCopy a copy or snapshot of the current game state
* (never null)
* @return an integer representing the chosen move.
* The interpretation of this value depends on the specific game.
*/
int getMove(GameR gameCopy);
}

View File

@@ -1,5 +1,8 @@
package org.toop.game.players;
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
import org.toop.framework.gameFramework.model.player.AbstractPlayer;
/**
* Represents a player controlled remotely or over a network.
* <p>
@@ -8,7 +11,7 @@ package org.toop.game.players;
* Currently, this class is a placeholder and does not implement move logic.
* </p>
*/
public class OnlinePlayer extends AbstractPlayer {
public class OnlinePlayer<T extends TurnBasedGame<T>> extends AbstractPlayer<T> {
/**
* Constructs a new OnlinePlayer.

View File

@@ -1,3 +0,0 @@
package org.toop.game.records;
public record Move(int position, char value) {}

View File

@@ -1,229 +0,0 @@
package org.toop.game.reversi;
import org.toop.game.TurnBasedGame;
import org.toop.framework.gameFramework.GameState;
import org.toop.game.records.Move;
import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public final class Reversi extends TurnBasedGame {
private int movesTaken;
private Set<Point> filledCells = new HashSet<>();
private Move[] mostRecentlyFlippedPieces;
public record Score(int player1Score, int player2Score) {}
public Reversi() {
super(8, 8, 2);
addStartPieces();
}
public Reversi(Reversi other) {
super(other);
this.movesTaken = other.movesTaken;
this.filledCells = other.filledCells;
this.mostRecentlyFlippedPieces = other.mostRecentlyFlippedPieces;
}
private void addStartPieces() {
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 (this.getBoard()[i] == 'W' || this.getBoard()[i] == 'B') {
filledCells.add(new Point(i % this.getColumnSize(), i / this.getRowSize()));
}
}
}
@Override
public Move[] getLegalMoves() {
final ArrayList<Move> legalMoves = new ArrayList<>();
char[][] boardGrid = makeBoardAGrid();
char currentPlayer = (this.getCurrentTurn()==0) ? 'B' : 'W';
Set<Point> adjCell = getAdjacentCells(boardGrid);
for (Point point : adjCell){
Move[] moves = getFlipsForPotentialMove(point,currentPlayer);
int score = moves.length;
if (score > 0){
legalMoves.add(new Move(point.x + point.y * this.getRowSize(), currentPlayer));
}
}
return legalMoves.toArray(new Move[0]);
}
private Set<Point> getAdjacentCells(char[][] boardGrid) {
Set<Point> possibleCells = new HashSet<>();
for (Point point : filledCells) { //for every filled cell
for (int deltaColumn = -1; deltaColumn <= 1; deltaColumn++){ //check adjacent cells
for (int deltaRow = -1; deltaRow <= 1; deltaRow++){ //orthogonally and diagonally
int newX = point.x + deltaColumn, newY = point.y + deltaRow;
if (deltaColumn == 0 && deltaRow == 0 //continue if out of bounds
|| !isOnBoard(newX, newY)) {
continue;
}
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
}
}
}
}
return possibleCells;
}
public Move[] getFlipsForPotentialMove(Point point, char currentPlayer) {
final ArrayList<Move> movesToFlip = new ArrayList<>();
for (int deltaColumn = -1; deltaColumn <= 1; deltaColumn++) { //for all directions
for (int deltaRow = -1; deltaRow <= 1; deltaRow++) {
if (deltaColumn == 0 && deltaRow == 0){
continue;
}
Move[] moves = getFlipsInDirection(point,makeBoardAGrid(),currentPlayer,deltaColumn,deltaRow);
if (moves != null) { //getFlipsInDirection
movesToFlip.addAll(Arrays.asList(moves));
}
}
}
return movesToFlip.toArray(new Move[0]);
}
private Move[] getFlipsInDirection(Point point, char[][] boardGrid, char currentPlayer, int dirX, int dirY) {
char opponent = getOpponent(currentPlayer);
final ArrayList<Move> movesToFlip = new ArrayList<>();
int x = point.x + dirX;
int y = point.y + dirY;
if (!isOnBoard(x, y) || boardGrid[y][x] != opponent) { //there must first be an opponents tile
return null;
}
while (isOnBoard(x, y) && boardGrid[y][x] == opponent) { //count the opponents tiles in this direction
movesToFlip.add(new Move(x+y*this.getRowSize(), currentPlayer));
x += dirX;
y += dirY;
}
if (isOnBoard(x, y) && boardGrid[y][x] == currentPlayer) {
return movesToFlip.toArray(new Move[0]); //only return the count if last tile is ours
}
return null;
}
private boolean isOnBoard(int x, int y) {
return x >= 0 && x < this.getColumnSize() && y >= 0 && y < this.getRowSize();
}
private char[][] makeBoardAGrid() {
char[][] boardGrid = new char[this.getRowSize()][this.getColumnSize()];
for (int i = 0; i < 64; i++) {
boardGrid[i / this.getRowSize()][i % this.getColumnSize()] = this.getBoard()[i]; //boardGrid[y -> row] [x -> column]
}
return boardGrid;
}
@Override
public GameState play(Move move) {
Move[] legalMoves = getLegalMoves();
boolean moveIsLegal = false;
for (Move legalMove : legalMoves) { //check if the move is legal
if (move.equals(legalMove)) {
moveIsLegal = true;
break;
}
}
if (!moveIsLegal) {
return null;
}
Move[] moves = sortMovesFromCenter(getFlipsForPotentialMove(new Point(move.position()%this.getColumnSize(),move.position()/this.getRowSize()), move.value()),move);
mostRecentlyFlippedPieces = moves;
this.setBoard(move); //place the move on the board
for (Move m : moves) {
this.setBoard(m); //flip the correct pieces on the board
}
filledCells.add(new Point(move.position() % this.getRowSize(), move.position() / this.getColumnSize()));
nextTurn();
if (getLegalMoves().length == 0) { //skip the players turn when there are no legal moves
skipMyTurn();
if (getLegalMoves().length > 0) {
return GameState.TURN_SKIPPED;
}
else { //end the game when neither player has a legal move
Score score = getScore();
if (score.player1Score() == score.player2Score()) {
return GameState.DRAW;
}
else {
return GameState.WIN;
}
}
}
return GameState.NORMAL;
}
private void skipMyTurn(){
IO.println("TURN " + getCurrentPlayer() + " SKIPPED");
//TODO: notify user that a turn has been skipped
nextTurn();
}
public char getCurrentPlayer() {
if (this.getCurrentTurn() == 0){
return 'B';
}
else {
return 'W';
}
}
private char getOpponent(char currentPlayer){
if (currentPlayer == 'B') {
return 'W';
}
else {
return 'B';
}
}
public Score getScore(){
int player1Score = 0, player2Score = 0;
for (int count = 0; count < this.getRowSize() * this.getColumnSize(); count++) {
if (this.getBoard()[count] == 'B') {
player1Score += 1;
}
if (this.getBoard()[count] == 'W') {
player2Score += 1;
}
}
return new Score(player1Score, player2Score);
}
private Move[] sortMovesFromCenter(Move[] moves, Move center) { //sorts the pieces to be flipped for animation purposes
int centerX = center.position()%this.getColumnSize();
int centerY = center.position()/this.getRowSize();
Arrays.sort(moves, (a, b) -> {
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;
return Integer.compare(distA, distB);
});
return moves;
}
public Move[] getMostRecentlyFlippedPieces() {
return mostRecentlyFlippedPieces;
}
}

View File

@@ -1,14 +0,0 @@
package org.toop.game.reversi;
import org.toop.game.AI;
import org.toop.game.records.Move;
public final class ReversiAI extends AI<Reversi> {
@Override
public Move findBestMove(Reversi game, int depth) {
Move[] moves = game.getLegalMoves();
int inty = (int)(Math.random() * moves.length-.5f);
if (moves.length == 0) return null;
return moves[inty];
}
}

View File

@@ -1,17 +0,0 @@
package org.toop.game.reversi;
import org.toop.framework.gameFramework.abstractClasses.AIR;
import java.util.Arrays;
import java.util.Random;
public final class ReversiAIR extends AIR<ReversiR> {
@Override
public int findBestMove(ReversiR game, int depth) {
int[] moves = game.getLegalMoves();
if (moves.length == 0) return -1;
int inty = new Random().nextInt(0, moves.length);
return moves[inty];
}
}

View File

@@ -1,103 +0,0 @@
package org.toop.game.tictactoe;
import java.util.ArrayList;
import org.toop.game.TurnBasedGame;
import org.toop.framework.gameFramework.GameState;
import org.toop.game.records.Move;
public final class TicTacToe extends TurnBasedGame {
private int movesLeft;
public TicTacToe() {
super(3, 3, 2);
movesLeft = this.getBoard().length;
}
public TicTacToe(TicTacToe other) {
super(other);
movesLeft = other.movesLeft;
}
@Override
public Move[] getLegalMoves() {
final ArrayList<Move> legalMoves = new ArrayList<>();
final char currentValue = getCurrentValue();
for (int i = 0; i < this.getBoard().length; i++) {
if (this.getBoard()[i] == EMPTY) {
legalMoves.add(new Move(i, currentValue));
}
}
return legalMoves.toArray(new Move[0]);
}
@Override
public GameState play(Move move) {
assert move != null;
assert move.position() >= 0 && move.position() < this.getBoard().length;
assert move.value() == getCurrentValue();
// TODO: Make sure this move is allowed, maybe on the board side?
this.setBoard(move);
movesLeft--;
if (checkForWin()) {
return GameState.WIN;
}
nextTurn();
if (movesLeft <= 2) {
if (movesLeft <= 0 || checkForEarlyDraw()) {
return GameState.DRAW;
}
}
return GameState.NORMAL;
}
private boolean checkForWin() {
// Horizontal
for (int i = 0; i < 3; i++) {
final int index = i * 3;
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 (this.getBoard()[i] != EMPTY && this.getBoard()[i] == this.getBoard()[i + 3] && this.getBoard()[i] == this.getBoard()[i + 6]) {
return true;
}
}
// B-Slash
if (this.getBoard()[0] != EMPTY && this.getBoard()[0] == this.getBoard()[4] && this.getBoard()[0] == this.getBoard()[8]) {
return true;
}
// F-Slash
return this.getBoard()[2] != EMPTY && this.getBoard()[2] == this.getBoard()[4] && this.getBoard()[2] == this.getBoard()[6];
}
private boolean checkForEarlyDraw() {
for (final Move move : this.getLegalMoves()) {
final TicTacToe copy = new TicTacToe(this);
if (copy.play(move) == GameState.WIN || !copy.checkForEarlyDraw()) {
return false;
}
}
return true;
}
private char getCurrentValue() {
return this.getCurrentTurn() == 0 ? 'X' : 'O';
}
}

View File

@@ -1,87 +0,0 @@
package org.toop.game.tictactoe;
import org.toop.game.AI;
import org.toop.framework.gameFramework.GameState;
import org.toop.game.records.Move;
public final class TicTacToeAI extends AI<TicTacToe> {
@Override
public Move findBestMove(TicTacToe game, int depth) {
assert game != null;
assert depth >= 0;
final Move[] legalMoves = game.getLegalMoves();
if (legalMoves.length == 0) {
return null;
}
if (legalMoves.length == 9) {
return switch ((int)(Math.random() * 4)) {
case 0 -> legalMoves[2];
case 1 -> legalMoves[6];
case 2 -> legalMoves[8];
default -> legalMoves[0];
};
}
int bestScore = -depth;
Move bestMove = null;
for (final Move move : legalMoves) {
final int score = getMoveScore(game, depth, move, true);
if (score > bestScore) {
bestMove = move;
bestScore = score;
}
}
return bestMove != null? bestMove : legalMoves[(int)(Math.random() * legalMoves.length)];
}
public Move findWorstMove(TicTacToe game, int depth){
Move[] legalMoves = game.getLegalMoves();
int bestScore = -depth;
Move bestMove = null;
for (final Move move : legalMoves) {
final int score = getMoveScore(game, depth, move, false);
if (score > bestScore) {
bestMove = move;
bestScore = score;
}
}
return bestMove;
}
private int getMoveScore(TicTacToe game, int depth, Move move, boolean maximizing) {
final TicTacToe copy = new TicTacToe(game);
final GameState state = copy.play(move);
switch (state) {
case GameState.DRAW: return 0;
case GameState.WIN: return maximizing? depth + 1 : -depth - 1;
}
if (depth <= 0) {
return 0;
}
final Move[] legalMoves = copy.getLegalMoves();
int score = maximizing? depth + 1 : -depth - 1;
for (final Move next : legalMoves) {
if (maximizing) {
score = Math.min(score, getMoveScore(copy, depth - 1, next, false));
} else {
score = Math.max(score, getMoveScore(copy, depth - 1, next, true));
}
}
return score;
}
}

View File

@@ -1,193 +0,0 @@
package org.toop.game.tictactoe;
import java.util.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.toop.framework.gameFramework.GameState;
import org.toop.game.records.Move;
import org.toop.game.reversi.Reversi;
import org.toop.game.reversi.ReversiAI;
import static org.junit.jupiter.api.Assertions.*;
class ReversiTest {
private Reversi game;
private ReversiAI ai;
@BeforeEach
void setup() {
game = new Reversi();
ai = new ReversiAI();
}
@Test
void testCorrectStartPiecesPlaced() {
assertNotNull(game);
assertEquals('W',game.getBoard()[27]);
assertEquals('B',game.getBoard()[28]);
assertEquals('B',game.getBoard()[35]);
assertEquals('W',game.getBoard()[36]);
}
@Test
void testGetLegalMovesAtStart() {
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<Move> expected, List<Move> actual) {
assertEquals(expected.size(), actual.size());
for (int i = 0; i < expected.size(); i++) {
assertTrue(actual.contains(expected.get(i)));
assertTrue(expected.contains(actual.get(i)));
}
}
@Test
void testMakeValidMoveFlipsPieces() {
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.getBoard().clone();
game.play(new Move(0, 'B'));
assertArrayEquals(before, game.getBoard(), "Board should not change on invalid move");
}
@Test
void testTurnSwitchesAfterValidMove() {
char current = game.getCurrentPlayer();
game.play(game.getLegalMoves()[0]);
assertNotEquals(current, game.getCurrentPlayer(), "Player turn should switch after a valid move");
}
@Test
void testCountScoreCorrectlyAtStart() {
long start = System.nanoTime();
Reversi.Score score = game.getScore();
assertEquals(2, score.player1Score()); // Black
assertEquals(2, score.player2Score()); // White
long end = System.nanoTime();
IO.println((end-start));
}
@Test
void zLegalMovesInCertainPosition() {
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));
assertMovesMatchIgnoreOrder(expectedMoves, Arrays.asList(moves));
}
@Test
void testCountScoreCorrectlyAtEnd() {
for (int i = 0; i < 1; i++){
game = new Reversi();
Move[] legalMoves = game.getLegalMoves();
while(legalMoves.length > 0) {
game.play(legalMoves[(int)(Math.random()*legalMoves.length)]);
legalMoves = game.getLegalMoves();
}
Reversi.Score score = game.getScore();
IO.println(score.player1Score());
IO.println(score.player2Score());
for (int r = 0; r < game.getRowSize(); r++) {
char[] row = Arrays.copyOfRange(game.getBoard(), r * game.getColumnSize(), (r + 1) * game.getColumnSize());
IO.println(Arrays.toString(row));
}
}
}
@Test
void testPlayerMustSkipTurnIfNoValidMoves() {
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));
}
@Test
void testGameShouldEndIfNoValidMoves() {
//European Grand Prix Ghent 2017: Replay Hassan - Verstuyft J. (3-17)
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);
Reversi.Score score = game.getScore();
assertEquals(3, score.player1Score());
assertEquals(17, score.player2Score());
}
@Test
void testAISelectsLegalMove() {
Move move = ai.findBestMove(game,4);
assertNotNull(move);
assertTrue(containsMove(game.getLegalMoves(),move), "AI should always choose a legal move");
}
private boolean containsMove(Move[] moves, Move move) {
for (Move m : moves) {
if (m.equals(move)) return true;
}
return false;
}
}

View File

@@ -2,6 +2,9 @@ package org.toop.game.tictactoe;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.toop.framework.gameFramework.model.player.Player;
import org.toop.game.games.tictactoe.TicTacToeAIR;
import org.toop.game.games.tictactoe.TicTacToeR;
import static org.junit.jupiter.api.Assertions.*;
@@ -11,7 +14,7 @@ final class TicTacToeAIRTest {
// Helper: play multiple moves in sequence on a fresh board
private TicTacToeR playSequence(int... moves) {
TicTacToeR game = new TicTacToeR();
TicTacToeR game = new TicTacToeR(new Player[2]);
for (int move : moves) {
game.play(move);
}
@@ -21,8 +24,8 @@ final class TicTacToeAIRTest {
@Test
@DisplayName("AI first move must choose a corner")
void testFirstMoveIsCorner() {
TicTacToeR game = new TicTacToeR();
int move = ai.findBestMove(game, 4);
TicTacToeR game = new TicTacToeR(new Player[2]);
int move = ai.getMove(game);
assertTrue(
move == 0 || move == 2 || move == 6 || move == 8,
@@ -34,7 +37,7 @@ final class TicTacToeAIRTest {
@DisplayName("AI doesn't make losing move in specific situation")
void testWinningMove(){
TicTacToeR game = playSequence(new int[] { 0, 4, 5, 3, 6, 1, 7});
int move = ai.findBestMove(game, 9);
int move = ai.getMove(game);
assertEquals(8, move);
}
@@ -55,7 +58,7 @@ final class TicTacToeAIRTest {
1, 4 // X, O
);
int move = ai.findBestMove(game, 4);
int move = ai.getMove(game);
assertEquals(2, move, "AI must take the winning move at index 2");
}
@@ -73,18 +76,18 @@ final class TicTacToeAIRTest {
8, 4 // X, O (O threatens at 5)
);
int move = ai.findBestMove(game, 4);
int move = ai.getMove(game);
assertEquals(5, move, "AI must block opponent at index 5");
}
@Test
@DisplayName("AI returns -1 when no legal moves exist")
void testNoMovesAvailable() {
TicTacToeR full = new TicTacToeR();
TicTacToeR full = new TicTacToeR(new Player[2]);
// Fill board alternating
for (int i = 0; i < 9; i++) full.play(i);
int move = ai.findBestMove(full, 3);
int move = ai.getMove(full);
assertEquals(-1, move, "AI should return -1 when board is full");
}
@@ -92,7 +95,7 @@ final class TicTacToeAIRTest {
@DisplayName("Minimax depth does not cause crashes and produces valid move")
void testDepthStability() {
TicTacToeR game = playSequence(0, 4); // Simple mid-game state
int move = ai.findBestMove(game, 6);
int move = ai.getMove(game);
assertTrue(move >= -1 && move <= 8, "AI must return a valid move index");
}
@@ -108,11 +111,11 @@ final class TicTacToeAIRTest {
//
// Legal moves: 5, 8
// Only move 5 avoids losing.
TicTacToeR game = new TicTacToeR();
TicTacToeR game = new TicTacToeR(new Player[2]);
int[] moves = {0,1,2,4,3,6,7}; // Hard-coded board setup
for (int m : moves) game.play(m);
int move = ai.findBestMove(game, 4);
int move = ai.getMove(game);
assertEquals(5, move, "AI must choose the only move that avoids losing");
}
}

View File

@@ -1,81 +0,0 @@
package org.toop.game.tictactoe;
import static org.junit.jupiter.api.Assertions.*;
import java.util.Set;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.toop.game.records.Move;
class TicTacToeAITest {
private TicTacToe game;
private TicTacToeAI ai;
@BeforeEach
void setup() {
game = new TicTacToe();
ai = new TicTacToeAI();
}
@Test
void testBestMove_returnWinningMoveWithDepth1() {
// X X -
// O O -
// - - -
game.play(new Move(0, 'X'));
game.play(new Move(3, 'O'));
game.play(new Move(1, 'X'));
game.play(new Move(4, 'O'));
final Move move = ai.findBestMove(game, 1);
assertNotNull(move);
assertEquals('X', move.value());
assertEquals(2, move.position());
}
@Test
void testBestMove_blockOpponentWinDepth1() {
// - - -
// O - -
// X X -
game.play(new Move(6, 'X'));
game.play(new Move(3, 'O'));
game.play(new Move(7, 'X'));
final Move move = ai.findBestMove(game, 1);
assertNotNull(move);
assertEquals('O', move.value());
assertEquals(8, move.position());
}
@Test
void testBestMove_preferCornerOnEmpty() {
final Move move = ai.findBestMove(game, 0);
assertNotNull(move);
assertEquals('X', move.value());
assertTrue(Set.of(0, 2, 6, 8).contains(move.position()));
}
@Test
void testBestMove_findBestMoveDraw() {
// O X -
// - O X
// X O X
game.play(new Move(1, 'X'));
game.play(new Move(0, 'O'));
game.play(new Move(5, 'X'));
game.play(new Move(4, 'O'));
game.play(new Move(6, 'X'));
game.play(new Move(7, 'O'));
game.play(new Move(8, 'X'));
final Move move = ai.findBestMove(game, game.getLegalMoves().length);
assertNotNull(move);
assertEquals('O', move.value());
assertEquals(2, move.position());
}
}