mirror of
https://github.com/2OOP/pism.git
synced 2026-02-04 19:04:49 +00:00
Merge bitboards into development (#285)
* added new classes for the games that use bitboards instead. also combined game with turnbasedgame * (DOES NOT COMPILE) In-between commit * turn updates * smalle fixes aan turn updates * Bitboard implemented with scuffed TicTacToe translation done by game. This should be done by the view. * Almost done with implementing bitboards. Reversi is broken and artifical players don't work yet. * better human/ai selector with bot selection and depth on TicTacToeAIR * fixed getLegalMoves * depth + thinktime back to AIs, along with a a specific TicTacToeAIRSleep * fixed overlapping back and disconnect buttons * Changed to debug instead of info * changed the transitionNextCustom to be easier to use * added getAllWidgets to WidgetContainer * Correct back view * added replacePrevious in ViewWidget * added removeIndexFromPreviousChain * fixed incorrect index counting * Fixt wrong view order * fixed? getLegalMoves * Everything is broken * Removed todo * fixed getLegalMoves & getFlips * Challenge popups "Fixed" * Fixed local and online play for both games * Popups now remove themselves * Removed souts for debugging * localize the ChallengePopup text * made the game text a header instead * made more classes deepClonable. * fixed getAllWidgets * Added comment * Escape popup * fixed redundant container * Made all network events async again * Escape remove popup * Working escape menu * Removed old AI and old files. Added a new generic random AI. game no longer deals with translation. * Drawing of board on canvas is now done from bitboards rather than translating. * Added a method getWinner() to game interface.Controller now tells gameThreads how to deal with drawing UI and sending a move to server. * Added find functionality * Added a ChatGPT generated MiniMaxAI based on the old MiniMaxAI but with alpha-beta pruning and heuristics for Reversi * Removed System-Outs to clean up console * Update BitGameCanvas.java * Merge fixes * Removed unused imports --------- Co-authored-by: ramollia <> Co-authored-by: michiel301b <m.brands.3@st.hanze.nl> Co-authored-by: lieght <49651652+BAFGdeJong@users.noreply.github.com>
This commit is contained in:
86
game/src/main/java/org/toop/game/BitboardGame.java
Normal file
86
game/src/main/java/org/toop/game/BitboardGame.java
Normal file
@@ -0,0 +1,86 @@
|
||||
package org.toop.game;
|
||||
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
// There is AI performance to be gained by getting rid of non-primitives and thus speeding up deepCopy
|
||||
public abstract class BitboardGame<T extends BitboardGame<T>> implements TurnBasedGame<T> {
|
||||
private final int columnSize;
|
||||
private final int rowSize;
|
||||
|
||||
private Player<T>[] players;
|
||||
|
||||
// long is 64 bits. Every game has a limit of 64 cells maximum.
|
||||
private final long[] playerBitboard;
|
||||
private int currentTurn = 0;
|
||||
|
||||
public BitboardGame(int columnSize, int rowSize, int playerCount, Player<T>[] players) {
|
||||
this.columnSize = columnSize;
|
||||
this.rowSize = rowSize;
|
||||
this.players = players;
|
||||
this.playerBitboard = new long[playerCount];
|
||||
|
||||
Arrays.fill(playerBitboard, 0L);
|
||||
}
|
||||
|
||||
public BitboardGame(BitboardGame<T> other) {
|
||||
this.columnSize = other.columnSize;
|
||||
this.rowSize = other.rowSize;
|
||||
|
||||
this.playerBitboard = other.playerBitboard.clone();
|
||||
this.currentTurn = other.currentTurn;
|
||||
this.players = Arrays.stream(other.players)
|
||||
.map(Player<T>::deepCopy)
|
||||
.toArray(Player[]::new);
|
||||
}
|
||||
|
||||
public int getColumnSize() {
|
||||
return this.columnSize;
|
||||
}
|
||||
|
||||
public int getRowSize() {
|
||||
return this.rowSize;
|
||||
}
|
||||
|
||||
public long getPlayerBitboard(int player) {
|
||||
return this.playerBitboard[player];
|
||||
}
|
||||
|
||||
public void setPlayerBitboard(int player, long bitboard) {
|
||||
this.playerBitboard[player] = bitboard;
|
||||
}
|
||||
|
||||
public int getPlayerCount() {
|
||||
return playerBitboard.length;
|
||||
}
|
||||
|
||||
public int getCurrentTurn() {
|
||||
return getCurrentPlayerIndex();
|
||||
}
|
||||
|
||||
public Player<T> getPlayer(int index) {return players[index];}
|
||||
|
||||
public int getCurrentPlayerIndex() {
|
||||
return currentTurn % playerBitboard.length;
|
||||
}
|
||||
|
||||
public int getNextPlayer() {
|
||||
return (currentTurn + 1) % playerBitboard.length;
|
||||
}
|
||||
|
||||
public Player<T> getCurrentPlayer(){
|
||||
return players[getCurrentPlayerIndex()];
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public long[] getBoard() {return this.playerBitboard;}
|
||||
|
||||
public void nextTurn() {
|
||||
currentTurn++;
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,8 @@ import org.toop.framework.gameFramework.view.GUIEvents;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* Handles local turn-based game logic at a fixed update rate.
|
||||
* <p>
|
||||
@@ -16,18 +18,14 @@ import org.toop.framework.gameFramework.model.player.Player;
|
||||
*/
|
||||
public class LocalFixedRateThreadBehaviour<T extends TurnBasedGame<T>> extends AbstractThreadBehaviour<T> implements Runnable {
|
||||
|
||||
/** All players participating in the game. */
|
||||
private final Player<T>[] 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(T game, Player<T>[] players) {
|
||||
public LocalFixedRateThreadBehaviour(T game) {
|
||||
super(game);
|
||||
this.players = players;
|
||||
}
|
||||
|
||||
/** Starts the game loop thread if not already running. */
|
||||
@@ -52,7 +50,7 @@ public class LocalFixedRateThreadBehaviour<T extends TurnBasedGame<T>> extends A
|
||||
*/
|
||||
@Override
|
||||
public void run() {
|
||||
final int UPS = 60;
|
||||
final int UPS = 1;
|
||||
final long UPDATE_INTERVAL = 1_000_000_000L / UPS;
|
||||
long nextUpdate = System.nanoTime();
|
||||
|
||||
@@ -62,9 +60,10 @@ public class LocalFixedRateThreadBehaviour<T extends TurnBasedGame<T>> extends A
|
||||
nextUpdate += UPDATE_INTERVAL;
|
||||
|
||||
Player<T> currentPlayer = game.getPlayer(game.getCurrentTurn());
|
||||
int move = currentPlayer.getMove(game.deepCopy());
|
||||
long move = currentPlayer.getMove(game.deepCopy());
|
||||
PlayResult result = game.play(move);
|
||||
new EventFlow().addPostEvent(GUIEvents.RefreshGameCanvas.class).postEvent();
|
||||
|
||||
updateUI();
|
||||
|
||||
GameState state = result.state();
|
||||
switch (state) {
|
||||
|
||||
@@ -8,6 +8,8 @@ import org.toop.framework.gameFramework.GameState;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* Handles local turn-based game logic in its own thread.
|
||||
* <p>
|
||||
@@ -20,9 +22,8 @@ public class LocalThreadBehaviour<T extends TurnBasedGame<T>> extends AbstractTh
|
||||
* 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(T game, Player<T>[] players) {
|
||||
public LocalThreadBehaviour(T game) {
|
||||
super(game);
|
||||
}
|
||||
|
||||
@@ -48,9 +49,10 @@ public class LocalThreadBehaviour<T extends TurnBasedGame<T>> extends AbstractTh
|
||||
public void run() {
|
||||
while (isRunning.get()) {
|
||||
Player<T> currentPlayer = game.getPlayer(game.getCurrentTurn());
|
||||
int move = currentPlayer.getMove(game.deepCopy());
|
||||
long move = currentPlayer.getMove(game.deepCopy());
|
||||
PlayResult result = game.play(move);
|
||||
new EventFlow().addPostEvent(GUIEvents.RefreshGameCanvas.class).postEvent();
|
||||
|
||||
updateUI();
|
||||
|
||||
GameState state = result.state();
|
||||
switch (state) {
|
||||
|
||||
@@ -3,9 +3,7 @@ package org.toop.game.gameThreads;
|
||||
import org.toop.framework.eventbus.EventFlow;
|
||||
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.model.game.SupportsOnlinePlay;
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
import org.toop.game.players.OnlinePlayer;
|
||||
@@ -17,19 +15,12 @@ import org.toop.game.players.OnlinePlayer;
|
||||
* for the local player while receiving moves from other players.
|
||||
*/
|
||||
public class OnlineThreadBehaviour<T extends TurnBasedGame<T>> extends AbstractThreadBehaviour<T> implements SupportsOnlinePlay {
|
||||
|
||||
/** The local player controlled by this client. */
|
||||
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(T game, Player<T>[] players) {
|
||||
public OnlineThreadBehaviour(T game) {
|
||||
super(game);
|
||||
this.playerTurn = getFirstNotOnlinePlayer(players);
|
||||
this.mainPlayer = players[this.playerTurn];
|
||||
}
|
||||
|
||||
/** Finds the first non-online player in the array. */
|
||||
@@ -59,33 +50,31 @@ public class OnlineThreadBehaviour<T extends TurnBasedGame<T>> extends AbstractT
|
||||
* Sends the generated move back to the server.
|
||||
*/
|
||||
@Override
|
||||
public void onYourTurn(NetworkEvents.YourTurnResponse event) {
|
||||
public void onYourTurn(long clientId) {
|
||||
if (!isRunning.get()) return;
|
||||
int move = mainPlayer.getMove(game.deepCopy());
|
||||
new EventFlow().addPostEvent(NetworkEvents.SendMove.class, event.clientId(), (short) move).postEvent();
|
||||
long move = game.getPlayer(game.getCurrentTurn()).getMove(game.deepCopy());
|
||||
sendMove(clientId, move);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles a move received from the server for any player.
|
||||
* Updates the game state and triggers a UI refresh.
|
||||
*/
|
||||
@Override
|
||||
public void onMoveReceived(NetworkEvents.GameMoveResponse event) {
|
||||
public void onMoveReceived(long move) {
|
||||
if (!isRunning.get()) return;
|
||||
game.play(Integer.parseInt(event.move()));
|
||||
new EventFlow().addPostEvent(GUIEvents.RefreshGameCanvas.class).postEvent();
|
||||
game.play(move);
|
||||
|
||||
updateUI();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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, 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();
|
||||
public void gameFinished(String condition) {
|
||||
switch(condition.toUpperCase()){
|
||||
case "WIN", "LOSS" -> new EventFlow().addPostEvent(GUIEvents.GameEnded.class, true, game.getWinner()).postEvent();
|
||||
case "DRAW" -> new EventFlow().addPostEvent(GUIEvents.GameEnded.class, false, -1).postEvent();
|
||||
default -> {
|
||||
logger.error("Invalid condition");
|
||||
throw new RuntimeException("Unknown condition");
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
package org.toop.game.gameThreads;
|
||||
|
||||
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.model.player.AbstractPlayer;
|
||||
|
||||
/**
|
||||
* Online thread behaviour that adds a fixed delay before processing
|
||||
@@ -11,16 +10,15 @@ import org.toop.framework.gameFramework.model.player.AbstractPlayer;
|
||||
* This is identical to {@link OnlineThreadBehaviour}, but inserts a
|
||||
* short sleep before delegating to the base implementation.
|
||||
*/
|
||||
public class OnlineWithSleepThreadBehaviour extends OnlineThreadBehaviour {
|
||||
public class OnlineWithSleepThreadBehaviour<T extends TurnBasedGame<T>> extends OnlineThreadBehaviour<T> {
|
||||
|
||||
/**
|
||||
* 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
|
||||
* @param game the online-capable turn-based game
|
||||
*/
|
||||
public OnlineWithSleepThreadBehaviour(AbstractGame game, AbstractPlayer[] players) {
|
||||
super(game, players);
|
||||
public OnlineWithSleepThreadBehaviour(T game) {
|
||||
super(game);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -29,14 +27,14 @@ public class OnlineWithSleepThreadBehaviour extends OnlineThreadBehaviour {
|
||||
* @param event the network event indicating it's this client's turn
|
||||
*/
|
||||
@Override
|
||||
public void onYourTurn(NetworkEvents.YourTurnResponse event) {
|
||||
public void onYourTurn(long clientId) {
|
||||
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
Thread.sleep(50);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
super.onYourTurn(event);
|
||||
super.onYourTurn(clientId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
package org.toop.game.games.reversi;
|
||||
|
||||
import org.toop.framework.gameFramework.GameState;
|
||||
import org.toop.framework.gameFramework.model.game.PlayResult;
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
import org.toop.game.BitboardGame;
|
||||
|
||||
public class BitboardReversi extends BitboardGame<BitboardReversi> {
|
||||
|
||||
public record Score(int black, int white) {}
|
||||
|
||||
private final long notAFile = 0xfefefefefefefefeL;
|
||||
private final long notHFile = 0x7f7f7f7f7f7f7f7fL;
|
||||
|
||||
public BitboardReversi(Player<BitboardReversi>[] players) {
|
||||
super(8, 8, 2, players);
|
||||
|
||||
// Black (player 0)
|
||||
setPlayerBitboard(0, (1L << (3 + 4 * 8)) | (1L << (4 + 3 * 8)));
|
||||
|
||||
// White (player 1)
|
||||
setPlayerBitboard(1, (1L << (3 + 3 * 8)) | (1L << (4 + 4 * 8)));
|
||||
}
|
||||
|
||||
public BitboardReversi(BitboardReversi other) {
|
||||
super(other);
|
||||
}
|
||||
|
||||
public long getLegalMoves() {
|
||||
final long player = getPlayerBitboard(getCurrentPlayerIndex());
|
||||
final long opponent = getPlayerBitboard(getNextPlayer());
|
||||
|
||||
long legalMoves = 0L;
|
||||
|
||||
// north & south
|
||||
legalMoves |= computeMoves(player, opponent, 8, -1L);
|
||||
legalMoves |= computeMoves(player, opponent, -8, -1L);
|
||||
|
||||
// east & west
|
||||
legalMoves |= computeMoves(player, opponent, 1, notAFile);
|
||||
legalMoves |= computeMoves(player, opponent, -1, notHFile);
|
||||
|
||||
// north-east & north-west & south-east & south-west
|
||||
legalMoves |= computeMoves(player, opponent, 9, notAFile);
|
||||
legalMoves |= computeMoves(player, opponent, 7, notHFile);
|
||||
legalMoves |= computeMoves(player, opponent, -7, notAFile);
|
||||
legalMoves |= computeMoves(player, opponent, -9, notHFile);
|
||||
|
||||
return legalMoves;
|
||||
}
|
||||
|
||||
public long getFlips(long move) {
|
||||
final long player = getPlayerBitboard(getCurrentPlayerIndex());
|
||||
final long opponent = getPlayerBitboard(getNextPlayer());
|
||||
|
||||
long flips = 0L;
|
||||
|
||||
// north & south
|
||||
flips |= computeFlips(move, player, opponent, 8, -1L);
|
||||
flips |= computeFlips(move, player, opponent, -8, -1L);
|
||||
|
||||
// east & west
|
||||
flips |= computeFlips(move, player, opponent, 1, notAFile);
|
||||
flips |= computeFlips(move, player, opponent, -1, notHFile);
|
||||
|
||||
// north-east & north-west & south-east & south-west
|
||||
flips |= computeFlips(move, player, opponent, 9, notAFile);
|
||||
flips |= computeFlips(move, player, opponent, 7, notHFile);
|
||||
flips |= computeFlips(move, player, opponent, -7, notAFile);
|
||||
flips |= computeFlips(move, player, opponent, -9, notHFile);
|
||||
|
||||
return flips;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BitboardReversi deepCopy() {return new BitboardReversi(this);}
|
||||
|
||||
public PlayResult play(long move) {
|
||||
final long flips = getFlips(move);
|
||||
|
||||
long player = getPlayerBitboard(getCurrentPlayerIndex());
|
||||
long opponent = getPlayerBitboard(getNextPlayer());
|
||||
|
||||
player |= move | flips;
|
||||
opponent &= ~flips;
|
||||
|
||||
setPlayerBitboard(getCurrentPlayerIndex(), player);
|
||||
setPlayerBitboard(getNextPlayer(), opponent);
|
||||
|
||||
nextTurn();
|
||||
|
||||
final long nextLegalMoves = getLegalMoves();
|
||||
|
||||
if (nextLegalMoves == 0) {
|
||||
nextTurn();
|
||||
|
||||
final long skippedLegalMoves = getLegalMoves();
|
||||
|
||||
if (skippedLegalMoves == 0) {
|
||||
int winner = getWinner();
|
||||
|
||||
if (winner == -1) {
|
||||
return new PlayResult(GameState.DRAW, -1);
|
||||
}
|
||||
|
||||
return new PlayResult(GameState.WIN, winner);
|
||||
}
|
||||
|
||||
return new PlayResult(GameState.TURN_SKIPPED, getCurrentPlayerIndex());
|
||||
}
|
||||
|
||||
return new PlayResult(GameState.NORMAL, getCurrentPlayerIndex());
|
||||
}
|
||||
|
||||
public Score getScore() {
|
||||
return new Score(
|
||||
Long.bitCount(getPlayerBitboard(0)),
|
||||
Long.bitCount(getPlayerBitboard(1))
|
||||
);
|
||||
}
|
||||
|
||||
public int getWinner(){
|
||||
final long black = getPlayerBitboard(0);
|
||||
final long white = getPlayerBitboard(1);
|
||||
|
||||
final int blackCount = Long.bitCount(black);
|
||||
final int whiteCount = Long.bitCount(white);
|
||||
|
||||
if (blackCount == whiteCount){
|
||||
return -1;
|
||||
}
|
||||
else if (blackCount > whiteCount){
|
||||
return 0;
|
||||
}
|
||||
else{
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private long computeMoves(long player, long opponent, int shift, long mask) {
|
||||
long moves = shift(player, shift, mask) & opponent;
|
||||
long captured = moves;
|
||||
|
||||
while (moves != 0) {
|
||||
moves = shift(moves, shift, mask) & opponent;
|
||||
captured |= moves;
|
||||
}
|
||||
|
||||
long landing = shift(captured, shift, mask);
|
||||
return landing & ~(player | opponent);
|
||||
}
|
||||
|
||||
private long computeFlips(long move, long player, long opponent, int shift, long mask) {
|
||||
long flips = 0L;
|
||||
long pos = move;
|
||||
|
||||
while (true) {
|
||||
pos = shift(pos, shift, mask);
|
||||
if (pos == 0) return 0L;
|
||||
|
||||
if ((pos & opponent) != 0) flips |= pos;
|
||||
else if ((pos & player) != 0) return flips;
|
||||
else return 0L;
|
||||
}
|
||||
}
|
||||
|
||||
private long shift(long bit, int shift, long mask) {
|
||||
return shift > 0 ? (bit << shift) & mask : (bit >>> -shift) & mask;
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
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];
|
||||
}
|
||||
}
|
||||
@@ -1,260 +0,0 @@
|
||||
package org.toop.game.games.reversi;
|
||||
|
||||
import org.toop.framework.gameFramework.GameState;
|
||||
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;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
|
||||
public final class ReversiR extends AbstractGame<ReversiR> {
|
||||
private int movesTaken;
|
||||
private Set<Point> filledCells = new HashSet<>();
|
||||
private int[] mostRecentlyFlippedPieces;
|
||||
|
||||
@Override
|
||||
public ReversiR deepCopy() {
|
||||
return new ReversiR(this);
|
||||
}
|
||||
|
||||
// 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();
|
||||
}
|
||||
|
||||
public ReversiR(ReversiR other) {
|
||||
super(other);
|
||||
this.movesTaken = other.movesTaken;
|
||||
this.filledCells = other.filledCells;
|
||||
this.mostRecentlyFlippedPieces = other.mostRecentlyFlippedPieces;
|
||||
}
|
||||
|
||||
|
||||
private void addStartPieces() {
|
||||
this.setBoard(27, 0);
|
||||
this.setBoard(28, 1);
|
||||
this.setBoard(35, 1);
|
||||
this.setBoard(36, 0);
|
||||
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 = deepCopy();
|
||||
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 (deepCopy().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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package org.toop.game.games.tictactoe;
|
||||
|
||||
import org.toop.framework.gameFramework.GameState;
|
||||
import org.toop.framework.gameFramework.model.game.PlayResult;
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
import org.toop.game.BitboardGame;
|
||||
|
||||
public class BitboardTicTacToe extends BitboardGame<BitboardTicTacToe> {
|
||||
private final long[] winningLines = {
|
||||
0b111000000L, // top row
|
||||
0b000111000L, // middle row
|
||||
0b000000111L, // bottom row
|
||||
0b100100100L, // left column
|
||||
0b010010010L, // middle column
|
||||
0b001001001L, // right column
|
||||
0b100010001L, // diagonal
|
||||
0b001010100L // anti-diagonal
|
||||
};
|
||||
|
||||
public BitboardTicTacToe(Player<BitboardTicTacToe>[] players) {
|
||||
super(3, 3, 2, players);
|
||||
}
|
||||
public BitboardTicTacToe(BitboardTicTacToe other) {
|
||||
super(other);
|
||||
}
|
||||
|
||||
public long getLegalMoves() {
|
||||
final long xBitboard = getPlayerBitboard(0);
|
||||
final long oBitboard = getPlayerBitboard(1);
|
||||
|
||||
final long taken = (xBitboard | oBitboard);
|
||||
return (~taken) & 0x1ffL;
|
||||
}
|
||||
|
||||
public int getWinner(){
|
||||
return getCurrentPlayerIndex();
|
||||
}
|
||||
|
||||
public PlayResult play(long move) {
|
||||
// Player loses if move is invalid
|
||||
if ((move & getLegalMoves()) == 0 || Long.bitCount(move) != 1){
|
||||
return new PlayResult(GameState.WIN, getNextPlayer());
|
||||
}
|
||||
|
||||
// Move is legal, make move
|
||||
long playerBitboard = getPlayerBitboard(getCurrentPlayerIndex());
|
||||
playerBitboard |= move;
|
||||
|
||||
setPlayerBitboard(getCurrentPlayerIndex(), playerBitboard);
|
||||
|
||||
// Check if current player won
|
||||
if (checkWin(playerBitboard)) {
|
||||
return new PlayResult(GameState.WIN, getCurrentPlayerIndex());
|
||||
}
|
||||
|
||||
// Proceed to next turn
|
||||
nextTurn();
|
||||
|
||||
|
||||
// Check for early draw
|
||||
if (getLegalMoves() == 0L || checkEarlyDraw()) {
|
||||
return new PlayResult(GameState.DRAW, -1);
|
||||
}
|
||||
|
||||
// Nothing weird happened, continue on as normal
|
||||
return new PlayResult(GameState.NORMAL, -1);
|
||||
}
|
||||
|
||||
private boolean checkWin(long board) {
|
||||
for (final long line : winningLines) {
|
||||
if ((board & line) == line) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean checkEarlyDraw() {
|
||||
final long xBitboard = getPlayerBitboard(0);
|
||||
final long oBitboard = getPlayerBitboard(1);
|
||||
|
||||
final long taken = (xBitboard | oBitboard);
|
||||
final long empty = (~taken) & 0x1FFL;
|
||||
|
||||
for (final long line : winningLines) {
|
||||
if (((line & xBitboard) != 0 && (line & oBitboard) != 0)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ((line & empty) != 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BitboardTicTacToe deepCopy() {
|
||||
return new BitboardTicTacToe(this);
|
||||
}
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
package org.toop.game.games.tictactoe;
|
||||
|
||||
import org.toop.framework.gameFramework.model.player.AbstractAI;
|
||||
import org.toop.framework.gameFramework.model.game.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 class TicTacToeAIR extends AbstractAI<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
|
||||
*/
|
||||
|
||||
private int depth;
|
||||
|
||||
public TicTacToeAIR(int depth) {
|
||||
this.depth = depth;
|
||||
}
|
||||
|
||||
public int getMove(TicTacToeR game) {
|
||||
assert game != null;
|
||||
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.deepCopy();
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
package org.toop.game.games.tictactoe;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
public class TicTacToeAIRSleep extends TicTacToeAIR {
|
||||
|
||||
private int thinkTime;
|
||||
|
||||
public TicTacToeAIRSleep(int depth, int thinkTime) {
|
||||
super(depth);
|
||||
this.thinkTime = thinkTime;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getMove(TicTacToeR game) {
|
||||
int score = super.getMove(game);
|
||||
try {
|
||||
Random random = new Random();
|
||||
Thread.sleep(this.thinkTime * 1000L + random.nextInt(1000));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return score;
|
||||
}
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
package org.toop.game.games.tictactoe;
|
||||
|
||||
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 AbstractGame<TicTacToeR> {
|
||||
private int movesLeft;
|
||||
|
||||
public TicTacToeR(Player<TicTacToeR>[] players) {
|
||||
super(3, 3, 2, players);
|
||||
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.deepCopy();
|
||||
|
||||
if (copy.play(move).state() == GameState.WIN || !copy.checkForEarlyDraw()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public TicTacToeR deepCopy() {
|
||||
return new TicTacToeR(this);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,6 @@
|
||||
package org.toop.game.players;
|
||||
|
||||
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.player.*;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
|
||||
/**
|
||||
@@ -17,18 +15,23 @@ import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
public class ArtificialPlayer<T extends TurnBasedGame<T>> extends AbstractPlayer<T> {
|
||||
|
||||
/** The AI instance used to calculate moves. */
|
||||
private final MoveProvider<T> ai;
|
||||
private final AI<T> ai;
|
||||
|
||||
/**
|
||||
* Constructs a new ArtificialPlayer using the specified AI.
|
||||
*
|
||||
* @param ai the AI instance that determines moves for this player
|
||||
*/
|
||||
public ArtificialPlayer(MoveProvider<T> ai, String name) {
|
||||
public ArtificialPlayer(AI<T> ai, String name) {
|
||||
super(name);
|
||||
this.ai = ai;
|
||||
}
|
||||
|
||||
public ArtificialPlayer(ArtificialPlayer<T> other) {
|
||||
super(other);
|
||||
this.ai = other.ai.deepCopy();
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines the next move for this player using its AI.
|
||||
* <p>
|
||||
@@ -41,7 +44,12 @@ public class ArtificialPlayer<T extends TurnBasedGame<T>> extends AbstractPlayer
|
||||
* @return the integer representing the chosen move
|
||||
* @throws ClassCastException if {@code gameCopy} is not of type {@code T}
|
||||
*/
|
||||
public int getMove(T gameCopy) {
|
||||
public long getMove(T gameCopy) {
|
||||
return ai.getMove(gameCopy);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ArtificialPlayer<T> deepCopy() {
|
||||
return new ArtificialPlayer<T>(this);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package org.toop.game.players;
|
||||
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
import org.toop.framework.gameFramework.model.player.AbstractPlayer;
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
@@ -10,18 +11,22 @@ 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<>();
|
||||
|
||||
private CompletableFuture<Integer> LastMove;
|
||||
private CompletableFuture<Long> LastMove;
|
||||
|
||||
public LocalPlayer(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
public LocalPlayer(LocalPlayer<T> other) {
|
||||
super(other);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getMove(T gameCopy) {
|
||||
public long getMove(T gameCopy) {
|
||||
return getValidMove(gameCopy);
|
||||
}
|
||||
|
||||
public void setMove(int move) {
|
||||
public void setMove(long move) {
|
||||
LastMove.complete(move);
|
||||
}
|
||||
|
||||
@@ -31,11 +36,12 @@ public class LocalPlayer<T extends TurnBasedGame<T>> extends AbstractPlayer<T> {
|
||||
return false;
|
||||
}
|
||||
|
||||
private int getMove2(T gameCopy) {
|
||||
private long getMove2(T gameCopy) {
|
||||
LastMove = new CompletableFuture<>();
|
||||
int move = -1;
|
||||
long move = 0;
|
||||
try {
|
||||
move = LastMove.get();
|
||||
System.out.println(Long.toBinaryString(move));
|
||||
} catch (InterruptedException | ExecutionException e) {
|
||||
// TODO: Add proper logging.
|
||||
e.printStackTrace();
|
||||
@@ -43,20 +49,25 @@ public class LocalPlayer<T extends TurnBasedGame<T>> extends AbstractPlayer<T> {
|
||||
return move;
|
||||
}
|
||||
|
||||
protected int getValidMove(T gameCopy){
|
||||
protected long getValidMove(T gameCopy){
|
||||
// Get this player's valid moves
|
||||
int[] validMoves = gameCopy.getLegalMoves();
|
||||
long 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.deepCopy());
|
||||
while (!contains(validMoves, move)) {
|
||||
long move = getMove2(gameCopy.deepCopy());
|
||||
while ((validMoves & move) == 0) {
|
||||
System.out.println("Not a valid move, try again");
|
||||
move = getMove2(gameCopy.deepCopy());
|
||||
}
|
||||
return move;
|
||||
}
|
||||
|
||||
@Override
|
||||
public LocalPlayer<T> deepCopy() {
|
||||
return new LocalPlayer<T>(this.getName());
|
||||
}
|
||||
|
||||
/*public void register() {
|
||||
// Listening to PlayerAttemptedMove
|
||||
new EventFlow().listen(GUIEvents.PlayerAttemptedMove.class, event -> {
|
||||
|
||||
165
game/src/main/java/org/toop/game/players/MiniMaxAI.java
Normal file
165
game/src/main/java/org/toop/game/players/MiniMaxAI.java
Normal file
@@ -0,0 +1,165 @@
|
||||
package org.toop.game.players;
|
||||
|
||||
import org.toop.framework.gameFramework.GameState;
|
||||
import org.toop.framework.gameFramework.model.game.PlayResult;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
import org.toop.framework.gameFramework.model.player.AbstractAI;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
|
||||
public class MiniMaxAI<T extends TurnBasedGame<T>> extends AbstractAI<T> {
|
||||
|
||||
private final int maxDepth;
|
||||
private final Random random = new Random();
|
||||
|
||||
public MiniMaxAI(int depth) {
|
||||
this.maxDepth = depth;
|
||||
}
|
||||
|
||||
public MiniMaxAI(MiniMaxAI<T> other) {
|
||||
this.maxDepth = other.maxDepth;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MiniMaxAI<T> deepCopy() {
|
||||
return new MiniMaxAI<>(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getMove(T game) {
|
||||
long legalMoves = game.getLegalMoves();
|
||||
if (legalMoves == 0) return 0;
|
||||
|
||||
List<Long> bestMoves = new ArrayList<>();
|
||||
int bestScore = Integer.MIN_VALUE;
|
||||
int aiPlayer = game.getCurrentTurn();
|
||||
|
||||
long movesLoop = legalMoves;
|
||||
while (movesLoop != 0) {
|
||||
long move = 1L << Long.numberOfTrailingZeros(movesLoop);
|
||||
T copy = game.deepCopy();
|
||||
PlayResult result = copy.play(move);
|
||||
|
||||
int score;
|
||||
switch (result.state()) {
|
||||
case WIN -> score = (result.player() == aiPlayer ? maxDepth : -maxDepth);
|
||||
case DRAW -> score = 0;
|
||||
default -> score = getMoveScore(copy, maxDepth - 1, false, aiPlayer, Integer.MIN_VALUE, Integer.MAX_VALUE);
|
||||
}
|
||||
|
||||
if (score > bestScore) {
|
||||
bestScore = score;
|
||||
bestMoves.clear();
|
||||
bestMoves.add(move);
|
||||
} else if (score == bestScore) {
|
||||
bestMoves.add(move);
|
||||
}
|
||||
|
||||
movesLoop &= movesLoop - 1;
|
||||
}
|
||||
|
||||
long chosenMove = bestMoves.get(random.nextInt(bestMoves.size()));
|
||||
return chosenMove;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursive minimax with alpha-beta pruning and heuristic evaluation.
|
||||
*
|
||||
* @param game Current game state
|
||||
* @param depth Remaining depth
|
||||
* @param maximizing True if AI is maximizing, false if opponent
|
||||
* @param aiPlayer AI's player index
|
||||
* @param alpha Alpha value
|
||||
* @param beta Beta value
|
||||
* @return score of the position
|
||||
*/
|
||||
private int getMoveScore(T game, int depth, boolean maximizing, int aiPlayer, int alpha, int beta) {
|
||||
long legalMoves = game.getLegalMoves();
|
||||
|
||||
// Terminal state
|
||||
PlayResult lastResult = null;
|
||||
if (legalMoves == 0) {
|
||||
lastResult = new PlayResult(GameState.DRAW, -1);
|
||||
}
|
||||
|
||||
// If the game is over or depth limit reached, evaluate
|
||||
if (depth <= 0 || legalMoves == 0) {
|
||||
if (lastResult != null) return 0;
|
||||
return evaluateBoard(game, aiPlayer);
|
||||
}
|
||||
|
||||
int bestScore = maximizing ? Integer.MIN_VALUE : Integer.MAX_VALUE;
|
||||
long movesLoop = legalMoves;
|
||||
|
||||
while (movesLoop != 0) {
|
||||
long move = 1L << Long.numberOfTrailingZeros(movesLoop);
|
||||
T copy = game.deepCopy();
|
||||
PlayResult result = copy.play(move);
|
||||
|
||||
int score;
|
||||
switch (result.state()) {
|
||||
case WIN -> score = (result.player() == aiPlayer ? depth : -depth);
|
||||
case DRAW -> score = 0;
|
||||
default -> score = getMoveScore(copy, depth - 1, !maximizing, aiPlayer, alpha, beta);
|
||||
}
|
||||
|
||||
if (maximizing) {
|
||||
bestScore = Math.max(bestScore, score);
|
||||
alpha = Math.max(alpha, bestScore);
|
||||
} else {
|
||||
bestScore = Math.min(bestScore, score);
|
||||
beta = Math.min(beta, bestScore);
|
||||
}
|
||||
|
||||
// Alpha-beta pruning
|
||||
if (beta <= alpha) break;
|
||||
|
||||
movesLoop &= movesLoop - 1;
|
||||
}
|
||||
|
||||
return bestScore;
|
||||
}
|
||||
|
||||
/**
|
||||
* Simple heuristic evaluation for Reversi-like games.
|
||||
* Positive = good for AI, Negative = good for opponent.
|
||||
*
|
||||
* @param game Game state
|
||||
* @param aiPlayer AI's player index
|
||||
* @return heuristic score
|
||||
*/
|
||||
private int evaluateBoard(T game, int aiPlayer) {
|
||||
long[] board = game.getBoard();
|
||||
int aiCount = 0;
|
||||
int opponentCount = 0;
|
||||
|
||||
// Count pieces for AI vs opponent
|
||||
for (int i = 0; i < board.length; i++) {
|
||||
long bits = board[i];
|
||||
for (int j = 0; j < 64; j++) {
|
||||
if ((bits & (1L << j)) != 0) {
|
||||
// Assume player 0 occupies even indices, player 1 occupies odd
|
||||
if ((i * 64 + j) % game.getPlayerCount() == aiPlayer) aiCount++;
|
||||
else opponentCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Mobility (number of legal moves)
|
||||
int mobility = Long.bitCount(game.getLegalMoves());
|
||||
|
||||
// Corner control (top-left, top-right, bottom-left, bottom-right)
|
||||
int corners = 0;
|
||||
long[] cornerMasks = {1L << 0, 1L << 7, 1L << 56, 1L << 63};
|
||||
for (long mask : cornerMasks) {
|
||||
for (long b : board) {
|
||||
if ((b & mask) != 0) corners += 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Weighted sum
|
||||
return (aiCount - opponentCount) + 2 * mobility + 5 * corners;
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package org.toop.game.players;
|
||||
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
import org.toop.framework.gameFramework.model.player.AbstractPlayer;
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
|
||||
/**
|
||||
* Represents a player controlled remotely or over a network.
|
||||
@@ -23,4 +24,13 @@ public class OnlinePlayer<T extends TurnBasedGame<T>> extends AbstractPlayer<T>
|
||||
public OnlinePlayer(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
public OnlinePlayer(OnlinePlayer<T> other) {
|
||||
super(other);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Player<T> deepCopy() {
|
||||
return new OnlinePlayer<>(this);
|
||||
}
|
||||
}
|
||||
|
||||
38
game/src/main/java/org/toop/game/players/RandomAI.java
Normal file
38
game/src/main/java/org/toop/game/players/RandomAI.java
Normal file
@@ -0,0 +1,38 @@
|
||||
package org.toop.game.players;
|
||||
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
import org.toop.framework.gameFramework.model.player.AbstractAI;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
|
||||
public class RandomAI<T extends TurnBasedGame<T>> extends AbstractAI<T> {
|
||||
|
||||
public RandomAI() {
|
||||
super();
|
||||
}
|
||||
|
||||
@Override
|
||||
public RandomAI<T> deepCopy() {
|
||||
return new RandomAI<T>();
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getMove(T game) {
|
||||
long legalMoves = game.getLegalMoves();
|
||||
int move = new Random().nextInt(Long.bitCount(legalMoves));
|
||||
return nthBitIndex(legalMoves, move);
|
||||
}
|
||||
|
||||
public static long nthBitIndex(long bb, int n) {
|
||||
while (bb != 0) {
|
||||
int tz = Long.numberOfTrailingZeros(bb);
|
||||
if (n == 0) {
|
||||
return 1L << tz;
|
||||
}
|
||||
bb &= bb - 1; // clear the least significant 1
|
||||
n--;
|
||||
}
|
||||
return 0L; // not enough 1s
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user