mirror of
https://github.com/2OOP/pism.git
synced 2026-02-04 19:04:49 +00:00
Compare commits
19 Commits
03dc6130e2
...
297-Fixing
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e5e79bb9b0 | ||
|
|
a982345791 | ||
|
|
d1176f2151 | ||
|
|
39df1be6ee | ||
|
|
4b80072042 | ||
|
|
e6e931b565 | ||
|
|
e5ad144783 | ||
|
|
550ee5874b | ||
|
|
1ae79daef0 | ||
|
|
cd8eb99559 | ||
|
|
0132981d94 | ||
|
|
322197494c | ||
|
|
a9c99df5d2 | ||
|
|
912d25c01f | ||
|
|
adc7b1a8f3 | ||
|
|
3a8b1c2454 | ||
|
|
846898988f | ||
|
|
ecd0fd26be | ||
|
|
afb4844084 |
80
.github/workflows/checks.yaml
vendored
80
.github/workflows/checks.yaml
vendored
@@ -1,42 +1,42 @@
|
||||
name: Checks
|
||||
#name: Checks
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- 'main'
|
||||
pull_request:
|
||||
branches:
|
||||
- 'main'
|
||||
#on:
|
||||
# push:
|
||||
# branches:
|
||||
# - 'main'
|
||||
# pull_request:
|
||||
# branches:
|
||||
# - 'main'
|
||||
#
|
||||
#jobs:
|
||||
# formatting-check:
|
||||
# name: Follow Google Formatting Guidelines
|
||||
# runs-on: ubuntu-latest
|
||||
# steps:
|
||||
# - uses: actions/checkout@v5
|
||||
# with:
|
||||
# fetch-depth: 0 # Fix for incremental formatting
|
||||
# - uses: actions/setup-java@v5
|
||||
# with:
|
||||
# java-version: '25'
|
||||
# distribution: 'temurin'
|
||||
# cache: maven
|
||||
# - name: Run Format Check
|
||||
# run: mvn spotless:check
|
||||
|
||||
jobs:
|
||||
formatting-check:
|
||||
name: Follow Google Formatting Guidelines
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0 # Fix for incremental formatting
|
||||
- uses: actions/setup-java@v5
|
||||
with:
|
||||
java-version: '25'
|
||||
distribution: 'temurin'
|
||||
cache: maven
|
||||
- name: Run Format Check
|
||||
run: mvn spotless:check
|
||||
|
||||
tests:
|
||||
name: Unittests
|
||||
runs-on: ${{ matrix.os }}
|
||||
needs: formatting-check
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-latest] #windows-latest, macos-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/setup-java@v5
|
||||
with:
|
||||
java-version: '25'
|
||||
distribution: 'temurin'
|
||||
cache: maven
|
||||
- name: Run Unittests
|
||||
run: mvn -B test
|
||||
# tests:
|
||||
# name: Unittests
|
||||
# runs-on: ${{ matrix.os }}
|
||||
# needs: formatting-check
|
||||
# strategy:
|
||||
# matrix:
|
||||
# os: [ubuntu-latest] #windows-latest, macos-latest
|
||||
# steps:
|
||||
# - uses: actions/checkout@v5
|
||||
# - uses: actions/setup-java@v5
|
||||
# with:
|
||||
# java-version: '25'
|
||||
# distribution: 'temurin'
|
||||
# cache: maven
|
||||
# - name: Run Unittests
|
||||
# run: mvn -B test
|
||||
|
||||
@@ -2,6 +2,7 @@ package org.toop.app;
|
||||
|
||||
import javafx.application.Platform;
|
||||
import javafx.scene.input.KeyCode;
|
||||
import javafx.scene.input.KeyCodeCombination;
|
||||
import javafx.scene.input.KeyEvent;
|
||||
|
||||
import org.toop.app.widget.Primitive;
|
||||
@@ -67,8 +68,8 @@ public final class App extends Application {
|
||||
|
||||
scene.getRoot();
|
||||
|
||||
stage.setMinWidth(1080);
|
||||
stage.setMinHeight(720);
|
||||
stage.setMinWidth(1200);
|
||||
stage.setMinHeight(800);
|
||||
stage.setOnCloseRequest(event -> {
|
||||
event.consume();
|
||||
quit();
|
||||
@@ -110,20 +111,19 @@ public final class App extends Application {
|
||||
Platform.runLater(() -> stage.setOpacity(1.0));
|
||||
}
|
||||
|
||||
Platform.runLater(() -> loading.setMaxAmount(e.isLoadingAmount()));
|
||||
|
||||
Platform.runLater(() -> {
|
||||
loading.setMaxAmount(e.isLoadingAmount());
|
||||
try {
|
||||
loading.setAmount(e.hasLoadedAmount());
|
||||
} catch (Exception ex) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
});
|
||||
|
||||
if (e.hasLoadedAmount() >= e.isLoadingAmount()) {
|
||||
if (e.hasLoadedAmount() >= e.isLoadingAmount()-1) {
|
||||
Platform.runLater(loading::triggerSuccess);
|
||||
loadingFlow.unsubscribe("init_loading");
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
}, false, "init_loading");
|
||||
|
||||
@@ -146,6 +146,11 @@ public final class App extends Application {
|
||||
escapePopup();
|
||||
}
|
||||
});
|
||||
stage.setFullScreenExitKeyCombination(
|
||||
new KeyCodeCombination(
|
||||
KeyCode.F11
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
public void escapePopup() {
|
||||
|
||||
@@ -2,9 +2,7 @@ package org.toop.app;
|
||||
|
||||
import javafx.application.Platform;
|
||||
import javafx.geometry.Pos;
|
||||
import org.toop.app.gameControllers.AbstractGameController;
|
||||
import org.toop.app.gameControllers.ReversiController;
|
||||
import org.toop.app.gameControllers.TicTacToeController;
|
||||
import org.toop.app.gameControllers.*;
|
||||
import org.toop.app.widget.Primitive;
|
||||
import org.toop.app.widget.WidgetContainer;
|
||||
import org.toop.app.widget.complex.LoadingWidget;
|
||||
@@ -13,16 +11,17 @@ import org.toop.app.widget.popup.ErrorPopup;
|
||||
import org.toop.app.widget.popup.SendChallengePopup;
|
||||
import org.toop.app.widget.view.ServerView;
|
||||
import org.toop.framework.eventbus.EventFlow;
|
||||
import org.toop.framework.gameFramework.controller.GameController;
|
||||
import org.toop.framework.eventbus.GlobalEventBus;
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
import org.toop.framework.networking.clients.TournamentNetworkingClient;
|
||||
import org.toop.framework.networking.events.NetworkEvents;
|
||||
import org.toop.framework.networking.types.NetworkingConnector;
|
||||
import org.toop.game.games.reversi.BitboardReversi;
|
||||
import org.toop.game.games.tictactoe.BitboardTicTacToe;
|
||||
import org.toop.game.players.ArtificialPlayer;
|
||||
import org.toop.game.players.OnlinePlayer;
|
||||
import org.toop.game.games.reversi.ReversiAIR;
|
||||
import org.toop.game.games.reversi.ReversiR;
|
||||
import org.toop.game.games.tictactoe.TicTacToeAIR;
|
||||
import org.toop.game.players.ai.RandomAI;
|
||||
import org.toop.local.AppContext;
|
||||
|
||||
import java.util.List;
|
||||
@@ -33,6 +32,7 @@ import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
public final class Server {
|
||||
// TODO: Keep track of listeners. Remove them on Server connection close so reference is deleted.
|
||||
private String user = "";
|
||||
private long clientId = -1;
|
||||
|
||||
@@ -42,7 +42,7 @@ public final class Server {
|
||||
private ServerView primary;
|
||||
private boolean isPolling = true;
|
||||
|
||||
private AbstractGameController<?> gameController;
|
||||
private GameController gameController;
|
||||
|
||||
private final AtomicBoolean isSingleGame = new AtomicBoolean(false);
|
||||
|
||||
@@ -201,26 +201,31 @@ public final class Server {
|
||||
information.players[0].computerThinkTime = 1;
|
||||
information.players[1].name = response.opponent();
|
||||
|
||||
Player[] players = new Player[2];
|
||||
|
||||
players[(myTurn + 1) % 2] = new OnlinePlayer<ReversiR>(response.opponent());
|
||||
|
||||
switch (type){
|
||||
/*switch (type){
|
||||
case TICTACTOE ->{
|
||||
players[myTurn] = new ArtificialPlayer<>(new TicTacToeAIR(9), user);
|
||||
}
|
||||
case REVERSI ->{
|
||||
players[myTurn] = new ArtificialPlayer<>(new ReversiAIR(), user);
|
||||
}
|
||||
}
|
||||
}*/
|
||||
|
||||
|
||||
|
||||
switch (type) {
|
||||
case TICTACTOE ->{
|
||||
gameController = new TicTacToeController(players, false);
|
||||
Player<BitboardTicTacToe>[] players = new Player[2];
|
||||
players[(myTurn + 1) % 2] = new OnlinePlayer<>(response.opponent());
|
||||
players[myTurn] = new ArtificialPlayer<>(new RandomAI<BitboardTicTacToe>(), user);
|
||||
gameController = new TicTacToeBitController(players);
|
||||
}
|
||||
case REVERSI ->
|
||||
gameController = new ReversiController(players, false);
|
||||
case REVERSI -> {
|
||||
Player<BitboardReversi>[] players = new Player[2];
|
||||
players[(myTurn + 1) % 2] = new OnlinePlayer<>(response.opponent());
|
||||
players[myTurn] = new ArtificialPlayer<>(new RandomAI<BitboardReversi>(), user);
|
||||
gameController = new ReversiBitController(players, false);}
|
||||
default -> new ErrorPopup("Unsupported game type.");
|
||||
|
||||
}
|
||||
|
||||
if (gameController != null){
|
||||
|
||||
248
app/src/main/java/org/toop/app/canvas/BitGameCanvas.java
Normal file
248
app/src/main/java/org/toop/app/canvas/BitGameCanvas.java
Normal file
@@ -0,0 +1,248 @@
|
||||
package org.toop.app.canvas;
|
||||
|
||||
import javafx.animation.KeyFrame;
|
||||
import javafx.animation.Timeline;
|
||||
import javafx.scene.canvas.Canvas;
|
||||
import javafx.scene.canvas.GraphicsContext;
|
||||
import javafx.scene.input.MouseButton;
|
||||
import javafx.scene.paint.Color;
|
||||
import javafx.scene.text.Font;
|
||||
import javafx.util.Duration;
|
||||
import org.toop.framework.eventbus.EventFlow;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
import org.toop.framework.gameFramework.view.GUIEvents;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public abstract class BitGameCanvas<T extends TurnBasedGame<T>> implements GameCanvas<T> {
|
||||
protected record Cell(float x, float y, float width, float height) {
|
||||
public boolean isInside(double x, double y) {
|
||||
return x >= this.x && x <= this.x + width &&
|
||||
y >= this.y && y <= this.y + height;
|
||||
}
|
||||
}
|
||||
|
||||
protected final Canvas canvas;
|
||||
protected final GraphicsContext graphics;
|
||||
|
||||
protected final Color color;
|
||||
protected final Color backgroundColor;
|
||||
|
||||
protected final int width;
|
||||
protected final int height;
|
||||
|
||||
protected final int rowSize;
|
||||
protected final int columnSize;
|
||||
|
||||
protected final int gapSize;
|
||||
protected final boolean edges;
|
||||
|
||||
protected final Cell[] cells;
|
||||
|
||||
private Consumer<Long> onCellCLicked;
|
||||
|
||||
public void setOnCellClicked(Consumer<Long> onClick) {
|
||||
this.onCellCLicked = onClick;
|
||||
}
|
||||
|
||||
protected BitGameCanvas(Color color, Color backgroundColor, int width, int height, int rowSize, int columnSize, int gapSize, boolean edges) {
|
||||
canvas = new Canvas(width, height);
|
||||
graphics = canvas.getGraphicsContext2D();
|
||||
|
||||
this.onCellCLicked = (c) -> new EventFlow().addPostEvent(GUIEvents.PlayerAttemptedMove.class, c).postEvent();
|
||||
|
||||
this.color = color;
|
||||
this.backgroundColor = backgroundColor;
|
||||
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
|
||||
this.rowSize = rowSize;
|
||||
this.columnSize = columnSize;
|
||||
|
||||
this.gapSize = gapSize;
|
||||
this.edges = edges;
|
||||
|
||||
cells = new Cell[rowSize * columnSize];
|
||||
|
||||
final float cellWidth = ((float) width - gapSize * rowSize - gapSize) / rowSize;
|
||||
final float cellHeight = ((float) height - gapSize * columnSize - gapSize) / columnSize;
|
||||
|
||||
for (int y = 0; y < columnSize; y++) {
|
||||
final float startY = y * cellHeight + y * gapSize + gapSize;
|
||||
|
||||
for (int x = 0; x < rowSize; x++) {
|
||||
final float startX = x * cellWidth + x * gapSize + gapSize;
|
||||
cells[x + y * rowSize] = new Cell(startX, startY, cellWidth, cellHeight);
|
||||
}
|
||||
}
|
||||
|
||||
canvas.setOnMouseClicked(event -> {
|
||||
if (event.getButton() != MouseButton.PRIMARY) {
|
||||
return;
|
||||
}
|
||||
|
||||
final int column = (int) ((event.getX() / this.width) * rowSize);
|
||||
final int row = (int) ((event.getY() / this.height) * columnSize);
|
||||
|
||||
final Cell cell = cells[column + row * rowSize];
|
||||
|
||||
if (cell.isInside(event.getX(), event.getY())) {
|
||||
event.consume();
|
||||
this.onCellCLicked.accept(1L << (column + row * rowSize));
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
render();
|
||||
}
|
||||
|
||||
public void loopOverBoard(long bb, Consumer<Integer> onCell){
|
||||
while (bb != 0) {
|
||||
int idx = Long.numberOfTrailingZeros(bb); // index of least-significant 1-bit
|
||||
onCell.accept(idx);
|
||||
|
||||
bb &= bb - 1; // clear LSB 1-bit
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void render() {
|
||||
graphics.setFill(backgroundColor);
|
||||
graphics.fillRect(0, 0, width, height);
|
||||
|
||||
graphics.setFill(color);
|
||||
|
||||
for (int x = 0; x < rowSize - 1; x++) {
|
||||
final float start = cells[x].x + cells[x].width;
|
||||
graphics.fillRect(start, gapSize, gapSize, height - gapSize * 2);
|
||||
}
|
||||
|
||||
for (int y = 0; y < columnSize - 1; y++) {
|
||||
final float start = cells[y * rowSize].y + cells[y * rowSize].height;
|
||||
graphics.fillRect(gapSize, start, width - gapSize * 2, gapSize);
|
||||
}
|
||||
|
||||
if (edges) {
|
||||
graphics.fillRect(0, 0, width, gapSize);
|
||||
graphics.fillRect(0, 0, gapSize, height);
|
||||
|
||||
graphics.fillRect(width - gapSize, 0, gapSize, height);
|
||||
graphics.fillRect(0, height - gapSize, width, gapSize);
|
||||
}
|
||||
}
|
||||
|
||||
public void fill(Color color, int cell) {
|
||||
final float x = cells[cell].x();
|
||||
final float y = cells[cell].y();
|
||||
|
||||
final float width = cells[cell].width();
|
||||
final float height = cells[cell].height();
|
||||
|
||||
graphics.setFill(color);
|
||||
graphics.fillRect(x, y, width, height);
|
||||
}
|
||||
|
||||
public void clear(int cell) {
|
||||
final float x = cells[cell].x();
|
||||
final float y = cells[cell].y();
|
||||
|
||||
final float width = cells[cell].width();
|
||||
final float height = cells[cell].height();
|
||||
|
||||
graphics.clearRect(x, y, width, height);
|
||||
|
||||
graphics.setFill(backgroundColor);
|
||||
graphics.fillRect(x, y, width, height);
|
||||
}
|
||||
|
||||
public void clearAll() {
|
||||
for (int i = 0; i < cells.length; i++) {
|
||||
clear(i);
|
||||
}
|
||||
}
|
||||
|
||||
public void drawPlayerMove(int player, int move) {
|
||||
final float x = cells[move].x() + gapSize;
|
||||
final float y = cells[move].y() + gapSize;
|
||||
|
||||
final float width = cells[move].width() - gapSize * 2;
|
||||
final float height = cells[move].height() - gapSize * 2;
|
||||
|
||||
graphics.setFill(color);
|
||||
graphics.setFont(Font.font("Arial", 40)); // TODO different font and size
|
||||
graphics.fillText(String.valueOf(player), x + width, y + height);
|
||||
}
|
||||
|
||||
public void drawDot(Color color, int cell) {
|
||||
final float x = cells[cell].x() + gapSize;
|
||||
final float y = cells[cell].y() + gapSize;
|
||||
|
||||
final float width = cells[cell].width() - gapSize * 2;
|
||||
final float height = cells[cell].height() - gapSize * 2;
|
||||
|
||||
graphics.setFill(color);
|
||||
graphics.fillOval(x, y, width, height);
|
||||
}
|
||||
|
||||
public void drawInnerDot(Color color, int cell, boolean slightlyBigger) {
|
||||
final float x = cells[cell].x() + gapSize;
|
||||
final float y = cells[cell].y() + gapSize;
|
||||
|
||||
float multiplier = slightlyBigger?1.4f:1.5f;
|
||||
|
||||
final float width = (cells[cell].width() - gapSize * 2)/multiplier;
|
||||
final float height = (cells[cell].height() - gapSize * 2)/multiplier;
|
||||
|
||||
float offset = slightlyBigger?5f:4f;
|
||||
|
||||
graphics.setFill(color);
|
||||
graphics.fillOval(x + width/offset, y + height/offset, width, height);
|
||||
}
|
||||
|
||||
private void drawDotScaled(Color color, int cell, double scale) {
|
||||
final float cx = cells[cell].x() + gapSize;
|
||||
final float cy = cells[cell].y() + gapSize;
|
||||
|
||||
final float fullWidth = cells[cell].width() - gapSize * 2;
|
||||
final float height = cells[cell].height() - gapSize * 2;
|
||||
|
||||
final float scaledWidth = (float)(fullWidth * scale);
|
||||
final float offsetX = (fullWidth - scaledWidth) / 2;
|
||||
|
||||
graphics.setFill(color);
|
||||
graphics.fillOval(cx + offsetX, cy, scaledWidth, height);
|
||||
}
|
||||
|
||||
public Timeline flipDot(Color fromColor, Color toColor, int cell) {
|
||||
final int steps = 60;
|
||||
final long duration = 250;
|
||||
final double interval = duration / (double) steps;
|
||||
|
||||
final Timeline timeline = new Timeline();
|
||||
|
||||
for (int i = 0; i <= steps; i++) {
|
||||
final double t = i / (double) steps;
|
||||
final KeyFrame keyFrame = new KeyFrame(Duration.millis(i * interval),
|
||||
_ -> {
|
||||
clear(cell);
|
||||
|
||||
final double scale = t <= 0.5 ? 1 - 2 * t : 2 * t - 1;
|
||||
final Color currentColor = t < 0.5 ? fromColor : toColor;
|
||||
|
||||
drawDotScaled(currentColor, cell, scale);
|
||||
}
|
||||
);
|
||||
|
||||
timeline.getKeyFrames().add(keyFrame);
|
||||
}
|
||||
|
||||
return timeline;
|
||||
}
|
||||
|
||||
public Canvas getCanvas() {
|
||||
return canvas;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package org.toop.app.canvas;
|
||||
|
||||
public interface BitLegalMoveDrawer {
|
||||
void showLegalMove(long move, int currentPlayerIndex);
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package org.toop.app.canvas;
|
||||
|
||||
import javafx.scene.paint.Color;
|
||||
import org.toop.framework.gameFramework.model.game.AbstractGame;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class Connect4Canvas extends GameCanvas {
|
||||
public Connect4Canvas(Color color, int width, int height, Consumer<Integer> onCellClicked) {
|
||||
super(color, Color.TRANSPARENT, width, height, 7, 6, 10, true, onCellClicked,null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void drawPlayerHover(int player, int move, AbstractGame game) {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
package org.toop.app.canvas;
|
||||
|
||||
import org.toop.framework.gameFramework.model.game.AbstractGame;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
|
||||
public interface DrawPlayerHover {
|
||||
void drawPlayerHover(int player, int move, AbstractGame game);
|
||||
void drawPlayerHover(int player, int move, TurnBasedGame game);
|
||||
}
|
||||
|
||||
@@ -1,237 +1,8 @@
|
||||
package org.toop.app.canvas;
|
||||
|
||||
import javafx.animation.KeyFrame;
|
||||
import javafx.animation.Timeline;
|
||||
import javafx.scene.canvas.Canvas;
|
||||
import javafx.scene.canvas.GraphicsContext;
|
||||
import javafx.scene.input.MouseButton;
|
||||
import javafx.scene.paint.Color;
|
||||
import javafx.scene.text.Font;
|
||||
import javafx.util.Duration;
|
||||
import org.toop.framework.gameFramework.model.game.AbstractGame;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public abstract class GameCanvas<T extends AbstractGame> implements DrawPlayerMove, DrawPlayerHover {
|
||||
protected record Cell(float x, float y, float width, float height) {
|
||||
public boolean isInside(double x, double y) {
|
||||
return x >= this.x && x <= this.x + width &&
|
||||
y >= this.y && y <= this.y + height;
|
||||
}
|
||||
}
|
||||
|
||||
protected final Canvas canvas;
|
||||
protected final GraphicsContext graphics;
|
||||
|
||||
protected final Color color;
|
||||
protected final Color backgroundColor;
|
||||
|
||||
protected final int width;
|
||||
protected final int height;
|
||||
|
||||
protected final int rowSize;
|
||||
protected final int columnSize;
|
||||
|
||||
protected final int gapSize;
|
||||
protected final boolean edges;
|
||||
|
||||
protected final Cell[] cells;
|
||||
|
||||
private Consumer<Integer> onCellCLicked;
|
||||
|
||||
public void setOnCellClicked(Consumer<Integer> onClick) {
|
||||
this.onCellCLicked = onClick;
|
||||
}
|
||||
|
||||
protected GameCanvas(Color color, Color backgroundColor, int width, int height, int rowSize, int columnSize, int gapSize, boolean edges, Consumer<Integer> onCellClicked, Consumer<Integer> newCellEntered) {
|
||||
canvas = new Canvas(width, height);
|
||||
graphics = canvas.getGraphicsContext2D();
|
||||
|
||||
this.onCellCLicked = onCellClicked;
|
||||
|
||||
this.color = color;
|
||||
this.backgroundColor = backgroundColor;
|
||||
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
|
||||
this.rowSize = rowSize;
|
||||
this.columnSize = columnSize;
|
||||
|
||||
this.gapSize = gapSize;
|
||||
this.edges = edges;
|
||||
|
||||
cells = new Cell[rowSize * columnSize];
|
||||
|
||||
final float cellWidth = ((float) width - gapSize * rowSize - gapSize) / rowSize;
|
||||
final float cellHeight = ((float) height - gapSize * columnSize - gapSize) / columnSize;
|
||||
|
||||
for (int y = 0; y < columnSize; y++) {
|
||||
final float startY = y * cellHeight + y * gapSize + gapSize;
|
||||
|
||||
for (int x = 0; x < rowSize; x++) {
|
||||
final float startX = x * cellWidth + x * gapSize + gapSize;
|
||||
cells[x + y * rowSize] = new Cell(startX, startY, cellWidth, cellHeight);
|
||||
}
|
||||
}
|
||||
|
||||
canvas.setOnMouseClicked(event -> {
|
||||
if (event.getButton() != MouseButton.PRIMARY) {
|
||||
return;
|
||||
}
|
||||
|
||||
final int column = (int) ((event.getX() / this.width) * rowSize);
|
||||
final int row = (int) ((event.getY() / this.height) * columnSize);
|
||||
|
||||
final Cell cell = cells[column + row * rowSize];
|
||||
|
||||
if (cell.isInside(event.getX(), event.getY())) {
|
||||
event.consume();
|
||||
this.onCellCLicked.accept(column + row * rowSize);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
render();
|
||||
}
|
||||
|
||||
private void render() {
|
||||
graphics.setFill(backgroundColor);
|
||||
graphics.fillRect(0, 0, width, height);
|
||||
|
||||
graphics.setFill(color);
|
||||
|
||||
for (int x = 0; x < rowSize - 1; x++) {
|
||||
final float start = cells[x].x + cells[x].width;
|
||||
graphics.fillRect(start, gapSize, gapSize, height - gapSize * 2);
|
||||
}
|
||||
|
||||
for (int y = 0; y < columnSize - 1; y++) {
|
||||
final float start = cells[y * rowSize].y + cells[y * rowSize].height;
|
||||
graphics.fillRect(gapSize, start, width - gapSize * 2, gapSize);
|
||||
}
|
||||
|
||||
if (edges) {
|
||||
graphics.fillRect(0, 0, width, gapSize);
|
||||
graphics.fillRect(0, 0, gapSize, height);
|
||||
|
||||
graphics.fillRect(width - gapSize, 0, gapSize, height);
|
||||
graphics.fillRect(0, height - gapSize, width, gapSize);
|
||||
}
|
||||
}
|
||||
|
||||
public void fill(Color color, int cell) {
|
||||
final float x = cells[cell].x();
|
||||
final float y = cells[cell].y();
|
||||
|
||||
final float width = cells[cell].width();
|
||||
final float height = cells[cell].height();
|
||||
|
||||
graphics.setFill(color);
|
||||
graphics.fillRect(x, y, width, height);
|
||||
}
|
||||
|
||||
public void clear(int cell) {
|
||||
final float x = cells[cell].x();
|
||||
final float y = cells[cell].y();
|
||||
|
||||
final float width = cells[cell].width();
|
||||
final float height = cells[cell].height();
|
||||
|
||||
graphics.clearRect(x, y, width, height);
|
||||
|
||||
graphics.setFill(backgroundColor);
|
||||
graphics.fillRect(x, y, width, height);
|
||||
}
|
||||
|
||||
public void clearAll() {
|
||||
for (int i = 0; i < cells.length; i++) {
|
||||
clear(i);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void drawPlayerMove(int player, int move) {
|
||||
final float x = cells[move].x() + gapSize;
|
||||
final float y = cells[move].y() + gapSize;
|
||||
|
||||
final float width = cells[move].width() - gapSize * 2;
|
||||
final float height = cells[move].height() - gapSize * 2;
|
||||
|
||||
graphics.setFill(color);
|
||||
graphics.setFont(Font.font("Arial", 40)); // TODO different font and size
|
||||
graphics.fillText(String.valueOf(player), x + width, y + height);
|
||||
}
|
||||
|
||||
public void drawDot(Color color, int cell) {
|
||||
final float x = cells[cell].x() + gapSize;
|
||||
final float y = cells[cell].y() + gapSize;
|
||||
|
||||
final float width = cells[cell].width() - gapSize * 2;
|
||||
final float height = cells[cell].height() - gapSize * 2;
|
||||
|
||||
graphics.setFill(color);
|
||||
graphics.fillOval(x, y, width, height);
|
||||
}
|
||||
|
||||
public void drawInnerDot(Color color, int cell, boolean slightlyBigger) {
|
||||
final float x = cells[cell].x() + gapSize;
|
||||
final float y = cells[cell].y() + gapSize;
|
||||
|
||||
float multiplier = slightlyBigger?1.4f:1.5f;
|
||||
|
||||
final float width = (cells[cell].width() - gapSize * 2)/multiplier;
|
||||
final float height = (cells[cell].height() - gapSize * 2)/multiplier;
|
||||
|
||||
float offset = slightlyBigger?5f:4f;
|
||||
|
||||
graphics.setFill(color);
|
||||
graphics.fillOval(x + width/offset, y + height/offset, width, height);
|
||||
}
|
||||
|
||||
private void drawDotScaled(Color color, int cell, double scale) {
|
||||
final float cx = cells[cell].x() + gapSize;
|
||||
final float cy = cells[cell].y() + gapSize;
|
||||
|
||||
final float fullWidth = cells[cell].width() - gapSize * 2;
|
||||
final float height = cells[cell].height() - gapSize * 2;
|
||||
|
||||
final float scaledWidth = (float)(fullWidth * scale);
|
||||
final float offsetX = (fullWidth - scaledWidth) / 2;
|
||||
|
||||
graphics.setFill(color);
|
||||
graphics.fillOval(cx + offsetX, cy, scaledWidth, height);
|
||||
}
|
||||
|
||||
public Timeline flipDot(Color fromColor, Color toColor, int cell) {
|
||||
final int steps = 60;
|
||||
final long duration = 250;
|
||||
final double interval = duration / (double) steps;
|
||||
|
||||
final Timeline timeline = new Timeline();
|
||||
|
||||
for (int i = 0; i <= steps; i++) {
|
||||
final double t = i / (double) steps;
|
||||
final KeyFrame keyFrame = new KeyFrame(Duration.millis(i * interval),
|
||||
_ -> {
|
||||
clear(cell);
|
||||
|
||||
final double scale = t <= 0.5 ? 1 - 2 * t : 2 * t - 1;
|
||||
final Color currentColor = t < 0.5 ? fromColor : toColor;
|
||||
|
||||
drawDotScaled(currentColor, cell, scale);
|
||||
}
|
||||
);
|
||||
|
||||
timeline.getKeyFrames().add(keyFrame);
|
||||
}
|
||||
|
||||
return timeline;
|
||||
}
|
||||
|
||||
public Canvas getCanvas() {
|
||||
return canvas;
|
||||
}
|
||||
public interface GameCanvas<T extends TurnBasedGame<T>> extends GameDrawer<T>{
|
||||
Canvas getCanvas();
|
||||
}
|
||||
7
app/src/main/java/org/toop/app/canvas/GameDrawer.java
Normal file
7
app/src/main/java/org/toop/app/canvas/GameDrawer.java
Normal file
@@ -0,0 +1,7 @@
|
||||
package org.toop.app.canvas;
|
||||
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
|
||||
public interface GameDrawer<T extends TurnBasedGame<T>> {
|
||||
void redraw(T gameCopy);
|
||||
}
|
||||
77
app/src/main/java/org/toop/app/canvas/ReversiBitCanvas.java
Normal file
77
app/src/main/java/org/toop/app/canvas/ReversiBitCanvas.java
Normal file
@@ -0,0 +1,77 @@
|
||||
package org.toop.app.canvas;
|
||||
|
||||
import javafx.scene.paint.Color;
|
||||
import org.toop.app.App;
|
||||
import org.toop.game.games.reversi.BitboardReversi;
|
||||
|
||||
public class ReversiBitCanvas extends BitGameCanvas<BitboardReversi> implements BitLegalMoveDrawer {
|
||||
|
||||
private final boolean switchColors;
|
||||
private final boolean local;
|
||||
|
||||
public ReversiBitCanvas(boolean switchColors, boolean local) {
|
||||
super(Color.GRAY, new Color(0f, 0.4f, 0.2f, 1f), (App.getHeight() / 4) * 3, (App.getHeight() / 4) * 3, 8, 8, 5, true);
|
||||
this.switchColors = switchColors;
|
||||
this.local = local;
|
||||
canvas.setOnMouseMoved(event -> {
|
||||
double mouseX = event.getX();
|
||||
double mouseY = event.getY();
|
||||
int cellId = -1;
|
||||
|
||||
BitGameCanvas.Cell hovered = null;
|
||||
for (BitGameCanvas.Cell cell : cells) {
|
||||
if (cell.isInside(mouseX, mouseY)) {
|
||||
hovered = cell;
|
||||
cellId = turnCoordsIntoCellId(mouseX, mouseY);
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private int turnCoordsIntoCellId(double x, double y) {
|
||||
final int column = (int) ((x / this.width) * rowSize);
|
||||
final int row = (int) ((y / this.height) * columnSize);
|
||||
return column + row * rowSize;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void redraw(BitboardReversi gameCopy) {
|
||||
clearAll();
|
||||
long[] board = gameCopy.getBoard();
|
||||
if (switchColors && local) {
|
||||
loopOverBoard(board[0], (i) -> drawDot(Color.BLACK, i));
|
||||
loopOverBoard(board[1], (i) -> drawDot(Color.WHITE, i));
|
||||
} else {
|
||||
loopOverBoard(board[0], (i) -> drawDot(Color.WHITE, i));
|
||||
loopOverBoard(board[1], (i) -> drawDot(Color.BLACK, i));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void showLegalMove(long move, int currentPlayerIndex) {
|
||||
int idx = Long.numberOfTrailingZeros(move);
|
||||
drawLegalMove(idx, currentPlayerIndex);
|
||||
}
|
||||
|
||||
public void drawLegalMove(int cell, int player) {
|
||||
Color innerColor;
|
||||
if (switchColors) {
|
||||
if (player == 0) {
|
||||
innerColor = new Color(0.0f, 0.0f, 0.0f, 0.6f);
|
||||
}
|
||||
else {
|
||||
innerColor = new Color(1.0f, 1.0f, 1.0f, 0.75f);
|
||||
}
|
||||
this.drawInnerDot(innerColor, cell, false);
|
||||
} else {
|
||||
if (player == 1) {
|
||||
innerColor = new Color(0.0f, 0.0f, 0.0f, 0.6f);
|
||||
}
|
||||
else {
|
||||
innerColor = new Color(1.0f, 1.0f, 1.0f, 0.75f);
|
||||
}
|
||||
this.drawInnerDot(innerColor, cell, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
package org.toop.app.canvas;
|
||||
|
||||
import javafx.scene.paint.Color;
|
||||
import org.toop.framework.gameFramework.model.game.AbstractGame;
|
||||
import org.toop.game.Move;
|
||||
import org.toop.game.games.reversi.ReversiR;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public final class ReversiCanvas extends GameCanvas<ReversiR> {
|
||||
private Move[] currentlyHighlightedMoves = null;
|
||||
public ReversiCanvas(Color color, int width, int height, Consumer<Integer> onCellClicked, Consumer<Integer> newCellEntered) {
|
||||
super(color, new Color(0f,0.4f,0.2f,1f), width, height, 8, 8, 5, true, onCellClicked, newCellEntered);
|
||||
drawStartingDots();
|
||||
|
||||
final AtomicReference<Cell> lastHoveredCell = new AtomicReference<>(null);
|
||||
|
||||
canvas.setOnMouseMoved(event -> {
|
||||
double mouseX = event.getX();
|
||||
double mouseY = event.getY();
|
||||
int cellId = -1;
|
||||
|
||||
Cell hovered = null;
|
||||
for (Cell cell : cells) {
|
||||
if (cell.isInside(mouseX, mouseY)) {
|
||||
hovered = cell;
|
||||
cellId = turnCoordsIntoCellId(mouseX, mouseY);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Cell previous = lastHoveredCell.get();
|
||||
|
||||
if (hovered != previous) {
|
||||
lastHoveredCell.set(hovered);
|
||||
newCellEntered.accept(cellId);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void setCurrentlyHighlightedMovesNull() {
|
||||
currentlyHighlightedMoves = null;
|
||||
}
|
||||
|
||||
public void drawHighlightDots(Move[] moves){
|
||||
if (currentlyHighlightedMoves != null){
|
||||
for (final Move move : currentlyHighlightedMoves){
|
||||
Color color = move.value() == 'W'? Color.BLACK: Color.WHITE;
|
||||
drawInnerDot(color, move.position(), true);
|
||||
}
|
||||
}
|
||||
currentlyHighlightedMoves = moves;
|
||||
if (moves != null) {
|
||||
for (Move move : moves) {
|
||||
Color color = move.value() == 'B' ? Color.BLACK : Color.WHITE;
|
||||
drawInnerDot(color, move.position(), false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private int turnCoordsIntoCellId(double x, double y) {
|
||||
final int column = (int) ((x / this.width) * rowSize);
|
||||
final int row = (int) ((y / this.height) * columnSize);
|
||||
return column + row * rowSize;
|
||||
}
|
||||
|
||||
public void drawStartingDots() {
|
||||
drawDot(Color.BLACK, 28);
|
||||
drawDot(Color.WHITE, 36);
|
||||
drawDot(Color.BLACK, 35);
|
||||
drawDot(Color.WHITE, 27);
|
||||
}
|
||||
|
||||
public void drawLegalPosition(int cell, char player) {
|
||||
|
||||
Color innerColor;
|
||||
if (player == 'B') {
|
||||
innerColor = new Color(0.0f, 0.0f, 0.0f, 0.6f);
|
||||
}
|
||||
else {
|
||||
innerColor = new Color(1.0f, 1.0f, 1.0f, 0.75f);
|
||||
}
|
||||
drawInnerDot(innerColor, cell,false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void drawPlayerMove(int player ,int move){
|
||||
super.drawPlayerMove(player, move);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void drawPlayerHover(int player, int move, AbstractGame game) {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package org.toop.app.canvas;
|
||||
|
||||
import javafx.scene.paint.Color;
|
||||
import org.toop.app.App;
|
||||
import org.toop.game.games.tictactoe.BitboardTicTacToe;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class TicTacToeBitCanvas extends BitGameCanvas<BitboardTicTacToe>{
|
||||
public TicTacToeBitCanvas() {
|
||||
super(
|
||||
Color.GRAY,
|
||||
Color.TRANSPARENT,
|
||||
(App.getHeight() / 4) * 3,
|
||||
(App.getHeight() / 4) * 3,
|
||||
3,
|
||||
3,
|
||||
30,
|
||||
false
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void redraw(BitboardTicTacToe gameCopy) {
|
||||
clearAll();
|
||||
drawMoves(gameCopy.getBoard());
|
||||
}
|
||||
|
||||
private void drawMoves(long[] gameBoard){
|
||||
loopOverBoard(gameBoard[0], (i) -> drawX(Color.RED, i));
|
||||
loopOverBoard(gameBoard[1], (i) -> drawO(Color.BLUE, i));
|
||||
}
|
||||
|
||||
|
||||
public void drawX(Color color, int cell) {
|
||||
graphics.setStroke(color);
|
||||
graphics.setLineWidth(gapSize);
|
||||
|
||||
final float x = cells[cell].x() + gapSize;
|
||||
final float y = cells[cell].y() + gapSize;
|
||||
|
||||
final float width = cells[cell].width() - gapSize * 2;
|
||||
final float height = cells[cell].height() - gapSize * 2;
|
||||
|
||||
graphics.strokeLine(x, y, x + width, y + height);
|
||||
graphics.strokeLine(x + width, y, x, y + height);
|
||||
}
|
||||
|
||||
public void drawO(Color color, int cell) {
|
||||
graphics.setStroke(color);
|
||||
graphics.setLineWidth(gapSize);
|
||||
|
||||
final float x = cells[cell].x() + gapSize;
|
||||
final float y = cells[cell].y() + gapSize;
|
||||
|
||||
final float width = cells[cell].width() - gapSize * 2;
|
||||
final float height = cells[cell].height() - gapSize * 2;
|
||||
|
||||
graphics.strokeOval(x, y, width, height);
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
package org.toop.app.canvas;
|
||||
|
||||
import javafx.scene.paint.Color;
|
||||
import org.toop.framework.gameFramework.model.game.AbstractGame;
|
||||
import org.toop.game.games.tictactoe.TicTacToeR;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public final class TicTacToeCanvas extends GameCanvas<TicTacToeR> {
|
||||
public TicTacToeCanvas(Color color, int width, int height, Consumer<Integer> onCellClicked) {
|
||||
super(color, Color.TRANSPARENT, width, height, 3, 3, 30, false, onCellClicked,null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void drawPlayerMove(int player, int move) {
|
||||
switch (player) {
|
||||
case 0 -> drawX(Color.RED, move);
|
||||
case 1 -> drawO(Color.BLUE, move);
|
||||
default -> super.drawPlayerMove(player, move);
|
||||
}
|
||||
}
|
||||
|
||||
public void drawX(Color color, int cell) {
|
||||
graphics.setStroke(color);
|
||||
graphics.setLineWidth(gapSize);
|
||||
|
||||
final float x = cells[cell].x() + gapSize;
|
||||
final float y = cells[cell].y() + gapSize;
|
||||
|
||||
final float width = cells[cell].width() - gapSize * 2;
|
||||
final float height = cells[cell].height() - gapSize * 2;
|
||||
|
||||
graphics.strokeLine(x, y, x + width, y + height);
|
||||
graphics.strokeLine(x + width, y, x, y + height);
|
||||
}
|
||||
|
||||
public void drawO(Color color, int cell) {
|
||||
graphics.setStroke(color);
|
||||
graphics.setLineWidth(gapSize);
|
||||
|
||||
final float x = cells[cell].x() + gapSize;
|
||||
final float y = cells[cell].y() + gapSize;
|
||||
|
||||
final float width = cells[cell].width() - gapSize * 2;
|
||||
final float height = cells[cell].height() - gapSize * 2;
|
||||
|
||||
graphics.strokeOval(x, y, width, height);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void drawPlayerHover(int player, int move, AbstractGame game) {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
package org.toop.app.gameControllers;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.toop.framework.gameFramework.controller.UpdatesGameUI;
|
||||
import org.toop.framework.gameFramework.view.GUIEvents;
|
||||
import org.toop.app.canvas.GameCanvas;
|
||||
import org.toop.framework.networking.events.NetworkEvents;
|
||||
import org.toop.framework.gameFramework.model.game.threadBehaviour.ThreadBehaviour;
|
||||
import org.toop.app.widget.view.GameView;
|
||||
import org.toop.framework.eventbus.EventFlow;
|
||||
import org.toop.game.gameThreads.OnlineThreadBehaviour;
|
||||
import org.toop.framework.gameFramework.model.game.AbstractGame;
|
||||
import org.toop.framework.gameFramework.model.game.SupportsOnlinePlay;
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public abstract class AbstractGameController<T extends AbstractGame<T>> implements UpdatesGameUI, ThreadBehaviour<T> {
|
||||
protected final EventFlow eventFlow = new EventFlow();
|
||||
|
||||
protected final List<Consumer<?>> listeners = new ArrayList<>();
|
||||
|
||||
// Logger for logging ofcourse
|
||||
protected final Logger logger = LogManager.getLogger(this.getClass());
|
||||
|
||||
// Reference to primary view
|
||||
protected final GameView primary;
|
||||
|
||||
// Reference to game canvas
|
||||
protected final GameCanvas<T> canvas;
|
||||
|
||||
private final Player<T>[] players; // List of players, can't be changed.
|
||||
protected final T game; // Reference to game instance
|
||||
private final ThreadBehaviour<T> gameThreadBehaviour;
|
||||
|
||||
// TODO: Change gameType to automatically happen with either dependency injection or something else.
|
||||
// TODO: Make visualisation of moves a behaviour.
|
||||
protected AbstractGameController(GameCanvas<T> canvas, Player<T>[] players, T game, ThreadBehaviour<T> gameThreadBehaviour, String gameType) {
|
||||
logger.info("Creating AbstractGameController");
|
||||
// Make sure player list matches expected size
|
||||
if (players.length != game.getPlayerCount()){
|
||||
logger.error("Player count mismatch");
|
||||
throw new IllegalArgumentException("players and game's players must have same length");
|
||||
}
|
||||
|
||||
this.canvas = canvas;
|
||||
this.players = players;
|
||||
this.game = game;
|
||||
this.gameThreadBehaviour = gameThreadBehaviour;
|
||||
|
||||
primary = new GameView(null, null, null, gameType);
|
||||
addListeners();
|
||||
}
|
||||
|
||||
public void start(){
|
||||
logger.info("Starting GameManager");
|
||||
gameThreadBehaviour.start();;
|
||||
}
|
||||
|
||||
public void stop(){
|
||||
logger.info("Stopping GameManager");
|
||||
removeListeners();
|
||||
gameThreadBehaviour.stop();
|
||||
}
|
||||
|
||||
public Player<T> getCurrentPlayer(){
|
||||
return game.getPlayer(getCurrentPlayerIndex());
|
||||
};
|
||||
|
||||
public int getCurrentPlayerIndex(){
|
||||
return game.getCurrentTurn();
|
||||
}
|
||||
|
||||
private void addListeners(){
|
||||
eventFlow
|
||||
.listen(GUIEvents.RefreshGameCanvas.class, this::onUpdateGameUI, false)
|
||||
.listen(GUIEvents.GameEnded.class, this::onGameFinish, false);
|
||||
}
|
||||
|
||||
private void removeListeners(){
|
||||
eventFlow.unsubscribeAll();
|
||||
}
|
||||
|
||||
private void onUpdateGameUI(GUIEvents.RefreshGameCanvas event){
|
||||
this.updateUI();
|
||||
}
|
||||
|
||||
private void onGameFinish(GUIEvents.GameEnded event){
|
||||
logger.info("Game Finished");
|
||||
String name = event.winner() == -1 ? null : getPlayer(event.winner()).getName();
|
||||
primary.gameOver(event.winOrTie(), name);
|
||||
stop();
|
||||
}
|
||||
|
||||
public Player<T> getPlayer(int player){
|
||||
if (player < 0 || player >= players.length){
|
||||
logger.error("Invalid player index");
|
||||
throw new IllegalArgumentException("player out of range");
|
||||
}
|
||||
return players[player];
|
||||
}
|
||||
|
||||
private boolean isOnline(){
|
||||
return this.gameThreadBehaviour instanceof SupportsOnlinePlay;
|
||||
}
|
||||
|
||||
public void onYourTurn(NetworkEvents.YourTurnResponse event){
|
||||
if (isOnline()){
|
||||
((OnlineThreadBehaviour<T>) this.gameThreadBehaviour).onYourTurn(event);
|
||||
}
|
||||
}
|
||||
|
||||
public void onMoveReceived(NetworkEvents.GameMoveResponse event){
|
||||
if (isOnline()){
|
||||
((OnlineThreadBehaviour<T>) this.gameThreadBehaviour).onMoveReceived(event);
|
||||
}
|
||||
}
|
||||
|
||||
public void gameFinished(NetworkEvents.GameResultResponse event){
|
||||
if (isOnline()){
|
||||
((OnlineThreadBehaviour<T>) this.gameThreadBehaviour).gameFinished(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package org.toop.app.gameControllers;
|
||||
|
||||
import javafx.application.Platform;
|
||||
import javafx.geometry.Pos;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.toop.app.canvas.GameCanvas;
|
||||
import org.toop.app.canvas.BitLegalMoveDrawer;
|
||||
import org.toop.app.widget.WidgetContainer;
|
||||
import org.toop.app.widget.view.GameView;
|
||||
import org.toop.framework.eventbus.EventFlow;
|
||||
import org.toop.framework.eventbus.GlobalEventBus;
|
||||
import org.toop.framework.gameFramework.controller.GameController;
|
||||
import org.toop.framework.gameFramework.model.game.SupportsOnlinePlay;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
import org.toop.framework.gameFramework.model.game.threadBehaviour.ThreadBehaviour;
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
import org.toop.framework.gameFramework.view.GUIEvents;
|
||||
import org.toop.framework.networking.events.NetworkEvents;
|
||||
import org.toop.game.players.LocalPlayer;
|
||||
|
||||
public class GenericGameController<T extends TurnBasedGame<T>, C extends GameCanvas<T>> implements GameController {
|
||||
protected final EventFlow eventFlow = new EventFlow();
|
||||
|
||||
// Logger for logging
|
||||
protected final Logger logger = LogManager.getLogger(this.getClass());
|
||||
|
||||
// Reference to gameView view
|
||||
protected final GameView gameView;
|
||||
|
||||
// Reference to String gametype
|
||||
protected final String gameType;
|
||||
|
||||
// Reference to game canvas
|
||||
protected final C canvas;
|
||||
|
||||
protected final TurnBasedGame<T> game; // Reference to game instance
|
||||
private final ThreadBehaviour gameThreadBehaviour;
|
||||
|
||||
// TODO: Change gameType to automatically happen with either dependency injection or something else.
|
||||
public GenericGameController(C canvas, T game, ThreadBehaviour gameThreadBehaviour, String gameType) {
|
||||
logger.info("Creating: " + this.getClass());
|
||||
|
||||
this.canvas = canvas;
|
||||
this.game = game;
|
||||
this.gameType = gameType;
|
||||
this.gameThreadBehaviour = gameThreadBehaviour;
|
||||
|
||||
// Tell thread how to send moves
|
||||
this.gameThreadBehaviour.setOnSendMove((id, m) -> GlobalEventBus.get().post(new NetworkEvents.SendMove(id, (short)translateMove(m))));
|
||||
|
||||
// Tell thread how to update UI
|
||||
this.gameThreadBehaviour.setOnUpdateUI(() -> Platform.runLater(this::updateUI));
|
||||
|
||||
// Change scene to game view
|
||||
gameView = new GameView(null, null, null, gameType);
|
||||
gameView.add(Pos.CENTER, canvas.getCanvas());
|
||||
WidgetContainer.getCurrentView().transitionNext(gameView, true);
|
||||
|
||||
// Listen to updates
|
||||
eventFlow
|
||||
.listen(GUIEvents.GameEnded.class, this::onGameFinish, false)
|
||||
.listen(GUIEvents.PlayerAttemptedMove.class, event -> {if (getCurrentPlayer() instanceof LocalPlayer<T> lp){lp.setLastMove(event.move());}}, false);
|
||||
}
|
||||
|
||||
public void start(){
|
||||
logger.info("Starting GameManager");
|
||||
updateUI();
|
||||
gameThreadBehaviour.start();
|
||||
}
|
||||
|
||||
public void stop(){
|
||||
logger.info("Stopping GameManager");
|
||||
removeListeners();
|
||||
gameThreadBehaviour.stop();
|
||||
}
|
||||
|
||||
public Player<T> getCurrentPlayer(){
|
||||
return game.getPlayer(getCurrentPlayerIndex());
|
||||
}
|
||||
|
||||
public int getCurrentPlayerIndex(){
|
||||
return game.getCurrentTurn();
|
||||
}
|
||||
|
||||
protected long translateMove(int move){
|
||||
return 1L << move;
|
||||
}
|
||||
|
||||
protected int translateMove(long move){
|
||||
return Long.numberOfTrailingZeros(move);
|
||||
}
|
||||
|
||||
private void removeListeners(){
|
||||
eventFlow.unsubscribeAll();
|
||||
}
|
||||
|
||||
private void onGameFinish(GUIEvents.GameEnded event){
|
||||
logger.info("Game Finished");
|
||||
String name = event.winner() == -1 ? null : getPlayer(event.winner()).getName();
|
||||
gameView.gameOver(event.winOrTie(), name);
|
||||
stop();
|
||||
}
|
||||
|
||||
public Player<T> getPlayer(int player){
|
||||
if (player < 0 || player >= 2){ // TODO: Make game turn player count
|
||||
logger.error("Invalid player index");
|
||||
throw new IllegalArgumentException("player out of range");
|
||||
}
|
||||
return game.getPlayer(player);
|
||||
}
|
||||
|
||||
private boolean isOnline(){
|
||||
return this.gameThreadBehaviour instanceof SupportsOnlinePlay;
|
||||
}
|
||||
|
||||
public void onYourTurn(NetworkEvents.YourTurnResponse event){
|
||||
if (isOnline()){
|
||||
((SupportsOnlinePlay) this.gameThreadBehaviour).onYourTurn(event.clientId());
|
||||
}
|
||||
}
|
||||
|
||||
public void onMoveReceived(NetworkEvents.GameMoveResponse event){
|
||||
if (isOnline()){
|
||||
((SupportsOnlinePlay) this.gameThreadBehaviour).onMoveReceived(
|
||||
translateMove(Integer.parseInt(event.move())));
|
||||
}
|
||||
}
|
||||
|
||||
public void gameFinished(NetworkEvents.GameResultResponse event){
|
||||
if (isOnline()){
|
||||
((SupportsOnlinePlay) this.gameThreadBehaviour).gameFinished(event.condition());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendMove(long clientId, long move) {
|
||||
new EventFlow().addPostEvent(NetworkEvents.SendMove.class, clientId, (short) Long.numberOfTrailingZeros(move)).asyncPostEvent();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateUI() {
|
||||
canvas.redraw(game.deepCopy());
|
||||
gameView.updatePlayerInfo(
|
||||
true,
|
||||
getCurrentPlayer().getName(),
|
||||
game.getCurrentTurn() == 0 ? "X" : "O",
|
||||
getPlayer((game.getCurrentTurn() + 1 ) % 2).getName(),
|
||||
this.gameType
|
||||
);
|
||||
// draw legal moves for bit canvasses
|
||||
if (canvas instanceof BitLegalMoveDrawer) {
|
||||
long movesLoop = game.getLegalMoves();
|
||||
while (movesLoop != 0) {
|
||||
long move = 1L << Long.numberOfTrailingZeros(movesLoop);
|
||||
((BitLegalMoveDrawer) canvas).showLegalMove(move, getCurrentPlayerIndex());
|
||||
movesLoop &= movesLoop - 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package org.toop.app.gameControllers;
|
||||
|
||||
import javafx.scene.paint.Color;
|
||||
import org.toop.app.canvas.ReversiBitCanvas;
|
||||
import org.toop.framework.gameFramework.model.game.threadBehaviour.ThreadBehaviour;
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
import org.toop.game.gameThreads.LocalThreadBehaviour;
|
||||
import org.toop.game.gameThreads.OnlineThreadBehaviour;
|
||||
import org.toop.game.games.reversi.BitboardReversi;
|
||||
import org.toop.game.players.LocalPlayer;
|
||||
import org.toop.game.players.OnlinePlayer;
|
||||
|
||||
public class ReversiBitController extends GenericGameController<BitboardReversi, ReversiBitCanvas> {
|
||||
public ReversiBitController(Player<BitboardReversi>[] players, boolean switchColors) {
|
||||
BitboardReversi game = new BitboardReversi(players);
|
||||
ThreadBehaviour thread = new LocalThreadBehaviour<>(game);
|
||||
for (Player<BitboardReversi> player : players) {
|
||||
if (player instanceof OnlinePlayer<BitboardReversi>) {
|
||||
thread = new OnlineThreadBehaviour<>(game);
|
||||
}
|
||||
}
|
||||
super(new ReversiBitCanvas(switchColors, players[0] instanceof LocalPlayer<BitboardReversi> || players[1] instanceof LocalPlayer<BitboardReversi>), game, thread, "Reversi");
|
||||
}
|
||||
}
|
||||
@@ -1,138 +0,0 @@
|
||||
package org.toop.app.gameControllers;
|
||||
|
||||
import javafx.animation.SequentialTransition;
|
||||
import javafx.geometry.Pos;
|
||||
import javafx.scene.paint.Color;
|
||||
import org.toop.app.App;
|
||||
import org.toop.app.canvas.ReversiCanvas;
|
||||
import org.toop.app.widget.WidgetContainer;
|
||||
import org.toop.framework.eventbus.EventFlow;
|
||||
import org.toop.framework.gameFramework.model.game.AbstractGame;
|
||||
import org.toop.framework.gameFramework.view.GUIEvents;
|
||||
import org.toop.game.gameThreads.LocalFixedRateThreadBehaviour;
|
||||
import org.toop.game.gameThreads.OnlineThreadBehaviour;
|
||||
import org.toop.game.players.LocalPlayer;
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
import org.toop.game.games.reversi.ReversiR;
|
||||
|
||||
public class ReversiController extends AbstractGameController<ReversiR> {
|
||||
// TODO: Refactor GUI update methods to follow designed system
|
||||
public ReversiController(Player<ReversiR>[] players, boolean local) {
|
||||
ReversiR ReversiR = new ReversiR(players);
|
||||
super(
|
||||
new ReversiCanvas(Color.GRAY, (App.getHeight() / 4) * 3, (App.getHeight() / 4) * 3,(c) -> {new EventFlow().addPostEvent(GUIEvents.PlayerAttemptedMove.class, c).postEvent();}, (c) -> {new EventFlow().addPostEvent(GUIEvents.PlayerMoveHovered.class, c).postEvent();}),
|
||||
players,
|
||||
ReversiR,
|
||||
local ? new LocalFixedRateThreadBehaviour<>(ReversiR, players) : new OnlineThreadBehaviour<>(ReversiR, players), // TODO: Player order matters here, this won't work atm
|
||||
"Reversi");
|
||||
eventFlow.listen(GUIEvents.PlayerAttemptedMove.class, event -> {if (getCurrentPlayer() instanceof LocalPlayer lp){lp.setMove(event.move());}}, false);
|
||||
eventFlow.listen(GUIEvents.PlayerMoveHovered.class, this::onHoverMove, false);
|
||||
initUI();
|
||||
}
|
||||
|
||||
|
||||
private void onHoverMove(GUIEvents.PlayerMoveHovered event){
|
||||
int cellEntered = event.move();
|
||||
canvas.drawPlayerHover(-1, cellEntered, game);
|
||||
/*// (information.players[game.getCurrentTurn()].isHuman) {
|
||||
int[] legalMoves = game.getLegalMoves();
|
||||
boolean isLegalMove = false;
|
||||
for (int move : legalMoves) {
|
||||
if (move == cellEntered){
|
||||
isLegalMove = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (cellEntered >= 0){
|
||||
int[] moves = null;
|
||||
if (isLegalMove) {
|
||||
moves = game.getFlipsForPotentialMove(
|
||||
new Point(cellEntered%game.getColumnSize(),cellEntered/game.getRowSize()),
|
||||
game.getCurrentPlayer());
|
||||
}
|
||||
canvas.drawHighlightDots(moves);
|
||||
}
|
||||
//}*/
|
||||
}
|
||||
|
||||
public ReversiController(Player<ReversiR>[] players) {
|
||||
this(players, true);
|
||||
}
|
||||
|
||||
private void updateCanvas(boolean animate) {
|
||||
// Todo: this is very inefficient. still very fast but if the grid is bigger it might cause issues. improve.
|
||||
canvas.clearAll();
|
||||
|
||||
for (int i = 0; i < game.getBoard().length; i++) {
|
||||
if (game.getBoard()[i] == 0) {
|
||||
canvas.drawDot(Color.WHITE, i);
|
||||
} else if (game.getBoard()[i] == 1) {
|
||||
canvas.drawDot(Color.BLACK, i);
|
||||
}
|
||||
}
|
||||
|
||||
final int[] flipped = game.getMostRecentlyFlippedPieces();
|
||||
|
||||
final SequentialTransition animation = new SequentialTransition();
|
||||
|
||||
final Color fromColor = getCurrentPlayerIndex() == 0? Color.WHITE : Color.BLACK;
|
||||
final Color toColor = getCurrentPlayerIndex() == 0? Color.BLACK : Color.WHITE;
|
||||
|
||||
if (animate && flipped != null) {
|
||||
for (final int flip : flipped) {
|
||||
canvas.clear(flip);
|
||||
canvas.drawDot(fromColor, flip);
|
||||
animation.getChildren().addFirst(canvas.flipDot(fromColor, toColor, flip));
|
||||
}
|
||||
}
|
||||
|
||||
animation.setOnFinished(_ -> {
|
||||
|
||||
if (getCurrentPlayer() instanceof LocalPlayer) {
|
||||
final int[] legalMoves = game.getLegalMoves();
|
||||
|
||||
for (final int legalMove : legalMoves) {
|
||||
drawLegalPosition(legalMove, getCurrentPlayerIndex());
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
animation.play();
|
||||
primary.nextPlayer(true, getCurrentPlayer().getName(), game.getCurrentTurn() == 0 ? "X" : "O", getPlayer((game.getCurrentTurn() + 1) % 2).getName(), 'R');
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateUI() {
|
||||
updateCanvas(false);
|
||||
}
|
||||
|
||||
public void drawLegalPosition(int cell, int player) {
|
||||
Color innerColor;
|
||||
if (player == 1) {
|
||||
innerColor = new Color(0.0f, 0.0f, 0.0f, 0.6f);
|
||||
}
|
||||
else {
|
||||
innerColor = new Color(1.0f, 1.0f, 1.0f, 0.75f);
|
||||
}
|
||||
canvas.drawInnerDot(innerColor, cell,false);
|
||||
}
|
||||
|
||||
private void initUI(){
|
||||
primary.add(Pos.CENTER, canvas.getCanvas());
|
||||
WidgetContainer.getCurrentView().transitionNext(primary, true);
|
||||
updateCanvas(false);
|
||||
}
|
||||
|
||||
private void drawMoves(){
|
||||
int[] board = game.getBoard();
|
||||
|
||||
// Draw each square
|
||||
for (int i = 0; i < board.length; i++){
|
||||
// If square isn't empty, draw player move
|
||||
if (board[i] != AbstractGame.EMPTY){
|
||||
canvas.drawPlayerMove(board[i], i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package org.toop.app.gameControllers;
|
||||
|
||||
import org.toop.app.canvas.TicTacToeBitCanvas;
|
||||
import org.toop.framework.gameFramework.model.game.threadBehaviour.ThreadBehaviour;
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
import org.toop.game.gameThreads.LocalFixedRateThreadBehaviour;
|
||||
import org.toop.game.gameThreads.LocalThreadBehaviour;
|
||||
import org.toop.game.gameThreads.OnlineThreadBehaviour;
|
||||
import org.toop.game.games.tictactoe.BitboardTicTacToe;
|
||||
import org.toop.game.players.OnlinePlayer;
|
||||
|
||||
public class TicTacToeBitController extends GenericGameController<BitboardTicTacToe, TicTacToeBitCanvas > {
|
||||
public TicTacToeBitController(Player<BitboardTicTacToe>[] players) {
|
||||
BitboardTicTacToe game = new BitboardTicTacToe(players);
|
||||
ThreadBehaviour thread = new LocalThreadBehaviour<>(game);
|
||||
for (Player<BitboardTicTacToe> player : players) {
|
||||
if (player instanceof OnlinePlayer<BitboardTicTacToe>){
|
||||
thread = new OnlineThreadBehaviour<>(game);
|
||||
}
|
||||
}
|
||||
super(new TicTacToeBitCanvas(), game, thread , "TicTacToe");
|
||||
}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
package org.toop.app.gameControllers;
|
||||
|
||||
import javafx.geometry.Pos;
|
||||
import javafx.scene.paint.Color;
|
||||
import org.toop.app.App;
|
||||
import org.toop.app.canvas.TicTacToeCanvas;
|
||||
import org.toop.framework.eventbus.EventFlow;
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
import org.toop.framework.gameFramework.view.GUIEvents;
|
||||
import org.toop.framework.gameFramework.model.game.AbstractGame;
|
||||
import org.toop.game.gameThreads.LocalThreadBehaviour;
|
||||
import org.toop.game.gameThreads.OnlineThreadBehaviour;
|
||||
import org.toop.game.players.LocalPlayer;
|
||||
import org.toop.app.widget.WidgetContainer;
|
||||
import org.toop.game.games.tictactoe.TicTacToeR;
|
||||
|
||||
public class TicTacToeController extends AbstractGameController<TicTacToeR> {
|
||||
|
||||
public TicTacToeController(Player<TicTacToeR>[] players, boolean local) {
|
||||
TicTacToeR ticTacToeR = new TicTacToeR(players);
|
||||
super(
|
||||
new TicTacToeCanvas(Color.GRAY, (App.getHeight() / 4) * 3, (App.getHeight() / 4) * 3,(c) -> {new EventFlow().addPostEvent(GUIEvents.PlayerAttemptedMove.class, c).postEvent();}),
|
||||
players,
|
||||
ticTacToeR,
|
||||
local ? new LocalThreadBehaviour(ticTacToeR, players) : new OnlineThreadBehaviour<>(ticTacToeR, players), // TODO: Player order matters here, this won't work atm
|
||||
"TicTacToe");
|
||||
|
||||
initUI();
|
||||
eventFlow.listen(GUIEvents.PlayerAttemptedMove.class, event -> {if (getCurrentPlayer() instanceof LocalPlayer lp){lp.setMove(event.move());}}, false);
|
||||
//addListener(GlobalEventBus.subscribe(GUIEvents.PlayerAttemptedMove.class, event -> {if (getCurrentPlayer() instanceof LocalPlayer lp){lp.setMove(event.move());}}));
|
||||
//new EventFlow().listen(GUIEvents.PlayerAttemptedMove.class, event -> {if (getCurrentPlayer() instanceof LocalPlayer lp){lp.setMove(event.move());}});
|
||||
}
|
||||
|
||||
public TicTacToeController(Player<TicTacToeR>[] players) {
|
||||
this(players, true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateUI() {
|
||||
canvas.clearAll();
|
||||
// TODO: wtf is even this pile of poop temp fix
|
||||
primary.nextPlayer(true, getCurrentPlayer().getName(), game.getCurrentTurn() == 0 ? "X" : "O", getPlayer((game.getCurrentTurn() + 1) % 2).getName(), 'T');
|
||||
drawMoves();
|
||||
}
|
||||
|
||||
private void initUI(){
|
||||
primary.add(Pos.CENTER, canvas.getCanvas());
|
||||
WidgetContainer.getCurrentView().transitionNext(primary, true);
|
||||
updateUI();
|
||||
}
|
||||
|
||||
private void drawMoves(){
|
||||
int[] board = game.getBoard();
|
||||
|
||||
// Draw each square
|
||||
for (int i = 0; i < board.length; i++){
|
||||
// If square isn't empty, draw player move
|
||||
if (board[i] != AbstractGame.EMPTY){
|
||||
canvas.drawPlayerMove(board[i], i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -37,7 +37,14 @@ public class PlayerInfoWidget {
|
||||
}
|
||||
|
||||
private Node buildContent() {
|
||||
|
||||
if (information.isHuman) {
|
||||
var spacer = Primitive.vbox(
|
||||
makeAIButton(0, 0, "zwartepiet"),
|
||||
makeAIButton(0, 0, "sinterklaas"),
|
||||
makeAIButton(0, 0, "santa")
|
||||
); //todo make a better solution
|
||||
spacer.setVisible(false);
|
||||
var nameInput = new LabeledInputWidget(
|
||||
"name",
|
||||
"enter-your-name",
|
||||
@@ -45,7 +52,7 @@ public class PlayerInfoWidget {
|
||||
newName -> information.name = newName
|
||||
);
|
||||
|
||||
return nameInput.getNode();
|
||||
return Primitive.vbox(spacer,nameInput.getNode());
|
||||
} else {
|
||||
var AIBox = Primitive.vbox(
|
||||
makeAIButton(0, 1, "zwartepiet"),
|
||||
|
||||
@@ -8,6 +8,7 @@ import org.toop.app.widget.complex.PopupWidget;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import javafx.geometry.Pos;
|
||||
import org.toop.local.AppContext;
|
||||
|
||||
public final class ChallengePopup extends PopupWidget {
|
||||
private final GameInformation.Player playerInformation;
|
||||
|
||||
@@ -16,14 +16,15 @@ import org.toop.app.widget.tutorial.Connect4TutorialWidget;
|
||||
import org.toop.app.widget.tutorial.ReversiTutorialWidget;
|
||||
import org.toop.app.widget.tutorial.TicTacToeTutorialWidget;
|
||||
import org.toop.local.AppContext;
|
||||
import org.toop.local.AppSettings;
|
||||
|
||||
public final class GameView extends ViewWidget {
|
||||
private final Text playerHeader;
|
||||
private final Text turnHeader;
|
||||
private final Text player1Header;
|
||||
private final Text player2Header;
|
||||
private Circle player1Icon;
|
||||
private Circle player2Icon;
|
||||
private final Circle player1Icon;
|
||||
private final Circle player2Icon;
|
||||
private final Button forfeitButton;
|
||||
private final Button exitButton;
|
||||
private final TextField chatInput;
|
||||
@@ -94,7 +95,7 @@ public final class GameView extends ViewWidget {
|
||||
}
|
||||
}
|
||||
|
||||
public void nextPlayer(boolean isMe, String currentPlayer, String currentMove, String nextPlayer, char GameType) {
|
||||
public void updatePlayerInfo(boolean isMe, String currentPlayer, String currentMove, String nextPlayer, String GameType) {
|
||||
Platform.runLater(() -> {
|
||||
if (!(hasSet)) {
|
||||
playerHeader.setText(currentPlayer + " vs. " + nextPlayer);
|
||||
@@ -112,8 +113,8 @@ public final class GameView extends ViewWidget {
|
||||
new GameOverPopup(iWon, winner).show(Pos.CENTER);
|
||||
}
|
||||
|
||||
private void setPlayerHeaders(boolean isMe, String currentPlayer, String nextPlayer, char GameType) {
|
||||
if (GameType == 'T') {
|
||||
private void setPlayerHeaders(boolean isMe, String currentPlayer, String nextPlayer, String GameType) {
|
||||
if (GameType.equals("TicTacToe")) {
|
||||
if (isMe) {
|
||||
player1Header.setText("X: " + currentPlayer);
|
||||
player2Header.setText("O: " + nextPlayer);
|
||||
@@ -124,15 +125,16 @@ public final class GameView extends ViewWidget {
|
||||
}
|
||||
setPlayerInfoTTT();
|
||||
}
|
||||
else if (GameType == 'R') {
|
||||
if (isMe) {
|
||||
player1Header.setText(currentPlayer);
|
||||
player2Header.setText(nextPlayer);
|
||||
}
|
||||
else {
|
||||
else if (GameType.equals("Reversi")) {
|
||||
boolean swap = AppSettings.getSettings().getSwitchReversi();
|
||||
if (!swap) {
|
||||
player1Header.setText(nextPlayer);
|
||||
player2Header.setText(currentPlayer);
|
||||
}
|
||||
else {
|
||||
player1Header.setText(currentPlayer);
|
||||
player2Header.setText(nextPlayer);
|
||||
}
|
||||
setPlayerInfoReversi();
|
||||
}
|
||||
}
|
||||
@@ -166,8 +168,8 @@ public final class GameView extends ViewWidget {
|
||||
var playerInfo = Primitive.vbox(
|
||||
playerHeader,
|
||||
Primitive.separator(),
|
||||
player1box,
|
||||
player2box
|
||||
player2box,
|
||||
player1box
|
||||
);
|
||||
|
||||
player1Icon.setRadius(player1Header.fontProperty().map(Font::getSize).getValue());
|
||||
|
||||
@@ -2,19 +2,21 @@ package org.toop.app.widget.view;
|
||||
|
||||
import javafx.application.Platform;
|
||||
import org.toop.app.GameInformation;
|
||||
import org.toop.app.gameControllers.AbstractGameController;
|
||||
import org.toop.app.gameControllers.ReversiController;
|
||||
import org.toop.app.gameControllers.TicTacToeController;
|
||||
import org.toop.app.gameControllers.ReversiBitController;
|
||||
import org.toop.app.gameControllers.TicTacToeBitController;
|
||||
import org.toop.framework.gameFramework.controller.GameController;
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
import org.toop.game.games.tictactoe.TicTacToeAIRSleep;
|
||||
import org.toop.game.games.reversi.BitboardReversi;
|
||||
import org.toop.game.games.tictactoe.BitboardTicTacToe;
|
||||
import org.toop.game.players.ArtificialPlayer;
|
||||
import org.toop.game.players.LocalPlayer;
|
||||
import org.toop.app.widget.Primitive;
|
||||
import org.toop.app.widget.complex.PlayerInfoWidget;
|
||||
import org.toop.app.widget.complex.ViewWidget;
|
||||
import org.toop.app.widget.popup.ErrorPopup;
|
||||
import org.toop.game.games.reversi.ReversiAIR;
|
||||
import org.toop.app.widget.tutorial.*;
|
||||
import org.toop.game.players.ai.MiniMaxAI;
|
||||
import org.toop.game.players.ai.RandomAI;
|
||||
import org.toop.local.AppContext;
|
||||
|
||||
import javafx.geometry.Pos;
|
||||
@@ -25,7 +27,7 @@ import org.toop.local.AppSettings;
|
||||
public class LocalMultiplayerView extends ViewWidget {
|
||||
private final GameInformation information;
|
||||
|
||||
private AbstractGameController<?> gameController;
|
||||
private GameController gameController;
|
||||
|
||||
public LocalMultiplayerView(GameInformation.Type type) {
|
||||
this(new GameInformation(type));
|
||||
@@ -44,7 +46,7 @@ public class LocalMultiplayerView extends ViewWidget {
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Fix this temporary ass way of setting the players (Only works for TicTacToe)
|
||||
// TODO: Fix this temporary ass way of setting the players
|
||||
Player[] players = new Player[2];
|
||||
|
||||
switch (information.type) {
|
||||
@@ -52,55 +54,56 @@ public class LocalMultiplayerView extends ViewWidget {
|
||||
if (information.players[0].isHuman) {
|
||||
players[0] = new LocalPlayer<>(information.players[0].name);
|
||||
} else {
|
||||
players[0] = new ArtificialPlayer<>(new TicTacToeAIRSleep(information.players[0].computerDifficulty, information.players[1].computerThinkTime), information.players[0].name);
|
||||
players[0] = new ArtificialPlayer<>(new RandomAI<BitboardTicTacToe>(), "Random AI");
|
||||
}
|
||||
if (information.players[1].isHuman) {
|
||||
players[1] = new LocalPlayer<>(information.players[1].name);
|
||||
} else {
|
||||
players[1] = new ArtificialPlayer<>(new TicTacToeAIRSleep(information.players[1].computerDifficulty, information.players[1].computerThinkTime), information.players[1].name);
|
||||
players[1] = new ArtificialPlayer<>(new MiniMaxAI<BitboardTicTacToe>(9), "MiniMax AI");
|
||||
}
|
||||
if (AppSettings.getSettings().getTutorialFlag() && AppSettings.getSettings().getFirstTTT()) {
|
||||
new ShowEnableTutorialWidget(
|
||||
() -> new TicTacToeTutorialWidget(() -> {
|
||||
gameController = new TicTacToeController(players);
|
||||
gameController = new TicTacToeBitController(players);
|
||||
gameController.start();
|
||||
}),
|
||||
() -> Platform.runLater(() -> {
|
||||
gameController = new TicTacToeController(players);
|
||||
gameController = new TicTacToeBitController(players);
|
||||
gameController.start();
|
||||
}),
|
||||
() -> AppSettings.getSettings().setFirstTTT(false)
|
||||
);
|
||||
} else {
|
||||
gameController = new TicTacToeController(players);
|
||||
gameController = new TicTacToeBitController(players);
|
||||
gameController.start();
|
||||
}
|
||||
break;
|
||||
case REVERSI:
|
||||
boolean swap = AppSettings.getSettings().getSwitchReversi();
|
||||
if (information.players[0].isHuman) {
|
||||
players[0] = new LocalPlayer<>(information.players[0].name);
|
||||
} else {
|
||||
players[0] = new ArtificialPlayer<>(new ReversiAIR(), information.players[0].name);
|
||||
players[0] = new ArtificialPlayer<>(new RandomAI<BitboardReversi>(), "Random AI");
|
||||
}
|
||||
if (information.players[1].isHuman) {
|
||||
players[1] = new LocalPlayer<>(information.players[1].name);
|
||||
} else {
|
||||
players[1] = new ArtificialPlayer<>(new ReversiAIR(), information.players[1].name);
|
||||
players[1] = new ArtificialPlayer<>(new MiniMaxAI<BitboardReversi>(6), "MiniMax");
|
||||
}
|
||||
if (AppSettings.getSettings().getTutorialFlag() && AppSettings.getSettings().getFirstReversi()) {
|
||||
new ShowEnableTutorialWidget(
|
||||
() -> new ReversiTutorialWidget(() -> {
|
||||
gameController = new ReversiController(players);
|
||||
gameController = new ReversiBitController(players, swap);
|
||||
gameController.start();
|
||||
}),
|
||||
() -> Platform.runLater(() -> {
|
||||
gameController = new ReversiController(players);
|
||||
gameController = new ReversiBitController(players, swap);
|
||||
gameController.start();
|
||||
}),
|
||||
() -> AppSettings.getSettings().setFirstReversi(false)
|
||||
);
|
||||
} else {
|
||||
gameController = new ReversiController(players);
|
||||
gameController = new ReversiBitController(players, swap);
|
||||
gameController.start();
|
||||
}
|
||||
break;
|
||||
|
||||
@@ -149,13 +149,22 @@ public class OptionsView extends ViewWidget {
|
||||
"small", "medium", "large"
|
||||
);
|
||||
|
||||
var swapReversiColors = new ToggleWidget(
|
||||
"reversinotswapped", "reversiswapped",
|
||||
AppSettings.getSettings().getSwitchReversi(),
|
||||
swap -> {
|
||||
AppSettings.getSettings().setSwitchReversi(swap);
|
||||
}
|
||||
);
|
||||
|
||||
return Primitive.vbox(
|
||||
Primitive.header("style"),
|
||||
Primitive.separator(),
|
||||
|
||||
themeWidget.getNode(),
|
||||
layoutWidget.getNode()
|
||||
layoutWidget.getNode(),
|
||||
Primitive.text("reversiswap"),
|
||||
swapReversiColors.getNode()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -5,18 +5,16 @@ import org.toop.framework.audio.VolumeControl;
|
||||
import org.toop.framework.audio.events.AudioEvents;
|
||||
import org.toop.framework.eventbus.EventFlow;
|
||||
import org.toop.framework.resource.ResourceManager;
|
||||
import org.toop.framework.resource.ResourceMeta;
|
||||
import org.toop.framework.resource.resources.SettingsAsset;
|
||||
import org.toop.framework.settings.Settings;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Locale;
|
||||
|
||||
public class AppSettings {
|
||||
private static SettingsAsset settingsAsset;
|
||||
|
||||
public static void applySettings() {
|
||||
settingsAsset = getPath();
|
||||
settingsAsset = getSettingsAsset();
|
||||
if (!settingsAsset.isLoaded()) {
|
||||
settingsAsset.load();
|
||||
}
|
||||
@@ -45,26 +43,9 @@ public class AppSettings {
|
||||
.postEvent();
|
||||
}
|
||||
|
||||
public static SettingsAsset getPath() {
|
||||
public static SettingsAsset getSettingsAsset() {
|
||||
if (settingsAsset == null) {
|
||||
String os = System.getProperty("os.name").toLowerCase();
|
||||
String basePath;
|
||||
|
||||
if (os.contains("win")) {
|
||||
basePath = System.getenv("APPDATA");
|
||||
if (basePath == null) {
|
||||
basePath = System.getProperty("user.home");
|
||||
}
|
||||
} else if (os.contains("mac")) {
|
||||
basePath = System.getProperty("user.home") + "/Library/Application Support";
|
||||
} else {
|
||||
basePath = System.getProperty("user.home") + "/.config";
|
||||
}
|
||||
|
||||
File settingsFile =
|
||||
new File(basePath + File.separator + "ISY1" + File.separator + "settings.json");
|
||||
// this.settingsAsset = new SettingsAsset(settingsFile);
|
||||
ResourceManager.addAsset(new ResourceMeta<>("settings.json", new SettingsAsset(settingsFile)));
|
||||
settingsAsset = SettingsAsset.getPath();
|
||||
}
|
||||
return ResourceManager.get("settings.json");
|
||||
}
|
||||
@@ -110,5 +91,6 @@ public class AppSettings {
|
||||
settingsAsset.setMusicVolume(15);
|
||||
settingsAsset.setTutorialFlag(true);
|
||||
settingsAsset.setLayoutSize("medium");
|
||||
settingsAsset.setSwitchReversi(false);
|
||||
}
|
||||
}
|
||||
@@ -89,6 +89,9 @@ turnof=\u062F\u0648\u0631\u0647
|
||||
zwartepiet=\u0633\u0647\u0644: Zwarte Piet
|
||||
sinterklaas=\u0645\u062a\u0648\u0633\u0637: Sint R. Klaas
|
||||
santa=\u0635\u0639\u0628: Santa
|
||||
reversiswapped=\u0645\u0628\u062F\u0651\u064E\u0644
|
||||
reversinotswapped=\u063A\u064A\u0631\u0020\u0645\u0628\u062F\u0651\u064E\u0644
|
||||
reversiswap=\u0647\u0644\u0020\u062A\u0631\u064A\u062F\u0020\u062A\u0628\u062F\u064A\u0644\u0020\u0623\u0644\u0648\u0627\u0646\u0020\u0627\u0644\u0631\u064A\u0641\u064E\u0631\u0633\u064A\u061F\u0020\u0645\u062D\u0644\u064A\u0020\u0641\u0642\u0637\u002E
|
||||
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629
|
||||
|
||||
@@ -91,6 +91,9 @@ turnof=ist dran
|
||||
zwartepiet=Leicht: Zwarte Piet
|
||||
sinterklaas=Mittel: Sint R. Klaas
|
||||
santa=Schwer: Santa
|
||||
reversiswapped=Getauscht
|
||||
reversinotswapped=Nicht getauscht
|
||||
reversiswap=M\u00F6chten Sie die Reversi-Farben tauschen? Nur lokal.
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (Arabisch)
|
||||
chinese=\u4e2d\u6587 (Chinesisch)
|
||||
|
||||
@@ -93,6 +93,9 @@ turnof='s turn
|
||||
zwartepiet=Easy: Zwarte Piet
|
||||
sinterklaas=Medium: Sint R. Klaas
|
||||
santa=Hard:Santa
|
||||
reversiswapped=Swapped
|
||||
reversinotswapped=Not Swapped
|
||||
reversiswap=Do you want to swap the Reversi colors? Local only.
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (Arabic)
|
||||
chinese=\u4e2d\u6587 (Chinese)
|
||||
|
||||
@@ -90,6 +90,9 @@ turnof=le toca
|
||||
zwartepiet=F\u00e1cil: Zwarte Piet
|
||||
sinterklaas=Medio: Sint R. Klaas
|
||||
santa=Dif\u00edcil: Santa
|
||||
reversiswapped=Cambiado
|
||||
reversinotswapped=No cambiado
|
||||
reversiswap=\u00BFDeseas intercambiar los colores de Reversi? Solo local.
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (Ar\u00e1bigo)
|
||||
chinese=\u4e2d\u6587 (Chino)
|
||||
|
||||
@@ -90,6 +90,9 @@ turnof=\u00E0 son tour
|
||||
zwartepiet=Facile: Zwarte Piet
|
||||
sinterklaas=Moyen : Sint R. Klaas
|
||||
santa=Difficile: Santa
|
||||
reversiswapped=\u00C9chang\u00E9
|
||||
reversinotswapped=Non \u00E9chang\u00E9
|
||||
reversiswap=Voulez-vous \u00E9changer les couleurs de Reversi ? Local uniquement.
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (Arabe)
|
||||
chinese=\u4e2d\u6587 (Chinois)
|
||||
|
||||
@@ -90,6 +90,9 @@ turnof=\u0915\u0940 \u092C\u093E\u0930\u0940
|
||||
zwartepiet=\u0905\u0938\u093e\u0928: Zwarte Piet
|
||||
sinterklaas=\u092e\u0927\u094d\u092f\u092e: Sint R. Klaas
|
||||
santa=\u0915\u0924\u093f\u0928: Santa
|
||||
reversiswapped=\u092C\u0926\u0932\u093E\u0020\u0939\u0941\u0906
|
||||
reversinotswapped=\u0928\u0939\u0940\u0902\u0020\u092C\u0926\u0932\u093E\u0020\u0939\u0941\u0906
|
||||
reversiswap=\u0915\u094D\u092F\u093E\u0020\u0906\u092A\u0020\u0930\u093F\u0935\u0930\u094D\u0938\u0940\u0020\u0915\u0947\u0020\u0930\u0902\u0917\u0020\u092C\u0926\u0932\u0928\u093E\u0020\u091A\u093E\u0939\u0924\u0947\u0020\u0939\u0948\u0902?\u0020\u0915\u0947\u0935\u0932\u0020\u0938\u094D\u0925\u093E\u0928\u0940\u092F\u002E
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (\u0905\u0930\u092c\u0940)
|
||||
chinese=\u4e2d\u6587 (\u091a\u0940\u0928\u0940)
|
||||
|
||||
@@ -89,6 +89,9 @@ turnof=\u00E8 il suo turno
|
||||
zwartepiet=Facile: Zwarte Piet
|
||||
sinterklaas=Medio: Sint R. Klaas
|
||||
santa=Difficile: Santa
|
||||
reversiswapped=Scambiato
|
||||
reversinotswapped=Non scambiato
|
||||
reversiswap=Vuoi scambiare i colori di Reversi? Solo locale.
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (Arabo)
|
||||
chinese=\u4e2d\u6587 (Cinese)
|
||||
|
||||
@@ -89,6 +89,10 @@ turnof=\u306E\u756A
|
||||
zwartepiet=\u7c21\u5358: Zwarte Piet
|
||||
sinterklaas=\u4e2d\u7d1a: Sint R. Klaas
|
||||
santa=\u96e3\u3057\u3044: Santa
|
||||
reversiswapped=\u5165\u308C\u66FF\u3048\u6E08\u307F
|
||||
reversinotswapped=\u672A\u5165\u308C\u66FF\u3048
|
||||
reversiswap=\u30EA\u30D0\u30FC\u30B7\u306E\u8272\u3092\u5165\u308C\u66FF\u3048\u307E\u3059\u304B?\u0020\u30ED\u30FC\u30AB\u30EB\u306E\u307F\u3067\u3059\u002E
|
||||
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (\u30a2\u30e9\u30d3\u30a2\u8a9e)
|
||||
chinese=\u4e2d\u6587 (\u4e2d\u6587)
|
||||
|
||||
@@ -89,6 +89,9 @@ turnof=\uC758 \uCC28\uB840
|
||||
zwartepiet=\uc218\uc601: Zwarte Piet
|
||||
sinterklaas=\ubcf4\ud1b5: Sint R. Klaas
|
||||
santa=\uc5d0\uc18c: Santa
|
||||
reversiswapped=\uAD50\uCCB4\uB428
|
||||
reversinotswapped=\uAD50\uCCB4\uB418\uC9C0 \uC54A\uC74C
|
||||
reversiswap=\uB9AC\uBC84\uC2DC \uC0C9\uC0C1\uC744 \uBC14\uAFB8\uC2DC\uACA0\uC2B5\uB2C8\uAE4C?\u0020\uB85C\uCEEC \uC804\uC6A9\u0020\uC785\uB2C8\uB2E4\u002E
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (\u0639\u0631\u0628\u064a\u0629)
|
||||
chinese=\u4e2d\u6587 (\u4e2d\u6587)
|
||||
|
||||
@@ -89,6 +89,9 @@ turnof=is aan de beurt
|
||||
zwartepiet=Makkelijk: Zwarte Piet
|
||||
sinterklaas=Gemiddeld: Sint R. Klaas
|
||||
santa=Moeilijk: Santa
|
||||
reversiswapped=Gewisseld
|
||||
reversinotswapped=Niet gewisseld
|
||||
reversiswap=Wil je de Reversi-kleuren wisselen? Alleen lokaal.
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (Arabisch)
|
||||
chinese=\u4e2d\u6587 (Chinees)
|
||||
|
||||
@@ -89,6 +89,9 @@ turnof=\u0445\u043E\u0434\u0438\u0442
|
||||
zwartepiet=\u041b\u0435\u0433\u043a\u043e: Zwarte Piet
|
||||
sinterklaas=\u0421\u0440\u0435\u0434\u043d\u0438\u0439: Sint R. Klaas
|
||||
santa=\u0421\u043b\u043e\u0436\u043d\u043e: Santa
|
||||
reversiswapped=\u041F\u043E\u043C\u0435\u043D\u044F\u043D\u043E
|
||||
reversinotswapped=\u041D\u0435 \u043F\u043E\u043C\u0435\u043D\u044F\u043D\u043E
|
||||
reversiswap=\u0425\u043E\u0442\u0438\u0442\u0435 \u043F\u043E\u043C\u0435\u043D\u044F\u0442\u044C \u0446\u0432\u0435\u0442\u0430 \u0420\u0435\u0432\u0435\u0440\u0441\u0438?\u0020\u0422\u043E\u043B\u044C\u043A\u043E \u043B\u043E\u043A\u0430\u043B\u044C\u043D\u043E\u002E
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (\u0410\u0440\u0430\u0431\u0441\u043a\u0438\u0439)
|
||||
chinese=\u4e2d\u6587 (\u041a\u0438\u0442\u0430\u0439\u0441\u043a\u0438\u0439)
|
||||
|
||||
@@ -89,6 +89,9 @@ turnof=\u7684\u56DE\u5408
|
||||
zwartepiet=\u7b80\u5355: Zwarte Piet
|
||||
sinterklaas=\u4e2d\u7b49: Sint R. Klaas
|
||||
santa=\u56f0\u96be: Santa
|
||||
reversiswapped=\u5DF2\u4EA4\u6362
|
||||
reversinotswapped=\u672A\u4EA4\u6362
|
||||
reversiswap=\u662F\u5426\u8981\u4EA4\u6362\u9ED1\u767D\u68CB\u7684\u989C\u8272\uFF1F\u4EC5\u9650\u672C\u5730\u002E
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (\u963f\u62c9\u4f2f\u8bed)
|
||||
chinese=\u4e2d\u6587
|
||||
|
||||
@@ -14,7 +14,8 @@ import org.toop.framework.eventbus.events.EventType;
|
||||
import org.toop.framework.eventbus.events.ResponseToUniqueEvent;
|
||||
import org.toop.framework.eventbus.events.UniqueEvent;
|
||||
import org.toop.framework.eventbus.bus.EventBus;
|
||||
import org.toop.framework.eventbus.subscriber.DefaultSubscriber;
|
||||
import org.toop.framework.eventbus.subscriber.DefaultNamedSubscriber;
|
||||
import org.toop.framework.eventbus.subscriber.NamedSubscriber;
|
||||
import org.toop.framework.eventbus.subscriber.Subscriber;
|
||||
|
||||
/**
|
||||
@@ -43,7 +44,7 @@ public class EventFlow {
|
||||
private EventType event = null;
|
||||
|
||||
/** The listener returned by GlobalEventBus subscription. Used for unsubscription. */
|
||||
private final List<Subscriber<?, ?>> listeners = new ArrayList<>();
|
||||
private final List<NamedSubscriber<?>> listeners = new ArrayList<>();
|
||||
|
||||
/** Holds the results returned from the subscribed event, if any. */
|
||||
private Map<String, ?> result = null;
|
||||
@@ -161,7 +162,7 @@ public class EventFlow {
|
||||
this.result = eventClass.result();
|
||||
};
|
||||
|
||||
var subscriber = new DefaultSubscriber<>(
|
||||
var subscriber = new DefaultNamedSubscriber<>(
|
||||
name,
|
||||
event,
|
||||
newAction
|
||||
@@ -248,7 +249,7 @@ public class EventFlow {
|
||||
}
|
||||
};
|
||||
|
||||
var listener = new DefaultSubscriber<>(
|
||||
var listener = new DefaultNamedSubscriber<>(
|
||||
name,
|
||||
(Class<TT>) action.getClass().getDeclaredMethods()[0].getParameterTypes()[0],
|
||||
newAction
|
||||
@@ -295,7 +296,7 @@ public class EventFlow {
|
||||
if (unsubscribeAfterSuccess) unsubscribe(String.valueOf(id));
|
||||
};
|
||||
|
||||
var listener = new DefaultSubscriber<>(
|
||||
var listener = new DefaultNamedSubscriber<>(
|
||||
name,
|
||||
event,
|
||||
newAction
|
||||
@@ -378,7 +379,7 @@ public class EventFlow {
|
||||
}
|
||||
};
|
||||
|
||||
var listener = new DefaultSubscriber<>(
|
||||
var listener = new DefaultNamedSubscriber<>(
|
||||
name,
|
||||
eventClass,
|
||||
newAction
|
||||
@@ -496,7 +497,7 @@ public class EventFlow {
|
||||
*
|
||||
* @return Copy of the list of listeners.
|
||||
*/
|
||||
public Subscriber<?, ?>[] getListeners() {
|
||||
public Subscriber<?>[] getListeners() {
|
||||
return listeners.toArray(new Subscriber[0]);
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ package org.toop.framework.eventbus;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.toop.framework.eventbus.bus.DisruptorEventBus;
|
||||
import org.toop.framework.eventbus.bus.EventBus;
|
||||
import org.toop.framework.eventbus.events.EventType;
|
||||
import org.toop.framework.eventbus.store.DefaultSubscriberStore;
|
||||
import org.toop.framework.eventbus.subscriber.Subscriber;
|
||||
|
||||
@@ -19,17 +20,17 @@ public class GlobalEventBus implements EventBus {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void subscribe(Subscriber<?, ?> listener) {
|
||||
public void subscribe(Subscriber<? extends EventType> listener) {
|
||||
INSTANCE.subscribe(listener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unsubscribe(Subscriber<?, ?> listener) {
|
||||
public void unsubscribe(Subscriber<? extends EventType> listener) {
|
||||
INSTANCE.unsubscribe(listener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> void post(T event) {
|
||||
public <T extends EventType> void post(T event) {
|
||||
INSTANCE.post(event);
|
||||
}
|
||||
|
||||
|
||||
@@ -17,22 +17,22 @@ public class DefaultEventBus implements EventBus {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void subscribe(Subscriber<?, ?> subscriber) {
|
||||
public void subscribe(Subscriber<? extends EventType> subscriber) {
|
||||
eventsHolder.add(subscriber);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unsubscribe(Subscriber<?, ?> subscriber) {
|
||||
public void unsubscribe(Subscriber<? extends EventType> subscriber) {
|
||||
eventsHolder.remove(subscriber);
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> void post(T event) {
|
||||
public <T extends EventType> void post(T event) {
|
||||
Class<T> eventType = (Class<T>) event.getClass();
|
||||
var subs = eventsHolder.get(eventType);
|
||||
if (subs != null) {
|
||||
for (Subscriber<?, ?> subscriber : subs) {
|
||||
for (Subscriber<?> subscriber : subs) {
|
||||
Class<T> eventClass = (Class<T>) subscriber.event();
|
||||
Consumer<EventType> action = (Consumer<EventType>) subscriber.handler();
|
||||
|
||||
|
||||
@@ -21,8 +21,8 @@ public class DisruptorEventBus implements EventBus {
|
||||
private final Logger logger;
|
||||
private final SubscriberStore eventsHolder;
|
||||
|
||||
private final Disruptor<EventHolder<?>> disruptor;
|
||||
private final RingBuffer<EventHolder<?>> ringBuffer;
|
||||
private final Disruptor<EventHolder<? extends EventType>> disruptor;
|
||||
private final RingBuffer<EventHolder<? extends EventType>> ringBuffer;
|
||||
|
||||
public DisruptorEventBus(Logger logger, SubscriberStore eventsHolder) {
|
||||
this.logger = logger;
|
||||
@@ -41,9 +41,9 @@ public class DisruptorEventBus implements EventBus {
|
||||
this.ringBuffer = disruptor.getRingBuffer();
|
||||
}
|
||||
|
||||
private Disruptor<EventHolder<?>> getEventHolderDisruptor(ThreadFactory threadFactory) {
|
||||
private Disruptor<EventHolder<? extends EventType>> getEventHolderDisruptor(ThreadFactory threadFactory) {
|
||||
int RING_BUFFER_SIZE = 1024 * 64;
|
||||
Disruptor<EventHolder<?>> disruptor = new Disruptor<>(
|
||||
Disruptor<EventHolder<? extends EventType>> disruptor = new Disruptor<>(
|
||||
EventHolder::new,
|
||||
RING_BUFFER_SIZE,
|
||||
threadFactory,
|
||||
@@ -61,17 +61,17 @@ public class DisruptorEventBus implements EventBus {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void subscribe(Subscriber<?, ?> listener) {
|
||||
public void subscribe(Subscriber<? extends EventType> listener) {
|
||||
eventsHolder.add(listener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unsubscribe(Subscriber<?, ?> listener) {
|
||||
public void unsubscribe(Subscriber<? extends EventType> listener) {
|
||||
eventsHolder.remove(listener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> void post(T event) {
|
||||
public <T extends EventType> void post(T event) {
|
||||
long seq = ringBuffer.next();
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
@@ -93,10 +93,10 @@ public class DisruptorEventBus implements EventBus {
|
||||
eventsHolder.reset();
|
||||
}
|
||||
|
||||
private <T> void dispatchEvent(T event) {
|
||||
private <T extends EventType> void dispatchEvent(T event) {
|
||||
var classListeners = eventsHolder.get(event.getClass());
|
||||
if (classListeners != null) {
|
||||
for (Subscriber<?, ?> listener : classListeners) {
|
||||
for (Subscriber<?> listener : classListeners) {
|
||||
try {
|
||||
callListener(listener, event);
|
||||
} catch (Throwable e) {
|
||||
@@ -108,7 +108,7 @@ public class DisruptorEventBus implements EventBus {
|
||||
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private <T> void callListener(Subscriber<?, ?> subscriber, T event) {
|
||||
private <T> void callListener(Subscriber<?> subscriber, T event) {
|
||||
Class<T> eventClass = (Class<T>) subscriber.event();
|
||||
Consumer<EventType> action = (Consumer<EventType>) subscriber.handler();
|
||||
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
package org.toop.framework.eventbus.bus;
|
||||
|
||||
import org.toop.framework.eventbus.events.EventType;
|
||||
import org.toop.framework.eventbus.subscriber.Subscriber;
|
||||
|
||||
public interface EventBus {
|
||||
void subscribe(Subscriber<?, ?> subscriber);
|
||||
void unsubscribe(Subscriber<?, ?> subscriber);
|
||||
<T> void post(T event);
|
||||
void subscribe(Subscriber<? extends EventType> subscriber);
|
||||
void unsubscribe(Subscriber<? extends EventType> subscriber);
|
||||
<T extends EventType> void post(T event);
|
||||
void shutdown();
|
||||
void reset();
|
||||
}
|
||||
|
||||
@@ -1,23 +1,24 @@
|
||||
package org.toop.framework.eventbus.store;
|
||||
|
||||
import org.toop.framework.eventbus.events.EventType;
|
||||
import org.toop.framework.eventbus.subscriber.Subscriber;
|
||||
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
|
||||
public class AsyncSubscriberStore implements SubscriberStore {
|
||||
private final ConcurrentHashMap<Class<?>, ConcurrentLinkedQueue<Subscriber<?, ?>>> queues = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<Class<?>, Subscriber<?, ?>[]> snapshots = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<Class<? extends EventType>, ConcurrentLinkedQueue<Subscriber<? extends EventType>>> queues = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<Class<? extends EventType>, Subscriber<? extends EventType>[]> snapshots = new ConcurrentHashMap<>();
|
||||
|
||||
@Override
|
||||
public void add(Subscriber<?, ?> sub) {
|
||||
public void add(Subscriber<? extends EventType> sub) {
|
||||
queues.computeIfAbsent(sub.event(), _ -> new ConcurrentLinkedQueue<>()).add(sub);
|
||||
rebuildSnapshot(sub.event());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove(Subscriber<?, ?> sub) {
|
||||
ConcurrentLinkedQueue<Subscriber<?, ?>> queue = queues.get(sub.event());
|
||||
public void remove(Subscriber<? extends EventType> sub) {
|
||||
ConcurrentLinkedQueue<Subscriber<?>> queue = queues.get(sub.event());
|
||||
if (queue != null) {
|
||||
queue.remove(sub);
|
||||
rebuildSnapshot(sub.event());
|
||||
@@ -25,8 +26,8 @@ public class AsyncSubscriberStore implements SubscriberStore {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Subscriber<?, ?>[] get(Class<?> event) {
|
||||
return snapshots.getOrDefault(event, new Subscriber[0]);
|
||||
public Subscriber<? extends EventType>[] get(Class<? extends EventType> event) {
|
||||
return snapshots.getOrDefault(event, new Subscriber<?>[0]);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -35,12 +36,12 @@ public class AsyncSubscriberStore implements SubscriberStore {
|
||||
snapshots.clear();
|
||||
}
|
||||
|
||||
private void rebuildSnapshot(Class<?> event) {
|
||||
ConcurrentLinkedQueue<Subscriber<?, ?>> queue = queues.get(event);
|
||||
private void rebuildSnapshot(Class<? extends EventType> event) {
|
||||
ConcurrentLinkedQueue<Subscriber<?>> queue = queues.get(event);
|
||||
if (queue != null) {
|
||||
snapshots.put(event, queue.toArray(new Subscriber[0]));
|
||||
snapshots.put(event, queue.toArray(new Subscriber<?>[0]));
|
||||
} else {
|
||||
snapshots.put(event, new Subscriber[0]);
|
||||
snapshots.put(event, new Subscriber<?>[0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,25 +1,27 @@
|
||||
package org.toop.framework.eventbus.store;
|
||||
|
||||
import org.toop.framework.eventbus.events.EventType;
|
||||
import org.toop.framework.eventbus.subscriber.NamedSubscriber;
|
||||
import org.toop.framework.eventbus.subscriber.Subscriber;
|
||||
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public class DefaultSubscriberStore implements SubscriberStore {
|
||||
|
||||
private static final Subscriber<?, ?>[] EMPTY = new Subscriber[0];
|
||||
private static final Subscriber<? extends EventType>[] EMPTY = new Subscriber<?>[0];
|
||||
|
||||
private final ConcurrentHashMap<Class<?>, Subscriber<?, ?>[]> listeners =
|
||||
new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<Class<? extends EventType>, Subscriber<? extends EventType>[]>
|
||||
listeners = new ConcurrentHashMap<>();
|
||||
|
||||
@Override
|
||||
public void add(Subscriber<?, ?> sub) {
|
||||
public void add(Subscriber<? extends EventType> sub) {
|
||||
listeners.compute(sub.event(), (_, arr) -> {
|
||||
if (arr == null || arr.length == 0) {
|
||||
return new Subscriber<?, ?>[]{sub};
|
||||
return new Subscriber<?>[]{sub};
|
||||
}
|
||||
|
||||
int len = arr.length;
|
||||
Subscriber<?, ?>[] newArr = new Subscriber[len + 1];
|
||||
Subscriber<?>[] newArr = new Subscriber[len + 1];
|
||||
System.arraycopy(arr, 0, newArr, 0, len);
|
||||
newArr[len] = sub;
|
||||
return newArr;
|
||||
@@ -27,7 +29,7 @@ public class DefaultSubscriberStore implements SubscriberStore {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove(Subscriber<?, ?> sub) {
|
||||
public void remove(Subscriber<? extends EventType> sub) {
|
||||
listeners.computeIfPresent(sub.event(), (_, arr) -> {
|
||||
int len = arr.length;
|
||||
|
||||
@@ -36,7 +38,7 @@ public class DefaultSubscriberStore implements SubscriberStore {
|
||||
}
|
||||
|
||||
int keep = 0;
|
||||
for (Subscriber<?, ?> s : arr) {
|
||||
for (Subscriber<?> s : arr) {
|
||||
if (!s.equals(sub)) keep++;
|
||||
}
|
||||
|
||||
@@ -47,9 +49,9 @@ public class DefaultSubscriberStore implements SubscriberStore {
|
||||
return null;
|
||||
}
|
||||
|
||||
Subscriber<?, ?>[] newArr = new Subscriber[keep];
|
||||
Subscriber<?>[] newArr = new Subscriber[keep];
|
||||
int i = 0;
|
||||
for (Subscriber<?, ?> s : arr) {
|
||||
for (Subscriber<?> s : arr) {
|
||||
if (!s.equals(sub)) {
|
||||
newArr[i++] = s;
|
||||
}
|
||||
@@ -60,7 +62,7 @@ public class DefaultSubscriberStore implements SubscriberStore {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Subscriber<?, ?>[] get(Class<?> event) {
|
||||
public Subscriber<? extends EventType>[] get(Class<? extends EventType> event) {
|
||||
return listeners.getOrDefault(event, EMPTY);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
package org.toop.framework.eventbus.store;
|
||||
|
||||
import org.toop.framework.eventbus.events.EventType;
|
||||
import org.toop.framework.eventbus.subscriber.Subscriber;
|
||||
|
||||
public interface SubscriberStore {
|
||||
void add(Subscriber<?, ?> subscriber);
|
||||
void remove(Subscriber<?, ?> subscriber);
|
||||
Subscriber<?, ?>[] get(Class<?> event);
|
||||
void add(Subscriber<? extends EventType> subscriber);
|
||||
void remove(Subscriber<? extends EventType> subscriber);
|
||||
Subscriber<? extends EventType>[] get(Class<? extends EventType> event);
|
||||
void reset();
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package org.toop.framework.eventbus.store;
|
||||
|
||||
import org.toop.framework.eventbus.events.EventType;
|
||||
import org.toop.framework.eventbus.subscriber.Subscriber;
|
||||
|
||||
import java.util.ArrayList;
|
||||
@@ -8,23 +9,23 @@ import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public class SyncSubscriberStore implements SubscriberStore {
|
||||
private final Map<Class<?>, List<Subscriber<?, ?>>> LISTENERS = new ConcurrentHashMap<>();
|
||||
private static final Subscriber<?, ?>[] EMPTY = new Subscriber[0];
|
||||
private final Map<Class<? extends EventType>, List<Subscriber<? extends EventType>>> LISTENERS = new ConcurrentHashMap<>();
|
||||
private static final Subscriber<? extends EventType>[] EMPTY = new Subscriber<?>[0];
|
||||
|
||||
@Override
|
||||
public void add(Subscriber<?, ?> sub) {
|
||||
public void add(Subscriber<? extends EventType> sub) {
|
||||
LISTENERS.computeIfAbsent(sub.event(), _ -> new ArrayList<>()).add(sub);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove(Subscriber<?, ?> sub) {
|
||||
public void remove(Subscriber<? extends EventType> sub) {
|
||||
LISTENERS.getOrDefault(sub.event(), new ArrayList<>()).remove(sub);
|
||||
LISTENERS.entrySet().removeIf(entry -> entry.getValue().isEmpty());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Subscriber<?, ?>[] get(Class<?> event) {
|
||||
List<Subscriber<?, ?>> list = LISTENERS.get(event);
|
||||
public Subscriber<? extends EventType>[] get(Class<? extends EventType> event) {
|
||||
List<Subscriber<? extends EventType>> list = LISTENERS.get(event);
|
||||
if (list == null || list.isEmpty()) return EMPTY;
|
||||
return list.toArray(EMPTY);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
package org.toop.framework.eventbus.subscriber;
|
||||
|
||||
import org.toop.framework.eventbus.events.EventType;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public record DefaultNamedSubscriber<K extends EventType>(String id, Class<K> event, Consumer<K> handler)
|
||||
implements NamedSubscriber<K> {}
|
||||
@@ -1,5 +1,8 @@
|
||||
package org.toop.framework.eventbus.subscriber;
|
||||
|
||||
import org.toop.framework.eventbus.events.EventType;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public record DefaultSubscriber<K>(String id, Class<K> event, Consumer<K> handler) implements NamedSubscriber<K> {}
|
||||
public record DefaultSubscriber<K extends EventType>(Class<K> event, Consumer<K> handler) implements Subscriber<K> {}
|
||||
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
package org.toop.framework.eventbus.subscriber;
|
||||
|
||||
public interface HasId<ID> {
|
||||
ID id();
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
package org.toop.framework.eventbus.subscriber;
|
||||
|
||||
public interface IdSubscriber<T> extends Subscriber<Long, T> {}
|
||||
import org.toop.framework.eventbus.events.EventType;
|
||||
|
||||
public interface IdSubscriber<K extends EventType> extends Subscriber<K>, HasId<Long> {}
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
package org.toop.framework.eventbus.subscriber;
|
||||
|
||||
import org.toop.framework.eventbus.events.EventType;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public record LongIdSubscriber<K>(Long id, Class<K> event, Consumer<K> handler) implements IdSubscriber<K> {}
|
||||
public record LongIdSubscriber<K extends EventType>(Long id, Class<K> event, Consumer<K> handler)
|
||||
implements IdSubscriber<K> {}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
package org.toop.framework.eventbus.subscriber;
|
||||
|
||||
public interface NamedSubscriber<T> extends Subscriber<String, T> {}
|
||||
import org.toop.framework.eventbus.events.EventType;
|
||||
|
||||
public interface NamedSubscriber<K extends EventType> extends Subscriber<K>, HasId<String> {}
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
package org.toop.framework.eventbus.subscriber;
|
||||
|
||||
import org.toop.framework.eventbus.events.EventType;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public interface Subscriber<ID, K> {
|
||||
ID id();
|
||||
public interface Subscriber<K extends EventType> {
|
||||
Class<K> event();
|
||||
Consumer<K> handler();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
package org.toop.framework.gameFramework;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface LongPairConsumer {
|
||||
void accept(long a, long b);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package org.toop.framework.gameFramework.controller;
|
||||
|
||||
import org.toop.framework.gameFramework.model.game.SupportsOnlinePlay;
|
||||
import org.toop.framework.gameFramework.model.game.threadBehaviour.Controllable;
|
||||
import org.toop.framework.networking.events.NetworkEvents;
|
||||
|
||||
public interface GameController extends Controllable, UpdatesGameUI {
|
||||
/** Called when it is this player's turn to make a move. */
|
||||
void onYourTurn(NetworkEvents.YourTurnResponse event);
|
||||
|
||||
/** Called when a move from another player is received. */
|
||||
void onMoveReceived(NetworkEvents.GameMoveResponse event);
|
||||
|
||||
/** Called when the game has finished, with the final result. */
|
||||
void gameFinished(NetworkEvents.GameResultResponse event);
|
||||
|
||||
void sendMove(long clientId, long move);
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
package org.toop.framework.gameFramework.model.game;
|
||||
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public abstract class AbstractGame<T extends TurnBasedGame<T>> implements TurnBasedGame<T> {
|
||||
private final int playerCount; // How many players are playing
|
||||
private final Player<T>[] players;
|
||||
private int turn = 0; // What turn it is in the game
|
||||
|
||||
/** Constant representing an empty position on the board. */
|
||||
public static final int EMPTY = -1;
|
||||
|
||||
/** Number of rows in the game board. */
|
||||
private final int rowSize;
|
||||
|
||||
/** Number of columns in the game board. */
|
||||
private final int columnSize;
|
||||
|
||||
/** The game board stored as a one-dimensional array. */
|
||||
private final int[] board;
|
||||
|
||||
|
||||
|
||||
protected AbstractGame(int rowSize, int columnSize, int playerCount, Player<T>[] players) {
|
||||
assert rowSize > 0 && columnSize > 0;
|
||||
|
||||
this.rowSize = rowSize;
|
||||
this.columnSize = columnSize;
|
||||
|
||||
this.players = players;
|
||||
|
||||
board = new int[rowSize * columnSize];
|
||||
Arrays.fill(board, EMPTY);
|
||||
|
||||
this.playerCount = playerCount;
|
||||
}
|
||||
|
||||
protected AbstractGame(AbstractGame<T> other){
|
||||
this.rowSize = other.rowSize;
|
||||
this.columnSize = other.columnSize;
|
||||
this.board = other.board.clone();
|
||||
this.playerCount = other.playerCount;
|
||||
this.turn = other.turn;
|
||||
// TODO: Make this a deep copy, add deep copy interface to Player
|
||||
this.players = other.players;
|
||||
|
||||
}
|
||||
|
||||
public static boolean contains(int[] array, int value) {
|
||||
// O(n)
|
||||
for (int element : array){
|
||||
if (element == value) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public Player<T> getPlayer(int index) {
|
||||
return players[index];
|
||||
}
|
||||
|
||||
public int getPlayerCount(){return this.playerCount;}
|
||||
|
||||
protected void nextTurn() {
|
||||
turn += 1;
|
||||
}
|
||||
|
||||
public int getCurrentTurn() {
|
||||
return turn % playerCount;
|
||||
}
|
||||
|
||||
protected void setBoard(int position) {
|
||||
setBoard(position, getCurrentTurn());
|
||||
}
|
||||
|
||||
protected void setBoard(int position, int player) {
|
||||
this.board[position] = player;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of rows in the board.
|
||||
*
|
||||
* @return number of rows
|
||||
*/
|
||||
public int getRowSize() {
|
||||
return this.rowSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of columns in the board.
|
||||
*
|
||||
* @return number of columns
|
||||
*/
|
||||
public int getColumnSize() {
|
||||
return this.columnSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a copy of the current board state.
|
||||
*
|
||||
* @return a cloned array representing the board
|
||||
*/
|
||||
public int[] getBoard() {
|
||||
return this.board.clone();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package org.toop.framework.gameFramework.model.game;
|
||||
|
||||
public interface BoardProvider {
|
||||
long[] getBoard();
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
package org.toop.framework.gameFramework.model.game;
|
||||
|
||||
public interface DeepCopyable<T extends TurnBasedGame<T>> {
|
||||
public interface DeepCopyable<T> {
|
||||
T deepCopy();
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ public interface Playable {
|
||||
*
|
||||
* @return an array of integers representing legal moves
|
||||
*/
|
||||
int[] getLegalMoves();
|
||||
long getLegalMoves();
|
||||
|
||||
/**
|
||||
* Plays the given move and returns the resulting game state.
|
||||
@@ -20,5 +20,5 @@ public interface Playable {
|
||||
* @param move the move to apply
|
||||
* @return the {@link GameState} and additional info after the move
|
||||
*/
|
||||
PlayResult play(int move);
|
||||
PlayResult play(long move);
|
||||
}
|
||||
|
||||
@@ -10,11 +10,11 @@ import org.toop.framework.networking.events.NetworkEvents;
|
||||
public interface SupportsOnlinePlay {
|
||||
|
||||
/** Called when it is this player's turn to make a move. */
|
||||
void onYourTurn(NetworkEvents.YourTurnResponse event);
|
||||
void onYourTurn(long clientId);
|
||||
|
||||
/** Called when a move from another player is received. */
|
||||
void onMoveReceived(NetworkEvents.GameMoveResponse event);
|
||||
void onMoveReceived(long move);
|
||||
|
||||
/** Called when the game has finished, with the final result. */
|
||||
void gameFinished(NetworkEvents.GameResultResponse event);
|
||||
void gameFinished(String condition);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package org.toop.framework.gameFramework.model.game;
|
||||
|
||||
public interface TurnBasedGame<T extends TurnBasedGame<T>> extends Playable, DeepCopyable<T>, PlayerProvider<T> {
|
||||
public interface TurnBasedGame<T extends TurnBasedGame<T>> extends Playable, DeepCopyable<T>, PlayerProvider<T>, BoardProvider {
|
||||
int getCurrentTurn();
|
||||
int getPlayerCount();
|
||||
int getWinner();
|
||||
}
|
||||
|
||||
@@ -2,9 +2,12 @@ package org.toop.framework.gameFramework.model.game.threadBehaviour;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.toop.framework.gameFramework.LongPairConsumer;
|
||||
import org.toop.framework.gameFramework.controller.GameController;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* Base class for thread-based game behaviours.
|
||||
@@ -13,8 +16,9 @@ import java.util.concurrent.atomic.AtomicBoolean;
|
||||
* a running flag, a game reference, and a logger.
|
||||
* Subclasses implement the actual game-loop logic.
|
||||
*/
|
||||
public abstract class AbstractThreadBehaviour<T extends TurnBasedGame<T>> implements ThreadBehaviour<T> {
|
||||
|
||||
public abstract class AbstractThreadBehaviour<T extends TurnBasedGame<T>> implements ThreadBehaviour {
|
||||
private LongPairConsumer onSendMove;
|
||||
private Runnable onUpdateUI;
|
||||
/** Indicates whether the game loop or event processing is active. */
|
||||
protected final AtomicBoolean isRunning = new AtomicBoolean();
|
||||
|
||||
@@ -32,4 +36,26 @@ public abstract class AbstractThreadBehaviour<T extends TurnBasedGame<T>> implem
|
||||
public AbstractThreadBehaviour(T game) {
|
||||
this.game = game;
|
||||
}
|
||||
|
||||
protected void updateUI(){
|
||||
if (onUpdateUI != null) {
|
||||
onUpdateUI.run();
|
||||
}
|
||||
}
|
||||
|
||||
protected void sendMove(long clientId, long move){
|
||||
if (onSendMove != null) {
|
||||
onSendMove.accept(clientId, move);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setOnUpdateUI(Runnable onUpdateUI) {
|
||||
this.onUpdateUI = onUpdateUI;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setOnSendMove(LongPairConsumer onSendMove) {
|
||||
this.onSendMove = onSendMove;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,18 @@
|
||||
package org.toop.framework.gameFramework.model.game.threadBehaviour;
|
||||
|
||||
import org.toop.framework.gameFramework.LongPairConsumer;
|
||||
import org.toop.framework.gameFramework.controller.GameController;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* Strategy interface for controlling game thread behavior.
|
||||
* <p>
|
||||
* Defines how a game's execution is started, stopped, and which player is active.
|
||||
*/
|
||||
public interface ThreadBehaviour<T extends TurnBasedGame<T>> extends Controllable {
|
||||
public interface ThreadBehaviour extends Controllable {
|
||||
void setOnUpdateUI(Runnable onUpdateUI);
|
||||
void setOnSendMove(LongPairConsumer onSendMove);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
package org.toop.framework.gameFramework.model.player;
|
||||
|
||||
import org.toop.framework.gameFramework.model.game.DeepCopyable;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
|
||||
public interface AI<T extends TurnBasedGame<T>> extends MoveProvider<T>, DeepCopyable<AI<T>> {
|
||||
}
|
||||
@@ -12,6 +12,6 @@ import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
*
|
||||
* @param <T> the specific type of game this AI can play, extending {@link GameR}
|
||||
*/
|
||||
public abstract class AbstractAI<T extends TurnBasedGame> implements MoveProvider<T> {
|
||||
public abstract class AbstractAI<T extends TurnBasedGame<T>> implements AI<T> {
|
||||
// Concrete AI implementations should override findBestMove(T game, int depth)
|
||||
}
|
||||
|
||||
@@ -5,43 +5,65 @@ import org.apache.logging.log4j.Logger;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
|
||||
/**
|
||||
* Abstract class representing a player in a game.
|
||||
* <p>
|
||||
* Players are entities that can make moves based on the current state of a game.
|
||||
* 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>
|
||||
* Base class for players in a turn-based game.
|
||||
*
|
||||
* @param <T> the game type
|
||||
*/
|
||||
public abstract class AbstractPlayer<T extends TurnBasedGame<T>> implements Player<T> {
|
||||
private int playerIndex = -1;
|
||||
|
||||
private Logger logger = LogManager.getLogger(this.getClass());
|
||||
|
||||
private final Logger logger = LogManager.getLogger(this.getClass());
|
||||
private final String name;
|
||||
|
||||
/**
|
||||
* Creates a new player with the given name.
|
||||
*
|
||||
* @param name the player 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>
|
||||
* Creates a copy of another player.
|
||||
*
|
||||
* @param gameCopy a snapshot of the current game state
|
||||
* @return an integer representing the chosen move
|
||||
* @throws UnsupportedOperationException if the method is not overridden
|
||||
* @param other the player to copy
|
||||
*/
|
||||
public int getMove(T gameCopy) {
|
||||
logger.error("Method getMove not implemented.");
|
||||
throw new UnsupportedOperationException("Not supported yet.");
|
||||
protected AbstractPlayer(AbstractPlayer<T> other) {
|
||||
this.name = other.name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the player's move for the given game state.
|
||||
* A deep copy is provided so the player cannot modify the real state.
|
||||
* <p>
|
||||
* This method uses the Template Method Pattern: it defines the fixed
|
||||
* algorithm and delegates the variable part to {@link #determineMove(T)}.
|
||||
*
|
||||
* @param game the current game
|
||||
* @return the chosen move
|
||||
*/
|
||||
public final long getMove(T game) {
|
||||
return determineMove(game.deepCopy());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Determines the player's move using a safe copy of the game.
|
||||
* <p>
|
||||
* This method is called by {@link #getMove(T)} and should contain
|
||||
* the player's strategy for choosing a move.
|
||||
*
|
||||
* @param gameCopy a deep copy of the game
|
||||
* @return the chosen move
|
||||
*/
|
||||
protected abstract long determineMove(T gameCopy);
|
||||
|
||||
|
||||
/**
|
||||
* Returns the player's name.
|
||||
*
|
||||
* @return the name
|
||||
*/
|
||||
public String getName() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
@@ -2,6 +2,6 @@ package org.toop.framework.gameFramework.model.player;
|
||||
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
|
||||
public interface MoveProvider<T extends TurnBasedGame> {
|
||||
int getMove(T game);
|
||||
public interface MoveProvider<T extends TurnBasedGame<T>> {
|
||||
long getMove(T game);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package org.toop.framework.gameFramework.model.player;
|
||||
|
||||
import org.toop.framework.gameFramework.model.game.DeepCopyable;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
|
||||
public interface Player<T extends TurnBasedGame<T>> extends NameProvider, MoveProvider<T> {
|
||||
public interface Player<T extends TurnBasedGame<T>> extends NameProvider, MoveProvider<T>, DeepCopyable<Player<T>> {
|
||||
}
|
||||
|
||||
@@ -10,10 +10,6 @@ import org.toop.framework.eventbus.events.GenericEvent;
|
||||
* player actions, and game completion.
|
||||
*/
|
||||
public class GUIEvents extends EventsBase {
|
||||
|
||||
/** Event to refresh or redraw the game canvas. */
|
||||
public record RefreshGameCanvas() implements GenericEvent {}
|
||||
|
||||
/**
|
||||
* Event indicating the game has ended.
|
||||
*
|
||||
@@ -23,8 +19,8 @@ public class GUIEvents extends EventsBase {
|
||||
public record GameEnded(boolean winOrTie, int winner) implements GenericEvent {}
|
||||
|
||||
/** Event indicating a player has attempted a move. */
|
||||
public record PlayerAttemptedMove(int move) implements GenericEvent {}
|
||||
public record PlayerAttemptedMove(long move) implements GenericEvent {}
|
||||
|
||||
/** Event indicating a player is hovering over a move (for UI feedback). */
|
||||
public record PlayerMoveHovered(int move) implements GenericEvent {}
|
||||
public record PlayerMoveHovered(long move) implements GenericEvent {}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,9 @@ package org.toop.framework.resource.resources;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Locale;
|
||||
|
||||
import org.toop.framework.resource.ResourceManager;
|
||||
import org.toop.framework.resource.ResourceMeta;
|
||||
import org.toop.framework.settings.Settings;
|
||||
|
||||
public class SettingsAsset extends JsonAsset<Settings> {
|
||||
@@ -54,6 +57,10 @@ public class SettingsAsset extends JsonAsset<Settings> {
|
||||
return getContent().firstReversi;
|
||||
}
|
||||
|
||||
public boolean getSwitchReversi() {
|
||||
return getContent().switchReversi;
|
||||
}
|
||||
|
||||
public void setVolume(int volume) {
|
||||
getContent().volume = volume;
|
||||
save();
|
||||
@@ -108,4 +115,51 @@ public class SettingsAsset extends JsonAsset<Settings> {
|
||||
getContent().firstReversi = firstReversi;
|
||||
save();
|
||||
}
|
||||
|
||||
public void setSwitchReversi(boolean switchReversi) {
|
||||
getContent().switchReversi = switchReversi;
|
||||
save();
|
||||
}
|
||||
|
||||
public void setContent(Settings settings) {
|
||||
setVolume(settings.volume);
|
||||
setFxVolume(settings.fxVolume);
|
||||
setMusicVolume(settings.musicVolume);
|
||||
setLocale(settings.locale);
|
||||
setFullscreen(settings.fullScreen);
|
||||
setTheme(settings.theme);
|
||||
setLayoutSize(settings.layoutSize);
|
||||
setTutorialFlag(settings.showTutorials);
|
||||
setFirstTTT(settings.firstTTT);
|
||||
setFirstConnect4(settings.firstConnect4);
|
||||
setFirstReversi(settings.firstReversi);
|
||||
setSwitchReversi(settings.switchReversi);
|
||||
}
|
||||
|
||||
public static SettingsAsset getPath() {
|
||||
SettingsAsset settingsAsset;
|
||||
try {
|
||||
settingsAsset = ResourceManager.get("settings.json");
|
||||
} catch (Exception e) {
|
||||
String os = System.getProperty("os.name").toLowerCase();
|
||||
String basePath;
|
||||
|
||||
if (os.contains("win")) {
|
||||
basePath = System.getenv("APPDATA");
|
||||
if (basePath == null) {
|
||||
basePath = System.getProperty("user.home");
|
||||
}
|
||||
} else if (os.contains("mac")) {
|
||||
basePath = System.getProperty("user.home") + "/Library/Application Support";
|
||||
} else {
|
||||
basePath = System.getProperty("user.home") + "/.config";
|
||||
}
|
||||
|
||||
File settingsFile =
|
||||
new File(basePath + File.separator + "ISY1" + File.separator + "settings.json");
|
||||
settingsAsset = new SettingsAsset(settingsFile);
|
||||
ResourceManager.addAsset(new ResourceMeta<>("settings.json", settingsAsset));
|
||||
}
|
||||
return settingsAsset;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,5 +12,5 @@ public class Settings {
|
||||
public Boolean firstReversi;
|
||||
public Boolean firstTTT;
|
||||
public Boolean firstConnect4;
|
||||
|
||||
public boolean switchReversi = false;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
package org.toop.framework.settings;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.toop.framework.resource.resources.SettingsAsset;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
public class SettingsAssetTest {
|
||||
|
||||
private Settings copySettings;
|
||||
private SettingsAsset settingsAsset;
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
this.settingsAsset = SettingsAsset.getPath();
|
||||
Settings original = settingsAsset.getContent();
|
||||
this.copySettings = new Settings();
|
||||
this.copySettings.volume = original.volume;
|
||||
this.copySettings.fxVolume = original.fxVolume;
|
||||
this.copySettings.musicVolume = original.musicVolume;
|
||||
this.copySettings.locale = original.locale;
|
||||
this.copySettings.fullScreen = original.fullScreen;
|
||||
this.copySettings.theme = original.theme;
|
||||
this.copySettings.layoutSize = original.layoutSize;
|
||||
this.copySettings.showTutorials = original.showTutorials;
|
||||
this.copySettings.firstTTT = original.firstTTT;
|
||||
this.copySettings.firstConnect4 = original.firstConnect4;
|
||||
this.copySettings.firstReversi = original.firstReversi;
|
||||
}
|
||||
|
||||
|
||||
@AfterEach
|
||||
void teardown() {
|
||||
settingsAsset.setContent(copySettings);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testVolume() {
|
||||
settingsAsset.setVolume(55);
|
||||
assertEquals(55, settingsAsset.getVolume());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testFxVolume() {
|
||||
settingsAsset.setFxVolume(33);
|
||||
assertEquals(33, settingsAsset.getFxVolume());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMusicVolume() {
|
||||
settingsAsset.setMusicVolume(77);
|
||||
assertEquals(77, settingsAsset.getMusicVolume());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testLocale() {
|
||||
settingsAsset.setLocale("es-ES");
|
||||
assertEquals(Locale.forLanguageTag("es-ES"), settingsAsset.getLocale());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testFullscreen() {
|
||||
settingsAsset.setFullscreen(true);
|
||||
assertTrue(settingsAsset.getFullscreen());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testTheme() {
|
||||
settingsAsset.setTheme("dark");
|
||||
assertEquals("dark", settingsAsset.getTheme());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testLayoutsize() {
|
||||
settingsAsset.setLayoutSize("large");
|
||||
assertEquals("large", settingsAsset.getLayoutSize());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testTutorialflag() {
|
||||
settingsAsset.setTutorialFlag(false);
|
||||
assertFalse(settingsAsset.getTutorialFlag());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testTTT() {
|
||||
settingsAsset.setFirstTTT(true);
|
||||
assertTrue(settingsAsset.getFirstTTT());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testConnect4() {
|
||||
settingsAsset.setFirstConnect4(false);
|
||||
assertFalse(settingsAsset.getFirstConnect4());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testReversi() {
|
||||
settingsAsset.setFirstReversi(true);
|
||||
assertTrue(settingsAsset.getFirstReversi());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testReplaceFields() {
|
||||
Settings newSettings = new Settings();
|
||||
newSettings.volume = 10;
|
||||
newSettings.fxVolume = 20;
|
||||
newSettings.musicVolume = 30;
|
||||
newSettings.locale = "fr-FR";
|
||||
newSettings.fullScreen = true;
|
||||
newSettings.theme = "light";
|
||||
newSettings.layoutSize = "medium";
|
||||
newSettings.showTutorials = false;
|
||||
newSettings.firstTTT = false;
|
||||
newSettings.firstConnect4 = true;
|
||||
newSettings.firstReversi = false;
|
||||
settingsAsset.setContent(newSettings);
|
||||
assertEquals(10, settingsAsset.getVolume());
|
||||
assertEquals(20, settingsAsset.getFxVolume());
|
||||
assertEquals(30, settingsAsset.getMusicVolume());
|
||||
assertEquals(Locale.forLanguageTag("fr-FR"), settingsAsset.getLocale());
|
||||
assertTrue(settingsAsset.getFullscreen());
|
||||
assertEquals("light", settingsAsset.getTheme());
|
||||
assertEquals("medium", settingsAsset.getLayoutSize());
|
||||
assertFalse(settingsAsset.getTutorialFlag());
|
||||
assertFalse(settingsAsset.getFirstTTT());
|
||||
assertTrue(settingsAsset.getFirstConnect4());
|
||||
assertFalse(settingsAsset.getFirstReversi());
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
*/
|
||||
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, 1);
|
||||
this.setBoard(28, 0);
|
||||
this.setBoard(35, 0);
|
||||
this.setBoard(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 = 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,47 +1,55 @@
|
||||
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;
|
||||
|
||||
/**
|
||||
* Represents a player controlled by an AI in a game.
|
||||
* <p>
|
||||
* 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>
|
||||
* Represents a player controlled by an AI.
|
||||
*
|
||||
* @param <T> the specific type of game this AI player can play
|
||||
* @param <T> the type of turn-based game
|
||||
*/
|
||||
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.
|
||||
* Creates a new AI-controlled player.
|
||||
*
|
||||
* @param ai the AI instance that determines moves for this player
|
||||
* @param ai the AI controlling this player
|
||||
* @param name the player's name
|
||||
*/
|
||||
public ArtificialPlayer(MoveProvider<T> ai, String name) {
|
||||
public ArtificialPlayer(AI<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>
|
||||
* Creates a copy of another AI-controlled player.
|
||||
*
|
||||
* @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}
|
||||
* @param other the player to copy
|
||||
*/
|
||||
public int getMove(T gameCopy) {
|
||||
public ArtificialPlayer(ArtificialPlayer<T> other) {
|
||||
super(other);
|
||||
this.ai = other.ai.deepCopy();
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines the player's move using the AI.
|
||||
*
|
||||
* @param gameCopy a copy of the current game
|
||||
* @return the move chosen by the AI
|
||||
*/
|
||||
protected long determineMove(T gameCopy) {
|
||||
return ai.getMove(gameCopy);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a deep copy of this AI player.
|
||||
*
|
||||
* @return a copy of this player
|
||||
*/
|
||||
@Override
|
||||
public ArtificialPlayer<T> deepCopy() {
|
||||
return new ArtificialPlayer<>(this);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,70 +6,82 @@ import org.toop.framework.gameFramework.model.player.AbstractPlayer;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
|
||||
/**
|
||||
* Represents a local player who provides moves manually.
|
||||
*
|
||||
* @param <T> the type of turn-based game
|
||||
*/
|
||||
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 = new CompletableFuture<>();
|
||||
|
||||
/**
|
||||
* Creates a new local player with the given name.
|
||||
*
|
||||
* @param name the player's name
|
||||
*/
|
||||
public LocalPlayer(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getMove(T gameCopy) {
|
||||
return getValidMove(gameCopy);
|
||||
/**
|
||||
* Creates a copy of another local player.
|
||||
*
|
||||
* @param other the player to copy
|
||||
*/
|
||||
public LocalPlayer(LocalPlayer<T> other) {
|
||||
super(other);
|
||||
this.LastMove = other.LastMove;
|
||||
}
|
||||
|
||||
public void setMove(int move) {
|
||||
/**
|
||||
* Waits for and returns the player's next legal move.
|
||||
*
|
||||
* @param gameCopy a copy of the current game
|
||||
* @return the chosen move
|
||||
*/
|
||||
@Override
|
||||
protected long determineMove(T gameCopy) {
|
||||
long legalMoves = gameCopy.getLegalMoves();
|
||||
long move;
|
||||
|
||||
do {
|
||||
move = getLastMove();
|
||||
} while ((legalMoves & move) == 0);
|
||||
|
||||
return move;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the player's last move.
|
||||
*
|
||||
* @param move the move to set
|
||||
*/
|
||||
public void setLastMove(long 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(T gameCopy) {
|
||||
LastMove = new CompletableFuture<>();
|
||||
int move = -1;
|
||||
/**
|
||||
* Waits for the next move from the player.
|
||||
*
|
||||
* @return the chosen move or 0 if interrupted
|
||||
*/
|
||||
private long getLastMove() {
|
||||
LastMove = new CompletableFuture<>(); // Reset the future
|
||||
try {
|
||||
move = LastMove.get();
|
||||
} catch (InterruptedException | ExecutionException e) {
|
||||
// TODO: Add proper logging.
|
||||
e.printStackTrace();
|
||||
return LastMove.get();
|
||||
} catch (ExecutionException | InterruptedException e) {
|
||||
return 0;
|
||||
}
|
||||
return move;
|
||||
}
|
||||
|
||||
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.deepCopy());
|
||||
while (!contains(validMoves, move)) {
|
||||
System.out.println("Not a valid move, try again");
|
||||
move = getMove2(gameCopy.deepCopy());
|
||||
/**
|
||||
* Creates a deep copy of this local player.
|
||||
*
|
||||
* @return a copy of this player
|
||||
*/
|
||||
@Override
|
||||
public LocalPlayer<T> deepCopy() {
|
||||
return new LocalPlayer<>(this);
|
||||
}
|
||||
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;
|
||||
}*/
|
||||
}
|
||||
|
||||
@@ -2,25 +2,50 @@ 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.
|
||||
* <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>
|
||||
* Represents a player that participates online.
|
||||
*
|
||||
* @param <T> the type of turn-based game
|
||||
*/
|
||||
public class OnlinePlayer<T extends TurnBasedGame<T>> extends AbstractPlayer<T> {
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Creates a new online player with the given name.
|
||||
*
|
||||
* @param name the name of the player
|
||||
*/
|
||||
public OnlinePlayer(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a copy of another online player.
|
||||
*
|
||||
* @param other the player to copy
|
||||
*/
|
||||
public OnlinePlayer(OnlinePlayer<T> other) {
|
||||
super(other);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
* <p>
|
||||
* This method is not supported for online players.
|
||||
*
|
||||
* @throws UnsupportedOperationException always
|
||||
*/
|
||||
@Override
|
||||
protected long determineMove(T gameCopy) {
|
||||
throw new UnsupportedOperationException("An online player does not support determining move");
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public Player<T> deepCopy() {
|
||||
return new OnlinePlayer<>(this);
|
||||
}
|
||||
}
|
||||
|
||||
165
game/src/main/java/org/toop/game/players/ai/MiniMaxAI.java
Normal file
165
game/src/main/java/org/toop/game/players/ai/MiniMaxAI.java
Normal file
@@ -0,0 +1,165 @@
|
||||
package org.toop.game.players.ai;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
38
game/src/main/java/org/toop/game/players/ai/RandomAI.java
Normal file
38
game/src/main/java/org/toop/game/players/ai/RandomAI.java
Normal file
@@ -0,0 +1,38 @@
|
||||
package org.toop.game.players.ai;
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -1,121 +0,0 @@
|
||||
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.*;
|
||||
|
||||
final class TicTacToeAIRTest {
|
||||
|
||||
private final TicTacToeAIR ai = new TicTacToeAIR(9);
|
||||
|
||||
// Helper: play multiple moves in sequence on a fresh board
|
||||
private TicTacToeR playSequence(int... moves) {
|
||||
TicTacToeR game = new TicTacToeR(new Player[2]);
|
||||
for (int move : moves) {
|
||||
game.play(move);
|
||||
}
|
||||
return game;
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("AI first move must choose a corner")
|
||||
void testFirstMoveIsCorner() {
|
||||
TicTacToeR game = new TicTacToeR(new Player[2]);
|
||||
int move = ai.getMove(game);
|
||||
|
||||
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.getMove(game);
|
||||
|
||||
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.getMove(game);
|
||||
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.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(new Player[2]);
|
||||
// Fill board alternating
|
||||
for (int i = 0; i < 9; i++) full.play(i);
|
||||
|
||||
int move = ai.getMove(full);
|
||||
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.getMove(game);
|
||||
|
||||
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(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.getMove(game);
|
||||
assertEquals(5, move, "AI must choose the only move that avoids losing");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user