mirror of
https://github.com/2OOP/pism.git
synced 2026-02-04 19:04:49 +00:00
Compare commits
41 Commits
TimerSongD
...
b33c85419c
| Author | SHA1 | Date | |
|---|---|---|---|
| b33c85419c | |||
| 449387c8ed | |||
| 237f708a54 | |||
| 64016bd3f0 | |||
| 38de4f2156 | |||
| b3a97a8978 | |||
| 3c283092a3 | |||
| 7d90d475f1 | |||
| 05dcea03a1 | |||
| 76f836b1c1 | |||
| 6607918635 | |||
| 86e740a34a | |||
|
|
be57e25a48 | ||
| 0993abeec7 | |||
|
|
7ea45586ae | ||
| 788cf08b49 | |||
|
|
d74e7b4517 | ||
| 21b489bbe7 | |||
| f4ee992166 | |||
|
|
f60df73b66 | ||
| 34d83ff7a5 | |||
| 8ca2399e6a | |||
| 8c75ac1471 | |||
|
|
f866eab8ba | ||
| b3d65e73a0 | |||
|
|
8d77f51355 | ||
|
|
040287ad70 | ||
|
|
740d2cf3db | ||
|
|
628e4f30b5 | ||
|
|
c25be04ff1 | ||
|
|
bc84171029 | ||
|
|
3c9b010dd3 | ||
|
|
4dbc4997a0 | ||
|
|
9f55f8e1c7 | ||
|
|
d9437c1b8a | ||
| c332033a06 | |||
|
|
3953762178 | ||
|
|
12a20a224e | ||
|
|
81740acd04 | ||
|
|
25c02c7ad0 | ||
|
|
ec0ce4ea37 |
@@ -11,30 +11,6 @@ import org.toop.framework.resource.resources.SoundEffectAsset;
|
||||
|
||||
public final class Main {
|
||||
static void main(String[] args) {
|
||||
initSystems();
|
||||
App.run(args);
|
||||
}
|
||||
|
||||
private static void initSystems() {
|
||||
ResourceManager.loadAssets(new ResourceLoader("app/src/main/resources/assets"));
|
||||
new Thread(() -> new NetworkingClientEventListener(new NetworkingClientManager())).start();
|
||||
|
||||
new Thread(() -> {
|
||||
MusicManager<MusicAsset> musicManager = new MusicManager<>(ResourceManager.getAllOfTypeAndRemoveWrapper(MusicAsset.class), true);
|
||||
SoundEffectManager<SoundEffectAsset> soundEffectManager = new SoundEffectManager<>(ResourceManager.getAllOfType(SoundEffectAsset.class));
|
||||
AudioVolumeManager audioVolumeManager = new AudioVolumeManager()
|
||||
.registerManager(VolumeControl.MASTERVOLUME, musicManager)
|
||||
.registerManager(VolumeControl.MASTERVOLUME, soundEffectManager)
|
||||
.registerManager(VolumeControl.FX, soundEffectManager)
|
||||
.registerManager(VolumeControl.MUSIC, musicManager);
|
||||
|
||||
new AudioEventListener<>(
|
||||
musicManager,
|
||||
soundEffectManager,
|
||||
audioVolumeManager
|
||||
).initListeners("medium-button-click.wav");
|
||||
|
||||
}).start();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,13 +1,26 @@
|
||||
package org.toop.app;
|
||||
|
||||
import javafx.application.Platform;
|
||||
import javafx.scene.paint.Color;
|
||||
import org.toop.Main;
|
||||
import org.toop.app.widget.Primitive;
|
||||
import org.toop.app.widget.Widget;
|
||||
import org.toop.app.widget.WidgetContainer;
|
||||
import org.toop.app.widget.complex.LoadingWidget;
|
||||
import org.toop.app.widget.display.SongDisplay;
|
||||
import org.toop.app.widget.popup.QuitPopup;
|
||||
import org.toop.app.widget.view.MainView;
|
||||
import org.toop.framework.audio.*;
|
||||
import org.toop.framework.audio.events.AudioEvents;
|
||||
import org.toop.framework.eventbus.EventFlow;
|
||||
import org.toop.framework.networking.NetworkingClientEventListener;
|
||||
import org.toop.framework.networking.NetworkingClientManager;
|
||||
import org.toop.framework.resource.ResourceLoader;
|
||||
import org.toop.framework.resource.ResourceManager;
|
||||
import org.toop.framework.resource.events.AssetLoaderEvents;
|
||||
import org.toop.framework.resource.resources.CssAsset;
|
||||
import org.toop.framework.resource.resources.MusicAsset;
|
||||
import org.toop.framework.resource.resources.SoundEffectAsset;
|
||||
import org.toop.local.AppContext;
|
||||
import org.toop.local.AppSettings;
|
||||
|
||||
@@ -32,14 +45,20 @@ public final class App extends Application {
|
||||
|
||||
@Override
|
||||
public void start(Stage stage) throws Exception {
|
||||
// Start loading localization
|
||||
ResourceManager.loadAssets(new ResourceLoader("app/src/main/resources/localization"));
|
||||
ResourceManager.loadAssets(new ResourceLoader("app/src/main/resources/style"));
|
||||
|
||||
final StackPane root = WidgetContainer.setup();
|
||||
final Scene scene = new Scene(root);
|
||||
|
||||
stage.setOpacity(0.0);
|
||||
|
||||
stage.setTitle(AppContext.getString("app-title"));
|
||||
stage.titleProperty().bind(AppContext.bindToKey("app-title"));
|
||||
|
||||
stage.setWidth(1080);
|
||||
stage.setHeight(720);
|
||||
stage.setWidth(0);
|
||||
stage.setHeight(0);
|
||||
|
||||
scene.getRoot();
|
||||
|
||||
@@ -47,14 +66,12 @@ public final class App extends Application {
|
||||
stage.setMinHeight(720);
|
||||
stage.setOnCloseRequest(event -> {
|
||||
event.consume();
|
||||
startQuit();
|
||||
quit();
|
||||
});
|
||||
|
||||
stage.setScene(scene);
|
||||
stage.setResizable(true);
|
||||
|
||||
stage.show();
|
||||
|
||||
App.stage = stage;
|
||||
App.scene = scene;
|
||||
|
||||
@@ -64,12 +81,102 @@ public final class App extends Application {
|
||||
App.isQuitting = false;
|
||||
|
||||
AppSettings.applySettings();
|
||||
new EventFlow().addPostEvent(new AudioEvents.StartBackgroundMusic()).asyncPostEvent();
|
||||
|
||||
WidgetContainer.add(Pos.CENTER, new MainView());
|
||||
WidgetContainer.add(Pos.BOTTOM_RIGHT, new SongDisplay());
|
||||
LoadingWidget loading = new LoadingWidget(Primitive.text(
|
||||
"Loading...", false), 0, 0, Integer.MAX_VALUE, false, false // Just set a high default
|
||||
);
|
||||
|
||||
WidgetContainer.setCurrentView(loading);
|
||||
|
||||
setOnLoadingSuccess(loading);
|
||||
|
||||
EventFlow loadingFlow = new EventFlow();
|
||||
|
||||
final boolean[] hasRun = {false};
|
||||
loadingFlow
|
||||
.listen(AssetLoaderEvents.LoadingProgressUpdate.class, e -> {
|
||||
if (!hasRun[0]) {
|
||||
hasRun[0] = true;
|
||||
try {
|
||||
Thread.sleep(100);
|
||||
} catch (InterruptedException ex) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
Platform.runLater(() -> stage.setOpacity(1.0));
|
||||
}
|
||||
|
||||
Platform.runLater(() -> loading.setMaxAmount(e.isLoadingAmount()));
|
||||
|
||||
Platform.runLater(() -> {
|
||||
try {
|
||||
loading.setAmount(e.hasLoadedAmount());
|
||||
} catch (Exception ex) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
});
|
||||
|
||||
if (e.hasLoadedAmount() >= e.isLoadingAmount()) {
|
||||
Platform.runLater(loading::triggerSuccess);
|
||||
loadingFlow.unsubscribe("init_loading");
|
||||
}
|
||||
|
||||
}, false, "init_loading");
|
||||
|
||||
// Start loading assets
|
||||
new Thread(() -> ResourceManager.loadAssets(new ResourceLoader("app/src/main/resources/assets")))
|
||||
.start();
|
||||
|
||||
stage.show();
|
||||
|
||||
}
|
||||
|
||||
private void setOnLoadingSuccess(LoadingWidget loading) {
|
||||
loading.setOnSuccess(() -> {
|
||||
initSystems();
|
||||
AppSettings.applyMusicVolumeSettings();
|
||||
new EventFlow().addPostEvent(new AudioEvents.StartBackgroundMusic()).postEvent();
|
||||
loading.hide();
|
||||
WidgetContainer.add(Pos.CENTER, new MainView());
|
||||
WidgetContainer.add(Pos.BOTTOM_RIGHT, new SongDisplay());
|
||||
stage.setOnCloseRequest(event -> {
|
||||
event.consume();
|
||||
startQuit();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private void initSystems() { // TODO Move to better place
|
||||
new Thread(() -> new NetworkingClientEventListener(new NetworkingClientManager())).start();
|
||||
|
||||
new Thread(() -> {
|
||||
MusicManager<MusicAsset> musicManager =
|
||||
new MusicManager<>(ResourceManager.getAllOfTypeAndRemoveWrapper(MusicAsset.class), true);
|
||||
|
||||
SoundEffectManager<SoundEffectAsset> soundEffectManager =
|
||||
new SoundEffectManager<>(ResourceManager.getAllOfType(SoundEffectAsset.class));
|
||||
|
||||
AudioVolumeManager audioVolumeManager = new AudioVolumeManager()
|
||||
.registerManager(VolumeControl.MASTERVOLUME, musicManager)
|
||||
.registerManager(VolumeControl.MASTERVOLUME, soundEffectManager)
|
||||
.registerManager(VolumeControl.FX, soundEffectManager)
|
||||
.registerManager(VolumeControl.MUSIC, musicManager);
|
||||
|
||||
new AudioEventListener<>(
|
||||
musicManager,
|
||||
soundEffectManager,
|
||||
audioVolumeManager
|
||||
).initListeners("medium-button-click.wav");
|
||||
|
||||
}).start();
|
||||
|
||||
// Threads must be ready, before continue, TODO use latch instead
|
||||
try {
|
||||
Thread.sleep(200);
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static void startQuit() {
|
||||
if (isQuitting) {
|
||||
return;
|
||||
|
||||
@@ -3,9 +3,7 @@ package org.toop.app;
|
||||
public class GameInformation {
|
||||
public enum Type {
|
||||
TICTACTOE(2, 5),
|
||||
REVERSI(2, 10),
|
||||
CONNECT4(2, 7),
|
||||
BATTLESHIP(2, 5);
|
||||
REVERSI(2, 10);
|
||||
|
||||
private final int playerCount;
|
||||
private final int maxDepth;
|
||||
|
||||
@@ -1,17 +1,26 @@
|
||||
package org.toop.app;
|
||||
|
||||
import org.toop.app.game.Connect4Game;
|
||||
import org.toop.app.game.ReversiGame;
|
||||
import org.toop.app.game.TicTacToeGame;
|
||||
import javafx.application.Platform;
|
||||
import javafx.geometry.Pos;
|
||||
import org.toop.app.gameControllers.*;
|
||||
import org.toop.app.widget.Primitive;
|
||||
import org.toop.app.widget.WidgetContainer;
|
||||
import org.toop.app.widget.complex.LoadingWidget;
|
||||
import org.toop.app.widget.popup.ChallengePopup;
|
||||
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.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.players.RandomAI;
|
||||
import org.toop.local.AppContext;
|
||||
|
||||
import java.util.List;
|
||||
@@ -22,6 +31,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;
|
||||
|
||||
@@ -31,24 +41,27 @@ public final class Server {
|
||||
private ServerView primary;
|
||||
private boolean isPolling = true;
|
||||
|
||||
private GameController gameController;
|
||||
|
||||
private final AtomicBoolean isSingleGame = new AtomicBoolean(false);
|
||||
|
||||
private ScheduledExecutorService scheduler;
|
||||
|
||||
private EventFlow eventFlow = new EventFlow();
|
||||
|
||||
public static GameInformation.Type gameToType(String game) {
|
||||
if (game.equalsIgnoreCase("tic-tac-toe")) {
|
||||
return GameInformation.Type.TICTACTOE;
|
||||
} else if (game.equalsIgnoreCase("reversi")) {
|
||||
return GameInformation.Type.REVERSI;
|
||||
} else if (game.equalsIgnoreCase("connect4")) {
|
||||
return GameInformation.Type.CONNECT4;
|
||||
// } else if (game.equalsIgnoreCase("battleship")) {
|
||||
// return GameInformation.Type.BATTLESHIP;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
// Server has to deal with ALL network related listen events. This "server" can then interact with the manager to make stuff happen.
|
||||
// This prevents data races where events get sent to the game manager but the manager isn't ready yet.
|
||||
public Server(String ip, String port, String user) {
|
||||
if (ip.split("\\.").length < 4) {
|
||||
new ErrorPopup("\"" + ip + "\" " + AppContext.getString("is-not-a-valid-ip-address"));
|
||||
@@ -69,27 +82,75 @@ public final class Server {
|
||||
return;
|
||||
}
|
||||
|
||||
new EventFlow()
|
||||
final int reconnectAttempts = 10;
|
||||
|
||||
LoadingWidget loading = new LoadingWidget(
|
||||
Primitive.text("connecting"), 0, 0, reconnectAttempts, true, true
|
||||
);
|
||||
|
||||
WidgetContainer.getCurrentView().transitionNext(loading);
|
||||
|
||||
var a = new EventFlow()
|
||||
.addPostEvent(NetworkEvents.StartClient.class,
|
||||
new TournamentNetworkingClient(),
|
||||
new NetworkingConnector(ip, parsedPort, 10, 1, TimeUnit.SECONDS)
|
||||
)
|
||||
.onResponse(NetworkEvents.StartClientResponse.class, e -> {
|
||||
this.user = user;
|
||||
clientId = e.clientId();
|
||||
new NetworkingConnector(ip, parsedPort, reconnectAttempts, 1, TimeUnit.SECONDS)
|
||||
);
|
||||
|
||||
new EventFlow().addPostEvent(new NetworkEvents.SendLogin(clientId, user)).postEvent();
|
||||
loading.setOnFailure(() -> {
|
||||
WidgetContainer.getCurrentView().transitionPrevious();
|
||||
a.unsubscribe("connecting");
|
||||
a.unsubscribe("startclient");
|
||||
WidgetContainer.add(
|
||||
Pos.CENTER,
|
||||
new ErrorPopup(AppContext.getString("connecting-failed") + " " + ip + ":" + port)
|
||||
);
|
||||
});
|
||||
|
||||
primary = new ServerView(user, this::sendChallenge, this::disconnect);
|
||||
WidgetContainer.getCurrentView().transitionNext(primary);
|
||||
a.onResponse(NetworkEvents.StartClientResponse.class, e -> {
|
||||
|
||||
startPopulateScheduler();
|
||||
populateGameList();
|
||||
if (!e.successful()) {
|
||||
return;
|
||||
}
|
||||
|
||||
}).postEvent();
|
||||
WidgetContainer.getCurrentView().transitionPrevious();
|
||||
|
||||
new EventFlow().listen(this::handleReceivedChallenge)
|
||||
.listen(this::handleMatchResponse);
|
||||
a.unsubscribe("connecting");
|
||||
a.unsubscribe("startclient");
|
||||
|
||||
this.user = user;
|
||||
clientId = e.clientId();
|
||||
|
||||
new EventFlow().addPostEvent(new NetworkEvents.SendLogin(clientId, user)).postEvent();
|
||||
|
||||
primary = new ServerView(user, this::sendChallenge, this::disconnect);
|
||||
WidgetContainer.getCurrentView().transitionNext(primary);
|
||||
|
||||
startPopulateScheduler();
|
||||
populateGameList();
|
||||
}, false, "startclient")
|
||||
.listen(
|
||||
NetworkEvents.ConnectTry.class,
|
||||
e -> Platform.runLater(
|
||||
() -> {
|
||||
try {
|
||||
loading.setAmount(e.amount());
|
||||
if (e.amount() >= loading.getMaxAmount()) {
|
||||
loading.triggerFailure();
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
),
|
||||
false, "connecting"
|
||||
)
|
||||
.postEvent();
|
||||
|
||||
eventFlow.listen(NetworkEvents.ChallengeResponse.class, this::handleReceivedChallenge, false)
|
||||
.listen(NetworkEvents.GameMatchResponse.class, this::handleMatchResponse, false)
|
||||
.listen(NetworkEvents.GameResultResponse.class, this::handleGameResult, false)
|
||||
.listen(NetworkEvents.GameMoveResponse.class, this::handleReceivedMove, false)
|
||||
.listen(NetworkEvents.YourTurnResponse.class, this::handleYourTurn, false);
|
||||
}
|
||||
|
||||
private void sendChallenge(String opponent) {
|
||||
@@ -102,10 +163,16 @@ public final class Server {
|
||||
}
|
||||
|
||||
private void handleMatchResponse(NetworkEvents.GameMatchResponse response) {
|
||||
if (!isPolling) return;
|
||||
// TODO: Redo all of this mess
|
||||
if (gameController != null) {
|
||||
gameController.stop();
|
||||
}
|
||||
|
||||
gameController = null;
|
||||
|
||||
//if (!isPolling) return;
|
||||
|
||||
String gameType = extractQuotedValue(response.gameType());
|
||||
|
||||
if (response.clientId() == clientId) {
|
||||
isPolling = false;
|
||||
onlinePlayers.clear();
|
||||
@@ -126,21 +193,61 @@ public final class Server {
|
||||
information.players[0].computerThinkTime = 1;
|
||||
information.players[1].name = response.opponent();
|
||||
|
||||
Runnable onGameOverRunnable = isSingleGame.get()? null: this::gameOver;
|
||||
/*switch (type){
|
||||
case TICTACTOE ->{
|
||||
players[myTurn] = new ArtificialPlayer<>(new TicTacToeAIR(), user);
|
||||
}
|
||||
case REVERSI ->{
|
||||
players[myTurn] = new ArtificialPlayer<>(new ReversiAIR(), user);
|
||||
}
|
||||
}*/
|
||||
|
||||
|
||||
|
||||
switch (type) {
|
||||
case TICTACTOE ->
|
||||
new TicTacToeGame(information, myTurn, this::forfeitGame, this::exitGame, this::sendMessage, onGameOverRunnable);
|
||||
case REVERSI ->
|
||||
new ReversiGame(information, myTurn, this::forfeitGame, this::exitGame, this::sendMessage, onGameOverRunnable);
|
||||
case CONNECT4 ->
|
||||
new Connect4Game(information, myTurn, this::forfeitGame, this::exitGame, this::sendMessage, onGameOverRunnable);
|
||||
case TICTACTOE ->{
|
||||
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 -> {
|
||||
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);}
|
||||
default -> new ErrorPopup("Unsupported game type.");
|
||||
|
||||
}
|
||||
|
||||
if (gameController != null){
|
||||
gameController.start();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void handleYourTurn(NetworkEvents.YourTurnResponse response) {
|
||||
if (gameController == null) {
|
||||
return;
|
||||
}
|
||||
gameController.onYourTurn(response);
|
||||
|
||||
}
|
||||
|
||||
private void handleGameResult(NetworkEvents.GameResultResponse response) {
|
||||
if (gameController == null) {
|
||||
return;
|
||||
}
|
||||
gameController.gameFinished(response);
|
||||
}
|
||||
|
||||
private void handleReceivedMove(NetworkEvents.GameMoveResponse response) {
|
||||
if (gameController == null) {
|
||||
return;
|
||||
}
|
||||
gameController.onMoveReceived(response);
|
||||
}
|
||||
|
||||
private void handleReceivedChallenge(NetworkEvents.ChallengeResponse response) {
|
||||
if (!isPolling) return;
|
||||
|
||||
@@ -200,7 +307,7 @@ public final class Server {
|
||||
} else {
|
||||
stopScheduler();
|
||||
}
|
||||
}, 0, 5, TimeUnit.SECONDS);
|
||||
}, 0, 1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
private void stopScheduler() {
|
||||
|
||||
247
app/src/main/java/org/toop/app/canvas/BitGameCanvas.java
Normal file
247
app/src/main/java/org/toop/app/canvas/BitGameCanvas.java
Normal file
@@ -0,0 +1,247 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
package org.toop.app.canvas;
|
||||
|
||||
import javafx.scene.paint.Color;
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package org.toop.app.canvas;
|
||||
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
|
||||
public interface DrawPlayerHover {
|
||||
void drawPlayerHover(int player, int move, TurnBasedGame game);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package org.toop.app.canvas;
|
||||
|
||||
public interface DrawPlayerMove {
|
||||
void drawPlayerMove(int player, int move);
|
||||
}
|
||||
@@ -1,215 +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.util.Duration;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public abstract class GameCanvas {
|
||||
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;
|
||||
|
||||
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.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();
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
42
app/src/main/java/org/toop/app/canvas/ReversiBitCanvas.java
Normal file
42
app/src/main/java/org/toop/app/canvas/ReversiBitCanvas.java
Normal file
@@ -0,0 +1,42 @@
|
||||
package org.toop.app.canvas;
|
||||
|
||||
import javafx.scene.paint.Color;
|
||||
import org.toop.app.App;
|
||||
import org.toop.game.games.reversi.BitboardReversi;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class ReversiBitCanvas extends BitGameCanvas<BitboardReversi> {
|
||||
public ReversiBitCanvas() {
|
||||
super(Color.GRAY, new Color(0f, 0.4f, 0.2f, 1f), (App.getHeight() / 4) * 3, (App.getHeight() / 4) * 3, 8, 8, 5, true);
|
||||
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();
|
||||
loopOverBoard(board[0], (i) -> drawDot(Color.WHITE, i));
|
||||
loopOverBoard(board[1], (i) -> drawDot(Color.BLACK, i));
|
||||
}
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
package org.toop.app.canvas;
|
||||
|
||||
import javafx.scene.paint.Color;
|
||||
import org.toop.game.records.Move;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public final class ReversiCanvas extends GameCanvas {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
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,38 +0,0 @@
|
||||
package org.toop.app.canvas;
|
||||
|
||||
import javafx.scene.paint.Color;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public final class TicTacToeCanvas extends GameCanvas {
|
||||
public TicTacToeCanvas(Color color, int width, int height, Consumer<Integer> onCellClicked) {
|
||||
super(color, Color.TRANSPARENT, width, height, 3, 3, 30, false, onCellClicked,null);
|
||||
}
|
||||
|
||||
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,122 +0,0 @@
|
||||
package org.toop.app.game;
|
||||
|
||||
import org.toop.app.GameInformation;
|
||||
import org.toop.app.widget.WidgetContainer;
|
||||
import org.toop.app.widget.view.GameView;
|
||||
import org.toop.framework.eventbus.EventFlow;
|
||||
import org.toop.framework.networking.events.NetworkEvents;
|
||||
import org.toop.game.Game;
|
||||
import org.toop.game.records.Move;
|
||||
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public abstract class BaseGameThread<TGame extends Game, TAI, TCanvas> {
|
||||
protected final GameInformation information;
|
||||
protected final int myTurn;
|
||||
protected final Runnable onGameOver;
|
||||
protected final BlockingQueue<Move> moveQueue;
|
||||
|
||||
protected final TGame game;
|
||||
protected final TAI ai;
|
||||
|
||||
protected final GameView primary;
|
||||
protected final TCanvas canvas;
|
||||
|
||||
protected final AtomicBoolean isRunning = new AtomicBoolean(true);
|
||||
|
||||
protected BaseGameThread(
|
||||
GameInformation information,
|
||||
int myTurn,
|
||||
Runnable onForfeit,
|
||||
Runnable onExit,
|
||||
Consumer<String> onMessage,
|
||||
Runnable onGameOver,
|
||||
Supplier<TGame> gameSupplier,
|
||||
Supplier<TAI> aiSupplier,
|
||||
Function<Consumer<Integer>, TCanvas> canvasFactory) {
|
||||
|
||||
this.information = information;
|
||||
this.myTurn = myTurn;
|
||||
this.onGameOver = onGameOver;
|
||||
this.moveQueue = new LinkedBlockingQueue<>();
|
||||
|
||||
this.game = gameSupplier.get();
|
||||
this.ai = aiSupplier.get();
|
||||
|
||||
String type = information.type.getTypeToString();
|
||||
if (onForfeit == null || onExit == null) {
|
||||
primary = new GameView(null, () -> {
|
||||
isRunning.set(false);
|
||||
WidgetContainer.getCurrentView().transitionPrevious();
|
||||
}, null, type);
|
||||
} else {
|
||||
primary = new GameView(onForfeit, () -> {
|
||||
isRunning.set(false);
|
||||
onExit.run();
|
||||
}, onMessage, type);
|
||||
}
|
||||
|
||||
this.canvas = canvasFactory.apply(this::onCellClicked);
|
||||
|
||||
addCanvasToPrimary();
|
||||
|
||||
WidgetContainer.getCurrentView().transitionNext(primary);
|
||||
|
||||
if (onForfeit == null || onExit == null)
|
||||
new Thread(this::localGameThread).start();
|
||||
else
|
||||
new EventFlow()
|
||||
.listen(NetworkEvents.GameMoveResponse.class, this::onMoveResponse)
|
||||
.listen(NetworkEvents.YourTurnResponse.class, this::onYourTurnResponse);
|
||||
|
||||
setGameLabels(myTurn == 0);
|
||||
}
|
||||
|
||||
private void onCellClicked(int cell) {
|
||||
if (!isRunning.get()) return;
|
||||
|
||||
final int currentTurn = getCurrentTurn();
|
||||
if (!information.players[currentTurn].isHuman) return;
|
||||
|
||||
final char value = getSymbolForTurn(currentTurn);
|
||||
|
||||
try {
|
||||
moveQueue.put(new Move(cell, value));
|
||||
} catch (InterruptedException _) {}
|
||||
}
|
||||
|
||||
protected void gameOver() {
|
||||
if (onGameOver != null) {
|
||||
isRunning.set(false);
|
||||
onGameOver.run();
|
||||
}
|
||||
}
|
||||
|
||||
protected void setGameLabels(boolean isMe) {
|
||||
final int currentTurn = getCurrentTurn();
|
||||
final String turnName = getNameForTurn(currentTurn);
|
||||
|
||||
primary.nextPlayer(
|
||||
isMe,
|
||||
information.players[isMe ? 0 : 1].name,
|
||||
turnName,
|
||||
information.players[isMe ? 1 : 0].name
|
||||
);
|
||||
}
|
||||
|
||||
protected abstract void addCanvasToPrimary();
|
||||
|
||||
protected abstract int getCurrentTurn();
|
||||
protected abstract char getSymbolForTurn(int turn);
|
||||
protected abstract String getNameForTurn(int turn);
|
||||
|
||||
protected abstract void onMoveResponse(NetworkEvents.GameMoveResponse response);
|
||||
protected abstract void onYourTurnResponse(NetworkEvents.YourTurnResponse response);
|
||||
|
||||
protected abstract void localGameThread();
|
||||
}
|
||||
@@ -1,265 +0,0 @@
|
||||
package org.toop.app.game;
|
||||
|
||||
import javafx.geometry.Pos;
|
||||
import javafx.scene.paint.Color;
|
||||
import org.toop.app.App;
|
||||
import org.toop.app.GameInformation;
|
||||
import org.toop.app.canvas.Connect4Canvas;
|
||||
import org.toop.app.widget.view.GameView;
|
||||
import org.toop.app.widget.WidgetContainer;
|
||||
import org.toop.framework.eventbus.EventFlow;
|
||||
import org.toop.framework.networking.events.NetworkEvents;
|
||||
import org.toop.game.Connect4.Connect4;
|
||||
import org.toop.game.Connect4.Connect4AI;
|
||||
import org.toop.game.enumerators.GameState;
|
||||
import org.toop.game.records.Move;
|
||||
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class Connect4Game {
|
||||
private final GameInformation information;
|
||||
|
||||
private final int myTurn;
|
||||
private Runnable onGameOver;
|
||||
private final BlockingQueue<Move> moveQueue;
|
||||
|
||||
private final Connect4 game;
|
||||
private final Connect4AI ai;
|
||||
private final int columnSize = 7;
|
||||
private final int rowSize = 6;
|
||||
|
||||
private final GameView primary;
|
||||
private final Connect4Canvas canvas;
|
||||
|
||||
private final AtomicBoolean isRunning;
|
||||
|
||||
public Connect4Game(GameInformation information, int myTurn, Runnable onForfeit, Runnable onExit, Consumer<String> onMessage, Runnable onGameOver) {
|
||||
this.information = information;
|
||||
this.myTurn = myTurn;
|
||||
this.onGameOver = onGameOver;
|
||||
moveQueue = new LinkedBlockingQueue<Move>();
|
||||
|
||||
|
||||
game = new Connect4();
|
||||
ai = new Connect4AI();
|
||||
|
||||
isRunning = new AtomicBoolean(true);
|
||||
|
||||
if (onForfeit == null || onExit == null) {
|
||||
primary = new GameView(null, () -> {
|
||||
isRunning.set(false);
|
||||
WidgetContainer.getCurrentView().transitionPrevious();
|
||||
}, null, "Connect4");
|
||||
} else {
|
||||
primary = new GameView(onForfeit, () -> {
|
||||
isRunning.set(false);
|
||||
onExit.run();
|
||||
}, onMessage, "Connect4");
|
||||
}
|
||||
|
||||
canvas = new Connect4Canvas(Color.GRAY,
|
||||
(App.getHeight() / 4) * 3, (App.getHeight() / 4) * 3,
|
||||
(cell) -> {
|
||||
if (onForfeit == null || onExit == null) {
|
||||
if (information.players[game.getCurrentTurn()].isHuman) {
|
||||
final char value = game.getCurrentTurn() == 0? 'X' : 'O';
|
||||
|
||||
try {
|
||||
moveQueue.put(new Move(cell%columnSize, value));
|
||||
} catch (InterruptedException _) {}
|
||||
}
|
||||
} else {
|
||||
if (information.players[0].isHuman) {
|
||||
final char value = myTurn == 0? 'X' : 'O';
|
||||
|
||||
try {
|
||||
moveQueue.put(new Move(cell%columnSize, value));
|
||||
} catch (InterruptedException _) {}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
primary.add(Pos.CENTER, canvas.getCanvas());
|
||||
WidgetContainer.getCurrentView().transitionNext(primary);
|
||||
|
||||
if (onForfeit == null || onExit == null) {
|
||||
new Thread(this::localGameThread).start();
|
||||
setGameLabels(information.players[0].isHuman);
|
||||
} else {
|
||||
new EventFlow()
|
||||
.listen(NetworkEvents.GameMoveResponse.class, this::onMoveResponse)
|
||||
.listen(NetworkEvents.YourTurnResponse.class, this::onYourTurnResponse);
|
||||
|
||||
setGameLabels(myTurn == 0);
|
||||
}
|
||||
updateCanvas();
|
||||
}
|
||||
|
||||
public Connect4Game(GameInformation information) {
|
||||
this(information, 0, null, null, null, null);
|
||||
}
|
||||
private void localGameThread() {
|
||||
while (isRunning.get()) {
|
||||
final int currentTurn = game.getCurrentTurn();
|
||||
final String currentValue = currentTurn == 0? "RED" : "BLUE";
|
||||
final int nextTurn = (currentTurn + 1) % information.type.getPlayerCount();
|
||||
|
||||
primary.nextPlayer(information.players[currentTurn].isHuman,
|
||||
information.players[currentTurn].name,
|
||||
currentValue,
|
||||
information.players[nextTurn].name);
|
||||
|
||||
Move move = null;
|
||||
|
||||
if (information.players[currentTurn].isHuman) {
|
||||
try {
|
||||
final Move wants = moveQueue.take();
|
||||
final Move[] legalMoves = game.getLegalMoves();
|
||||
|
||||
for (final Move legalMove : legalMoves) {
|
||||
if (legalMove.position() == wants.position() &&
|
||||
legalMove.value() == wants.value()) {
|
||||
move = wants;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (InterruptedException _) {}
|
||||
} else {
|
||||
final long start = System.currentTimeMillis();
|
||||
|
||||
move = ai.findBestMove(game, information.players[currentTurn].computerDifficulty);
|
||||
|
||||
if (information.players[currentTurn].computerThinkTime > 0) {
|
||||
final long elapsedTime = System.currentTimeMillis() - start;
|
||||
final long sleepTime = Math.abs(information.players[currentTurn].computerThinkTime * 1000L - elapsedTime);
|
||||
|
||||
try {
|
||||
Thread.sleep((long)(sleepTime * Math.random()));
|
||||
} catch (InterruptedException _) {}
|
||||
}
|
||||
}
|
||||
|
||||
if (move == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
final GameState state = game.play(move);
|
||||
updateCanvas();
|
||||
/*
|
||||
if (move.value() == 'X') {
|
||||
canvas.drawX(Color.INDIANRED, move.position());
|
||||
} else if (move.value() == 'O') {
|
||||
canvas.drawO(Color.ROYALBLUE, move.position());
|
||||
}
|
||||
*/
|
||||
if (state != GameState.NORMAL) {
|
||||
if (state == GameState.WIN) {
|
||||
primary.gameOver(true, information.players[currentTurn].name);
|
||||
} else if (state == GameState.DRAW) {
|
||||
primary.gameOver(false, "");
|
||||
}
|
||||
|
||||
isRunning.set(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void onMoveResponse(NetworkEvents.GameMoveResponse response) {
|
||||
if (!isRunning.get()) {
|
||||
return;
|
||||
}
|
||||
|
||||
char playerChar;
|
||||
|
||||
if (response.player().equalsIgnoreCase(information.players[0].name)) {
|
||||
playerChar = myTurn == 0? 'X' : 'O';
|
||||
} else {
|
||||
playerChar = myTurn == 0? 'O' : 'X';
|
||||
}
|
||||
|
||||
final Move move = new Move(Integer.parseInt(response.move()), playerChar);
|
||||
final GameState state = game.play(move);
|
||||
|
||||
if (state != GameState.NORMAL) {
|
||||
if (state == GameState.WIN) {
|
||||
if (response.player().equalsIgnoreCase(information.players[0].name)) {
|
||||
primary.gameOver(true, information.players[0].name);
|
||||
gameOver();
|
||||
} else {
|
||||
primary.gameOver(false, information.players[1].name);
|
||||
gameOver();
|
||||
}
|
||||
} else if (state == GameState.DRAW) {
|
||||
primary.gameOver(false, "");
|
||||
gameOver();
|
||||
}
|
||||
}
|
||||
|
||||
if (move.value() == 'X') {
|
||||
canvas.drawDot(Color.INDIANRED, move.position());
|
||||
} else if (move.value() == 'O') {
|
||||
canvas.drawDot(Color.ROYALBLUE, move.position());
|
||||
}
|
||||
|
||||
updateCanvas();
|
||||
setGameLabels(game.getCurrentTurn() == myTurn);
|
||||
}
|
||||
|
||||
private void gameOver() {
|
||||
if (onGameOver == null){
|
||||
return;
|
||||
}
|
||||
isRunning.set(false);
|
||||
onGameOver.run();
|
||||
}
|
||||
|
||||
private void onYourTurnResponse(NetworkEvents.YourTurnResponse response) {
|
||||
|
||||
if (!isRunning.get()) {
|
||||
return;
|
||||
}
|
||||
|
||||
moveQueue.clear();
|
||||
|
||||
int position = -1;
|
||||
|
||||
if (information.players[0].isHuman) {
|
||||
try {
|
||||
position = moveQueue.take().position();
|
||||
} catch (InterruptedException _) {}
|
||||
} else {
|
||||
final Move move = ai.findBestMove(game, information.players[0].computerDifficulty);
|
||||
|
||||
assert move != null;
|
||||
position = move.position();
|
||||
}
|
||||
|
||||
new EventFlow().addPostEvent(new NetworkEvents.SendMove(response.clientId(), (short)position))
|
||||
.postEvent();
|
||||
}
|
||||
|
||||
private void updateCanvas() {
|
||||
canvas.clearAll();
|
||||
|
||||
for (int i = 0; i < game.getBoard().length; i++) {
|
||||
if (game.getBoard()[i] == 'X') {
|
||||
canvas.drawDot(Color.RED, i);
|
||||
} else if (game.getBoard()[i] == 'O') {
|
||||
canvas.drawDot(Color.BLUE, i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void setGameLabels(boolean isMe) {
|
||||
final int currentTurn = game.getCurrentTurn();
|
||||
final String currentValue = currentTurn == 0? "RED" : "BLUE";
|
||||
|
||||
primary.nextPlayer(isMe,
|
||||
information.players[isMe? 0 : 1].name,
|
||||
currentValue,
|
||||
information.players[isMe? 1 : 0].name);
|
||||
}
|
||||
}
|
||||
@@ -1,333 +0,0 @@
|
||||
package org.toop.app.game;
|
||||
|
||||
import javafx.animation.SequentialTransition;
|
||||
import org.toop.app.App;
|
||||
import org.toop.app.GameInformation;
|
||||
import org.toop.app.canvas.ReversiCanvas;
|
||||
import org.toop.app.widget.WidgetContainer;
|
||||
import org.toop.app.widget.view.GameView;
|
||||
import org.toop.framework.eventbus.EventFlow;
|
||||
import org.toop.framework.networking.events.NetworkEvents;
|
||||
import org.toop.game.enumerators.GameState;
|
||||
import org.toop.game.records.Move;
|
||||
import org.toop.game.reversi.Reversi;
|
||||
import org.toop.game.reversi.ReversiAI;
|
||||
|
||||
import javafx.geometry.Pos;
|
||||
import javafx.scene.paint.Color;
|
||||
|
||||
import java.awt.*;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public final class ReversiGame {
|
||||
private final GameInformation information;
|
||||
|
||||
private final int myTurn;
|
||||
private final Runnable onGameOver;
|
||||
private final BlockingQueue<Move> moveQueue;
|
||||
|
||||
private final Reversi game;
|
||||
private final ReversiAI ai;
|
||||
|
||||
private final GameView primary;
|
||||
private final ReversiCanvas canvas;
|
||||
|
||||
private final AtomicBoolean isRunning;
|
||||
private final AtomicBoolean isPaused;
|
||||
|
||||
public ReversiGame(GameInformation information, int myTurn, Runnable onForfeit, Runnable onExit, Consumer<String> onMessage, Runnable onGameOver) {
|
||||
this.information = information;
|
||||
|
||||
this.myTurn = myTurn;
|
||||
this.onGameOver = onGameOver;
|
||||
moveQueue = new LinkedBlockingQueue<>();
|
||||
|
||||
game = new Reversi();
|
||||
ai = new ReversiAI();
|
||||
|
||||
isRunning = new AtomicBoolean(true);
|
||||
isPaused = new AtomicBoolean(false);
|
||||
|
||||
if (onForfeit == null || onExit == null) {
|
||||
primary = new GameView(null, () -> {
|
||||
isRunning.set(false);
|
||||
WidgetContainer.getCurrentView().transitionPrevious();
|
||||
}, null, "Reversi");
|
||||
} else {
|
||||
primary = new GameView(onForfeit, () -> {
|
||||
isRunning.set(false);
|
||||
onExit.run();
|
||||
}, onMessage, "Reversi");
|
||||
}
|
||||
|
||||
canvas = new ReversiCanvas(Color.BLACK,
|
||||
(App.getHeight() / 4) * 3, (App.getHeight() / 4) * 3,
|
||||
(cell) -> {
|
||||
if (onForfeit == null || onExit == null) {
|
||||
if (information.players[game.getCurrentTurn()].isHuman) {
|
||||
final char value = game.getCurrentTurn() == 0? 'B' : 'W';
|
||||
|
||||
try {
|
||||
moveQueue.put(new Move(cell, value));
|
||||
} catch (InterruptedException _) {}
|
||||
}
|
||||
} else {
|
||||
if (information.players[0].isHuman) {
|
||||
final char value = myTurn == 0? 'B' : 'W';
|
||||
|
||||
try {
|
||||
moveQueue.put(new Move(cell, value));
|
||||
} catch (InterruptedException _) {}
|
||||
}
|
||||
}
|
||||
},this::highlightCells);
|
||||
|
||||
|
||||
|
||||
primary.add(Pos.CENTER, canvas.getCanvas());
|
||||
WidgetContainer.getCurrentView().transitionNext(primary);
|
||||
|
||||
if (onForfeit == null || onExit == null) {
|
||||
new Thread(this::localGameThread).start();
|
||||
setGameLabels(information.players[0].isHuman);
|
||||
} else {
|
||||
new EventFlow()
|
||||
.listen(NetworkEvents.GameMoveResponse.class, this::onMoveResponse)
|
||||
.listen(NetworkEvents.YourTurnResponse.class, this::onYourTurnResponse);
|
||||
|
||||
setGameLabels(myTurn == 0);
|
||||
}
|
||||
|
||||
updateCanvas(false);
|
||||
}
|
||||
|
||||
public ReversiGame(GameInformation information) {
|
||||
this(information, 0, null, null, null,null);
|
||||
}
|
||||
|
||||
private void localGameThread() {
|
||||
while (isRunning.get()) {
|
||||
if (isPaused.get()) {
|
||||
try {
|
||||
Thread.sleep(200);
|
||||
} catch (InterruptedException _) {}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
final int currentTurn = game.getCurrentTurn();
|
||||
final String currentValue = currentTurn == 0? "BLACK" : "WHITE";
|
||||
final int nextTurn = (currentTurn + 1) % information.type.getPlayerCount();
|
||||
|
||||
primary.nextPlayer(information.players[currentTurn].isHuman,
|
||||
information.players[currentTurn].name,
|
||||
currentValue,
|
||||
information.players[nextTurn].name);
|
||||
|
||||
Move move = null;
|
||||
|
||||
if (information.players[currentTurn].isHuman) {
|
||||
try {
|
||||
final Move wants = moveQueue.take();
|
||||
final Move[] legalMoves = game.getLegalMoves();
|
||||
|
||||
for (final Move legalMove : legalMoves) {
|
||||
if (legalMove.position() == wants.position() &&
|
||||
legalMove.value() == wants.value()) {
|
||||
move = wants;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (InterruptedException _) {}
|
||||
} else {
|
||||
final long start = System.currentTimeMillis();
|
||||
|
||||
move = ai.findBestMove(game, information.players[currentTurn].computerDifficulty);
|
||||
|
||||
if (information.players[currentTurn].computerThinkTime > 0) {
|
||||
final long elapsedTime = System.currentTimeMillis() - start;
|
||||
final long sleepTime = information.players[currentTurn].computerThinkTime * 1000L - elapsedTime;
|
||||
|
||||
try {
|
||||
Thread.sleep((long) (sleepTime * Math.random()));
|
||||
} catch (InterruptedException _) {}
|
||||
}
|
||||
}
|
||||
|
||||
if (move == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
canvas.setCurrentlyHighlightedMovesNull();
|
||||
final GameState state = game.play(move);
|
||||
updateCanvas(true);
|
||||
|
||||
if (state != GameState.NORMAL) {
|
||||
if (state == GameState.TURN_SKIPPED){
|
||||
continue;
|
||||
}
|
||||
int winningPLayerNumber = getPlayerNumberWithHighestScore();
|
||||
if (state == GameState.WIN && winningPLayerNumber > -1) {
|
||||
primary.gameOver(true, information.players[winningPLayerNumber].name);
|
||||
} else if (state == GameState.DRAW || winningPLayerNumber == -1) {
|
||||
primary.gameOver(false, "");
|
||||
}
|
||||
|
||||
isRunning.set(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private int getPlayerNumberWithHighestScore(){
|
||||
Reversi.Score score = game.getScore();
|
||||
if (score.player1Score() > score.player2Score()) return 0;
|
||||
if (score.player1Score() < score.player2Score()) return 1;
|
||||
return -1;
|
||||
}
|
||||
|
||||
private void onMoveResponse(NetworkEvents.GameMoveResponse response) {
|
||||
if (!isRunning.get()) {
|
||||
return;
|
||||
}
|
||||
|
||||
char playerChar;
|
||||
|
||||
if (response.player().equalsIgnoreCase(information.players[0].name)) {
|
||||
playerChar = myTurn == 0? 'B' : 'W';
|
||||
} else {
|
||||
playerChar = myTurn == 0? 'W' : 'B';
|
||||
}
|
||||
|
||||
final Move move = new Move(Integer.parseInt(response.move()), playerChar);
|
||||
final GameState state = game.play(move);
|
||||
|
||||
if (state != GameState.NORMAL) {
|
||||
if (state == GameState.WIN) {
|
||||
if (response.player().equalsIgnoreCase(information.players[0].name)) {
|
||||
primary.gameOver(true, information.players[0].name);
|
||||
gameOver();
|
||||
} else {
|
||||
primary.gameOver(false, information.players[1].name);
|
||||
gameOver();
|
||||
}
|
||||
} else if (state == GameState.DRAW) {
|
||||
primary.gameOver(false, "");
|
||||
game.play(move);
|
||||
}
|
||||
}
|
||||
|
||||
updateCanvas(false);
|
||||
setGameLabels(game.getCurrentTurn() == myTurn);
|
||||
}
|
||||
|
||||
private void gameOver() {
|
||||
if (onGameOver == null){
|
||||
return;
|
||||
}
|
||||
isRunning.set(false);
|
||||
onGameOver.run();
|
||||
}
|
||||
|
||||
private void onYourTurnResponse(NetworkEvents.YourTurnResponse response) {
|
||||
if (!isRunning.get()) {
|
||||
return;
|
||||
}
|
||||
|
||||
moveQueue.clear();
|
||||
|
||||
int position = -1;
|
||||
|
||||
if (information.players[0].isHuman) {
|
||||
try {
|
||||
position = moveQueue.take().position();
|
||||
} catch (InterruptedException _) {}
|
||||
} else {
|
||||
final Move move = ai.findBestMove(game, information.players[0].computerDifficulty);
|
||||
|
||||
assert move != null;
|
||||
position = move.position();
|
||||
}
|
||||
|
||||
new EventFlow().addPostEvent(new NetworkEvents.SendMove(response.clientId(), (short) position))
|
||||
.postEvent();
|
||||
}
|
||||
|
||||
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] == 'B') {
|
||||
canvas.drawDot(Color.BLACK, i);
|
||||
} else if (game.getBoard()[i] == 'W') {
|
||||
canvas.drawDot(Color.WHITE, i);
|
||||
}
|
||||
}
|
||||
|
||||
final Move[] flipped = game.getMostRecentlyFlippedPieces();
|
||||
|
||||
final SequentialTransition animation = new SequentialTransition();
|
||||
isPaused.set(true);
|
||||
|
||||
final Color fromColor = game.getCurrentPlayer() == 'W'? Color.WHITE : Color.BLACK;
|
||||
final Color toColor = game.getCurrentPlayer() == 'W'? Color.BLACK : Color.WHITE;
|
||||
|
||||
if (animate && flipped != null) {
|
||||
for (final Move flip : flipped) {
|
||||
canvas.clear(flip.position());
|
||||
canvas.drawDot(fromColor, flip.position());
|
||||
animation.getChildren().addFirst(canvas.flipDot(fromColor, toColor, flip.position()));
|
||||
}
|
||||
}
|
||||
|
||||
animation.setOnFinished(_ -> {
|
||||
isPaused.set(false);
|
||||
|
||||
if (information.players[game.getCurrentTurn()].isHuman) {
|
||||
final Move[] legalMoves = game.getLegalMoves();
|
||||
|
||||
for (final Move legalMove : legalMoves) {
|
||||
canvas.drawLegalPosition(legalMove.position(), game.getCurrentPlayer());
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
animation.play();
|
||||
}
|
||||
|
||||
private void setGameLabels(boolean isMe) {
|
||||
final int currentTurn = game.getCurrentTurn();
|
||||
final String currentValue = currentTurn == 0? "BLACK" : "WHITE";
|
||||
|
||||
primary.nextPlayer(isMe,
|
||||
information.players[isMe? 0 : 1].name,
|
||||
currentValue,
|
||||
information.players[isMe? 1 : 0].name);
|
||||
}
|
||||
|
||||
private void highlightCells(int cellEntered) {
|
||||
if (information.players[game.getCurrentTurn()].isHuman) {
|
||||
Move[] legalMoves = game.getLegalMoves();
|
||||
boolean isLegalMove = false;
|
||||
for (Move move : legalMoves) {
|
||||
if (move.position() == cellEntered){
|
||||
isLegalMove = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (cellEntered >= 0){
|
||||
Move[] moves = null;
|
||||
if (isLegalMove) {
|
||||
moves = game.getFlipsForPotentialMove(
|
||||
new Point(cellEntered%game.getColumnSize(),cellEntered/game.getRowSize()),
|
||||
game.getCurrentPlayer());
|
||||
}
|
||||
canvas.drawHighlightDots(moves);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,250 +0,0 @@
|
||||
package org.toop.app.game;
|
||||
|
||||
import org.toop.app.App;
|
||||
import org.toop.app.GameInformation;
|
||||
import org.toop.app.canvas.TicTacToeCanvas;
|
||||
import org.toop.app.widget.WidgetContainer;
|
||||
import org.toop.app.widget.view.GameView;
|
||||
import org.toop.framework.eventbus.EventFlow;
|
||||
import org.toop.framework.networking.events.NetworkEvents;
|
||||
import org.toop.game.enumerators.GameState;
|
||||
import org.toop.game.records.Move;
|
||||
import org.toop.game.tictactoe.TicTacToe;
|
||||
import org.toop.game.tictactoe.TicTacToeAI;
|
||||
|
||||
import javafx.geometry.Pos;
|
||||
import javafx.scene.paint.Color;
|
||||
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public final class TicTacToeGame {
|
||||
private final GameInformation information;
|
||||
|
||||
private final int myTurn;
|
||||
private final Runnable onGameOver;
|
||||
private final BlockingQueue<Move> moveQueue;
|
||||
|
||||
private final TicTacToe game;
|
||||
private final TicTacToeAI ai;
|
||||
|
||||
private final GameView primary;
|
||||
private final TicTacToeCanvas canvas;
|
||||
|
||||
private final AtomicBoolean isRunning;
|
||||
|
||||
public TicTacToeGame(GameInformation information, int myTurn, Runnable onForfeit, Runnable onExit, Consumer<String> onMessage, Runnable onGameOver) {
|
||||
this.information = information;
|
||||
|
||||
this.myTurn = myTurn;
|
||||
this.onGameOver = onGameOver;
|
||||
moveQueue = new LinkedBlockingQueue<Move>();
|
||||
|
||||
game = new TicTacToe();
|
||||
ai = new TicTacToeAI();
|
||||
|
||||
isRunning = new AtomicBoolean(true);
|
||||
|
||||
if (onForfeit == null || onExit == null) {
|
||||
primary = new GameView(null, () -> {
|
||||
isRunning.set(false);
|
||||
WidgetContainer.getCurrentView().transitionPrevious();
|
||||
}, null, "TicTacToe");
|
||||
} else {
|
||||
primary = new GameView(onForfeit, () -> {
|
||||
isRunning.set(false);
|
||||
onExit.run();
|
||||
}, onMessage, "TicTacToe");
|
||||
}
|
||||
|
||||
canvas = new TicTacToeCanvas(Color.GRAY,
|
||||
(App.getHeight() / 4) * 3, (App.getHeight() / 4) * 3,
|
||||
(cell) -> {
|
||||
if (onForfeit == null || onExit == null) {
|
||||
if (information.players[game.getCurrentTurn()].isHuman) {
|
||||
final char value = game.getCurrentTurn() == 0? 'X' : 'O';
|
||||
|
||||
try {
|
||||
moveQueue.put(new Move(cell, value));
|
||||
} catch (InterruptedException _) {}
|
||||
}
|
||||
} else {
|
||||
if (information.players[0].isHuman) {
|
||||
final char value = myTurn == 0? 'X' : 'O';
|
||||
|
||||
try {
|
||||
moveQueue.put(new Move(cell, value));
|
||||
} catch (InterruptedException _) {}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
primary.add(Pos.CENTER, canvas.getCanvas());
|
||||
WidgetContainer.getCurrentView().transitionNext(primary);
|
||||
|
||||
if (onForfeit == null || onExit == null) {
|
||||
new Thread(this::localGameThread).start();
|
||||
} else {
|
||||
new EventFlow()
|
||||
.listen(NetworkEvents.GameMoveResponse.class, this::onMoveResponse)
|
||||
.listen(NetworkEvents.YourTurnResponse.class, this::onYourTurnResponse);
|
||||
|
||||
setGameLabels(myTurn == 0);
|
||||
}
|
||||
}
|
||||
|
||||
public TicTacToeGame(GameInformation information) {
|
||||
this(information, 0, null, null, null, null);
|
||||
}
|
||||
|
||||
private void localGameThread() {
|
||||
while (isRunning.get()) {
|
||||
final int currentTurn = game.getCurrentTurn();
|
||||
final String currentValue = currentTurn == 0? "X" : "O";
|
||||
final int nextTurn = (currentTurn + 1) % information.type.getPlayerCount();
|
||||
|
||||
primary.nextPlayer(information.players[currentTurn].isHuman,
|
||||
information.players[currentTurn].name,
|
||||
currentValue,
|
||||
information.players[nextTurn].name);
|
||||
|
||||
Move move = null;
|
||||
|
||||
if (information.players[currentTurn].isHuman) {
|
||||
try {
|
||||
final Move wants = moveQueue.take();
|
||||
final Move[] legalMoves = game.getLegalMoves();
|
||||
|
||||
for (final Move legalMove : legalMoves) {
|
||||
if (legalMove.position() == wants.position() &&
|
||||
legalMove.value() == wants.value()) {
|
||||
move = wants;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (InterruptedException _) {}
|
||||
} else {
|
||||
final long start = System.currentTimeMillis();
|
||||
|
||||
move = ai.findBestMove(game, information.players[currentTurn].computerDifficulty);
|
||||
|
||||
if (information.players[currentTurn].computerThinkTime > 0) {
|
||||
final long elapsedTime = System.currentTimeMillis() - start;
|
||||
final long sleepTime = information.players[currentTurn].computerThinkTime * 1000L - elapsedTime;
|
||||
|
||||
try {
|
||||
Thread.sleep((long)(sleepTime * Math.random()));
|
||||
} catch (InterruptedException _) {}
|
||||
}
|
||||
}
|
||||
|
||||
if (move == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
final GameState state = game.play(move);
|
||||
|
||||
if (move.value() == 'X') {
|
||||
canvas.drawX(Color.INDIANRED, move.position());
|
||||
} else if (move.value() == 'O') {
|
||||
canvas.drawO(Color.ROYALBLUE, move.position());
|
||||
}
|
||||
|
||||
if (state != GameState.NORMAL) {
|
||||
if (state == GameState.WIN) {
|
||||
primary.gameOver(true, information.players[currentTurn].name);
|
||||
} else if (state == GameState.DRAW) {
|
||||
primary.gameOver(false, "");
|
||||
}
|
||||
|
||||
isRunning.set(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void onMoveResponse(NetworkEvents.GameMoveResponse response) {
|
||||
if (!isRunning.get()) {
|
||||
return;
|
||||
}
|
||||
|
||||
char playerChar;
|
||||
|
||||
if (response.player().equalsIgnoreCase(information.players[0].name)) {
|
||||
playerChar = myTurn == 0? 'X' : 'O';
|
||||
} else {
|
||||
playerChar = myTurn == 0? 'O' : 'X';
|
||||
}
|
||||
|
||||
final Move move = new Move(Integer.parseInt(response.move()), playerChar);
|
||||
final GameState state = game.play(move);
|
||||
|
||||
if (state != GameState.NORMAL) {
|
||||
if (state == GameState.WIN) {
|
||||
if (response.player().equalsIgnoreCase(information.players[0].name)) {
|
||||
primary.gameOver(true, information.players[0].name);
|
||||
gameOver();
|
||||
} else {
|
||||
primary.gameOver(false, information.players[1].name);
|
||||
gameOver();
|
||||
}
|
||||
} else if (state == GameState.DRAW) {
|
||||
if(game.getLegalMoves().length == 0) { //only return draw in online multiplayer if the game is actually over.
|
||||
primary.gameOver(false, "");
|
||||
gameOver();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (move.value() == 'X') {
|
||||
canvas.drawX(Color.RED, move.position());
|
||||
} else if (move.value() == 'O') {
|
||||
canvas.drawO(Color.BLUE, move.position());
|
||||
}
|
||||
|
||||
setGameLabels(game.getCurrentTurn() == myTurn);
|
||||
}
|
||||
|
||||
private void gameOver() {
|
||||
if (onGameOver == null){
|
||||
return;
|
||||
}
|
||||
isRunning.set(false);
|
||||
onGameOver.run();
|
||||
}
|
||||
|
||||
private void onYourTurnResponse(NetworkEvents.YourTurnResponse response) {
|
||||
if (!isRunning.get()) {
|
||||
return;
|
||||
}
|
||||
|
||||
moveQueue.clear();
|
||||
|
||||
int position = -1;
|
||||
|
||||
if (information.players[0].isHuman) {
|
||||
try {
|
||||
position = moveQueue.take().position();
|
||||
} catch (InterruptedException _) {}
|
||||
} else {
|
||||
final Move move;
|
||||
move = ai.findBestMove(game, information.players[0].computerDifficulty);
|
||||
assert move != null;
|
||||
position = move.position();
|
||||
}
|
||||
|
||||
new EventFlow().addPostEvent(new NetworkEvents.SendMove(response.clientId(), (short)position))
|
||||
.postEvent();
|
||||
}
|
||||
|
||||
private void setGameLabels(boolean isMe) {
|
||||
final int currentTurn = game.getCurrentTurn();
|
||||
final String currentValue = currentTurn == 0? "X" : "O";
|
||||
|
||||
primary.nextPlayer(isMe,
|
||||
information.players[isMe? 0 : 1].name,
|
||||
currentValue,
|
||||
information.players[isMe? 1 : 0].name);
|
||||
}
|
||||
}
|
||||
@@ -1,176 +0,0 @@
|
||||
package org.toop.app.game;
|
||||
|
||||
import org.toop.app.App;
|
||||
import org.toop.app.GameInformation;
|
||||
import org.toop.app.canvas.TicTacToeCanvas;
|
||||
import org.toop.framework.eventbus.EventFlow;
|
||||
import org.toop.framework.networking.events.NetworkEvents;
|
||||
import org.toop.game.enumerators.GameState;
|
||||
import org.toop.game.records.Move;
|
||||
import org.toop.game.tictactoe.TicTacToe;
|
||||
import org.toop.game.tictactoe.TicTacToeAI;
|
||||
import java.util.function.Consumer;
|
||||
import javafx.geometry.Pos;
|
||||
import javafx.scene.paint.Color;
|
||||
|
||||
public final class TicTacToeGameThread extends BaseGameThread<TicTacToe, TicTacToeAI, TicTacToeCanvas> {
|
||||
public TicTacToeGameThread(GameInformation info, int myTurn, Runnable onForfeit, Runnable onExit, Consumer<String> onMessage, Runnable onGameOver) {
|
||||
super(info, myTurn, onForfeit, onExit, onMessage, onGameOver,
|
||||
TicTacToe::new,
|
||||
TicTacToeAI::new,
|
||||
clickHandler -> new TicTacToeCanvas(Color.GRAY, (App.getHeight() / 4) * 3, (App.getHeight() / 4) * 3, clickHandler)
|
||||
);
|
||||
}
|
||||
|
||||
public TicTacToeGameThread(GameInformation info) {
|
||||
this(info, 0, null, null, null, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void addCanvasToPrimary() {
|
||||
primary.add(Pos.CENTER, canvas.getCanvas());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int getCurrentTurn() {
|
||||
return game.getCurrentTurn();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected char getSymbolForTurn(int turn) {
|
||||
return turn == 0 ? 'X' : 'O';
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getNameForTurn(int turn) {
|
||||
return turn == 0 ? "X" : "O";
|
||||
}
|
||||
|
||||
private void drawMove(Move move) {
|
||||
if (move.value() == 'X') canvas.drawX(Color.RED, move.position());
|
||||
else canvas.drawO(Color.BLUE, move.position());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onMoveResponse(NetworkEvents.GameMoveResponse response) {
|
||||
if (!isRunning.get()) {
|
||||
return;
|
||||
}
|
||||
|
||||
char playerChar;
|
||||
|
||||
if (response.player().equalsIgnoreCase(information.players[0].name)) {
|
||||
playerChar = myTurn == 0? 'X' : 'O';
|
||||
} else {
|
||||
playerChar = myTurn == 0? 'O' : 'X';
|
||||
}
|
||||
|
||||
final Move move = new Move(Integer.parseInt(response.move()), playerChar);
|
||||
final GameState state = game.play(move);
|
||||
|
||||
if (state != GameState.NORMAL) {
|
||||
if (state == GameState.WIN) {
|
||||
if (response.player().equalsIgnoreCase(information.players[0].name)) {
|
||||
primary.gameOver(true, information.players[0].name);
|
||||
gameOver();
|
||||
} else {
|
||||
primary.gameOver(false, information.players[1].name);
|
||||
gameOver();
|
||||
}
|
||||
} else if (state == GameState.DRAW) {
|
||||
if (game.getLegalMoves().length == 0) {
|
||||
primary.gameOver(false, "");
|
||||
gameOver();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
drawMove(move);
|
||||
setGameLabels(game.getCurrentTurn() == myTurn);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onYourTurnResponse(NetworkEvents.YourTurnResponse response) {
|
||||
if (!isRunning.get()) {
|
||||
return;
|
||||
}
|
||||
|
||||
moveQueue.clear();
|
||||
|
||||
int position = -1;
|
||||
|
||||
if (information.players[0].isHuman) {
|
||||
try {
|
||||
position = moveQueue.take().position();
|
||||
} catch (InterruptedException _) {}
|
||||
} else {
|
||||
final Move move;
|
||||
if (information.players[1].name.equalsIgnoreCase("pism")) {
|
||||
move = ai.findWorstMove(game,9);
|
||||
}else{
|
||||
move = ai.findBestMove(game, information.players[0].computerDifficulty);
|
||||
}
|
||||
|
||||
assert move != null;
|
||||
position = move.position();
|
||||
}
|
||||
|
||||
new EventFlow().addPostEvent(new NetworkEvents.SendMove(response.clientId(), (short)position))
|
||||
.postEvent();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void localGameThread() {
|
||||
while (isRunning.get()) {
|
||||
final int currentTurn = game.getCurrentTurn();
|
||||
setGameLabels(currentTurn == myTurn);
|
||||
|
||||
Move move = null;
|
||||
|
||||
if (information.players[currentTurn].isHuman) {
|
||||
try {
|
||||
final Move wants = moveQueue.take();
|
||||
final Move[] legalMoves = game.getLegalMoves();
|
||||
|
||||
for (final Move legalMove : legalMoves) {
|
||||
if (legalMove.position() == wants.position() &&
|
||||
legalMove.value() == wants.value()) {
|
||||
move = wants;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (InterruptedException _) {}
|
||||
} else {
|
||||
final long start = System.currentTimeMillis();
|
||||
|
||||
move = ai.findBestMove(game, information.players[currentTurn].computerDifficulty);
|
||||
|
||||
if (information.players[currentTurn].computerThinkTime > 0) {
|
||||
final long elapsedTime = System.currentTimeMillis() - start;
|
||||
final long sleepTime = information.players[currentTurn].computerThinkTime * 1000L - elapsedTime;
|
||||
|
||||
try {
|
||||
Thread.sleep((long)(sleepTime * Math.random()));
|
||||
} catch (InterruptedException _) {}
|
||||
}
|
||||
}
|
||||
|
||||
if (move == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
final GameState state = game.play(move);
|
||||
drawMove(move);
|
||||
|
||||
if (state != GameState.NORMAL) {
|
||||
if (state == GameState.WIN) {
|
||||
primary.gameOver(information.players[currentTurn].isHuman, information.players[currentTurn].name);
|
||||
} else if (state == GameState.DRAW) {
|
||||
primary.gameOver(false, "");
|
||||
}
|
||||
|
||||
isRunning.set(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
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.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;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class GenericGameController<T extends TurnBasedGame<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 game canvas
|
||||
protected final GameCanvas<T> 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(GameCanvas<T> canvas, T game, ThreadBehaviour gameThreadBehaviour, String gameType) {
|
||||
logger.info("Creating: " + this.getClass());
|
||||
|
||||
this.canvas = canvas;
|
||||
this.game = game;
|
||||
this.gameThreadBehaviour = gameThreadBehaviour;
|
||||
|
||||
// Tell thread how to send moves
|
||||
this.gameThreadBehaviour.setOnSendMove((id, m) -> GlobalEventBus.postAsync(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.setMove(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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package org.toop.app.gameControllers;
|
||||
|
||||
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.OnlinePlayer;
|
||||
|
||||
public class ReversiBitController extends GenericGameController<BitboardReversi> {
|
||||
public ReversiBitController(Player<BitboardReversi>[] players) {
|
||||
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(), game, thread, "Reversi");
|
||||
}
|
||||
}
|
||||
@@ -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> {
|
||||
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,10 +1,11 @@
|
||||
package org.toop.app.widget;
|
||||
|
||||
import javafx.scene.image.ImageView;
|
||||
import org.toop.framework.audio.events.AudioEvents;
|
||||
import org.toop.framework.eventbus.EventFlow;
|
||||
import org.toop.framework.resource.resources.ImageAsset;
|
||||
import org.toop.local.AppContext;
|
||||
|
||||
import java.awt.*;
|
||||
import java.io.File;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
@@ -22,31 +23,39 @@ import javafx.scene.layout.VBox;
|
||||
import javafx.scene.text.Text;
|
||||
import javafx.util.StringConverter;
|
||||
|
||||
public final class Primitive {
|
||||
public static Text header(String key) {
|
||||
public final class Primitive {
|
||||
public static Text header(String key, boolean localize) {
|
||||
var header = new Text();
|
||||
header.getStyleClass().add("header");
|
||||
|
||||
if (!key.isEmpty()) {
|
||||
header.setText(AppContext.getString(key));
|
||||
header.textProperty().bind(AppContext.bindToKey(key));
|
||||
if (localize) header.setText(AppContext.getString(key)); else header.setText(key);
|
||||
header.textProperty().bind(AppContext.bindToKey(key, localize));
|
||||
}
|
||||
|
||||
return header;
|
||||
}
|
||||
|
||||
public static Text text(String key) {
|
||||
public static Text header(String key) {
|
||||
return header(key, true);
|
||||
}
|
||||
|
||||
public static Text text(String key, boolean localize) {
|
||||
var text = new Text();
|
||||
text.getStyleClass().add("text");
|
||||
|
||||
if (!key.isEmpty()) {
|
||||
text.setText(AppContext.getString(key));
|
||||
text.textProperty().bind(AppContext.bindToKey(key));
|
||||
if (localize) text.setText(AppContext.getString(key)); else text.setText(key);
|
||||
text.textProperty().bind(AppContext.bindToKey(key, localize));
|
||||
}
|
||||
|
||||
return text;
|
||||
}
|
||||
|
||||
public static Text text(String key) {
|
||||
return text(key, true);
|
||||
}
|
||||
|
||||
public static ImageView image(ImageAsset imageAsset) {
|
||||
ImageView imageView = new ImageView(imageAsset.getImage());
|
||||
imageView.getStyleClass().add("image");
|
||||
@@ -56,30 +65,36 @@ public final class Primitive {
|
||||
return imageView;
|
||||
}
|
||||
|
||||
public static Button button(String key, Runnable onAction) {
|
||||
public static Button button(String key, Runnable onAction, boolean localize) {
|
||||
var button = new Button();
|
||||
button.getStyleClass().add("button");
|
||||
|
||||
if (!key.isEmpty()) {
|
||||
button.setText(AppContext.getString(key));
|
||||
button.textProperty().bind(AppContext.bindToKey(key));
|
||||
if (localize) button.setText(AppContext.getString(key)); else button.setText(key);
|
||||
button.textProperty().bind(AppContext.bindToKey(key, localize));
|
||||
}
|
||||
|
||||
if (onAction != null) {
|
||||
button.setOnAction(_ ->
|
||||
onAction.run());
|
||||
button.setOnAction(_ -> {
|
||||
onAction.run();
|
||||
playButtonSound();
|
||||
});
|
||||
}
|
||||
|
||||
return button;
|
||||
}
|
||||
|
||||
public static TextField input(String promptKey, String text, Consumer<String> onValueChanged) {
|
||||
public static Button button(String key, Runnable onAction) {
|
||||
return button(key, onAction, true);
|
||||
}
|
||||
|
||||
public static TextField input(String promptKey, String text, Consumer<String> onValueChanged, boolean localize) {
|
||||
var input = new TextField();
|
||||
input.getStyleClass().add("input");
|
||||
|
||||
if (!promptKey.isEmpty()) {
|
||||
input.setPromptText(AppContext.getString(promptKey));
|
||||
input.promptTextProperty().bind(AppContext.bindToKey(promptKey));
|
||||
if (localize) input.setPromptText(AppContext.getString(promptKey)); else input.setPromptText(promptKey);
|
||||
input.promptTextProperty().bind(AppContext.bindToKey(promptKey, localize));
|
||||
}
|
||||
|
||||
input.setText(text);
|
||||
@@ -92,6 +107,10 @@ public final class Primitive {
|
||||
return input;
|
||||
}
|
||||
|
||||
public static TextField input(String promptKey, String text, Consumer<String> onValueChanged) {
|
||||
return input(promptKey, text, onValueChanged, true);
|
||||
}
|
||||
|
||||
public static Slider slider(int min, int max, int value, Consumer<Integer> onValueChanged) {
|
||||
var slider = new Slider();
|
||||
slider.getStyleClass().add("slider");
|
||||
@@ -100,12 +119,17 @@ public final class Primitive {
|
||||
slider.setMax(max);
|
||||
slider.setValue(value);
|
||||
|
||||
if (onValueChanged != null) {
|
||||
slider.valueProperty().addListener((_, _, newValue) ->
|
||||
onValueChanged.accept(newValue.intValue()));
|
||||
}
|
||||
if (onValueChanged != null) {
|
||||
slider.valueProperty().addListener((_, _, newValue) -> {
|
||||
onValueChanged.accept(newValue.intValue());
|
||||
});
|
||||
}
|
||||
|
||||
return slider;
|
||||
slider.setOnMouseReleased(event -> {
|
||||
playButtonSound();
|
||||
});
|
||||
|
||||
return slider;
|
||||
}
|
||||
|
||||
@SafeVarargs
|
||||
@@ -122,9 +146,11 @@ public final class Primitive {
|
||||
}
|
||||
|
||||
if (onValueChanged != null) {
|
||||
choice.valueProperty().addListener((_, _, newValue) ->
|
||||
onValueChanged.accept(newValue));
|
||||
}
|
||||
choice.valueProperty().addListener((_, _, newValue) -> {
|
||||
onValueChanged.accept(newValue);
|
||||
playButtonSound();
|
||||
});
|
||||
}
|
||||
|
||||
choice.setItems(FXCollections.observableArrayList(items));
|
||||
|
||||
@@ -176,4 +202,8 @@ public final class Primitive {
|
||||
|
||||
return vbox;
|
||||
}
|
||||
|
||||
private static void playButtonSound() {
|
||||
new EventFlow().addPostEvent(new AudioEvents.ClickButton()).postEvent();
|
||||
}
|
||||
}
|
||||
162
app/src/main/java/org/toop/app/widget/complex/LoadingWidget.java
Normal file
162
app/src/main/java/org/toop/app/widget/complex/LoadingWidget.java
Normal file
@@ -0,0 +1,162 @@
|
||||
package org.toop.app.widget.complex;
|
||||
|
||||
import javafx.application.Platform;
|
||||
import javafx.geometry.Pos;
|
||||
import javafx.scene.control.Control;
|
||||
import javafx.scene.control.ProgressBar;
|
||||
import javafx.scene.control.ProgressIndicator;
|
||||
import javafx.scene.layout.VBox;
|
||||
import javafx.scene.text.Text;
|
||||
import org.toop.app.widget.Primitive;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
public class LoadingWidget extends ViewWidget implements Update { // TODO make of widget type
|
||||
private final Text loadingText; // TODO Make changeable
|
||||
private final ProgressIndicator progressBar;
|
||||
private final AtomicBoolean successTriggered = new AtomicBoolean(false);
|
||||
private final AtomicBoolean failureTriggered = new AtomicBoolean(false);
|
||||
|
||||
private Runnable success = () -> {};
|
||||
private Runnable failure = () -> {};
|
||||
private int maxAmount;
|
||||
private int minAmount;
|
||||
private int amount;
|
||||
private Callable<Boolean> successTrigger = () -> (amount >= maxAmount);
|
||||
private Callable<Boolean> failureTrigger = () -> (amount < minAmount);
|
||||
private float percentage = 0.0f;
|
||||
|
||||
private boolean isInfinite = false;
|
||||
|
||||
/**
|
||||
*
|
||||
* Widget that shows a loading bar.
|
||||
*
|
||||
* @param loadingText Text above the loading bar.
|
||||
* @param minAmount The minimum amount.
|
||||
* @param startAmount The starting amount.
|
||||
* @param maxAmount The max amount.
|
||||
*/
|
||||
public LoadingWidget(Text loadingText, int minAmount, int startAmount, int maxAmount, boolean infinite, boolean circle) {
|
||||
isInfinite = infinite;
|
||||
|
||||
this.maxAmount = maxAmount;
|
||||
this.minAmount = minAmount;
|
||||
amount = startAmount;
|
||||
|
||||
this.loadingText = loadingText;
|
||||
progressBar = circle ? new ProgressIndicator() : new ProgressBar();
|
||||
|
||||
VBox box = Primitive.vbox(this.loadingText, progressBar);
|
||||
progressBar.getStyleClass().add("loading-progress-bar");
|
||||
add(Pos.CENTER, box);
|
||||
}
|
||||
|
||||
public void setMaxAmount(int maxAmount) {
|
||||
this.maxAmount = maxAmount;
|
||||
}
|
||||
|
||||
public void setAmount(int amount) throws Exception {
|
||||
this.amount = amount;
|
||||
update();
|
||||
}
|
||||
|
||||
public int getMaxAmount() {
|
||||
return maxAmount;
|
||||
}
|
||||
|
||||
public int getAmount() {
|
||||
return amount;
|
||||
}
|
||||
|
||||
public float getPercentage() {
|
||||
return percentage;
|
||||
}
|
||||
|
||||
public boolean isTriggered() {
|
||||
return (failureTriggered.get() || successTriggered.get());
|
||||
}
|
||||
|
||||
public ProgressIndicator getProgressBar() {
|
||||
return progressBar;
|
||||
}
|
||||
|
||||
/**
|
||||
* What to do when success is triggered.
|
||||
* @param onSuccess The lambda that gets run on success.
|
||||
*/
|
||||
public void setOnSuccess(Runnable onSuccess) {
|
||||
success = onSuccess;
|
||||
}
|
||||
|
||||
/**
|
||||
* What to do when failure is triggered.
|
||||
* @param onFailure The lambda that gets run on failure.
|
||||
*/
|
||||
public void setOnFailure(Runnable onFailure) {
|
||||
failure = onFailure;
|
||||
}
|
||||
|
||||
/**
|
||||
* The trigger to activate onSuccess.
|
||||
* @param trigger The lambda that triggers onSuccess.
|
||||
*/
|
||||
public void setSuccessTrigger(Callable<Boolean> trigger) {
|
||||
successTrigger = trigger;
|
||||
}
|
||||
|
||||
/**
|
||||
* The trigger to activate onFailure.
|
||||
* @param trigger The lambda that triggers onFailure.
|
||||
*/
|
||||
public void setFailureTrigger(Callable<Boolean> trigger) {
|
||||
failureTrigger = trigger;
|
||||
}
|
||||
|
||||
/**
|
||||
* Forcefully trigger success.
|
||||
*/
|
||||
public void triggerSuccess() {
|
||||
if (successTriggered.compareAndSet(false, true)) {
|
||||
Platform.runLater(() -> {
|
||||
if (success != null) success.run();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Forcefully trigger failure.
|
||||
*/
|
||||
public void triggerFailure() {
|
||||
if (failureTriggered.compareAndSet(false, true)) {
|
||||
Platform.runLater(() -> {
|
||||
if (failure != null) failure.run();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void update() throws Exception { // TODO Better exception
|
||||
if (successTriggered.get() || failureTriggered.get()) { // If already triggered, throw exception.
|
||||
throw new RuntimeException();
|
||||
}
|
||||
|
||||
if (successTrigger.call()) {
|
||||
triggerSuccess();
|
||||
this.remove(this);
|
||||
return;
|
||||
} else if (failureTrigger.call()) {
|
||||
triggerFailure();
|
||||
this.remove(this);
|
||||
return;
|
||||
}
|
||||
|
||||
if (maxAmount != 0) {
|
||||
percentage = (float) amount / maxAmount;
|
||||
}
|
||||
if (!isInfinite) {
|
||||
progressBar.setProgress(percentage);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,8 @@ package org.toop.app.widget.complex;
|
||||
|
||||
import org.toop.app.widget.Primitive;
|
||||
import org.toop.app.widget.Widget;
|
||||
import org.toop.framework.audio.events.AudioEvents;
|
||||
import org.toop.framework.eventbus.EventFlow;
|
||||
import org.toop.local.AppContext;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
@@ -29,8 +31,9 @@ public class ToggleWidget implements Widget {
|
||||
state = !state;
|
||||
updateText();
|
||||
if (onToggle != null) {
|
||||
onToggle.accept(state);
|
||||
}
|
||||
onToggle.accept(state);
|
||||
new EventFlow().addPostEvent(new AudioEvents.ClickButton()).postEvent(); // TODO FIX PRIMITIVES
|
||||
}
|
||||
});
|
||||
|
||||
container = Primitive.vbox(button);
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
package org.toop.app.widget.complex;
|
||||
|
||||
public interface Update {
|
||||
void update() throws Exception;
|
||||
}
|
||||
@@ -16,8 +16,18 @@ public abstract class ViewWidget extends StackWidget {
|
||||
replace(Pos.CENTER, view);
|
||||
}
|
||||
|
||||
public void transitionNext(ViewWidget view) {
|
||||
view.previous = this;
|
||||
public void transitionNext(ViewWidget view) {
|
||||
transitionNext(view, false);
|
||||
}
|
||||
|
||||
public void transitionNext(ViewWidget view, boolean aware) {
|
||||
if (aware && this.getClass().equals(view.getClass())) {
|
||||
view.previous = this.previous;
|
||||
}
|
||||
else{
|
||||
view.previous = this;
|
||||
}
|
||||
|
||||
replace(Pos.CENTER, view);
|
||||
|
||||
var backButton = Primitive.button("back", () -> {
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
package org.toop.app.widget.display;
|
||||
|
||||
import javafx.animation.KeyFrame;
|
||||
import javafx.animation.Timeline;
|
||||
import javafx.util.Duration;
|
||||
import org.toop.app.widget.Widget;
|
||||
import org.toop.framework.audio.events.AudioEvents;
|
||||
import org.toop.framework.eventbus.EventFlow;
|
||||
@@ -18,17 +15,14 @@ import javafx.scene.layout.Region;
|
||||
import javafx.scene.layout.VBox;
|
||||
import javafx.scene.text.Text;
|
||||
|
||||
import java.util.Timer;
|
||||
|
||||
public class SongDisplay extends VBox implements Widget {
|
||||
private final Text songTitle;
|
||||
private final ProgressBar progressBar;
|
||||
private final Text progressText;
|
||||
private boolean canClick = true;
|
||||
|
||||
public SongDisplay() {
|
||||
new EventFlow()
|
||||
.listen(this::updateTheSong);
|
||||
.listen(AudioEvents.PlayingMusic.class, this::updateTheSong, false);
|
||||
|
||||
setAlignment(Pos.CENTER);
|
||||
setMaxHeight(Region.USE_PREF_SIZE);
|
||||
@@ -39,7 +33,7 @@ public class SongDisplay extends VBox implements Widget {
|
||||
songTitle.getStyleClass().add("song-title");
|
||||
|
||||
progressBar = new ProgressBar(0);
|
||||
progressBar.getStyleClass().add("progress-bar");
|
||||
progressBar.getStyleClass().add("loading-progress-bar");
|
||||
|
||||
progressText = new Text("0:00/0:00");
|
||||
progressText.getStyleClass().add("progress-text");
|
||||
@@ -55,13 +49,10 @@ public class SongDisplay extends VBox implements Widget {
|
||||
previousButton.getStyleClass().setAll("previous-button");
|
||||
|
||||
skipButton.setOnAction( event -> {
|
||||
if (!canClick) { return; }
|
||||
GlobalEventBus.post(new AudioEvents.SkipMusic());
|
||||
doCooldown();
|
||||
});
|
||||
|
||||
pauseButton.setOnAction(event -> {
|
||||
if (!canClick) { return; }
|
||||
GlobalEventBus.post(new AudioEvents.PauseMusic());
|
||||
if (pauseButton.getText().equals("⏸")) {
|
||||
pauseButton.setText("▶");
|
||||
@@ -69,13 +60,10 @@ public class SongDisplay extends VBox implements Widget {
|
||||
else if (pauseButton.getText().equals("▶")) {
|
||||
pauseButton.setText("⏸");
|
||||
}
|
||||
doCooldown();
|
||||
});
|
||||
|
||||
previousButton.setOnAction( event -> {
|
||||
if (!canClick) { return; }
|
||||
GlobalEventBus.post(new AudioEvents.PreviousMusic());
|
||||
doCooldown();
|
||||
});
|
||||
|
||||
HBox control = new HBox(10, previousButton, pauseButton, skipButton);
|
||||
@@ -122,16 +110,6 @@ public class SongDisplay extends VBox implements Widget {
|
||||
return time;
|
||||
}
|
||||
|
||||
private void doCooldown() {
|
||||
canClick = false;
|
||||
Timeline cooldown = new Timeline(
|
||||
new KeyFrame(Duration.millis(300), event -> canClick = true)
|
||||
);
|
||||
cooldown.setCycleCount(1);
|
||||
cooldown.play();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Node getNode() {
|
||||
return this;
|
||||
|
||||
@@ -7,18 +7,17 @@ import org.toop.local.AppContext;
|
||||
import javafx.geometry.Pos;
|
||||
|
||||
public final class GameOverPopup extends PopupWidget {
|
||||
public GameOverPopup(boolean iWon, String winner) {
|
||||
public GameOverPopup(boolean winOrTie, String winner) {
|
||||
var confirmWidget = new ConfirmWidget("game-over");
|
||||
|
||||
if (winner.isEmpty()) {
|
||||
confirmWidget.setMessage(AppContext.getString("the-game-ended-in-a-draw"));
|
||||
} else if (iWon) {
|
||||
confirmWidget.setMessage(AppContext.getString("you-win"));
|
||||
} else {
|
||||
confirmWidget.setMessage(AppContext.getString("you-lost-against") + ": " + winner);
|
||||
}
|
||||
if (winOrTie) {
|
||||
confirmWidget.setMessage(winner + " won the game!");
|
||||
}
|
||||
else{
|
||||
confirmWidget.setMessage("It was a tie!");
|
||||
}
|
||||
|
||||
confirmWidget.addButton("ok", () -> hide());
|
||||
confirmWidget.addButton("ok", this::hide);
|
||||
|
||||
add(Pos.CENTER, confirmWidget);
|
||||
}
|
||||
|
||||
@@ -87,7 +87,6 @@ public class BaseTutorialWidget extends PopupWidget implements Updatable {
|
||||
this.hide();
|
||||
nextScreen.run();
|
||||
});
|
||||
|
||||
} else {
|
||||
nextButton.textProperty().unbind();
|
||||
nextButton.setText(AppContext.getString(">"));
|
||||
|
||||
@@ -2,24 +2,39 @@ package org.toop.app.widget.view;
|
||||
|
||||
import javafx.application.Platform;
|
||||
import org.toop.app.GameInformation;
|
||||
import org.toop.app.game.Connect4Game;
|
||||
import org.toop.app.game.ReversiGame;
|
||||
import org.toop.app.game.TicTacToeGameThread;
|
||||
import org.toop.app.canvas.ReversiBitCanvas;
|
||||
import org.toop.app.canvas.TicTacToeBitCanvas;
|
||||
import org.toop.app.gameControllers.GenericGameController;
|
||||
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.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.WidgetContainer;
|
||||
import org.toop.app.widget.complex.PlayerInfoWidget;
|
||||
import org.toop.app.widget.complex.ViewWidget;
|
||||
import org.toop.app.widget.popup.ErrorPopup;
|
||||
import org.toop.app.widget.tutorial.*;
|
||||
import org.toop.game.players.MiniMaxAI;
|
||||
import org.toop.game.players.RandomAI;
|
||||
import org.toop.local.AppContext;
|
||||
|
||||
import javafx.geometry.Pos;
|
||||
import javafx.scene.control.ScrollPane;
|
||||
import javafx.scene.layout.VBox;
|
||||
import org.toop.local.AppSettings;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Random;
|
||||
|
||||
public class LocalMultiplayerView extends ViewWidget {
|
||||
private final GameInformation information;
|
||||
|
||||
private GameController gameController;
|
||||
|
||||
public LocalMultiplayerView(GameInformation.Type type) {
|
||||
this(new GameInformation(type));
|
||||
}
|
||||
@@ -27,6 +42,9 @@ public class LocalMultiplayerView extends ViewWidget {
|
||||
public LocalMultiplayerView(GameInformation information) {
|
||||
this.information = information;
|
||||
var playButton = Primitive.button("play", () -> {
|
||||
if (gameController != null) {
|
||||
gameController.stop();
|
||||
}
|
||||
for (var player : information.players) {
|
||||
if (player.isHuman && player.name.isEmpty()) {
|
||||
new ErrorPopup(AppContext.getString("please-enter-your-name")).show(Pos.CENTER);
|
||||
@@ -34,42 +52,67 @@ public class LocalMultiplayerView extends ViewWidget {
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Fix this temporary ass way of setting the players
|
||||
Player[] players = new Player[2];
|
||||
|
||||
switch (information.type) {
|
||||
case TICTACTOE:
|
||||
if (AppSettings.getSettings().getTutorialFlag() && AppSettings.getSettings().getFirstTTT()) {
|
||||
new ShowEnableTutorialWidget(
|
||||
() -> new TicTacToeTutorialWidget(() -> new TicTacToeGameThread(information)),
|
||||
() -> Platform.runLater(() -> new TicTacToeGameThread(information)),
|
||||
() -> AppSettings.getSettings().setFirstTTT(false)
|
||||
);
|
||||
if (information.players[0].isHuman) {
|
||||
players[0] = new LocalPlayer<>(information.players[0].name);
|
||||
} else {
|
||||
new TicTacToeGameThread(information);
|
||||
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 MiniMaxAI<BitboardTicTacToe>(9), "MiniMax AI");
|
||||
}
|
||||
if (AppSettings.getSettings().getTutorialFlag() && AppSettings.getSettings().getFirstTTT()) {
|
||||
new ShowEnableTutorialWidget(
|
||||
() -> new TicTacToeTutorialWidget(() -> {
|
||||
gameController = new TicTacToeBitController(players);
|
||||
gameController.start();
|
||||
}),
|
||||
() -> Platform.runLater(() -> {
|
||||
gameController = new TicTacToeBitController(players);
|
||||
gameController.start();
|
||||
}),
|
||||
() -> AppSettings.getSettings().setFirstTTT(false)
|
||||
);
|
||||
} else {
|
||||
gameController = new TicTacToeBitController(players);
|
||||
gameController.start();
|
||||
}
|
||||
break;
|
||||
case REVERSI:
|
||||
if (information.players[0].isHuman) {
|
||||
players[0] = new LocalPlayer<>(information.players[0].name);
|
||||
} else {
|
||||
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 MiniMaxAI<BitboardReversi>(6), "MiniMax");
|
||||
}
|
||||
if (AppSettings.getSettings().getTutorialFlag() && AppSettings.getSettings().getFirstReversi()) {
|
||||
new ShowEnableTutorialWidget(
|
||||
() -> new ReversiTutorialWidget(() -> new ReversiGame(information)),
|
||||
() -> Platform.runLater(() -> new ReversiGame(information)),
|
||||
() -> new ReversiTutorialWidget(() -> {
|
||||
gameController = new ReversiBitController(players);
|
||||
gameController.start();
|
||||
}),
|
||||
() -> Platform.runLater(() -> {
|
||||
gameController = new ReversiBitController(players);
|
||||
gameController.start();
|
||||
}),
|
||||
() -> AppSettings.getSettings().setFirstReversi(false)
|
||||
);
|
||||
} else {
|
||||
new ReversiGame(information);
|
||||
}
|
||||
break;
|
||||
case CONNECT4:
|
||||
if (AppSettings.getSettings().getTutorialFlag() && AppSettings.getSettings().getFirstConnect4()) {
|
||||
new ShowEnableTutorialWidget(
|
||||
() -> new Connect4TutorialWidget(() -> new Connect4Game(information)),
|
||||
() -> Platform.runLater(() -> new Connect4Game(information)),
|
||||
() -> AppSettings.getSettings().setFirstConnect4(false)
|
||||
);
|
||||
} else {
|
||||
new Connect4Game(information);
|
||||
gameController = new ReversiBitController(players);
|
||||
gameController.start();
|
||||
}
|
||||
break;
|
||||
}
|
||||
// case BATTLESHIP -> new BattleshipGame(information);
|
||||
});
|
||||
|
||||
var playerSection = setupPlayerSections();
|
||||
|
||||
@@ -16,14 +16,9 @@ public class LocalView extends ViewWidget {
|
||||
transitionNext(new LocalMultiplayerView(GameInformation.Type.REVERSI));
|
||||
});
|
||||
|
||||
var connect4Button = Primitive.button("connect4", () -> {
|
||||
transitionNext(new LocalMultiplayerView(GameInformation.Type.CONNECT4));
|
||||
});
|
||||
|
||||
add(Pos.CENTER, Primitive.vbox(
|
||||
ticTacToeButton,
|
||||
reversiButton,
|
||||
connect4Button
|
||||
reversiButton
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package org.toop.app.widget.view;
|
||||
import org.toop.app.Server;
|
||||
import org.toop.app.widget.Primitive;
|
||||
import org.toop.app.widget.complex.LabeledInputWidget;
|
||||
import org.toop.app.widget.complex.LoadingWidget;
|
||||
import org.toop.app.widget.complex.ViewWidget;
|
||||
|
||||
import javafx.geometry.Pos;
|
||||
|
||||
@@ -29,7 +29,7 @@ public final class ServerView extends ViewWidget {
|
||||
}
|
||||
|
||||
private void setupLayout() {
|
||||
var playerHeader = Primitive.header(user);
|
||||
var playerHeader = Primitive.header(user, false);
|
||||
|
||||
var playerListSection = Primitive.vbox(
|
||||
playerHeader,
|
||||
@@ -52,7 +52,7 @@ public final class ServerView extends ViewWidget {
|
||||
listView.getItems().clear();
|
||||
|
||||
for (String player : players) {
|
||||
var playerButton = Primitive.button(player, () -> onPlayerClicked.accept(player));
|
||||
var playerButton = Primitive.button(player, () -> onPlayerClicked.accept(player), false);
|
||||
listView.getItems().add(playerButton);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -58,10 +58,19 @@ public class AppContext {
|
||||
return "MISSING RESOURCE";
|
||||
}
|
||||
|
||||
public static StringBinding bindToKey(String key) {
|
||||
return Bindings.createStringBinding(
|
||||
() -> localization.getString(key, locale),
|
||||
localeProperty
|
||||
);
|
||||
public static StringBinding bindToKey(String key, boolean localize) {
|
||||
if (localize) return Bindings.createStringBinding(
|
||||
() -> localization.getString(key, locale),
|
||||
localeProperty
|
||||
);
|
||||
|
||||
return Bindings.createStringBinding(
|
||||
() -> key
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
public static StringBinding bindToKey(String key) {
|
||||
return bindToKey(key, true);
|
||||
}
|
||||
}
|
||||
@@ -27,18 +27,24 @@ public class AppSettings {
|
||||
|
||||
AppContext.setLocale(Locale.of(settingsData.locale));
|
||||
App.setFullscreen(settingsData.fullScreen);
|
||||
new EventFlow()
|
||||
.addPostEvent(new AudioEvents.ChangeVolume(settingsData.volume, VolumeControl.MASTERVOLUME))
|
||||
.asyncPostEvent();
|
||||
new EventFlow()
|
||||
.addPostEvent(new AudioEvents.ChangeVolume(settingsData.fxVolume, VolumeControl.FX))
|
||||
.asyncPostEvent();
|
||||
new EventFlow()
|
||||
.addPostEvent(new AudioEvents.ChangeVolume(settingsData.musicVolume, VolumeControl.MUSIC))
|
||||
.asyncPostEvent();
|
||||
|
||||
App.setStyle(settingsAsset.getTheme(), settingsAsset.getLayoutSize());
|
||||
}
|
||||
|
||||
public static void applyMusicVolumeSettings() {
|
||||
Settings settingsData = settingsAsset.getContent();
|
||||
|
||||
new EventFlow()
|
||||
.addPostEvent(new AudioEvents.ChangeVolume(settingsData.volume, VolumeControl.MASTERVOLUME))
|
||||
.asyncPostEvent();
|
||||
new EventFlow()
|
||||
.addPostEvent(new AudioEvents.ChangeVolume(settingsData.fxVolume, VolumeControl.FX))
|
||||
.asyncPostEvent();
|
||||
new EventFlow()
|
||||
.addPostEvent(new AudioEvents.ChangeVolume(settingsData.musicVolume, VolumeControl.MUSIC))
|
||||
.asyncPostEvent();
|
||||
}
|
||||
|
||||
public static SettingsAsset getPath() {
|
||||
if (settingsAsset == null) {
|
||||
String os = System.getProperty("os.name").toLowerCase();
|
||||
|
||||
@@ -83,6 +83,8 @@ reversi2=\u0639\u0646\u062f\u0645\u0627 \u062a\u0646\u0642\u0631 \u0639\u0644\u0
|
||||
reversi3=\u0645\u0631\u062a\u0643 \u0642\u062f \u064a\u062a\u063a\u0627\u0637 \u0625\u0630\u0627 \u0644\u0645 \u064a\u0643\u0646 \u0647\u0646\u0627\u0643 \u062d\u0631\u0643 \u0642\u0627\u0646\u0648\u0646\u064a.
|
||||
reversi4=\u0627\u0644\u0644\u0627\u0639\u0628 \u0627\u0644\u0630\u064a \u064a\u0641\u0648\u0632 \u0641\u064a \u0646\u0647\u0627\u064a\u0629 \u0627\u0644\u0644\u0639\u0628 \u0647\u0648 \u0627\u0644\u0630\u064a \u064a\u0643\u0648\u0646 \u0644\u062f\u064a\u0647 \u0627\u0644\u0623\u0643\u062b\u0631 \u0645\u0646 \u0627\u0644\u0644\u0648\u0639\u0627\u0628 \u0639\u0644\u0649 \u0627\u0644\u0644\u0648\u062d\u0629.
|
||||
tutorialstring=\u0627\u0644\u062f\u0631\u0633 \u0627\u0644\u062a\u0648\u0636\u064a\u062d\u064a
|
||||
startgame=\u0627\u0628\u062f\u0623 \u0627\u0644\u0644\u0639\u0628\u0629!
|
||||
goback=\u0627\u0631\u062c\u0639
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629
|
||||
chinese=\u4e2d\u6587 (\u0627\u0644\u0635\u064a\u0646\u064a\u0629)
|
||||
@@ -85,6 +85,8 @@ reversi2=Wenn du auf einen Punkt klickst, werden alle Spielsteine dazwischen umg
|
||||
reversi3=Dein Zug kann übersprungen werden, wenn es keinen legalen Zug gibt. Dein Gegner spielt dann weiter, bis du einen legalen Zug machen kannst.
|
||||
reversi4=Der Spieler, der am Ende die meisten Steine auf dem Brett hat, gewinnt.
|
||||
tutorialstring=Tutorial
|
||||
startgame=Spiel starten!
|
||||
goback=Zurück
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (Arabisch)
|
||||
chinese=\u4e2d\u6587 (Chinesisch)
|
||||
@@ -9,6 +9,8 @@ computer-difficulty=Computer difficulty
|
||||
computer-think-time=Computer think time
|
||||
computer=Computer
|
||||
connect=Connect
|
||||
connecting=Connecting to server...
|
||||
connecting-failed=Could not connect to server:
|
||||
credits=Credits
|
||||
dark=Dark
|
||||
deny=Deny
|
||||
@@ -84,6 +84,8 @@ reversi2=Al hacer clic en un punto, se voltear
|
||||
reversi3=Tu turno puede ser saltado si no hay un movimiento legal. Esto permitirá que tu oponente juegue nuevamente hasta que tengas una oportunidad legal.
|
||||
reversi4=El jugador que gane al final del juego es quien tenga más fichas en el tablero.
|
||||
tutorialstring=Tutorial
|
||||
startgame=\u00a1Iniciar juego!
|
||||
goback=Volver
|
||||
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (Ar\u00e1bigo)
|
||||
@@ -84,6 +84,8 @@ reversi2=Cliquer sur un point retournera tous les pions entre le point plac
|
||||
reversi3=Votre tour peut être sauté s'il n'y a pas de coup légal. Cela permettra à votre adversaire de jouer jusqu'à ce que vous ayez un coup légal.
|
||||
reversi4=Le joueur qui a le plus de pions à la fin du jeu gagne.
|
||||
tutorialstring=Tutoriel
|
||||
startgame=D\u00e9marrer le jeu!
|
||||
goback=Retour
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (Arabe)
|
||||
chinese=\u4e2d\u6587 (Chinois)
|
||||
@@ -84,6 +84,8 @@ reversi2=\u0915\u093f\u0938 \u092a\u0930 \u092a\u093f\u0938 \u092a\u0948\u0918 \
|
||||
reversi3=\u092f\u0939 \u092a\u0930\u094d\u092f \u0938\u0947 \u0938\u0947\u091a \u0915\u0940 \u091c\u093e\u0902\u091c \u0928\u0939\u0940\u0902 \u0939\u0948 \u0914\u0938\u0924\u0947 \u0915\u0948 \u092a\u0948\u0928 \u092a\u0930\u094d\u092f \u0939\u0948 \u0914\u092a\u0915\u0940 \u0915\u0940 \u092a\u0932\u0947 \u092d\u0942\u0924 \u0915\u0940 \u0906\u0927\u093e \u092a\u0948\u0928 \u091c\u093e\u0902\u091c \u0915\u0930 \u0938\u0915\u0924\u0947 \u0939\u0948\u0902.
|
||||
reversi4=\u0916\u0941\u092f \u0915\u093f \u0915\u0940 \u0928\u093f\u092e\u0940 \u092e\u0947\u0902 \u091a\u093e\u0932 \u0938\u092c\u0938\u0947 \u091a\u0942\u0928\u094d\u0928\u0947 \u0939\u0948, \u0935\u0949 \u0915\u0947 \u092e\u093e\u0924\u094d\u0930 \u091c\u0940\u0924\u0947 \u0939\u0948.
|
||||
tutorialstring=\u0924\u0942\u091f\u0949\u0930\u093f\u092f\u0932
|
||||
startgame=\u0916\u0947\u0932 \u0936\u0941\u0930\u0942 \u0915\u0930\u0947\u0902!
|
||||
goback=\u0935\u093e\u092a\u0938 \u091c\u093e\u090f\u0901
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (\u0905\u0930\u092c\u0940)
|
||||
chinese=\u4e2d\u6587 (\u091a\u0940\u0928\u0940)
|
||||
@@ -83,6 +83,8 @@ reversi2=Cliccando su un punto, tutti i pezzi tra dove metti il punto e il pross
|
||||
reversi3=Il tuo turno può essere saltato se non ci sono mosse legali. Questo permetterà al tuo avversario di giocare fino a quando non avrai un'opportunità legale.
|
||||
reversi4=Il giocatore che alla fine del gioco ha più pezzi sulla scacchiera vince.
|
||||
tutorialstring=Tutorial
|
||||
startgame=Avvia il gioco!
|
||||
goback=Indietro
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (Arabo)
|
||||
chinese=\u4e2d\u6587 (Cinese)
|
||||
@@ -83,6 +83,8 @@ reversi2=\u30af\u30ea\u30c3\u30af\u3059\u308b\u3068\u3001\u3064\u306a\u304c\u308
|
||||
reversi3=\u6b21\u306e\u52d5\u304b\u3057\u304c\u306a\u3044\u5834\u5408\u3001\u8a8d\u5b9a\u3055\u308c\u305f\u52d5\u304b\u3057\u306e\u6642\u9593\u306f\u62d2\u7d76\u3055\u308c\u308b\u3053\u3068\u304c\u3042\u308a\u307e\u3059\u3002
|
||||
reversi4=\u672c\u6b21\u306b\u30dc\u30fc\u30c9\u4e0a\u3067\u6700\u591a\u306e\u8ca0\u3051\u3092\u6301\u3064\u30d7\u30ec\u30a4\u30e4\u30fc\u304c\u52dd\u3061\u307e\u3059\u3002
|
||||
tutorialstring=\u30c1\u30e5\u30fc\u30c8\u30ea\u30a2\u30eb
|
||||
startgame=\u30b2\u30fc\u30e0\u3092\u958b\u59cb\uff01
|
||||
goback=\u623b\u308b
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (\u30a2\u30e9\u30d3\u30a2\u8a9e)
|
||||
chinese=\u4e2d\u6587 (\u4e2d\u6587)
|
||||
@@ -83,6 +83,8 @@ reversi2=\ud074\ub9ad \ud558\uba70, \ub2e4\ub978 \ud648 \uc704\ub85c \ucd5c\uc2e
|
||||
reversi3=\uc0ac\uc6a9\uc790\uc758 \ud648\uc744 \ud074 \uc218 \uc5c6\uc2b5\uc2b5\ub2c8\ub2e4. \uc0ac\uc6a9\uc790 \ub2f5\uc5d0 \ub300\ud574 \uc811\ub2c8\ub2e4.
|
||||
reversi4=\uacbd\uc6b0 \uc5d0\uc11c \ucd5c\ub300 \ud648\uc744 \uac00\uc838\ub294 \uc0ac\uc6a9\uc790\uc774 \uc52c\uc544\uc624\uba70 \uc0ac\uc6a9\uc790\uc758 \ud648\uc744 \uc54c\ub824\ud569\ub2c8\ub2e4.
|
||||
tutorialstring=\ud14c\ud2b8\ub9ad
|
||||
startgame=\uac8c\uc784 \uc2dc\uc791!
|
||||
goback=\ub4a4\ub85c \uac00\uae30
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (\u0639\u0631\u0628\u064a\u0629)
|
||||
chinese=\u4e2d\u6587 (\u4e2d\u6587)
|
||||
@@ -83,6 +83,8 @@ reversi2=Door op een stip te klikken draai je alle stukken om tussen de plaats w
|
||||
reversi3=Je beurt kan worden overgeslagen als er geen legale zet is. Hierdoor kan je tegenstander doorgaan tot jij een legale zet kunt doen.
|
||||
reversi4=De speler die aan het einde van het spel de meeste stukken op het bord heeft, wint.
|
||||
tutorialstring=Tutorial
|
||||
startgame=Spel starten!
|
||||
goback=Ga terug
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (Arabisch)
|
||||
chinese=\u4e2d\u6587 (Chinees)
|
||||
@@ -83,6 +83,8 @@ reversi2=\u041d043 \u043d043 \u0430043 \u043a043 \u0430043 \u043a043 \u043e043 \
|
||||
reversi3=\u0412043 \u0430043 \u0436043 \u0434043 \u0430043 \u043d043 \u0438043 \u043d043 \u0435043 \u0435043 \u0432043 \u0430043.
|
||||
reversi4=\u0418043 \u0433043 \u0440043 \u043e043 \u043a043 \u043e043 \u0442043 \u043e043 \u0442043 \u043e043 \u0435043 \u0435043 \u0430043 \u0435043 \u043d043 \u0438043 \u0435043 \u0435043 \u043c043 \u0430043.
|
||||
tutorialstring=\u0423\u0447\u0435\u0431\u043d\u0438\u043a
|
||||
startgame=\u041d\u0430\u0447\u0430\u0442\u044c \u0438\u0433\u0440\u0443!
|
||||
goback=\u041d\u0430\u0437\u0430\u0434
|
||||
|
||||
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)
|
||||
@@ -83,6 +83,8 @@ reversi2=\u70b9\u51fb\u4e00\u4e2a\u70b9\u65f6\u5c06\u5c06\u6240\u6709\u4e2d\u95f
|
||||
reversi3=\u5982\u679c\u6ca1\u6709\u5408\u6cd5\u64cd\u4f5c\u4f60\u7684\u8fdb\u6b65\u53ef\u80fd\u88ab\u5ffd\u7565. \u8fd9\u4f1a\u8ba9\u5bf9\u624b\u518d\u6b21\u64cd\u4f5c\u5230\u4f60\u6709\u5408\u6cd5\u64cd\u4f5c\u65f6.
|
||||
reversi4=\u672c\u6e38\u620f\u7ed3\u675f\u65f6\u8d62\u5f97\u6ee1\u8fc7\u76d8\u9762\u7684\u4ee3\u7406\u6570\u6700\u591a\u7684\u4eba\u5c31\u80dc.
|
||||
tutorialstring=\u6559\u7a0b
|
||||
startgame=\u5f00\u59cb\u6e38\u620f\uff01
|
||||
goback=\u8fd4\u56de
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (\u963f\u62c9\u4f2f\u8bed)
|
||||
chinese=\u4e2d\u6587
|
||||
@@ -16,7 +16,6 @@
|
||||
-fx-padding: 8 12 8 12;
|
||||
-fx-spacing: 6px;
|
||||
-fx-alignment: center;
|
||||
-fx-effect: dropshadow(gaussian, rgba(0, 0, 0, 0.5), 6, 0.5, 0, 2);
|
||||
-fx-min-width: 220px;
|
||||
-fx-max-width: 260px;
|
||||
}
|
||||
@@ -39,6 +38,18 @@
|
||||
-fx-background-radius: 30px;
|
||||
}
|
||||
|
||||
.loading-progress-bar {
|
||||
-fx-progress-color: #3caf3f;
|
||||
}
|
||||
|
||||
.loading-progress-bar > .bar {
|
||||
-fx-background-color: #3caf3f;
|
||||
}
|
||||
|
||||
.loading-progress-bar > .track {
|
||||
-fx-background-color: rgba(0,0,0,0.15);
|
||||
}
|
||||
|
||||
.progress-text {
|
||||
-fx-font-size: 11px;
|
||||
-fx-fill: white;
|
||||
@@ -13,68 +13,77 @@
|
||||
}
|
||||
|
||||
.song-display {
|
||||
-fx-padding: 8 12 8 12;
|
||||
-fx-spacing: 6px;
|
||||
-fx-alignment: center;
|
||||
-fx-effect: dropshadow(gaussian, rgba(0, 0, 0, 0.5), 6, 0.5, 0, 2);
|
||||
-fx-min-width: 220px;
|
||||
-fx-max-width: 260px;
|
||||
-fx-padding: 8 12 8 12;
|
||||
-fx-spacing: 6px;
|
||||
-fx-alignment: center;
|
||||
-fx-min-width: 220px;
|
||||
-fx-max-width: 260px;
|
||||
}
|
||||
|
||||
.song-title {
|
||||
-fx-font-size: 14px;
|
||||
-fx-fill: white;
|
||||
-fx-font-size: 14px;
|
||||
-fx-fill: white;
|
||||
}
|
||||
|
||||
.progress-bar {
|
||||
-fx-pref-width: 200px;
|
||||
-fx-accent: red;
|
||||
-fx-inner-background-color: black;
|
||||
-fx-pref-width: 200px;
|
||||
-fx-accent: red;
|
||||
}
|
||||
|
||||
.progress-bar > .track {
|
||||
-fx-background-radius: 30;
|
||||
-fx-background-radius: 30;
|
||||
}
|
||||
|
||||
.progress-bar > .bar {
|
||||
-fx-background-radius: 30px;
|
||||
-fx-background-radius: 30px;
|
||||
}
|
||||
|
||||
.loading-progress-bar {
|
||||
-fx-progress-color: #28a428;
|
||||
}
|
||||
|
||||
.loading-progress-bar > .bar {
|
||||
-fx-background-color: #28a428;
|
||||
}
|
||||
|
||||
.loading-progress-bar > .track {
|
||||
-fx-background-color: rgba(0,0,0,0.15);
|
||||
}
|
||||
|
||||
.progress-text {
|
||||
-fx-font-size: 11px;
|
||||
-fx-fill: white;
|
||||
-fx-font-size: 11px;
|
||||
-fx-fill: white;
|
||||
}
|
||||
|
||||
.skip-button {
|
||||
-fx-background-color: transparent;
|
||||
-fx-background-radius: 0;
|
||||
-fx-cursor: hand;
|
||||
-fx-text-fill: white;
|
||||
}
|
||||
-fx-background-color: transparent;
|
||||
-fx-background-radius: 0;
|
||||
-fx-cursor: hand;
|
||||
}
|
||||
|
||||
.skip-button .text {
|
||||
-fx-fill: white;
|
||||
.skip-button > .text {
|
||||
-fx-fill: white;
|
||||
}
|
||||
|
||||
.pause-button {
|
||||
-fx-background-color: transparent;
|
||||
-fx-background-radius: 0;
|
||||
-fx-cursor: hand;
|
||||
-fx-text-fill: white;
|
||||
}
|
||||
-fx-background-color: transparent;
|
||||
-fx-background-radius: 0;
|
||||
-fx-cursor: hand;
|
||||
}
|
||||
|
||||
.pause-button .text {
|
||||
-fx-fill: white;
|
||||
.pause-button > .text {
|
||||
-fx-fill: white;
|
||||
}
|
||||
|
||||
.previous-button {
|
||||
-fx-background-color: transparent;
|
||||
-fx-background-radius: 0;
|
||||
-fx-cursor: hand;
|
||||
-fx-text-fill: white;
|
||||
}
|
||||
-fx-background-color: transparent;
|
||||
-fx-background-radius: 0;
|
||||
-fx-cursor: hand;
|
||||
}
|
||||
|
||||
.previous-button .text {
|
||||
-fx-fill: white;
|
||||
.previous-button > .text {
|
||||
-fx-fill: white;
|
||||
}
|
||||
|
||||
.button {
|
||||
@@ -13,69 +13,79 @@
|
||||
}
|
||||
|
||||
.song-display {
|
||||
-fx-padding: 8 12 8 12;
|
||||
-fx-spacing: 6px;
|
||||
-fx-alignment: center;
|
||||
-fx-effect: dropshadow(gaussian, rgba(0, 0, 0, 0.5), 6, 0.5, 0, 2);
|
||||
-fx-min-width: 220px;
|
||||
-fx-max-width: 260px;
|
||||
-fx-padding: 8 12 8 12;
|
||||
-fx-spacing: 6px;
|
||||
-fx-alignment: center;
|
||||
-fx-min-width: 220px;
|
||||
-fx-max-width: 260px;
|
||||
}
|
||||
|
||||
.song-title {
|
||||
-fx-font-size: 14px;
|
||||
-fx-fill: black;
|
||||
-fx-font-size: 14px;
|
||||
-fx-effect: null;
|
||||
}
|
||||
|
||||
.progress-bar {
|
||||
-fx-inner-background-color: black;
|
||||
-fx-pref-width: 200px;
|
||||
-fx-accent: red;
|
||||
-fx-inner-background-color: black;
|
||||
-fx-pref-width: 200px;
|
||||
-fx-accent: red;
|
||||
}
|
||||
|
||||
.progress-bar > .track {
|
||||
-fx-background-radius: 30;
|
||||
-fx-background-radius: 30;
|
||||
}
|
||||
|
||||
.progress-bar > .bar {
|
||||
-fx-background-radius: 30px;
|
||||
-fx-background-radius: 30px;
|
||||
}
|
||||
|
||||
.loading-progress-bar {
|
||||
-fx-progress-color: #3caf3f;
|
||||
}
|
||||
|
||||
.loading-progress-bar > .bar {
|
||||
-fx-background-color: linear-gradient(to bottom, #a2d1a1, #b8e3b9);
|
||||
}
|
||||
|
||||
.loading-progress-bar > .track {
|
||||
-fx-background-color: rgba(0,0,0,0.15);
|
||||
}
|
||||
|
||||
.progress-text {
|
||||
-fx-font-size: 11px;
|
||||
-fx-fill: black;
|
||||
-fx-font-size: 11px;
|
||||
-fx-effect: null;
|
||||
}
|
||||
|
||||
.skip-button {
|
||||
-fx-background-color: transparent;
|
||||
-fx-background-radius: 0;
|
||||
-fx-cursor: hand;
|
||||
-fx-text-fill: black;
|
||||
}
|
||||
-fx-background-color: transparent;
|
||||
-fx-background-radius: 0;
|
||||
-fx-cursor: hand;
|
||||
-fx-effect: null;
|
||||
}
|
||||
|
||||
.skip-button .text {
|
||||
-fx-fill: black;
|
||||
}
|
||||
|
||||
.pause-button {
|
||||
-fx-background-color: transparent;
|
||||
-fx-background-radius: 0;
|
||||
-fx-cursor: hand;
|
||||
-fx-text-fill: black;
|
||||
}
|
||||
-fx-background-color: transparent;
|
||||
-fx-background-radius: 0;
|
||||
-fx-cursor: hand;
|
||||
-fx-effect: null;
|
||||
}
|
||||
|
||||
.pause-button .text {
|
||||
-fx-fill: black;
|
||||
-fx-effect: null;
|
||||
}
|
||||
|
||||
.previous-button {
|
||||
-fx-background-color: transparent;
|
||||
-fx-background-radius: 0;
|
||||
-fx-cursor: hand;
|
||||
-fx-text-fill: black;
|
||||
}
|
||||
-fx-background-color: transparent;
|
||||
-fx-background-radius: 0;
|
||||
-fx-cursor: hand;
|
||||
-fx-effect: null;
|
||||
}
|
||||
|
||||
.previous-button .text {
|
||||
-fx-fill: black;
|
||||
-fx-effect: null;
|
||||
}
|
||||
|
||||
.button {
|
||||
@@ -25,17 +25,16 @@ public class AudioEventListener<T extends AudioResource, K extends AudioResource
|
||||
|
||||
public AudioEventListener<?, ?> initListeners(String buttonSoundToPlay) {
|
||||
new EventFlow()
|
||||
.listen(this::handleStopMusicManager)
|
||||
.listen(this::handlePlaySound)
|
||||
.listen(this::handleSkipSong)
|
||||
.listen(this::handlePauseSong)
|
||||
.listen(this::handlePreviousSong)
|
||||
.listen(this::handleStopSound)
|
||||
.listen(this::handleMusicStart)
|
||||
.listen(this::handleVolumeChange)
|
||||
.listen(this::handleGetVolume)
|
||||
.listen(AudioEvents.ClickButton.class, _ ->
|
||||
soundEffectManager.play(buttonSoundToPlay, false));
|
||||
.listen(AudioEvents.StopAudioManager.class, this::handleStopMusicManager, false)
|
||||
.listen(AudioEvents.PlayEffect.class, this::handlePlaySound, false)
|
||||
.listen(AudioEvents.SkipMusic.class, this::handleSkipSong, false)
|
||||
.listen(AudioEvents.PauseMusic.class, this::handlePauseSong, false)
|
||||
.listen(AudioEvents.PreviousMusic.class, this::handlePreviousSong, false)
|
||||
.listen(AudioEvents.StopEffect.class, this::handleStopSound, false)
|
||||
.listen(AudioEvents.StartBackgroundMusic.class, this::handleMusicStart, false)
|
||||
.listen(AudioEvents.ChangeVolume.class, this::handleVolumeChange, false)
|
||||
.listen(AudioEvents.GetVolume.class, this::handleGetVolume,false)
|
||||
.listen(AudioEvents.ClickButton.class, _ -> soundEffectManager.play(buttonSoundToPlay, false), false);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ public class EventFlow {
|
||||
private EventType event = null;
|
||||
|
||||
/** The listener returned by GlobalEventBus subscription. Used for unsubscription. */
|
||||
private final List<ListenerHandler> listeners = new ArrayList<>();
|
||||
private final List<ListenerHandler<?>> listeners = new ArrayList<>();
|
||||
|
||||
/** Holds the results returned from the subscribed event, if any. */
|
||||
private Map<String, ?> result = null;
|
||||
@@ -46,16 +46,15 @@ public class EventFlow {
|
||||
/** Empty constructor (event must be added via {@link #addPostEvent(Class, Object...)}). */
|
||||
public EventFlow() {}
|
||||
|
||||
public EventFlow addPostEvent(EventType event) {
|
||||
this.event = event;
|
||||
return this;
|
||||
}
|
||||
|
||||
public EventFlow addPostEvent(Supplier<? extends EventType> eventSupplier) {
|
||||
this.event = eventSupplier.get();
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Add an event that will be triggered when {@link #postEvent()} or {@link #asyncPostEvent()} is called.
|
||||
*
|
||||
* @param eventClass The event that will be posted.
|
||||
* @param args The event arguments, see the added event record for more information.
|
||||
* @return {@link #EventFlow}
|
||||
*
|
||||
*/
|
||||
public <T extends EventType> EventFlow addPostEvent(Class<T> eventClass, Object... args) {
|
||||
try {
|
||||
boolean isUuidEvent = UniqueEvent.class.isAssignableFrom(eventClass);
|
||||
@@ -98,155 +97,421 @@ public class EventFlow {
|
||||
}
|
||||
}
|
||||
|
||||
/** Subscribe by ID: only fires if UUID matches this publisher's eventId. */
|
||||
public <TT extends ResponseToUniqueEvent> EventFlow onResponse(
|
||||
Class<TT> eventClass, Consumer<TT> action, boolean unsubscribeAfterSuccess) {
|
||||
ListenerHandler[] listenerHolder = new ListenerHandler[1];
|
||||
listenerHolder[0] =
|
||||
new ListenerHandler(
|
||||
GlobalEventBus.subscribe(
|
||||
eventClass,
|
||||
event -> {
|
||||
if (event.getIdentifier() != this.eventSnowflake) return;
|
||||
|
||||
action.accept(event);
|
||||
|
||||
if (unsubscribeAfterSuccess && listenerHolder[0] != null) {
|
||||
GlobalEventBus.unsubscribe(listenerHolder[0]);
|
||||
this.listeners.remove(listenerHolder[0]);
|
||||
}
|
||||
|
||||
this.result = event.result();
|
||||
}));
|
||||
this.listeners.add(listenerHolder[0]);
|
||||
/**
|
||||
*
|
||||
* Add an event that will be triggered when {@link #postEvent()} or {@link #asyncPostEvent()} is called.
|
||||
*
|
||||
* @param event The event to be posted.
|
||||
* @return {@link #EventFlow}
|
||||
*
|
||||
*/
|
||||
public EventFlow addPostEvent(EventType event) {
|
||||
this.event = event;
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Subscribe by ID: only fires if UUID matches this publisher's eventId. */
|
||||
public <TT extends ResponseToUniqueEvent> EventFlow onResponse(Class<TT> eventClass, Consumer<TT> action) {
|
||||
return this.onResponse(eventClass, action, true);
|
||||
/**
|
||||
*
|
||||
* Add an event that will be triggered when {@link #postEvent()} or {@link #asyncPostEvent()} is called.
|
||||
*
|
||||
* @param eventSupplier The event that will be posted through a Supplier.
|
||||
* @return {@link #EventFlow}
|
||||
*
|
||||
*/
|
||||
public EventFlow addPostEvent(Supplier<? extends EventType> eventSupplier) {
|
||||
this.event = eventSupplier.get();
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Subscribe by ID without explicit class. */
|
||||
/**
|
||||
*
|
||||
* Start listening for an event and trigger when ID correlates.
|
||||
*
|
||||
* @param event The {@link ResponseToUniqueEvent} to trigger the lambda.
|
||||
* @param action The lambda to run when triggered.
|
||||
* @param unsubscribeAfterSuccess Enable/disable auto unsubscribing to event after being triggered.
|
||||
* @param name A name given to the event, can later be used to unsubscribe.
|
||||
* @return {@link #EventFlow}
|
||||
*
|
||||
*/
|
||||
public <TT extends ResponseToUniqueEvent> EventFlow onResponse(
|
||||
Class<TT> event, Consumer<TT> action, boolean unsubscribeAfterSuccess, String name
|
||||
) {
|
||||
|
||||
final long id = SnowflakeGenerator.nextId();
|
||||
|
||||
Consumer<TT> newAction = eventClass -> {
|
||||
if (eventClass.getIdentifier() != this.eventSnowflake) return;
|
||||
|
||||
action.accept(eventClass);
|
||||
|
||||
if (unsubscribeAfterSuccess) unsubscribe(id);
|
||||
|
||||
this.result = eventClass.result();
|
||||
};
|
||||
|
||||
// TODO Remove casts
|
||||
var listener = new ListenerHandler<>(
|
||||
id,
|
||||
name,
|
||||
(Class<ResponseToUniqueEvent>) event,
|
||||
(Consumer<ResponseToUniqueEvent>) newAction
|
||||
);
|
||||
|
||||
GlobalEventBus.subscribe(listener);
|
||||
this.listeners.add(listener);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Start listening for an event and trigger when ID correlates, auto unsubscribes after being triggered and adds an empty name.
|
||||
*
|
||||
* @param event The {@link ResponseToUniqueEvent} to trigger the lambda.
|
||||
* @param action The lambda to run when triggered.
|
||||
* @return {@link #EventFlow}
|
||||
*
|
||||
*/
|
||||
public <TT extends ResponseToUniqueEvent> EventFlow onResponse(Class<TT> event, Consumer<TT> action) {
|
||||
return this.onResponse(event, action, true, "");
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Start listening for an event and trigger when ID correlates, auto adds an empty name.
|
||||
*
|
||||
* @param event The {@link ResponseToUniqueEvent} to trigger the lambda.
|
||||
* @param action The lambda to run when triggered.
|
||||
* @param unsubscribeAfterSuccess Enable/disable auto unsubscribing to event after being triggered.
|
||||
* @return {@link #EventFlow}
|
||||
*
|
||||
*/
|
||||
public <TT extends ResponseToUniqueEvent> EventFlow onResponse(Class<TT> event, Consumer<TT> action, boolean unsubscribeAfterSuccess) {
|
||||
return this.onResponse(event, action, unsubscribeAfterSuccess, "");
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Start listening for an event and trigger when ID correlates, auto unsubscribes after being triggered.
|
||||
*
|
||||
* @param event The {@link ResponseToUniqueEvent} to trigger the lambda.
|
||||
* @param action The lambda to run when triggered.
|
||||
* @param name A name given to the event, can later be used to unsubscribe.
|
||||
* @return {@link #EventFlow}
|
||||
*
|
||||
*/
|
||||
public <TT extends ResponseToUniqueEvent> EventFlow onResponse(Class<TT> event, Consumer<TT> action, String name) {
|
||||
return this.onResponse(event, action, true, name);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Subscribe by ID without explicit class.
|
||||
*
|
||||
* @param action The lambda to run when triggered.
|
||||
* @return {@link #EventFlow}
|
||||
*
|
||||
* @deprecated use {@link #onResponse(Class, Consumer, boolean, String)} instead.
|
||||
*/
|
||||
@Deprecated
|
||||
@SuppressWarnings("unchecked")
|
||||
public <TT extends ResponseToUniqueEvent> EventFlow onResponse(
|
||||
Consumer<TT> action, boolean unsubscribeAfterSuccess) {
|
||||
ListenerHandler[] listenerHolder = new ListenerHandler[1];
|
||||
listenerHolder[0] =
|
||||
new ListenerHandler(
|
||||
GlobalEventBus.subscribe(
|
||||
event -> {
|
||||
if (!(event instanceof UniqueEvent uuidEvent)) return;
|
||||
if (uuidEvent.getIdentifier() == this.eventSnowflake) {
|
||||
try {
|
||||
TT typedEvent = (TT) uuidEvent;
|
||||
action.accept(typedEvent);
|
||||
if (unsubscribeAfterSuccess
|
||||
&& listenerHolder[0] != null) {
|
||||
GlobalEventBus.unsubscribe(listenerHolder[0]);
|
||||
this.listeners.remove(listenerHolder[0]);
|
||||
}
|
||||
this.result = typedEvent.result();
|
||||
} catch (ClassCastException _) {
|
||||
throw new ClassCastException(
|
||||
"Cannot cast "
|
||||
+ event.getClass().getName()
|
||||
+ " to UniqueEvent");
|
||||
}
|
||||
}
|
||||
}));
|
||||
this.listeners.add(listenerHolder[0]);
|
||||
Consumer<TT> action, boolean unsubscribeAfterSuccess, String name) {
|
||||
|
||||
final long id = SnowflakeGenerator.nextId();
|
||||
|
||||
Consumer<TT> newAction = event -> {
|
||||
if (!(event instanceof UniqueEvent uuidEvent)) return;
|
||||
if (uuidEvent.getIdentifier() == this.eventSnowflake) {
|
||||
try {
|
||||
TT typedEvent = (TT) uuidEvent;
|
||||
action.accept(typedEvent);
|
||||
|
||||
if (unsubscribeAfterSuccess) unsubscribe(id);
|
||||
|
||||
this.result = typedEvent.result();
|
||||
} catch (ClassCastException _) {
|
||||
throw new ClassCastException(
|
||||
"Cannot cast "
|
||||
+ event.getClass().getName()
|
||||
+ " to UniqueEvent");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
var listener = new ListenerHandler<>(
|
||||
id,
|
||||
name,
|
||||
(Class<TT>) action.getClass().getDeclaredMethods()[0].getParameterTypes()[0],
|
||||
newAction
|
||||
);
|
||||
|
||||
GlobalEventBus.subscribe(listener);
|
||||
this.listeners.add(listener);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Subscribe by ID without explicit class.
|
||||
*
|
||||
* @param action The lambda to run when triggered.
|
||||
* @return {@link #EventFlow}
|
||||
*
|
||||
* @deprecated use {@link #onResponse(Class, Consumer)} instead.
|
||||
*/
|
||||
@Deprecated
|
||||
public <TT extends ResponseToUniqueEvent> EventFlow onResponse(Consumer<TT> action) {
|
||||
return this.onResponse(action, true);
|
||||
return this.onResponse(action, true, "");
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Start listening for an event, and run a lambda when triggered.
|
||||
*
|
||||
* @param event The {@link EventType} to trigger the lambda.
|
||||
* @param action The lambda to run when triggered.
|
||||
* @param unsubscribeAfterSuccess Enable/disable auto unsubscribing to event after being triggered.
|
||||
* @param name A name given to the event, can later be used to unsubscribe.
|
||||
* @return {@link #EventFlow}
|
||||
*
|
||||
*/
|
||||
public <TT extends EventType> EventFlow listen(
|
||||
Class<TT> eventClass, Consumer<TT> action, boolean unsubscribeAfterSuccess) {
|
||||
ListenerHandler[] listenerHolder = new ListenerHandler[1];
|
||||
listenerHolder[0] =
|
||||
new ListenerHandler(
|
||||
GlobalEventBus.subscribe(
|
||||
eventClass,
|
||||
event -> {
|
||||
action.accept(event);
|
||||
Class<TT> event, Consumer<TT> action, boolean unsubscribeAfterSuccess, String name) {
|
||||
|
||||
if (unsubscribeAfterSuccess && listenerHolder[0] != null) {
|
||||
GlobalEventBus.unsubscribe(listenerHolder[0]);
|
||||
this.listeners.remove(listenerHolder[0]);
|
||||
}
|
||||
}));
|
||||
this.listeners.add(listenerHolder[0]);
|
||||
long id = SnowflakeGenerator.nextId();
|
||||
|
||||
Consumer<TT> newAction = eventc -> {
|
||||
action.accept(eventc);
|
||||
|
||||
if (unsubscribeAfterSuccess) unsubscribe(id);
|
||||
};
|
||||
|
||||
var listener = new ListenerHandler<>(
|
||||
id,
|
||||
name,
|
||||
event,
|
||||
newAction
|
||||
);
|
||||
|
||||
GlobalEventBus.subscribe(listener);
|
||||
this.listeners.add(listener);
|
||||
return this;
|
||||
}
|
||||
|
||||
public <TT extends EventType> EventFlow listen(Class<TT> eventClass, Consumer<TT> action) {
|
||||
return this.listen(eventClass, action, true);
|
||||
/**
|
||||
*
|
||||
* Start listening for an event, and run a lambda when triggered, auto unsubscribes.
|
||||
*
|
||||
* @param event The {@link EventType} to trigger the lambda.
|
||||
* @param action The lambda to run when triggered.
|
||||
* @param name A name given to the event, can later be used to unsubscribe.
|
||||
* @return {@link #EventFlow}
|
||||
*
|
||||
*/
|
||||
public <TT extends EventType> EventFlow listen(Class<TT> event, Consumer<TT> action, String name) {
|
||||
return this.listen(event, action, true, name);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Start listening for an event, and run a lambda when triggered, auto unsubscribe and gives it an empty name.
|
||||
*
|
||||
* @param event The {@link EventType} to trigger the lambda.
|
||||
* @param action The lambda to run when triggered.
|
||||
* @return {@link #EventFlow}
|
||||
*
|
||||
*/
|
||||
public <TT extends EventType> EventFlow listen(Class<TT> event, Consumer<TT> action) {
|
||||
return this.listen(event, action, true, "");
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Start listening for an event, and run a lambda when triggered, adds an empty name.
|
||||
*
|
||||
* @param event The {@link EventType} to trigger the lambda.
|
||||
* @param action The lambda to run when triggered.
|
||||
* @param unsubscribeAfterSuccess Enable/disable auto unsubscribing to event after being triggered.
|
||||
* @return {@link #EventFlow}
|
||||
*
|
||||
*/
|
||||
public <TT extends EventType> EventFlow listen(Class<TT> event, Consumer<TT> action, boolean unsubscribeAfterSuccess) {
|
||||
return this.listen(event, action, unsubscribeAfterSuccess, "");
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Start listening to an event.
|
||||
*
|
||||
* @param action The lambda to run when triggered.
|
||||
* @return {@link EventFlow}
|
||||
*
|
||||
* @deprecated use {@link #listen(Class, Consumer, boolean, String)} instead.
|
||||
*/
|
||||
@Deprecated
|
||||
@SuppressWarnings("unchecked")
|
||||
public <TT extends EventType> EventFlow listen(
|
||||
Consumer<TT> action, boolean unsubscribeAfterSuccess) {
|
||||
ListenerHandler[] listenerHolder = new ListenerHandler[1];
|
||||
listenerHolder[0] =
|
||||
new ListenerHandler(
|
||||
GlobalEventBus.subscribe(
|
||||
event -> {
|
||||
if (!(event instanceof EventType nonUuidEvent)) return;
|
||||
try {
|
||||
TT typedEvent = (TT) nonUuidEvent;
|
||||
action.accept(typedEvent);
|
||||
if (unsubscribeAfterSuccess && listenerHolder[0] != null) {
|
||||
GlobalEventBus.unsubscribe(listenerHolder[0]);
|
||||
this.listeners.remove(listenerHolder[0]);
|
||||
}
|
||||
} catch (ClassCastException _) {
|
||||
throw new ClassCastException(
|
||||
"Cannot cast "
|
||||
+ event.getClass().getName()
|
||||
+ " to UniqueEvent");
|
||||
}
|
||||
}));
|
||||
this.listeners.add(listenerHolder[0]);
|
||||
Consumer<TT> action, boolean unsubscribeAfterSuccess, String name) {
|
||||
long id = SnowflakeGenerator.nextId();
|
||||
|
||||
Class<TT> eventClass = (Class<TT>) action.getClass().getDeclaredMethods()[0].getParameterTypes()[0];
|
||||
|
||||
Consumer<TT> newAction = event -> {
|
||||
if (!(event instanceof EventType nonUuidEvent)) return;
|
||||
try {
|
||||
TT typedEvent = (TT) nonUuidEvent;
|
||||
action.accept(typedEvent);
|
||||
if (unsubscribeAfterSuccess) unsubscribe(id);
|
||||
} catch (ClassCastException _) {
|
||||
throw new ClassCastException(
|
||||
"Cannot cast "
|
||||
+ event.getClass().getName()
|
||||
+ " to UniqueEvent");
|
||||
}
|
||||
};
|
||||
|
||||
var listener = new ListenerHandler<>(
|
||||
id,
|
||||
name,
|
||||
eventClass,
|
||||
newAction
|
||||
);
|
||||
|
||||
GlobalEventBus.subscribe(listener);
|
||||
this.listeners.add(listener);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Start listening to an event.
|
||||
*
|
||||
* @param action The lambda to run when triggered.
|
||||
* @return {@link EventFlow}
|
||||
*
|
||||
* @deprecated use {@link #listen(Class, Consumer)} instead.
|
||||
*/
|
||||
@Deprecated
|
||||
public <TT extends EventType> EventFlow listen(Consumer<TT> action) {
|
||||
return this.listen(action, true);
|
||||
return this.listen(action, true, "");
|
||||
}
|
||||
|
||||
/** Post synchronously */
|
||||
/**
|
||||
* Posts the event added through {@link #addPostEvent}.
|
||||
*/
|
||||
public EventFlow postEvent() {
|
||||
GlobalEventBus.post(this.event);
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Post asynchronously */
|
||||
/**
|
||||
* Posts the event added through {@link #addPostEvent} asynchronously.
|
||||
*/
|
||||
public EventFlow asyncPostEvent() {
|
||||
GlobalEventBus.postAsync(this.event);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Unsubscribe from an event.
|
||||
*
|
||||
* @param listenerObject The listener object to remove and unsubscribe.
|
||||
*/
|
||||
public void unsubscribe(Object listenerObject) {
|
||||
this.listeners.removeIf(handler -> {
|
||||
if (handler.getListener() == listenerObject) {
|
||||
GlobalEventBus.unsubscribe(handler);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Unsubscribe from an event.
|
||||
*
|
||||
* @param listenerId The id given to the {@link ListenerHandler}.
|
||||
*/
|
||||
public void unsubscribe(long listenerId) {
|
||||
this.listeners.removeIf(handler -> {
|
||||
if (handler.getId() == listenerId) {
|
||||
GlobalEventBus.unsubscribe(handler);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Unsubscribe from an event.
|
||||
*
|
||||
* @param name The name given to the listener.
|
||||
*/
|
||||
public void unsubscribe(String name) {
|
||||
this.listeners.removeIf(handler -> {
|
||||
if (handler.getName().equals(name)) {
|
||||
GlobalEventBus.unsubscribe(handler);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Unsubscribe all events.
|
||||
*/
|
||||
public void unsubscribeAll() {
|
||||
listeners.removeIf(handler -> {
|
||||
GlobalEventBus.unsubscribe(handler);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean and remove everything inside {@link EventFlow}.
|
||||
*/
|
||||
private void clean() {
|
||||
this.listeners.clear();
|
||||
unsubscribeAll();
|
||||
this.event = null;
|
||||
this.result = null;
|
||||
} // TODO
|
||||
|
||||
/**
|
||||
* TODO
|
||||
*
|
||||
* @return TODO
|
||||
*/
|
||||
public Map<String, ?> getResult() {
|
||||
return this.result;
|
||||
}
|
||||
|
||||
/**
|
||||
* TODO
|
||||
*
|
||||
* @return TODO
|
||||
*/
|
||||
public EventType getEvent() {
|
||||
return event;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Returns a copy of the list of listeners.
|
||||
*
|
||||
* @return Copy of the list of listeners.
|
||||
*/
|
||||
public ListenerHandler[] getListeners() {
|
||||
return listeners.toArray(new ListenerHandler[0]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the generated snowflake for the {@link EventFlow}
|
||||
*
|
||||
* @return The generated snowflake for this {@link EventFlow}
|
||||
*/
|
||||
public long getEventSnowflake() {
|
||||
return eventSnowflake;
|
||||
}
|
||||
|
||||
@@ -6,6 +6,9 @@ import com.lmax.disruptor.dsl.ProducerType;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.toop.framework.eventbus.events.EventType;
|
||||
import org.toop.framework.eventbus.events.UniqueEvent;
|
||||
|
||||
@@ -14,9 +17,10 @@ import org.toop.framework.eventbus.events.UniqueEvent;
|
||||
* publishing.
|
||||
*/
|
||||
public final class GlobalEventBus {
|
||||
private static final Logger logger = LogManager.getLogger(GlobalEventBus.class);
|
||||
|
||||
/** Map of event class to type-specific listeners. */
|
||||
private static final Map<Class<?>, CopyOnWriteArrayList<Consumer<? super EventType>>>
|
||||
private static final Map<Class<?>, CopyOnWriteArrayList<ListenerHandler<?>>>
|
||||
LISTENERS = new ConcurrentHashMap<>();
|
||||
|
||||
/** Map of event class to Snowflake-ID-specific listeners. */
|
||||
@@ -49,7 +53,6 @@ public final class GlobalEventBus {
|
||||
ProducerType.MULTI,
|
||||
new BusySpinWaitStrategy());
|
||||
|
||||
// Single consumer that dispatches to subscribers
|
||||
DISRUPTOR.handleEventsWith(
|
||||
(holder, seq, endOfBatch) -> {
|
||||
if (holder.event != null) {
|
||||
@@ -73,23 +76,12 @@ public final class GlobalEventBus {
|
||||
// ------------------------------------------------------------------------
|
||||
// Subscription
|
||||
// ------------------------------------------------------------------------
|
||||
public static <T extends EventType> Consumer<? super EventType> subscribe(
|
||||
Class<T> eventClass, Consumer<T> listener) {
|
||||
|
||||
CopyOnWriteArrayList<Consumer<? super EventType>> list =
|
||||
LISTENERS.computeIfAbsent(eventClass, k -> new CopyOnWriteArrayList<>());
|
||||
|
||||
Consumer<? super EventType> wrapper = event -> listener.accept(eventClass.cast(event));
|
||||
list.add(wrapper);
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
public static Consumer<? super EventType> subscribe(Consumer<Object> listener) {
|
||||
Consumer<? super EventType> wrapper = event -> listener.accept(event);
|
||||
LISTENERS.computeIfAbsent(Object.class, _ -> new CopyOnWriteArrayList<>()).add(wrapper);
|
||||
return wrapper;
|
||||
public static <T extends EventType> void subscribe(ListenerHandler<T> listener) {
|
||||
logger.debug("Subscribing to {}: {}", listener.getListenerClass().getSimpleName(), listener.getListener().getClass().getSimpleName());
|
||||
LISTENERS.computeIfAbsent(listener.getListenerClass(), _ -> new CopyOnWriteArrayList<>()).add(listener);
|
||||
}
|
||||
|
||||
// TODO
|
||||
public static <T extends UniqueEvent> void subscribeById(
|
||||
Class<T> eventClass, long eventId, Consumer<T> listener) {
|
||||
UUID_LISTENERS
|
||||
@@ -97,10 +89,14 @@ public final class GlobalEventBus {
|
||||
.put(eventId, listener);
|
||||
}
|
||||
|
||||
public static void unsubscribe(Object listener) {
|
||||
LISTENERS.values().forEach(list -> list.remove(listener));
|
||||
public static void unsubscribe(ListenerHandler<?> listener) {
|
||||
logger.debug("Unsubscribing from {}: {}", listener.getListenerClass().getSimpleName(), listener.getListener().getClass().getSimpleName());
|
||||
LISTENERS.getOrDefault(listener.getListenerClass(), new CopyOnWriteArrayList<>())
|
||||
.remove(listener);
|
||||
LISTENERS.entrySet().removeIf(entry -> entry.getValue().isEmpty());
|
||||
}
|
||||
|
||||
// TODO
|
||||
public static <T extends UniqueEvent> void unsubscribeById(
|
||||
Class<T> eventClass, long eventId) {
|
||||
Map<Long, Consumer<? extends UniqueEvent>> map = UUID_LISTENERS.get(eventClass);
|
||||
@@ -124,36 +120,44 @@ public final class GlobalEventBus {
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static <T extends EventType> void callListener(ListenerHandler<?> raw, EventType event) {
|
||||
ListenerHandler<T> handler = (ListenerHandler<T>) raw;
|
||||
Consumer<T> listener = handler.getListener();
|
||||
|
||||
T casted = (T) event;
|
||||
|
||||
listener.accept(casted);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static void dispatchEvent(EventType event) {
|
||||
Class<?> clazz = event.getClass();
|
||||
|
||||
// class-specific listeners
|
||||
CopyOnWriteArrayList<Consumer<? super EventType>> classListeners = LISTENERS.get(clazz);
|
||||
logger.debug("Triggered event: {}", event.getClass().getSimpleName());
|
||||
|
||||
CopyOnWriteArrayList<ListenerHandler<?>> classListeners = LISTENERS.get(clazz);
|
||||
if (classListeners != null) {
|
||||
for (Consumer<? super EventType> listener : classListeners) {
|
||||
for (ListenerHandler<?> listener : classListeners) {
|
||||
try {
|
||||
listener.accept(event);
|
||||
callListener(listener, event);
|
||||
} catch (Throwable e) {
|
||||
// e.printStackTrace();
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// generic listeners
|
||||
CopyOnWriteArrayList<Consumer<? super EventType>> genericListeners =
|
||||
LISTENERS.get(Object.class);
|
||||
CopyOnWriteArrayList<ListenerHandler<?>> genericListeners = LISTENERS.get(Object.class);
|
||||
if (genericListeners != null) {
|
||||
for (Consumer<? super EventType> listener : genericListeners) {
|
||||
for (ListenerHandler<?> listener : genericListeners) {
|
||||
try {
|
||||
listener.accept(event);
|
||||
callListener(listener, event);
|
||||
} catch (Throwable e) {
|
||||
// e.printStackTrace();
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// snowflake listeners
|
||||
if (event instanceof UniqueEvent snowflakeEvent) {
|
||||
Map<Long, Consumer<? extends UniqueEvent>> map = UUID_LISTENERS.get(clazz);
|
||||
if (map != null) {
|
||||
@@ -182,4 +186,8 @@ public final class GlobalEventBus {
|
||||
LISTENERS.clear();
|
||||
UUID_LISTENERS.clear();
|
||||
}
|
||||
|
||||
public static Map<Class<?>, CopyOnWriteArrayList<ListenerHandler<?>>> getAllListeners() {
|
||||
return LISTENERS;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,25 +1,48 @@
|
||||
package org.toop.framework.eventbus;
|
||||
|
||||
public class ListenerHandler {
|
||||
private Object listener;
|
||||
import org.toop.framework.SnowflakeGenerator;
|
||||
import org.toop.framework.eventbus.events.EventType;
|
||||
|
||||
// private boolean unsubscribeAfterSuccess = true;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
// public ListenerHandler(Object listener, boolean unsubAfterSuccess) {
|
||||
// this.listener = listener;
|
||||
// this.unsubscribeAfterSuccess = unsubAfterSuccess;
|
||||
// }
|
||||
public class ListenerHandler<T extends EventType> {
|
||||
private final long id;
|
||||
private final String name;
|
||||
private final Class<T> clazz;
|
||||
private final Consumer<T> listener;
|
||||
|
||||
public ListenerHandler(Object listener) {
|
||||
public ListenerHandler(long id, String name, Class<T> clazz, Consumer<T> listener) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.clazz = clazz;
|
||||
this.listener = listener;
|
||||
}
|
||||
|
||||
public Object getListener() {
|
||||
return this.listener;
|
||||
public ListenerHandler(String name, Class<T> clazz, Consumer<T> listener) {
|
||||
this(SnowflakeGenerator.nextId(), name, clazz, listener);
|
||||
}
|
||||
|
||||
// public boolean isUnsubscribeAfterSuccess() {
|
||||
// return this.unsubscribeAfterSuccess;
|
||||
// }
|
||||
public ListenerHandler(long id, Class<T> clazz, Consumer<T> listener) {
|
||||
this(id, String.valueOf(id), clazz, listener);
|
||||
}
|
||||
|
||||
public ListenerHandler(Class<T> clazz, Consumer<T> listener) {
|
||||
this(SnowflakeGenerator.nextId(), clazz, listener);
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public Consumer<T> getListener() {
|
||||
return listener;
|
||||
}
|
||||
|
||||
public Class<T> getListenerClass() {
|
||||
return clazz;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package org.toop.framework.gameFramework;
|
||||
|
||||
/**
|
||||
* Represents the current state of a turn-based game.
|
||||
*/
|
||||
public enum GameState {
|
||||
/** Game is ongoing and no special condition applies. */
|
||||
NORMAL,
|
||||
|
||||
/** Game ended in a draw. */
|
||||
DRAW,
|
||||
|
||||
/** Game ended with a win for a player. */
|
||||
WIN,
|
||||
|
||||
/** Next player's turn was skipped. */
|
||||
TURN_SKIPPED,
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package org.toop.framework.gameFramework.controller;
|
||||
|
||||
/**
|
||||
* Interface for classes that can trigger a UI update.
|
||||
*/
|
||||
public interface UpdatesGameUI {
|
||||
|
||||
/** Called to refresh or update the game UI. */
|
||||
void updateUI();
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package org.toop.framework.gameFramework.model.game;
|
||||
|
||||
public interface BoardProvider {
|
||||
long[] getBoard();
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package org.toop.framework.gameFramework.model.game;
|
||||
|
||||
public interface DeepCopyable<T> {
|
||||
T deepCopy();
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package org.toop.framework.gameFramework.model.game;
|
||||
|
||||
import org.toop.framework.gameFramework.GameState;
|
||||
|
||||
/**
|
||||
* Represents the result of a move in a turn-based game.
|
||||
*
|
||||
* @param state the resulting {@link GameState} after the move
|
||||
* @param player the index of the player associated with the result (winner or relevant player)
|
||||
*/
|
||||
public record PlayResult(GameState state, int player) {
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package org.toop.framework.gameFramework.model.game;
|
||||
|
||||
import org.toop.framework.gameFramework.GameState;
|
||||
|
||||
/**
|
||||
* Interface for turn-based games that can be played and queried for legal moves.
|
||||
*/
|
||||
public interface Playable {
|
||||
|
||||
/**
|
||||
* Returns the moves that are currently valid in the game.
|
||||
*
|
||||
* @return an array of integers representing legal moves
|
||||
*/
|
||||
long getLegalMoves();
|
||||
|
||||
/**
|
||||
* Plays the given move and returns the resulting game state.
|
||||
*
|
||||
* @param move the move to apply
|
||||
* @return the {@link GameState} and additional info after the move
|
||||
*/
|
||||
PlayResult play(long move);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package org.toop.framework.gameFramework.model.game;
|
||||
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
|
||||
public interface PlayerProvider<T extends TurnBasedGame<T>> {
|
||||
Player<T> getPlayer(int index);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package org.toop.framework.gameFramework.model.game;
|
||||
|
||||
import org.toop.framework.networking.events.NetworkEvents;
|
||||
|
||||
/**
|
||||
* Interface for games that support online multiplayer play.
|
||||
* <p>
|
||||
* Methods are called in response to network events from the server.
|
||||
*/
|
||||
public interface SupportsOnlinePlay {
|
||||
|
||||
/** Called when it is this player's turn to make a move. */
|
||||
void onYourTurn(long clientId);
|
||||
|
||||
/** Called when a move from another player is received. */
|
||||
void onMoveReceived(long move);
|
||||
|
||||
/** Called when the game has finished, with the final result. */
|
||||
void gameFinished(String condition);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package org.toop.framework.gameFramework.model.game;
|
||||
|
||||
public interface TurnBasedGame<T extends TurnBasedGame<T>> extends Playable, DeepCopyable<T>, PlayerProvider<T>, BoardProvider {
|
||||
int getCurrentTurn();
|
||||
int getPlayerCount();
|
||||
int getWinner();
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
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 org.toop.framework.gameFramework.model.player.Player;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* Base class for thread-based game behaviours.
|
||||
* <p>
|
||||
* Provides common functionality for managing game state and execution:
|
||||
* a running flag, a game reference, and a logger.
|
||||
* Subclasses implement the actual game-loop logic.
|
||||
*/
|
||||
public abstract class 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();
|
||||
|
||||
/** The game instance controlled by this behaviour. */
|
||||
protected final T game;
|
||||
|
||||
/** Logger for the subclass to report errors or debug info. */
|
||||
protected final Logger logger = LogManager.getLogger(this.getClass());
|
||||
|
||||
/**
|
||||
* Creates a new base behaviour for the specified game.
|
||||
*
|
||||
* @param game the turn-based game to control
|
||||
*/
|
||||
public 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package org.toop.framework.gameFramework.model.game.threadBehaviour;
|
||||
|
||||
public interface Controllable {
|
||||
void start();
|
||||
|
||||
void stop();
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
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 org.toop.framework.gameFramework.model.player.AbstractPlayer;
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
|
||||
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 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>> {
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package org.toop.framework.gameFramework.model.player;
|
||||
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
|
||||
/**
|
||||
* Abstract base class for AI implementations for games extending {@link GameR}.
|
||||
* <p>
|
||||
* Provides a common superclass for specific AI algorithms. Concrete subclasses
|
||||
* must implement the {@link #findBestMove(GameR, int)} method defined by
|
||||
* {@link IAIMoveR} to determine the best move given a game state and a search depth.
|
||||
* </p>
|
||||
*
|
||||
* @param <T> the specific type of game this AI can play, extending {@link GameR}
|
||||
*/
|
||||
public abstract class AbstractAI<T extends TurnBasedGame<T>> implements AI<T> {
|
||||
// Concrete AI implementations should override findBestMove(T game, int depth)
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package org.toop.framework.gameFramework.model.player;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
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>
|
||||
*/
|
||||
public abstract class AbstractPlayer<T extends TurnBasedGame<T>> implements Player<T> {
|
||||
private final Logger logger = LogManager.getLogger(this.getClass());
|
||||
|
||||
private final String name;
|
||||
|
||||
protected AbstractPlayer(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
protected AbstractPlayer(AbstractPlayer<T> other) {
|
||||
this.name = other.name;
|
||||
}
|
||||
/**
|
||||
* Determines the next move based on the provided game state.
|
||||
* <p>
|
||||
* The default implementation throws an {@link UnsupportedOperationException},
|
||||
* indicating that concrete subclasses must override this method to provide
|
||||
* actual move logic.
|
||||
* </p>
|
||||
*
|
||||
* @param gameCopy a snapshot of the current game state
|
||||
* @return an integer representing the chosen move
|
||||
* @throws UnsupportedOperationException if the method is not overridden
|
||||
*/
|
||||
public long getMove(T gameCopy) {
|
||||
logger.error("Method getMove not implemented.");
|
||||
throw new UnsupportedOperationException("Not supported yet.");
|
||||
}
|
||||
|
||||
public String getName(){
|
||||
return this.name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package org.toop.framework.gameFramework.model.player;
|
||||
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
|
||||
public interface MoveProvider<T extends TurnBasedGame<T>> {
|
||||
long getMove(T game);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package org.toop.framework.gameFramework.model.player;
|
||||
|
||||
public interface NameProvider {
|
||||
String getName();
|
||||
}
|
||||
@@ -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 Player<T extends TurnBasedGame<T>> extends NameProvider, MoveProvider<T>, DeepCopyable<Player<T>> {
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package org.toop.framework.gameFramework.view;
|
||||
|
||||
import org.toop.framework.eventbus.events.EventsBase;
|
||||
import org.toop.framework.eventbus.events.GenericEvent;
|
||||
|
||||
/**
|
||||
* Defines GUI-related events for the event bus.
|
||||
* <p>
|
||||
* These events notify the UI about updates such as game progress,
|
||||
* player actions, and game completion.
|
||||
*/
|
||||
public class GUIEvents extends EventsBase {
|
||||
/**
|
||||
* Event indicating the game has ended.
|
||||
*
|
||||
* @param winOrTie true if the game ended in a win, false for a draw
|
||||
* @param winner the index of the winning player, or -1 if no winner
|
||||
*/
|
||||
public record GameEnded(boolean winOrTie, int winner) implements GenericEvent {}
|
||||
|
||||
/** Event indicating a player has attempted a move. */
|
||||
public record PlayerAttemptedMove(long move) implements GenericEvent {}
|
||||
|
||||
/** Event indicating a player is hovering over a move (for UI feedback). */
|
||||
public record PlayerMoveHovered(long move) implements GenericEvent {}
|
||||
}
|
||||
@@ -17,25 +17,25 @@ public class NetworkingClientEventListener {
|
||||
public NetworkingClientEventListener(NetworkingClientManager clientManager) {
|
||||
this.clientManager = clientManager;
|
||||
new EventFlow()
|
||||
.listen(this::handleStartClient)
|
||||
.listen(this::handleCommand)
|
||||
.listen(this::handleSendLogin)
|
||||
.listen(this::handleSendLogout)
|
||||
.listen(this::handleSendGetPlayerlist)
|
||||
.listen(this::handleSendGetGamelist)
|
||||
.listen(this::handleSendSubscribe)
|
||||
.listen(this::handleSendMove)
|
||||
.listen(this::handleSendChallenge)
|
||||
.listen(this::handleSendAcceptChallenge)
|
||||
.listen(this::handleSendForfeit)
|
||||
.listen(this::handleSendMessage)
|
||||
.listen(this::handleSendHelp)
|
||||
.listen(this::handleSendHelpForCommand)
|
||||
.listen(this::handleCloseClient)
|
||||
.listen(this::handleReconnect)
|
||||
.listen(this::handleChangeAddress)
|
||||
.listen(this::handleGetAllConnections)
|
||||
.listen(this::handleShutdownAll);
|
||||
.listen(NetworkEvents.StartClient.class, this::handleStartClient, false)
|
||||
.listen(NetworkEvents.SendCommand.class, this::handleCommand, false)
|
||||
.listen(NetworkEvents.SendLogin.class, this::handleSendLogin, false)
|
||||
.listen(NetworkEvents.SendLogout.class, this::handleSendLogout, false)
|
||||
.listen(NetworkEvents.SendGetPlayerlist.class, this::handleSendGetPlayerlist, false)
|
||||
.listen(NetworkEvents.SendGetGamelist.class, this::handleSendGetGamelist, false)
|
||||
.listen(NetworkEvents.SendSubscribe.class, this::handleSendSubscribe, false)
|
||||
.listen(NetworkEvents.SendMove.class, this::handleSendMove, false)
|
||||
.listen(NetworkEvents.SendChallenge.class, this::handleSendChallenge, false)
|
||||
.listen(NetworkEvents.SendAcceptChallenge.class, this::handleSendAcceptChallenge, false)
|
||||
.listen(NetworkEvents.SendForfeit.class, this::handleSendForfeit, false)
|
||||
.listen(NetworkEvents.SendMessage.class, this::handleSendMessage, false)
|
||||
.listen(NetworkEvents.SendHelp.class, this::handleSendHelp, false)
|
||||
.listen(NetworkEvents.SendHelpForCommand.class, this::handleSendHelpForCommand, false)
|
||||
.listen(NetworkEvents.CloseClient.class, this::handleCloseClient, false)
|
||||
.listen(NetworkEvents.Reconnect.class, this::handleReconnect, false)
|
||||
.listen(NetworkEvents.ChangeAddress.class, this::handleChangeAddress, false)
|
||||
.listen(NetworkEvents.RequestsAllClients.class, this::handleGetAllConnections, false)
|
||||
.listen(NetworkEvents.ForceCloseAllClients.class, this::handleShutdownAll, false);
|
||||
}
|
||||
|
||||
void handleStartClient(NetworkEvents.StartClient event) {
|
||||
|
||||
@@ -8,6 +8,8 @@ import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.toop.framework.eventbus.GlobalEventBus;
|
||||
import org.toop.framework.networking.events.NetworkEvents;
|
||||
import org.toop.framework.networking.exceptions.ClientNotFoundException;
|
||||
import org.toop.framework.networking.exceptions.CouldNotConnectException;
|
||||
import org.toop.framework.networking.interfaces.NetworkingClient;
|
||||
@@ -44,6 +46,7 @@ public class NetworkingClientManager implements org.toop.framework.networking.in
|
||||
nClient.connect(id, nConnector.host(), nConnector.port());
|
||||
networkClients.put(id, nClient);
|
||||
logger.info("New client started successfully for {}:{}", nConnector.host(), nConnector.port());
|
||||
GlobalEventBus.post(new NetworkEvents.ConnectTry(id, attempts, nConnector.reconnectAttempts(), true));
|
||||
onSuccess.run();
|
||||
scheduler.shutdown();
|
||||
} catch (CouldNotConnectException e) {
|
||||
@@ -51,14 +54,17 @@ public class NetworkingClientManager implements org.toop.framework.networking.in
|
||||
if (attempts < nConnector.reconnectAttempts()) {
|
||||
logger.warn("Could not connect to {}:{}. Retrying in {} {}",
|
||||
nConnector.host(), nConnector.port(), nConnector.timeout(), nConnector.timeUnit());
|
||||
GlobalEventBus.post(new NetworkEvents.ConnectTry(id, attempts, nConnector.reconnectAttempts(), false));
|
||||
scheduler.schedule(this, nConnector.timeout(), nConnector.timeUnit());
|
||||
} else {
|
||||
logger.error("Failed to start client for {}:{} after {} attempts", nConnector.host(), nConnector.port(), attempts);
|
||||
GlobalEventBus.post(new NetworkEvents.ConnectTry(id, -1, nConnector.reconnectAttempts(), false));
|
||||
onFailure.run();
|
||||
scheduler.shutdown();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("Unexpected exception during startClient", e);
|
||||
GlobalEventBus.post(new NetworkEvents.ConnectTry(id, -1, nConnector.reconnectAttempts(), false));
|
||||
onFailure.run();
|
||||
scheduler.shutdown();
|
||||
}
|
||||
|
||||
@@ -181,6 +181,8 @@ public class NetworkEvents extends EventsBase {
|
||||
public record StartClientResponse(long clientId, boolean successful, long identifier)
|
||||
implements ResponseToUniqueEvent {}
|
||||
|
||||
public record ConnectTry(long clientId, int amount, int maxAmount, boolean success) implements GenericEvent {}
|
||||
|
||||
/**
|
||||
* Requests reconnection of an existing client using its previous configuration.
|
||||
* <p>
|
||||
|
||||
@@ -2,6 +2,8 @@ package org.toop.framework.networking.handlers;
|
||||
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
|
||||
import java.util.regex.MatchResult;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
@@ -70,7 +72,7 @@ public class NetworkingGameClientHandler extends ChannelInboundHandlerAdapter {
|
||||
case "CHALLENGE":
|
||||
gameChallengeHandler(recSrvRemoved);
|
||||
return;
|
||||
case "WIN", "DRAW", "LOSE":
|
||||
case "WIN", "DRAW", "LOSS":
|
||||
gameWinConditionHandler(recSrvRemoved);
|
||||
return;
|
||||
default:
|
||||
@@ -119,13 +121,12 @@ public class NetworkingGameClientHandler extends ChannelInboundHandlerAdapter {
|
||||
}
|
||||
|
||||
private void gameWinConditionHandler(String rec) {
|
||||
@SuppressWarnings("StreamToString")
|
||||
String condition =
|
||||
Pattern.compile("\\b(win|draw|lose)\\b", Pattern.CASE_INSENSITIVE)
|
||||
.matcher(rec)
|
||||
.results()
|
||||
.toString()
|
||||
.trim();
|
||||
String condition = Pattern.compile("\\b(win|draw|loss)\\b", Pattern.CASE_INSENSITIVE)
|
||||
.matcher(rec)
|
||||
.results()
|
||||
.map(MatchResult::group)
|
||||
.findFirst()
|
||||
.orElse("");
|
||||
|
||||
new EventFlow()
|
||||
.addPostEvent(new NetworkEvents.GameResultResponse(this.connectionId, condition))
|
||||
|
||||
@@ -1,235 +1,222 @@
|
||||
// package org.toop.framework.eventbus;
|
||||
//
|
||||
// import org.junit.jupiter.api.Tag;
|
||||
// import org.junit.jupiter.api.Test;
|
||||
// import org.toop.framework.eventbus.events.UniqueEvent;
|
||||
//
|
||||
// import java.math.BigInteger;
|
||||
// import java.util.concurrent.*;
|
||||
// import java.util.concurrent.atomic.LongAdder;
|
||||
//
|
||||
// import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
//
|
||||
// class EventFlowStressTest {
|
||||
//
|
||||
// /** Top-level record to ensure runtime type matches subscription */
|
||||
// public record HeavyEvent(String payload, long eventSnowflake) implements UniqueEvent {
|
||||
// @Override
|
||||
// public java.util.Map<String, Object> result() {
|
||||
// return java.util.Map.of("payload", payload, "eventId", eventSnowflake);
|
||||
// }
|
||||
//
|
||||
// @Override
|
||||
// public long eventSnowflake() {
|
||||
// return this.eventSnowflake;
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// public record HeavyEventSuccess(String payload, long eventSnowflake) implements
|
||||
// UniqueEvent {
|
||||
// @Override
|
||||
// public java.util.Map<String, Object> result() {
|
||||
// return java.util.Map.of("payload", payload, "eventId", eventSnowflake);
|
||||
// }
|
||||
//
|
||||
// @Override
|
||||
// public long eventSnowflake() {
|
||||
// return eventSnowflake;
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// private static final int THREADS = 32;
|
||||
// private static final long EVENTS_PER_THREAD = 10_000_000;
|
||||
//
|
||||
// @Tag("stress")
|
||||
// @Test
|
||||
// void extremeConcurrencySendTest_progressWithMemory() throws InterruptedException {
|
||||
// LongAdder counter = new LongAdder();
|
||||
// ExecutorService executor = Executors.newFixedThreadPool(THREADS);
|
||||
//
|
||||
// BigInteger totalEvents = BigInteger.valueOf(THREADS)
|
||||
// .multiply(BigInteger.valueOf(EVENTS_PER_THREAD));
|
||||
//
|
||||
// long startTime = System.currentTimeMillis();
|
||||
//
|
||||
// // Monitor thread for EPS and memory
|
||||
// Thread monitor = new Thread(() -> {
|
||||
// long lastCount = 0;
|
||||
// long lastTime = System.currentTimeMillis();
|
||||
// Runtime runtime = Runtime.getRuntime();
|
||||
//
|
||||
// while (counter.sum() < totalEvents.longValue()) {
|
||||
// try { Thread.sleep(200); } catch (InterruptedException ignored) {}
|
||||
//
|
||||
// long now = System.currentTimeMillis();
|
||||
// long completed = counter.sum();
|
||||
// long eventsThisPeriod = completed - lastCount;
|
||||
// double eps = eventsThisPeriod / ((now - lastTime) / 1000.0);
|
||||
//
|
||||
// long usedMemory = runtime.totalMemory() - runtime.freeMemory();
|
||||
// double usedPercent = usedMemory * 100.0 / runtime.maxMemory();
|
||||
//
|
||||
// System.out.printf(
|
||||
// "Progress: %d/%d (%.2f%%), EPS: %.0f, Memory Used: %.2f MB (%.2f%%)%n",
|
||||
// completed,
|
||||
// totalEvents.longValue(),
|
||||
// completed * 100.0 / totalEvents.doubleValue(),
|
||||
// eps,
|
||||
// usedMemory / 1024.0 / 1024.0,
|
||||
// usedPercent
|
||||
// );
|
||||
//
|
||||
// lastCount = completed;
|
||||
// lastTime = now;
|
||||
// }
|
||||
// });
|
||||
// monitor.setDaemon(true);
|
||||
// monitor.start();
|
||||
//
|
||||
// var listener = new EventFlow().listen(HeavyEvent.class, _ -> counter.increment());
|
||||
//
|
||||
// // Submit events asynchronously
|
||||
// for (int t = 0; t < THREADS; t++) {
|
||||
// executor.submit(() -> {
|
||||
// for (int i = 0; i < EVENTS_PER_THREAD; i++) {
|
||||
// var _ = new EventFlow().addPostEvent(HeavyEvent.class, "payload-" + i)
|
||||
// .asyncPostEvent();
|
||||
// }
|
||||
// });
|
||||
// }
|
||||
//
|
||||
// executor.shutdown();
|
||||
// executor.awaitTermination(10, TimeUnit.MINUTES);
|
||||
//
|
||||
// listener.getResult();
|
||||
//
|
||||
// long endTime = System.currentTimeMillis();
|
||||
// double durationSeconds = (endTime - startTime) / 1000.0;
|
||||
//
|
||||
// System.out.println("Posted " + totalEvents + " events in " + durationSeconds + "
|
||||
// seconds");
|
||||
// double averageEps = totalEvents.doubleValue() / durationSeconds;
|
||||
// System.out.printf("Average EPS: %.0f%n", averageEps);
|
||||
//
|
||||
// assertEquals(totalEvents.longValue(), counter.sum());
|
||||
// }
|
||||
//
|
||||
// @Tag("stress")
|
||||
// @Test
|
||||
// void extremeConcurrencySendAndReturnTest_progressWithMemory() throws InterruptedException {
|
||||
// LongAdder counter = new LongAdder();
|
||||
// ExecutorService executor = Executors.newFixedThreadPool(THREADS);
|
||||
//
|
||||
// BigInteger totalEvents = BigInteger.valueOf(THREADS)
|
||||
// .multiply(BigInteger.valueOf(EVENTS_PER_THREAD));
|
||||
//
|
||||
// long startTime = System.currentTimeMillis();
|
||||
//
|
||||
// // Monitor thread for EPS and memory
|
||||
// Thread monitor = new Thread(() -> {
|
||||
// long lastCount = 0;
|
||||
// long lastTime = System.currentTimeMillis();
|
||||
// Runtime runtime = Runtime.getRuntime();
|
||||
//
|
||||
// while (counter.sum() < totalEvents.longValue()) {
|
||||
// try { Thread.sleep(200); } catch (InterruptedException ignored) {}
|
||||
//
|
||||
// long now = System.currentTimeMillis();
|
||||
// long completed = counter.sum();
|
||||
// long eventsThisPeriod = completed - lastCount;
|
||||
// double eps = eventsThisPeriod / ((now - lastTime) / 1000.0);
|
||||
//
|
||||
// long usedMemory = runtime.totalMemory() - runtime.freeMemory();
|
||||
// double usedPercent = usedMemory * 100.0 / runtime.maxMemory();
|
||||
//
|
||||
// System.out.printf(
|
||||
// "Progress: %d/%d (%.2f%%), EPS: %.0f, Memory Used: %.2f MB (%.2f%%)%n",
|
||||
// completed,
|
||||
// totalEvents.longValue(),
|
||||
// completed * 100.0 / totalEvents.doubleValue(),
|
||||
// eps,
|
||||
// usedMemory / 1024.0 / 1024.0,
|
||||
// usedPercent
|
||||
// );
|
||||
//
|
||||
// lastCount = completed;
|
||||
// lastTime = now;
|
||||
// }
|
||||
// });
|
||||
// monitor.setDaemon(true);
|
||||
// monitor.start();
|
||||
//
|
||||
// // Submit events asynchronously
|
||||
// for (int t = 0; t < THREADS; t++) {
|
||||
// executor.submit(() -> {
|
||||
// for (int i = 0; i < EVENTS_PER_THREAD; i++) {
|
||||
// var a = new EventFlow().addPostEvent(HeavyEvent.class, "payload-" + i)
|
||||
// .onResponse(HeavyEventSuccess.class, _ -> counter.increment())
|
||||
// .postEvent();
|
||||
//
|
||||
// new EventFlow().addPostEvent(HeavyEventSuccess.class, "payload-" + i,
|
||||
// a.getEventSnowflake())
|
||||
// .postEvent();
|
||||
// }
|
||||
// });
|
||||
// }
|
||||
//
|
||||
// executor.shutdown();
|
||||
// executor.awaitTermination(10, TimeUnit.MINUTES);
|
||||
//
|
||||
// long endTime = System.currentTimeMillis();
|
||||
// double durationSeconds = (endTime - startTime) / 1000.0;
|
||||
//
|
||||
// System.out.println("Posted " + totalEvents + " events in " + durationSeconds + "
|
||||
// seconds");
|
||||
// double averageEps = totalEvents.doubleValue() / durationSeconds;
|
||||
// System.out.printf("Average EPS: %.0f%n", averageEps);
|
||||
//
|
||||
// assertEquals(totalEvents.longValue(), counter.sum());
|
||||
// }
|
||||
//
|
||||
//
|
||||
// @Tag("stress")
|
||||
// @Test
|
||||
// void efficientExtremeConcurrencyTest() throws InterruptedException {
|
||||
// final int THREADS = Runtime.getRuntime().availableProcessors();
|
||||
// final int EVENTS_PER_THREAD = 5000;
|
||||
//
|
||||
// ExecutorService executor = Executors.newFixedThreadPool(THREADS);
|
||||
// ConcurrentLinkedQueue<HeavyEvent> processedEvents = new ConcurrentLinkedQueue<>();
|
||||
//
|
||||
// long start = System.nanoTime();
|
||||
//
|
||||
// for (int t = 0; t < THREADS; t++) {
|
||||
// executor.submit(() -> {
|
||||
// for (int i = 0; i < EVENTS_PER_THREAD; i++) {
|
||||
// new EventFlow().addPostEvent(HeavyEvent.class, "payload-" + i)
|
||||
// .onResponse(HeavyEvent.class, processedEvents::add)
|
||||
// .postEvent();
|
||||
// }
|
||||
// });
|
||||
// }
|
||||
//
|
||||
// executor.shutdown();
|
||||
// executor.awaitTermination(10, TimeUnit.MINUTES);
|
||||
//
|
||||
// long end = System.nanoTime();
|
||||
// double durationSeconds = (end - start) / 1_000_000_000.0;
|
||||
//
|
||||
// BigInteger totalEvents = BigInteger.valueOf((long)
|
||||
// THREADS).multiply(BigInteger.valueOf(EVENTS_PER_THREAD));
|
||||
// double eps = totalEvents.doubleValue() / durationSeconds;
|
||||
//
|
||||
// System.out.printf("Posted %s events in %.3f seconds%n", totalEvents, durationSeconds);
|
||||
// System.out.printf("Throughput: %.0f events/sec%n", eps);
|
||||
//
|
||||
// Runtime rt = Runtime.getRuntime();
|
||||
// System.out.printf("Used memory: %.2f MB%n", (rt.totalMemory() - rt.freeMemory()) / 1024.0
|
||||
// / 1024.0);
|
||||
//
|
||||
// assertEquals(totalEvents.intValue(), processedEvents.size());
|
||||
// }
|
||||
//
|
||||
package org.toop.framework.eventbus;
|
||||
|
||||
import org.junit.jupiter.api.Tag;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.toop.framework.eventbus.events.ResponseToUniqueEvent;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.LongAdder;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class EventFlowStressTest {
|
||||
|
||||
public record HeavyEvent(String payload, long eventSnowflake) implements ResponseToUniqueEvent {
|
||||
@Override
|
||||
public long getIdentifier() {
|
||||
return eventSnowflake;
|
||||
}
|
||||
}
|
||||
|
||||
public record HeavyEventSuccess(String payload, long eventSnowflake) implements ResponseToUniqueEvent {
|
||||
@Override
|
||||
public long getIdentifier() {
|
||||
return eventSnowflake;
|
||||
}
|
||||
}
|
||||
|
||||
private static final int THREADS = 32;
|
||||
private static final long EVENTS_PER_THREAD = 10_000_000;
|
||||
|
||||
@Tag("stress")
|
||||
@Test
|
||||
void extremeConcurrencySendTest_progressWithMemory() throws InterruptedException {
|
||||
LongAdder counter = new LongAdder();
|
||||
ExecutorService executor = Executors.newFixedThreadPool(THREADS);
|
||||
|
||||
BigInteger totalEvents = BigInteger.valueOf(THREADS)
|
||||
.multiply(BigInteger.valueOf(EVENTS_PER_THREAD));
|
||||
|
||||
long startTime = System.currentTimeMillis();
|
||||
|
||||
Thread monitor = new Thread(() -> {
|
||||
long lastCount = 0;
|
||||
long lastTime = System.currentTimeMillis();
|
||||
Runtime runtime = Runtime.getRuntime();
|
||||
|
||||
while (counter.sum() < totalEvents.longValue()) {
|
||||
try { Thread.sleep(200); } catch (InterruptedException ignored) {}
|
||||
|
||||
long now = System.currentTimeMillis();
|
||||
long completed = counter.sum();
|
||||
long eventsThisPeriod = completed - lastCount;
|
||||
double eps = eventsThisPeriod / ((now - lastTime) / 1000.0);
|
||||
|
||||
long usedMemory = runtime.totalMemory() - runtime.freeMemory();
|
||||
double usedPercent = usedMemory * 100.0 / runtime.maxMemory();
|
||||
|
||||
System.out.printf(
|
||||
"Progress: %d/%d (%.2f%%), EPS: %.0f, Memory Used: %.2f MB (%.2f%%)%n",
|
||||
completed,
|
||||
totalEvents.longValue(),
|
||||
completed * 100.0 / totalEvents.doubleValue(),
|
||||
eps,
|
||||
usedMemory / 1024.0 / 1024.0,
|
||||
usedPercent
|
||||
);
|
||||
|
||||
lastCount = completed;
|
||||
lastTime = now;
|
||||
}
|
||||
});
|
||||
monitor.setDaemon(true);
|
||||
monitor.start();
|
||||
|
||||
var listener = new EventFlow().listen(HeavyEvent.class, _ -> counter.increment());
|
||||
|
||||
for (int t = 0; t < THREADS; t++) {
|
||||
executor.submit(() -> {
|
||||
for (int i = 0; i < EVENTS_PER_THREAD; i++) {
|
||||
var _ = new EventFlow().addPostEvent(HeavyEvent.class, "payload-" + i)
|
||||
.asyncPostEvent();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
executor.shutdown();
|
||||
executor.awaitTermination(10, TimeUnit.MINUTES);
|
||||
|
||||
listener.getResult();
|
||||
|
||||
long endTime = System.currentTimeMillis();
|
||||
double durationSeconds = (endTime - startTime) / 1000.0;
|
||||
|
||||
System.out.println("Posted " + totalEvents + " events in " + durationSeconds + " seconds");
|
||||
double averageEps = totalEvents.doubleValue() / durationSeconds;
|
||||
System.out.printf("Average EPS: %.0f%n", averageEps);
|
||||
|
||||
assertEquals(totalEvents.longValue(), counter.sum());
|
||||
}
|
||||
|
||||
@Tag("stress")
|
||||
@Test
|
||||
void extremeConcurrencySendAndReturnTest_progressWithMemory() throws InterruptedException {
|
||||
LongAdder counter = new LongAdder();
|
||||
ExecutorService executor = Executors.newFixedThreadPool(THREADS);
|
||||
|
||||
BigInteger totalEvents = BigInteger.valueOf(THREADS)
|
||||
.multiply(BigInteger.valueOf(EVENTS_PER_THREAD));
|
||||
|
||||
long startTime = System.currentTimeMillis();
|
||||
|
||||
Thread monitor = new Thread(() -> {
|
||||
long lastCount = 0;
|
||||
long lastTime = System.currentTimeMillis();
|
||||
Runtime runtime = Runtime.getRuntime();
|
||||
|
||||
while (counter.sum() < totalEvents.longValue()) {
|
||||
try { Thread.sleep(500); } catch (InterruptedException ignored) {}
|
||||
|
||||
long now = System.currentTimeMillis();
|
||||
long completed = counter.sum();
|
||||
long eventsThisPeriod = completed - lastCount;
|
||||
double eps = eventsThisPeriod / ((now - lastTime) / 1000.0);
|
||||
|
||||
long usedMemory = runtime.totalMemory() - runtime.freeMemory();
|
||||
double usedPercent = usedMemory * 100.0 / runtime.maxMemory();
|
||||
|
||||
System.out.printf(
|
||||
"Progress: %d/%d (%.2f%%), EPS: %.0f, Memory Used: %.2f MB (%.2f%%)%n",
|
||||
completed,
|
||||
totalEvents.longValue(),
|
||||
completed * 100.0 / totalEvents.doubleValue(),
|
||||
eps,
|
||||
usedMemory / 1024.0 / 1024.0,
|
||||
usedPercent
|
||||
);
|
||||
|
||||
lastCount = completed;
|
||||
lastTime = now;
|
||||
}
|
||||
});
|
||||
monitor.setDaemon(true);
|
||||
monitor.start();
|
||||
|
||||
EventFlow sharedFlow = new EventFlow();
|
||||
sharedFlow.listen(HeavyEventSuccess.class, _ -> counter.increment(), false, "heavyEventSuccessListener");
|
||||
|
||||
for (int t = 0; t < THREADS; t++) {
|
||||
executor.submit(() -> {
|
||||
EventFlow threadFlow = new EventFlow();
|
||||
|
||||
for (int i = 0; i < EVENTS_PER_THREAD; i++) {
|
||||
var heavyEvent = threadFlow.addPostEvent(HeavyEvent.class, "payload-" + i)
|
||||
.postEvent();
|
||||
|
||||
threadFlow.addPostEvent(HeavyEventSuccess.class, "payload-" + i, heavyEvent.getEventSnowflake())
|
||||
.postEvent();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
executor.shutdown();
|
||||
executor.awaitTermination(10, TimeUnit.MINUTES);
|
||||
|
||||
long endTime = System.currentTimeMillis();
|
||||
double durationSeconds = (endTime - startTime) / 1000.0;
|
||||
|
||||
System.out.println("Posted " + totalEvents + " events in " + durationSeconds + " seconds");
|
||||
double averageEps = totalEvents.doubleValue() / durationSeconds;
|
||||
System.out.printf("Average EPS: %.0f%n", averageEps);
|
||||
|
||||
assertEquals(totalEvents.longValue(), counter.sum());
|
||||
}
|
||||
|
||||
@Tag("stress")
|
||||
@Test
|
||||
void efficientExtremeConcurrencyTest() throws InterruptedException {
|
||||
final int THREADS = Runtime.getRuntime().availableProcessors();
|
||||
final int EVENTS_PER_THREAD = 1_000_000;
|
||||
|
||||
ExecutorService executor = Executors.newFixedThreadPool(THREADS);
|
||||
ConcurrentLinkedQueue<HeavyEvent> processedEvents = new ConcurrentLinkedQueue<>();
|
||||
|
||||
long start = System.nanoTime();
|
||||
|
||||
EventFlow sharedFlow = new EventFlow();
|
||||
sharedFlow.listen(HeavyEvent.class, processedEvents::add, false, "heavyEventListener");
|
||||
|
||||
for (int t = 0; t < THREADS; t++) {
|
||||
executor.submit(() -> {
|
||||
EventFlow threadFlow = new EventFlow();
|
||||
|
||||
for (int i = 0; i < EVENTS_PER_THREAD; i++) {
|
||||
threadFlow.addPostEvent(HeavyEvent.class, "payload-" + i)
|
||||
.postEvent();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
executor.shutdown();
|
||||
executor.awaitTermination(10, TimeUnit.MINUTES);
|
||||
|
||||
long end = System.nanoTime();
|
||||
double durationSeconds = (end - start) / 1_000_000_000.0;
|
||||
|
||||
BigInteger totalEvents = BigInteger.valueOf(THREADS)
|
||||
.multiply(BigInteger.valueOf(EVENTS_PER_THREAD));
|
||||
double eps = totalEvents.doubleValue() / durationSeconds;
|
||||
|
||||
System.out.printf("Posted %s events in %.3f seconds%n", totalEvents, durationSeconds);
|
||||
System.out.printf("Throughput: %.0f events/sec%n", eps);
|
||||
|
||||
Runtime rt = Runtime.getRuntime();
|
||||
System.out.printf("Used memory: %.2f MB%n", (rt.totalMemory() - rt.freeMemory()) / 1024.0 / 1024.0);
|
||||
|
||||
assertEquals(totalEvents.intValue(), processedEvents.size());
|
||||
}
|
||||
|
||||
// @Tag("stress")
|
||||
// @Test
|
||||
// void constructorCacheVsReflection() throws Throwable {
|
||||
@@ -247,7 +234,6 @@
|
||||
// long endHandle = System.nanoTime();
|
||||
//
|
||||
// System.out.println("Reflection: " + (endReflect - startReflect) / 1_000_000 + " ms");
|
||||
// System.out.println("MethodHandle Cache: " + (endHandle - startHandle) / 1_000_000 + "
|
||||
// ms");
|
||||
// System.out.println("MethodHandle Cache: " + (endHandle - startHandle) / 1_000_000 + " ms");
|
||||
// }
|
||||
// }
|
||||
}
|
||||
|
||||
@@ -99,8 +99,14 @@
|
||||
<artifactId>error_prone_annotations</artifactId>
|
||||
<version>2.42.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.toop</groupId>
|
||||
<artifactId>framework</artifactId>
|
||||
<version>0.1</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
package org.toop.game;
|
||||
|
||||
import org.toop.game.interfaces.IAIMove;
|
||||
|
||||
public abstract class AI<T extends Game> implements IAIMove<T> {
|
||||
}
|
||||
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++;
|
||||
}
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
package org.toop.game.Connect4;
|
||||
|
||||
import org.toop.game.TurnBasedGame;
|
||||
import org.toop.game.enumerators.GameState;
|
||||
import org.toop.game.records.Move;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class Connect4 extends TurnBasedGame {
|
||||
private int movesLeft;
|
||||
|
||||
public Connect4() {
|
||||
super(6, 7, 2);
|
||||
movesLeft = this.getBoard().length;
|
||||
}
|
||||
|
||||
public Connect4(Connect4 other) {
|
||||
super(other);
|
||||
movesLeft = other.movesLeft;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Move[] getLegalMoves() {
|
||||
final ArrayList<Move> legalMoves = new ArrayList<>();
|
||||
final char currentValue = getCurrentValue();
|
||||
|
||||
for (int i = 0; i < this.getColumnSize(); i++) {
|
||||
if (this.getBoard()[i] == EMPTY) {
|
||||
legalMoves.add(new Move(i, currentValue));
|
||||
}
|
||||
}
|
||||
return legalMoves.toArray(new Move[0]);
|
||||
}
|
||||
|
||||
@Override
|
||||
public GameState play(Move move) {
|
||||
assert move != null;
|
||||
assert move.position() >= 0 && move.position() < this.getBoard().length;
|
||||
assert move.value() == getCurrentValue();
|
||||
|
||||
int lowestEmptySpot = move.position();
|
||||
for (int i = 0; i < this.getRowSize(); i++) {
|
||||
int checkMovePosition = move.position() + this.getColumnSize() * i;
|
||||
if (checkMovePosition < this.getBoard().length) {
|
||||
if (this.getBoard()[checkMovePosition] == EMPTY) {
|
||||
lowestEmptySpot = checkMovePosition;
|
||||
}
|
||||
}
|
||||
}
|
||||
this.getBoard()[lowestEmptySpot] = move.value();
|
||||
movesLeft--;
|
||||
|
||||
if (checkForWin()) {
|
||||
return GameState.WIN;
|
||||
}
|
||||
|
||||
nextTurn();
|
||||
|
||||
|
||||
return GameState.NORMAL;
|
||||
}
|
||||
|
||||
private boolean checkForWin() {
|
||||
char[][] boardGrid = makeBoardAGrid();
|
||||
|
||||
for (int row = 0; row < this.getRowSize(); row++) {
|
||||
for (int col = 0; col < this.getColumnSize(); col++) {
|
||||
char cell = boardGrid[row][col];
|
||||
if (cell == ' ' || cell == 0) continue;
|
||||
|
||||
if (col + 3 < this.getColumnSize() &&
|
||||
cell == boardGrid[row][col + 1] &&
|
||||
cell == boardGrid[row][col + 2] &&
|
||||
cell == boardGrid[row][col + 3]) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (row + 3 < this.getRowSize() &&
|
||||
cell == boardGrid[row + 1][col] &&
|
||||
cell == boardGrid[row + 2][col] &&
|
||||
cell == boardGrid[row + 3][col]) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (row + 3 < this.getRowSize() && col + 3 < this.getColumnSize() &&
|
||||
cell == boardGrid[row + 1][col + 1] &&
|
||||
cell == boardGrid[row + 2][col + 2] &&
|
||||
cell == boardGrid[row + 3][col + 3]) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (row + 3 < this.getRowSize() && col - 3 >= 0 &&
|
||||
cell == boardGrid[row + 1][col - 1] &&
|
||||
cell == boardGrid[row + 2][col - 2] &&
|
||||
cell == boardGrid[row + 3][col - 3]) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private char[][] makeBoardAGrid() {
|
||||
char[][] boardGrid = new char[this.getRowSize()][this.getColumnSize()];
|
||||
for (int i = 0; i < this.getRowSize()*this.getColumnSize(); i++) {
|
||||
boardGrid[i / this.getColumnSize()][i % this.getColumnSize()] = this.getBoard()[i]; //this.getBoard()Grid[y -> row] [x -> column]
|
||||
}
|
||||
return boardGrid;
|
||||
}
|
||||
|
||||
private char getCurrentValue() {
|
||||
return this.getCurrentTurn() == 0 ? 'X' : 'O';
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
package org.toop.game.Connect4;
|
||||
|
||||
import org.toop.game.AI;
|
||||
import org.toop.game.enumerators.GameState;
|
||||
import org.toop.game.records.Move;
|
||||
|
||||
public class Connect4AI extends AI<Connect4> {
|
||||
|
||||
|
||||
public Move findBestMove(Connect4 game, int depth) {
|
||||
assert game != null;
|
||||
assert depth >= 0;
|
||||
|
||||
final Move[] legalMoves = game.getLegalMoves();
|
||||
|
||||
if (legalMoves.length <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
int bestScore = -depth;
|
||||
Move bestMove = null;
|
||||
|
||||
for (final Move move : legalMoves) {
|
||||
final int score = getMoveScore(game, depth, move, true);
|
||||
|
||||
if (score > bestScore) {
|
||||
bestMove = move;
|
||||
bestScore = score;
|
||||
}
|
||||
}
|
||||
|
||||
return bestMove != null? bestMove : legalMoves[(int)(Math.random() * legalMoves.length)];
|
||||
}
|
||||
|
||||
private int getMoveScore(Connect4 game, int depth, Move move, boolean maximizing) {
|
||||
final Connect4 copy = new Connect4(game);
|
||||
final GameState state = copy.play(move);
|
||||
|
||||
switch (state) {
|
||||
case GameState.DRAW: return 0;
|
||||
case GameState.WIN: return maximizing? depth + 1 : -depth - 1;
|
||||
}
|
||||
|
||||
if (depth <= 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
final Move[] legalMoves = copy.getLegalMoves();
|
||||
int score = maximizing? depth + 1 : -depth - 1;
|
||||
|
||||
for (final Move next : legalMoves) {
|
||||
if (maximizing) {
|
||||
score = Math.min(score, getMoveScore(copy, depth - 1, next, false));
|
||||
} else {
|
||||
score = Math.max(score, getMoveScore(copy, depth - 1, next, true));
|
||||
}
|
||||
}
|
||||
|
||||
return score;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
package org.toop.game;
|
||||
|
||||
import org.toop.game.interfaces.IPlayable;
|
||||
import org.toop.game.records.Move;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public abstract class Game implements IPlayable {
|
||||
|
||||
public static final char EMPTY = (char)0; // Constant
|
||||
|
||||
private final int rowSize;
|
||||
private final int columnSize;
|
||||
private final char[] board;
|
||||
|
||||
protected Game(int rowSize, int columnSize) {
|
||||
assert rowSize > 0 && columnSize > 0;
|
||||
|
||||
this.rowSize = rowSize;
|
||||
this.columnSize = columnSize;
|
||||
|
||||
board = new char[rowSize * columnSize];
|
||||
Arrays.fill(board, EMPTY);
|
||||
}
|
||||
|
||||
protected Game(Game other) {
|
||||
rowSize = other.rowSize;
|
||||
columnSize = other.columnSize;
|
||||
board = Arrays.copyOf(other.board, other.board.length);
|
||||
}
|
||||
|
||||
public int getRowSize() {return this.rowSize;}
|
||||
|
||||
public int getColumnSize() {return this.columnSize;}
|
||||
|
||||
public char[] getBoard() {return this.board;}
|
||||
|
||||
protected void setBoard(Move move){this.board[move.position()] = move.value();}
|
||||
|
||||
}
|
||||
3
game/src/main/java/org/toop/game/Move.java
Normal file
3
game/src/main/java/org/toop/game/Move.java
Normal file
@@ -0,0 +1,3 @@
|
||||
package org.toop.game;
|
||||
// TODO: Remove this, only used in ReversiCanvas. Needs to not
|
||||
public record Move(int position, char value) {}
|
||||
@@ -1,25 +0,0 @@
|
||||
package org.toop.game;
|
||||
|
||||
public abstract class TurnBasedGame extends Game {
|
||||
private final int playerCount; // How many players are playing
|
||||
private int turn = 0; // What turn it is in the game
|
||||
|
||||
protected TurnBasedGame(int rowSize, int columnSize, int playerCount) {
|
||||
super(rowSize, columnSize);
|
||||
this.playerCount = playerCount;
|
||||
}
|
||||
|
||||
protected TurnBasedGame(TurnBasedGame other) {
|
||||
super(other);
|
||||
playerCount = other.playerCount;
|
||||
turn = other.turn;
|
||||
}
|
||||
|
||||
protected void nextTurn() {
|
||||
turn += 1;
|
||||
}
|
||||
|
||||
public int getCurrentTurn() {
|
||||
return turn % playerCount;
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package org.toop.game.enumerators;
|
||||
|
||||
public enum GameState {
|
||||
NORMAL,
|
||||
DRAW,
|
||||
WIN,
|
||||
|
||||
TURN_SKIPPED,
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package org.toop.game.gameThreads;
|
||||
|
||||
import org.toop.framework.eventbus.EventFlow;
|
||||
import org.toop.framework.gameFramework.GameState;
|
||||
import org.toop.framework.gameFramework.model.game.PlayResult;
|
||||
import org.toop.framework.gameFramework.model.game.threadBehaviour.AbstractThreadBehaviour;
|
||||
import org.toop.framework.gameFramework.view.GUIEvents;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* Handles local turn-based game logic at a fixed update rate.
|
||||
* <p>
|
||||
* Runs a separate thread that executes game turns at a fixed frequency (default 60 updates/sec),
|
||||
* applying player moves, updating the game state, and dispatching UI events.
|
||||
*/
|
||||
public class LocalFixedRateThreadBehaviour<T extends TurnBasedGame<T>> extends AbstractThreadBehaviour<T> implements Runnable {
|
||||
|
||||
|
||||
/**
|
||||
* Creates a fixed-rate behaviour for a local turn-based game.
|
||||
*
|
||||
* @param game the game instance
|
||||
*/
|
||||
public LocalFixedRateThreadBehaviour(T game) {
|
||||
super(game);
|
||||
}
|
||||
|
||||
/** Starts the game loop thread if not already running. */
|
||||
@Override
|
||||
public void start() {
|
||||
if (isRunning.compareAndSet(false, true)) {
|
||||
new Thread(this).start();
|
||||
}
|
||||
}
|
||||
|
||||
/** Stops the game loop after the current iteration. */
|
||||
@Override
|
||||
public void stop() {
|
||||
isRunning.set(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Main loop running at a fixed rate.
|
||||
* <p>
|
||||
* Fetches the current player's move, applies it to the game,
|
||||
* updates the UI, and handles game-ending states.
|
||||
*/
|
||||
@Override
|
||||
public void run() {
|
||||
final int UPS = 1;
|
||||
final long UPDATE_INTERVAL = 1_000_000_000L / UPS;
|
||||
long nextUpdate = System.nanoTime();
|
||||
|
||||
while (isRunning.get()) {
|
||||
long now = System.nanoTime();
|
||||
if (now >= nextUpdate) {
|
||||
nextUpdate += UPDATE_INTERVAL;
|
||||
|
||||
Player<T> currentPlayer = game.getPlayer(game.getCurrentTurn());
|
||||
long move = currentPlayer.getMove(game.deepCopy());
|
||||
PlayResult result = game.play(move);
|
||||
|
||||
updateUI();
|
||||
|
||||
GameState state = result.state();
|
||||
switch (state) {
|
||||
case WIN, DRAW -> {
|
||||
isRunning.set(false);
|
||||
new EventFlow().addPostEvent(GUIEvents.GameEnded.class, state == GameState.WIN, result.player()).postEvent();
|
||||
}
|
||||
case NORMAL, TURN_SKIPPED -> { /* continue */ }
|
||||
default -> {
|
||||
logger.error("Unexpected state {}", state);
|
||||
isRunning.set(false);
|
||||
throw new RuntimeException("Unknown state: " + state);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
Thread.sleep(10);
|
||||
} catch (InterruptedException ignored) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
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.PlayResult;
|
||||
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>
|
||||
* Repeatedly gets the current player's move, applies it to the game,
|
||||
* updates the UI, and stops when the game ends or {@link #stop()} is called.
|
||||
*/
|
||||
public class LocalThreadBehaviour<T extends TurnBasedGame<T>> extends AbstractThreadBehaviour<T> implements Runnable {
|
||||
|
||||
/**
|
||||
* Creates a new behaviour for a local turn-based game.
|
||||
*
|
||||
* @param game the game instance
|
||||
*/
|
||||
public LocalThreadBehaviour(T game) {
|
||||
super(game);
|
||||
}
|
||||
|
||||
/** Starts the game loop in a new thread. */
|
||||
@Override
|
||||
public void start() {
|
||||
if (isRunning.compareAndSet(false, true)) {
|
||||
new Thread(this).start();
|
||||
}
|
||||
}
|
||||
|
||||
/** Stops the game loop after the current iteration. */
|
||||
@Override
|
||||
public void stop() {
|
||||
isRunning.set(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Main game loop: gets the current player's move, applies it,
|
||||
* updates the UI, and handles end-of-game states.
|
||||
*/
|
||||
@Override
|
||||
public void run() {
|
||||
while (isRunning.get()) {
|
||||
Player<T> currentPlayer = game.getPlayer(game.getCurrentTurn());
|
||||
long move = currentPlayer.getMove(game.deepCopy());
|
||||
PlayResult result = game.play(move);
|
||||
|
||||
updateUI();
|
||||
|
||||
GameState state = result.state();
|
||||
switch (state) {
|
||||
case WIN, DRAW -> {
|
||||
isRunning.set(false);
|
||||
new EventFlow().addPostEvent(
|
||||
GUIEvents.GameEnded.class,
|
||||
state == GameState.WIN,
|
||||
result.player()
|
||||
).postEvent();
|
||||
}
|
||||
case NORMAL, TURN_SKIPPED -> { /* continue normally */ }
|
||||
default -> {
|
||||
logger.error("Unexpected state {}", state);
|
||||
isRunning.set(false);
|
||||
throw new RuntimeException("Unknown state: " + state);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
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.TurnBasedGame;
|
||||
import org.toop.framework.gameFramework.model.game.SupportsOnlinePlay;
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
import org.toop.game.players.OnlinePlayer;
|
||||
|
||||
/**
|
||||
* Handles online multiplayer game logic.
|
||||
* <p>
|
||||
* Reacts to server events, sending moves and updating the game state
|
||||
* for the local player while receiving moves from other players.
|
||||
*/
|
||||
public class OnlineThreadBehaviour<T extends TurnBasedGame<T>> extends AbstractThreadBehaviour<T> implements SupportsOnlinePlay {
|
||||
/**
|
||||
* Creates behaviour and sets the first local player
|
||||
* (non-online player) from the given array.
|
||||
*/
|
||||
public OnlineThreadBehaviour(T game) {
|
||||
super(game);
|
||||
}
|
||||
|
||||
/** Finds the first non-online player in the array. */
|
||||
private int getFirstNotOnlinePlayer(Player<T>[] players) {
|
||||
for (int i = 0; i < players.length; i++) {
|
||||
if (!(players[i] instanceof OnlinePlayer)) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
throw new RuntimeException("All players are online players");
|
||||
}
|
||||
|
||||
/** Starts processing network events for the local player. */
|
||||
@Override
|
||||
public void start() {
|
||||
isRunning.set(true);
|
||||
}
|
||||
|
||||
/** Stops processing network events. */
|
||||
@Override
|
||||
public void stop() {
|
||||
isRunning.set(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when the server notifies that it is the local player's turn.
|
||||
* Sends the generated move back to the server.
|
||||
*/
|
||||
@Override
|
||||
public void onYourTurn(long clientId) {
|
||||
if (!isRunning.get()) return;
|
||||
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.
|
||||
*/
|
||||
public void onMoveReceived(long move) {
|
||||
if (!isRunning.get()) return;
|
||||
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.
|
||||
*/
|
||||
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");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package org.toop.game.gameThreads;
|
||||
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
import org.toop.framework.networking.events.NetworkEvents;
|
||||
|
||||
/**
|
||||
* Online thread behaviour that adds a fixed delay before processing
|
||||
* the local player's turn.
|
||||
* <p>
|
||||
* This is identical to {@link OnlineThreadBehaviour}, but inserts a
|
||||
* short sleep before delegating to the base implementation.
|
||||
*/
|
||||
public class OnlineWithSleepThreadBehaviour<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
|
||||
*/
|
||||
public OnlineWithSleepThreadBehaviour(T game) {
|
||||
super(game);
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits briefly before handling the "your turn" event.
|
||||
*
|
||||
* @param event the network event indicating it's this client's turn
|
||||
*/
|
||||
@Override
|
||||
public void onYourTurn(long clientId) {
|
||||
|
||||
try {
|
||||
Thread.sleep(50);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user