Merge remote-tracking branch 'origin/Development' into Development

This commit is contained in:
ramollia
2025-12-02 11:25:42 +01:00
54 changed files with 2121 additions and 78 deletions

View File

@@ -99,8 +99,14 @@
<artifactId>error_prone_annotations</artifactId>
<version>2.42.0</version>
</dependency>
<dependency>
<groupId>org.toop</groupId>
<artifactId>framework</artifactId>
<version>0.1</version>
<scope>compile</scope>
</dependency>
</dependencies>
</dependencies>
<build>
<plugins>

View File

@@ -1,7 +1,7 @@
package org.toop.game.Connect4;
import org.toop.game.TurnBasedGame;
import org.toop.game.enumerators.GameState;
import org.toop.framework.gameFramework.GameState;
import org.toop.game.records.Move;
import java.util.ArrayList;

View File

@@ -1,7 +1,7 @@
package org.toop.game.Connect4;
import org.toop.game.AI;
import org.toop.game.enumerators.GameState;
import org.toop.framework.gameFramework.GameState;
import org.toop.game.records.Move;
public class Connect4AI extends AI<Connect4> {

View File

@@ -0,0 +1,24 @@
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

@@ -0,0 +1,94 @@
package org.toop.game.GameThreadBehaviour;
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;
/**
* Handles local turn-based game logic at a fixed update rate.
* <p>
* 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 {
/** All players participating in the game. */
private final AbstractPlayer[] players;
/**
* Creates a fixed-rate behaviour for a local turn-based game.
*
* @param game the game instance
* @param players the list of players in turn order
*/
public LocalFixedRateThreadBehaviour(TurnBasedGameR game, AbstractPlayer[] players) {
super(game, players);
this.players = players;
}
/** Starts the game loop thread if not already running. */
@Override
public void start() {
if (isRunning.compareAndSet(false, true)) {
new Thread(this).start();
}
}
/** Stops the game loop after the current iteration. */
@Override
public void stop() {
isRunning.set(false);
}
/**
* Main loop running at a fixed rate.
* <p>
* Fetches the current player's move, applies it to the game,
* updates the UI, and handles game-ending states.
*/
@Override
public void run() {
final int UPS = 60;
final long UPDATE_INTERVAL = 1_000_000_000L / UPS;
long nextUpdate = System.nanoTime();
while (isRunning.get()) {
long now = System.nanoTime();
if (now >= nextUpdate) {
nextUpdate += UPDATE_INTERVAL;
AbstractPlayer currentPlayer = getCurrentPlayer();
int move = currentPlayer.getMove(game.clone());
PlayResult result = game.play(move);
new EventFlow().addPostEvent(GUIEvents.RefreshGameCanvas.class).postEvent();
GameState state = result.state();
switch (state) {
case WIN, DRAW -> {
isRunning.set(false);
new EventFlow().addPostEvent(GUIEvents.GameEnded.class, state == GameState.WIN, result.player()).postEvent();
}
case NORMAL, TURN_SKIPPED -> { /* continue */ }
default -> {
logger.error("Unexpected state {}", state);
isRunning.set(false);
throw new RuntimeException("Unknown state: " + state);
}
}
} else {
try {
Thread.sleep(10);
} catch (InterruptedException ignored) {}
}
}
}
/** Returns the player whose turn it currently is. */
@Override
public AbstractPlayer getCurrentPlayer() {
return players[game.getCurrentTurn()];
}
}

View File

@@ -0,0 +1,73 @@
package org.toop.game.GameThreadBehaviour;
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.GameState;
import org.toop.game.players.AbstractPlayer;
/**
* Handles local turn-based game logic in its own thread.
* <p>
* 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 {
/**
* Creates a new behaviour for a local turn-based game.
*
* @param game the game instance
* @param players the list of players in turn order
*/
public LocalThreadBehaviour(TurnBasedGameR game, AbstractPlayer[] players) {
super(game, players);
}
/** Starts the game loop in a new thread. */
@Override
public void start() {
if (isRunning.compareAndSet(false, true)) {
new Thread(this).start();
}
}
/** Stops the game loop after the current iteration. */
@Override
public void stop() {
isRunning.set(false);
}
/**
* Main game loop: gets the current player's move, applies it,
* updates the UI, and handles end-of-game states.
*/
@Override
public void run() {
while (isRunning.get()) {
AbstractPlayer currentPlayer = getCurrentPlayer();
int move = currentPlayer.getMove(game.clone());
PlayResult result = game.play(move);
new EventFlow().addPostEvent(GUIEvents.RefreshGameCanvas.class).postEvent();
GameState state = result.state();
switch (state) {
case WIN, DRAW -> {
isRunning.set(false);
new EventFlow().addPostEvent(
GUIEvents.GameEnded.class,
state == GameState.WIN,
result.player()
).postEvent();
}
case NORMAL, TURN_SKIPPED -> { /* continue normally */ }
default -> {
logger.error("Unexpected state {}", state);
isRunning.set(false);
throw new RuntimeException("Unknown state: " + state);
}
}
}
}
}

View File

@@ -0,0 +1,92 @@
package org.toop.game.GameThreadBehaviour;
import org.toop.framework.eventbus.EventFlow;
import org.toop.framework.gameFramework.GUIEvents;
import org.toop.framework.gameFramework.abstractClasses.GameR;
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.game.players.OnlinePlayer;
/**
* Handles online multiplayer game logic.
* <p>
* 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 {
/** The local player controlled by this client. */
private AbstractPlayer mainPlayer;
/**
* 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);
}
/** Finds the first non-online player in the array. */
private AbstractPlayer getFirstNotOnlinePlayer(AbstractPlayer[] players) {
for (AbstractPlayer player : players) {
if (!(player instanceof OnlinePlayer)) {
return player;
}
}
throw new RuntimeException("All players are online players");
}
/** Starts processing network events for the local player. */
@Override
public void start() {
isRunning.set(true);
}
/** Stops processing network events. */
@Override
public void stop() {
isRunning.set(false);
}
/**
* Called when the server notifies that it is the local player's turn.
* Sends the generated move back to the server.
*/
@Override
public void yourTurn(NetworkEvents.YourTurnResponse event) {
if (!isRunning.get()) return;
int move = mainPlayer.getMove(game.clone());
new EventFlow().addPostEvent(NetworkEvents.SendMove.class, event.clientId(), (short) move).postEvent();
}
/**
* Handles a move received from the server for any player.
* Updates the game state and triggers a UI refresh.
*/
@Override
public void moveReceived(NetworkEvents.GameMoveResponse event) {
if (!isRunning.get()) return;
game.play(Integer.parseInt(event.move()));
new EventFlow().addPostEvent(GUIEvents.RefreshGameCanvas.class).postEvent();
}
/**
* Handles the end of the game as notified by the server.
* Updates the UI to show a win or draw result for the local player.
*/
@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();
default -> {
logger.error("Invalid condition");
throw new RuntimeException("Unknown condition");
}
}
}
}

View File

@@ -0,0 +1,42 @@
package org.toop.game.GameThreadBehaviour;
import org.toop.framework.gameFramework.abstractClasses.TurnBasedGameR;
import org.toop.framework.networking.events.NetworkEvents;
import org.toop.game.players.AbstractPlayer;
/**
* Online thread behaviour that adds a fixed delay before processing
* the local player's turn.
* <p>
* This is identical to {@link OnlineThreadBehaviour}, but inserts a
* short sleep before delegating to the base implementation.
*/
public class OnlineWithSleepThreadBehaviour extends OnlineThreadBehaviour {
/**
* Creates the behaviour and forwards the players to the base class.
*
* @param game the online-capable turn-based game
* @param players the list of local and remote players
*/
public OnlineWithSleepThreadBehaviour(TurnBasedGameR game, AbstractPlayer[] players) {
super(game, players);
}
/**
* Waits briefly before handling the "your turn" event.
*
* @param event the network event indicating it's this client's turn
*/
@Override
public void yourTurn(NetworkEvents.YourTurnResponse event) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
super.yourTurn(event);
}
}

View File

@@ -0,0 +1,57 @@
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

@@ -1,9 +0,0 @@
package org.toop.game.enumerators;
public enum GameState {
NORMAL,
DRAW,
WIN,
TURN_SKIPPED,
}

View File

@@ -1,6 +1,6 @@
package org.toop.game.interfaces;
import org.toop.game.enumerators.GameState;
import org.toop.framework.gameFramework.GameState;
import org.toop.game.records.Move;
public interface IPlayable {

View File

@@ -0,0 +1,51 @@
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

@@ -0,0 +1,46 @@
package org.toop.game.players;
import org.toop.framework.gameFramework.abstractClasses.AIR;
import org.toop.framework.gameFramework.abstractClasses.GameR;
/**
* Represents a player controlled by an AI in a game.
* <p>
* This player uses an {@link AIR} 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 {
/** The AI instance used to calculate moves. */
private final AIR<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) {
super(name);
this.ai = ai;
}
/**
* Determines the next move for this player using its AI.
* <p>
* This method overrides {@link AbstractPlayer#getMove(GameR)}. Because the AI is
* typed to {@code T}, a runtime cast is required. It is the caller's
* responsibility to ensure that {@code gameCopy} is of type {@code T}.
* </p>
*
* @param gameCopy a copy of the current game state
* @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
}
}

View File

@@ -0,0 +1,74 @@
package org.toop.game.players;
import org.toop.framework.gameFramework.abstractClasses.GameR;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class LocalPlayer extends AbstractPlayer {
// Future can be used with event system, IF unsubscribeAfterSuccess works...
// private CompletableFuture<Integer> LastMove = new CompletableFuture<>();
private CompletableFuture<Integer> LastMove;
public LocalPlayer(String name) {
super(name);
}
@Override
public int getMove(GameR gameCopy) {
return getValidMove(gameCopy);
}
public void setMove(int move) {
LastMove.complete(move);
}
// TODO: helper function, would like to replace to get rid of this method
public static boolean contains(int[] array, int value){
for (int i : array) if (i == value) return true;
return false;
}
private int getMove2(GameR gameCopy) {
LastMove = new CompletableFuture<>();
int move = -1;
try {
move = LastMove.get();
} catch (InterruptedException | ExecutionException e) {
// TODO: Add proper logging.
e.printStackTrace();
}
return move;
}
protected int getValidMove(GameR 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());
while (!contains(validMoves, move)) {
System.out.println("Not a valid move, try again");
move = getMove2(gameCopy.clone());
}
return move;
}
/*public void register() {
// Listening to PlayerAttemptedMove
new EventFlow().listen(GUIEvents.PlayerAttemptedMove.class, event -> {
if (!LastMove.isDone()) {
LastMove.complete(event.move()); // complete the future
}
}, true); // auto-unsubscribe
}
// This blocks until the next move arrives
public int take() throws ExecutionException, InterruptedException {
int move = LastMove.get(); // blocking
LastMove = new CompletableFuture<>(); // reset for next move
return move;
}*/
}

View File

@@ -0,0 +1,23 @@
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

@@ -0,0 +1,23 @@
package org.toop.game.players;
/**
* Represents a player controlled remotely or over a network.
* <p>
* This class extends {@link AbstractPlayer} and can be used to implement game logic
* where moves are provided by an external source (e.g., another user or a server).
* Currently, this class is a placeholder and does not implement move logic.
* </p>
*/
public class OnlinePlayer extends AbstractPlayer {
/**
* Constructs a new OnlinePlayer.
* <p>
* Currently, no additional initialization is performed. Subclasses or
* future implementations should provide mechanisms to receive moves from
* an external source.
*/
public OnlinePlayer(String name) {
super(name);
}
}

View File

@@ -1,7 +1,7 @@
package org.toop.game.reversi;
import org.toop.game.TurnBasedGame;
import org.toop.game.enumerators.GameState;
import org.toop.framework.gameFramework.GameState;
import org.toop.game.records.Move;
import java.awt.*;

View File

@@ -0,0 +1,17 @@
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

@@ -0,0 +1,259 @@
package org.toop.game.reversi;
import org.toop.framework.gameFramework.GameState;
import org.toop.framework.gameFramework.PlayResult;
import org.toop.framework.gameFramework.abstractClasses.TurnBasedGameR;
import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public final class ReversiR extends TurnBasedGameR {
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() {
return new ReversiR(this);
}
public ReversiR() {
super(8, 8, 2);
addStartPieces();
}
public ReversiR(ReversiR other) {
super(other);
this.movesTaken = other.movesTaken;
this.filledCells = other.filledCells;
this.mostRecentlyFlippedPieces = other.mostRecentlyFlippedPieces;
}
private void addStartPieces() {
this.setBoardPosition(27, 1);
this.setBoardPosition(28, 0);
this.setBoardPosition(35, 0);
this.setBoardPosition(36, 1);
updateFilledCellsSet();
}
private void updateFilledCellsSet() {
for (int i = 0; i < 64; i++) {
if (this.getBoard()[i] != EMPTY) {
filledCells.add(new Point(i % this.getColumnSize(), i / this.getRowSize()));
}
}
}
@Override
public int[] getLegalMoves() {
final ArrayList<Integer> legalMoves = new ArrayList<>();
int[][] boardGrid = makeBoardAGrid();
int currentPlayer = this.getCurrentTurn();
Set<Point> adjCell = getAdjacentCells(boardGrid);
for (Point point : adjCell){
int[] moves = getFlipsForPotentialMove(point,currentPlayer);
int score = moves.length;
if (score > 0){
legalMoves.add(point.x + point.y * this.getRowSize());
}
}
return legalMoves.stream().mapToInt(Integer::intValue).toArray();
}
private Set<Point> getAdjacentCells(int[][] 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 int[] getFlipsForPotentialMove(Point point, int currentPlayer) {
final ArrayList<Integer> 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;
}
int[] moves = getFlipsInDirection(point,makeBoardAGrid(),currentPlayer,deltaColumn,deltaRow);
if (moves != null) { //getFlipsInDirection
Arrays.stream(moves).forEach(movesToFlip::add);
}
}
}
return movesToFlip.stream().mapToInt(Integer::intValue).toArray();
}
private int[] getFlipsInDirection(Point point, int[][] boardGrid, int currentPlayer, int dirX, int dirY) {
int opponent = getOpponent(currentPlayer);
final ArrayList<Integer> 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(x+y*this.getRowSize());
x += dirX;
y += dirY;
}
if (isOnBoard(x, y) && boardGrid[y][x] == currentPlayer) {
return movesToFlip.stream().mapToInt(Integer::intValue).toArray(); //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 int[][] makeBoardAGrid() {
int[][] boardGrid = new int[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;
}
private boolean gameOver(){
ReversiR gameCopy = clone();
return gameCopy.getLegalMoves().length == 0 && gameCopy.skipTurn().getLegalMoves().length == 0;
}
@Override
public PlayResult play(int move) {
/*int[] legalMoves = getLegalMoves();
boolean moveIsLegal = false;
for (int legalMove : legalMoves) { //check if the move is legal
if (move == legalMove) {
moveIsLegal = true;
break;
}
}
if (!moveIsLegal) {
return null;
}
int[] moves = sortMovesFromCenter(Arrays.stream(getFlipsForPotentialMove(new Point(move%this.getColumnSize(),move/this.getRowSize()), getCurrentTurn())).boxed().toArray(Integer[]::new),move);
mostRecentlyFlippedPieces = moves;
this.setBoard(move); //place the move on the board
for (int m : moves) {
this.setBoard(m); //flip the correct pieces on the board
}
filledCells.add(new Point(move % this.getRowSize(), move / this.getColumnSize()));
nextTurn();
if (getLegalMoves().length == 0) { //skip the players turn when there are no legal moves
skipMyTurn();
if (getLegalMoves().length > 0) {
return new PlayResult(GameState.TURN_SKIPPED, getCurrentTurn());
}
else { //end the game when neither player has a legal move
Score score = getScore();
if (score.player1Score() == score.player2Score()) {
return new PlayResult(GameState.DRAW, EMPTY);
}
else {
return new PlayResult(GameState.WIN, getCurrentTurn());
}
}
}
return new PlayResult(GameState.NORMAL, EMPTY);*/
// Check if move is legal
if (!contains(getLegalMoves(), move)){
// Next person wins
return new PlayResult(GameState.WIN, (getCurrentTurn() + 1) % 2);
}
// Move is legal, proceed as normal
int[] moves = sortMovesFromCenter(Arrays.stream(getFlipsForPotentialMove(new Point(move%this.getColumnSize(),move/this.getRowSize()), getCurrentTurn())).boxed().toArray(Integer[]::new),move);
mostRecentlyFlippedPieces = moves;
this.setBoard(move); //place the move on the board
for (int m : moves) {
this.setBoard(m); //flip the correct pieces on the board
}
filledCells.add(new Point(move % this.getRowSize(), move / this.getColumnSize()));
nextTurn();
// Check for forced turn skip
if (getLegalMoves().length == 0){
PlayResult result;
// Check if next turn is also a force skip
if (clone().skipTurn().getLegalMoves().length == 0){
// Game over
int winner = getWinner();
result = new PlayResult(winner == EMPTY ? GameState.DRAW : GameState.WIN, winner);
}else{
// Turn skipped
result = new PlayResult(GameState.TURN_SKIPPED, getCurrentTurn());
skipTurn();
}
return result;
}
return new PlayResult(GameState.NORMAL, EMPTY);
}
private ReversiR skipTurn(){
nextTurn();
return this;
}
private int getOpponent(int currentPlayer){
return (currentPlayer + 1)%2;
}
public int getWinner(){
int player1Score = 0, player2Score = 0;
for (int count = 0; count < this.getRowSize() * this.getColumnSize(); count++) {
if (this.getBoard()[count] == 0) {
player1Score += 1;
}
if (this.getBoard()[count] == 1) {
player2Score += 1;
}
}
return player1Score == player2Score? -1 : player1Score > player2Score ? 0 : 1;
}
private int[] sortMovesFromCenter(Integer[] moves, int center) { //sorts the pieces to be flipped for animation purposes
int centerX = center%this.getColumnSize();
int centerY = center/this.getRowSize();
Arrays.sort(moves, (a, b) -> {
int dxA = a%this.getColumnSize() - centerX;
int dyA = a/this.getRowSize() - centerY;
int dxB = b%this.getColumnSize() - centerX;
int dyB = b/this.getRowSize() - centerY;
int distA = dxA * dxA + dyA * dyA;
int distB = dxB * dxB + dyB * dyB;
return Integer.compare(distA, distB);
});
return Arrays.stream(moves).mapToInt(Integer::intValue).toArray();
}
public int[] getMostRecentlyFlippedPieces() {
return mostRecentlyFlippedPieces;
}
}

View File

@@ -2,7 +2,7 @@ package org.toop.game.tictactoe;
import java.util.ArrayList;
import org.toop.game.TurnBasedGame;
import org.toop.game.enumerators.GameState;
import org.toop.framework.gameFramework.GameState;
import org.toop.game.records.Move;
public final class TicTacToe extends TurnBasedGame {

View File

@@ -1,7 +1,7 @@
package org.toop.game.tictactoe;
import org.toop.game.AI;
import org.toop.game.enumerators.GameState;
import org.toop.framework.gameFramework.GameState;
import org.toop.game.records.Move;
public final class TicTacToeAI extends AI<TicTacToe> {

View File

@@ -0,0 +1,103 @@
package org.toop.game.tictactoe;
import org.toop.framework.gameFramework.abstractClasses.AIR;
import org.toop.framework.gameFramework.PlayResult;
import org.toop.framework.gameFramework.GameState;
/**
* AI implementation for playing Tic-Tac-Toe.
* <p>
* This AI uses a recursive minimax-like strategy with a limited depth to
* evaluate moves. It attempts to maximize its chances of winning while
* minimizing the opponent's opportunities. Random moves are used in the
* opening or when no clear best move is found.
* </p>
*/
public final class TicTacToeAIR extends AIR<TicTacToeR> {
/**
* Determines the best move for the given Tic-Tac-Toe game state.
* <p>
* Uses a depth-limited recursive strategy to score each legal move and
* selects the move with the highest score. If no legal moves are available,
* returns -1. If multiple moves are equally good, picks one randomly.
* </p>
*
* @param game the current Tic-Tac-Toe game state
* @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) {
assert game != null;
assert depth >= 0;
final int[] legalMoves = game.getLegalMoves();
// If there are no moves, return -1
if (legalMoves.length == 0) {
return -1;
}
// If first move, pick a corner
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;
int bestMove = -1;
// Calculate Move score of each move, keep track what moves had the best score
for (final int move : legalMoves) {
final int score = getMoveScore(game, depth, move, true);
if (score > bestScore) {
bestMove = move;
bestScore = score;
}
}
return bestMove != -1 ? bestMove : legalMoves[(int)(Math.random() * legalMoves.length)];
}
/**
* Recursively evaluates the score of a potential move using a minimax-like approach.
*
* @param game the current Tic-Tac-Toe game state
* @param depth remaining depth to evaluate
* @param move the move to evaluate
* @param maximizing true if the AI is to maximize score, false if minimizing
* @return the score of the move
*/
private int getMoveScore(TicTacToeR game, int depth, int move, boolean maximizing) {
final TicTacToeR copy = game.clone();
final PlayResult result = copy.play(move);
GameState state = result.state();
switch (state) {
case DRAW: return 0;
case WIN: return maximizing ? depth + 1 : -depth - 1;
}
if (depth <= 0) {
return 0;
}
final int[] legalMoves = copy.getLegalMoves();
int score = maximizing ? depth + 1 : -depth - 1;
for (final int 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

@@ -0,0 +1,118 @@
package org.toop.game.tictactoe;
import org.toop.framework.gameFramework.PlayResult;
import org.toop.framework.gameFramework.abstractClasses.TurnBasedGameR;
import org.toop.framework.gameFramework.GameState;
import java.util.ArrayList;
import java.util.Objects;
public final class TicTacToeR extends TurnBasedGameR {
private int movesLeft;
public TicTacToeR() {
super(3, 3, 2);
movesLeft = this.getBoard().length;
}
public TicTacToeR(TicTacToeR other) {
super(other);
movesLeft = other.movesLeft;
}
@Override
public int[] getLegalMoves() {
final ArrayList<Integer> legalMoves = new ArrayList<Integer>();
for (int i = 0; i < this.getBoard().length; i++) {
if (Objects.equals(this.getBoard()[i], EMPTY)) {
legalMoves.add(i);
}
}
return legalMoves.stream().mapToInt(Integer::intValue).toArray();
}
@Override
public PlayResult play(int move) {
// NOT MY ASSERTIONS - Stef
assert move >= 0 && move < this.getBoard().length;
// Player loses if move is invalid
if (!contains(getLegalMoves(), move)) {
// Next player wins
return new PlayResult(GameState.WIN, (getCurrentTurn() + 1)%2); // TODO: Make this a generic method like getNextPlayer() or something similar.
}
// Move is valid, make move.
this.setBoard(move);
movesLeft--;
nextTurn();
// Check if current player won TODO: Make this generic?
// Not sure why I am checking for ANY win when only current player should be able to win.
int t = checkForWin();
if (t != EMPTY) {
return new PlayResult(GameState.WIN, t);
}
// Check for (early) draw
if (movesLeft <= 3) {
if (checkForEarlyDraw()) {
return new PlayResult(GameState.DRAW, EMPTY);
}
}
// Nothing weird happened, continue on as normal
return new PlayResult(GameState.NORMAL, EMPTY);
}
private int checkForWin() {
// Horizontal
for (int i = 0; i < 3; i++) {
final int index = i * 3;
if (!Objects.equals(this.getBoard()[index], EMPTY)
&& Objects.equals(this.getBoard()[index], this.getBoard()[index + 1])
&& Objects.equals(this.getBoard()[index], this.getBoard()[index + 2])) {
return this.getBoard()[index];
}
}
// Vertical
for (int i = 0; i < 3; i++) {
if (!Objects.equals(this.getBoard()[i], EMPTY) && Objects.equals(this.getBoard()[i], this.getBoard()[i + 3]) && Objects.equals(this.getBoard()[i], this.getBoard()[i + 6])) {
return this.getBoard()[i];
}
}
// B-Slash
if (!Objects.equals(this.getBoard()[0], EMPTY) && Objects.equals(this.getBoard()[0], this.getBoard()[4]) && Objects.equals(this.getBoard()[0], this.getBoard()[8])) {
return this.getBoard()[0];
}
// F-Slash
if (!Objects.equals(this.getBoard()[2], EMPTY) && Objects.equals(this.getBoard()[2], this.getBoard()[4]) && Objects.equals(this.getBoard()[2], this.getBoard()[6]))
return this.getBoard()[2];
// Default return
return EMPTY;
}
private boolean checkForEarlyDraw() {
for (final int move : this.getLegalMoves()) {
final TicTacToeR copy = this.clone();
if (copy.play(move).state() == GameState.WIN || !copy.checkForEarlyDraw()) {
return false;
}
}
return true;
}
@Override
public TicTacToeR clone() {
return new TicTacToeR(this);
}
}

View File

@@ -4,7 +4,7 @@ import java.util.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.toop.game.enumerators.GameState;
import org.toop.framework.gameFramework.GameState;
import org.toop.game.records.Move;
import org.toop.game.reversi.Reversi;
import org.toop.game.reversi.ReversiAI;

View File

@@ -0,0 +1,118 @@
package org.toop.game.tictactoe;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
final class TicTacToeAIRTest {
private final TicTacToeAIR ai = new TicTacToeAIR();
// Helper: play multiple moves in sequence on a fresh board
private TicTacToeR playSequence(int... moves) {
TicTacToeR game = new TicTacToeR();
for (int move : moves) {
game.play(move);
}
return game;
}
@Test
@DisplayName("AI first move must choose a corner")
void testFirstMoveIsCorner() {
TicTacToeR game = new TicTacToeR();
int move = ai.findBestMove(game, 4);
assertTrue(
move == 0 || move == 2 || move == 6 || move == 8,
"AI should pick a corner as first move"
);
}
@Test
@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);
assertEquals(8, move);
}
@Test
@DisplayName("AI takes immediate winning move")
void testAiTakesWinningMove() {
// X = AI, O = opponent
// Board state (X to play):
// X | X | .
// O | O | .
// . | . | .
//
// AI must play 2 (top-right) to win.
TicTacToeR game = playSequence(
0, 3, // X, O
1, 4 // X, O
);
int move = ai.findBestMove(game, 4);
assertEquals(2, move, "AI must take the winning move at index 2");
}
@Test
@DisplayName("AI blocks opponent's winning move")
void testAiBlocksOpponent() {
// Opponent threatens to win:
// X | . | .
// O | O | .
// . | . | X
// O is about to win at index 5; AI must block it.
TicTacToeR game = playSequence(
0, 3, // X, O
8, 4 // X, O (O threatens at 5)
);
int move = ai.findBestMove(game, 4);
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();
// Fill board alternating
for (int i = 0; i < 9; i++) full.play(i);
int move = ai.findBestMove(full, 3);
assertEquals(-1, move, "AI should return -1 when board is full");
}
@Test
@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);
assertTrue(move >= -1 && move <= 8, "AI must return a valid move index");
}
@Test
@DisplayName("AI chooses the optimal forced draw move")
void testForcedDrawScenario() {
// Scenario where only one move avoids immediate loss:
//
// X | O | X
// X | O | .
// O | X | .
//
// Legal moves: 5, 8
// Only move 5 avoids losing.
TicTacToeR game = new TicTacToeR();
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);
assertEquals(5, move, "AI must choose the only move that avoids losing");
}
}