mirror of
https://github.com/2OOP/pism.git
synced 2026-02-04 19:04:49 +00:00
Compare commits
4 Commits
056d9180b9
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b3e29a3262 | ||
|
|
429e5bc90b | ||
|
|
8146be16ed | ||
|
|
afb4844084 |
80
.github/workflows/checks.yaml
vendored
80
.github/workflows/checks.yaml
vendored
@@ -1,42 +1,42 @@
|
|||||||
name: Checks
|
#name: Checks
|
||||||
|
|
||||||
on:
|
#on:
|
||||||
push:
|
# push:
|
||||||
branches:
|
# branches:
|
||||||
- 'main'
|
# - 'main'
|
||||||
pull_request:
|
# pull_request:
|
||||||
branches:
|
# branches:
|
||||||
- 'main'
|
# - 'main'
|
||||||
|
#
|
||||||
|
#jobs:
|
||||||
|
# formatting-check:
|
||||||
|
# name: Follow Google Formatting Guidelines
|
||||||
|
# runs-on: ubuntu-latest
|
||||||
|
# steps:
|
||||||
|
# - uses: actions/checkout@v5
|
||||||
|
# with:
|
||||||
|
# fetch-depth: 0 # Fix for incremental formatting
|
||||||
|
# - uses: actions/setup-java@v5
|
||||||
|
# with:
|
||||||
|
# java-version: '25'
|
||||||
|
# distribution: 'temurin'
|
||||||
|
# cache: maven
|
||||||
|
# - name: Run Format Check
|
||||||
|
# run: mvn spotless:check
|
||||||
|
|
||||||
jobs:
|
# tests:
|
||||||
formatting-check:
|
# name: Unittests
|
||||||
name: Follow Google Formatting Guidelines
|
# runs-on: ${{ matrix.os }}
|
||||||
runs-on: ubuntu-latest
|
# needs: formatting-check
|
||||||
steps:
|
# strategy:
|
||||||
- uses: actions/checkout@v5
|
# matrix:
|
||||||
with:
|
# os: [ubuntu-latest] #windows-latest, macos-latest
|
||||||
fetch-depth: 0 # Fix for incremental formatting
|
# steps:
|
||||||
- uses: actions/setup-java@v5
|
# - uses: actions/checkout@v5
|
||||||
with:
|
# - uses: actions/setup-java@v5
|
||||||
java-version: '25'
|
# with:
|
||||||
distribution: 'temurin'
|
# java-version: '25'
|
||||||
cache: maven
|
# distribution: 'temurin'
|
||||||
- name: Run Format Check
|
# cache: maven
|
||||||
run: mvn spotless:check
|
# - name: Run Unittests
|
||||||
|
# run: mvn -B test
|
||||||
tests:
|
|
||||||
name: Unittests
|
|
||||||
runs-on: ${{ matrix.os }}
|
|
||||||
needs: formatting-check
|
|
||||||
strategy:
|
|
||||||
matrix:
|
|
||||||
os: [ubuntu-latest] #windows-latest, macos-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v5
|
|
||||||
- uses: actions/setup-java@v5
|
|
||||||
with:
|
|
||||||
java-version: '25'
|
|
||||||
distribution: 'temurin'
|
|
||||||
cache: maven
|
|
||||||
- name: Run Unittests
|
|
||||||
run: mvn -B test
|
|
||||||
|
|||||||
2
.idea/inspectionProfiles/Project_Default.xml
generated
2
.idea/inspectionProfiles/Project_Default.xml
generated
@@ -2,7 +2,7 @@
|
|||||||
<profile version="1.0">
|
<profile version="1.0">
|
||||||
<option name="myName" value="Project Default" />
|
<option name="myName" value="Project Default" />
|
||||||
<inspection_tool class="AutoCloseableResource" enabled="true" level="WARNING" enabled_by_default="true">
|
<inspection_tool class="AutoCloseableResource" enabled="true" level="WARNING" enabled_by_default="true">
|
||||||
<option name="METHOD_MATCHER_CONFIG" value="java.util.Formatter,format,java.io.Writer,append,com.google.common.base.Preconditions,checkNotNull,org.hibernate.Session,close,java.io.PrintWriter,printf,java.io.PrintStream,printf,java.lang.foreign.Arena,ofAuto,java.lang.foreign.Arena,global,org.toop.framework.audio.AudioPlayer,play,java.util.Map,remove,java.util.concurrent.Executors,newSingleThreadScheduledExecutor" />
|
<option name="METHOD_MATCHER_CONFIG" value="java.util.Formatter,format,java.io.Writer,append,com.google.common.base.Preconditions,checkNotNull,org.hibernate.Session,close,java.io.PrintWriter,printf,java.io.PrintStream,printf,java.lang.foreign.Arena,ofAuto,java.lang.foreign.Arena,global,org.toop.framework.audio.AudioPlayer,play,java.util.Map,remove,java.util.concurrent.Executors,newSingleThreadScheduledExecutor|newFixedThreadPool|newSingleThreadExecutor" />
|
||||||
</inspection_tool>
|
</inspection_tool>
|
||||||
<inspection_tool class="WriteOnlyObject" enabled="false" level="WARNING" enabled_by_default="false" />
|
<inspection_tool class="WriteOnlyObject" enabled="false" level="WARNING" enabled_by_default="false" />
|
||||||
</profile>
|
</profile>
|
||||||
|
|||||||
@@ -1,13 +1,6 @@
|
|||||||
package org.toop;
|
package org.toop;
|
||||||
|
|
||||||
import org.toop.app.App;
|
import org.toop.app.App;
|
||||||
import org.toop.framework.audio.*;
|
|
||||||
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.resources.MusicAsset;
|
|
||||||
import org.toop.framework.resource.resources.SoundEffectAsset;
|
|
||||||
|
|
||||||
public final class Main {
|
public final class Main {
|
||||||
static void main(String[] args) {
|
static void main(String[] args) {
|
||||||
|
|||||||
@@ -1,9 +1,14 @@
|
|||||||
package org.toop.app;
|
package org.toop.app;
|
||||||
|
|
||||||
|
import javafx.application.Application;
|
||||||
import javafx.application.Platform;
|
import javafx.application.Platform;
|
||||||
|
import javafx.geometry.Pos;
|
||||||
|
import javafx.scene.Scene;
|
||||||
import javafx.scene.input.KeyCode;
|
import javafx.scene.input.KeyCode;
|
||||||
|
import javafx.scene.input.KeyCodeCombination;
|
||||||
import javafx.scene.input.KeyEvent;
|
import javafx.scene.input.KeyEvent;
|
||||||
|
import javafx.scene.layout.StackPane;
|
||||||
|
import javafx.stage.Stage;
|
||||||
import org.toop.app.widget.Primitive;
|
import org.toop.app.widget.Primitive;
|
||||||
import org.toop.app.widget.WidgetContainer;
|
import org.toop.app.widget.WidgetContainer;
|
||||||
import org.toop.app.widget.complex.LoadingWidget;
|
import org.toop.app.widget.complex.LoadingWidget;
|
||||||
@@ -14,8 +19,9 @@ import org.toop.app.widget.view.MainView;
|
|||||||
import org.toop.framework.audio.*;
|
import org.toop.framework.audio.*;
|
||||||
import org.toop.framework.audio.events.AudioEvents;
|
import org.toop.framework.audio.events.AudioEvents;
|
||||||
import org.toop.framework.eventbus.EventFlow;
|
import org.toop.framework.eventbus.EventFlow;
|
||||||
import org.toop.framework.networking.NetworkingClientEventListener;
|
import org.toop.framework.eventbus.GlobalEventBus;
|
||||||
import org.toop.framework.networking.NetworkingClientManager;
|
import org.toop.framework.networking.connection.NetworkingClientEventListener;
|
||||||
|
import org.toop.framework.networking.connection.NetworkingClientManager;
|
||||||
import org.toop.framework.resource.ResourceLoader;
|
import org.toop.framework.resource.ResourceLoader;
|
||||||
import org.toop.framework.resource.ResourceManager;
|
import org.toop.framework.resource.ResourceManager;
|
||||||
import org.toop.framework.resource.events.AssetLoaderEvents;
|
import org.toop.framework.resource.events.AssetLoaderEvents;
|
||||||
@@ -25,13 +31,10 @@ import org.toop.framework.resource.resources.SoundEffectAsset;
|
|||||||
import org.toop.local.AppContext;
|
import org.toop.local.AppContext;
|
||||||
import org.toop.local.AppSettings;
|
import org.toop.local.AppSettings;
|
||||||
|
|
||||||
import javafx.application.Application;
|
|
||||||
import javafx.geometry.Pos;
|
|
||||||
import javafx.scene.Scene;
|
|
||||||
import javafx.scene.layout.StackPane;
|
|
||||||
import javafx.stage.Stage;
|
|
||||||
|
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
|
import java.util.concurrent.CountDownLatch;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
|
||||||
public final class App extends Application {
|
public final class App extends Application {
|
||||||
private static Stage stage;
|
private static Stage stage;
|
||||||
@@ -45,7 +48,7 @@ public final class App extends Application {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void start(Stage stage) throws Exception {
|
public void start(Stage stage) {
|
||||||
// Start loading localization
|
// Start loading localization
|
||||||
ResourceManager.loadAssets(new ResourceLoader("app/src/main/resources/localization"));
|
ResourceManager.loadAssets(new ResourceLoader("app/src/main/resources/localization"));
|
||||||
ResourceManager.loadAssets(new ResourceLoader("app/src/main/resources/style"));
|
ResourceManager.loadAssets(new ResourceLoader("app/src/main/resources/style"));
|
||||||
@@ -63,8 +66,8 @@ public final class App extends Application {
|
|||||||
|
|
||||||
scene.getRoot();
|
scene.getRoot();
|
||||||
|
|
||||||
stage.setMinWidth(1080);
|
stage.setMinWidth(1200);
|
||||||
stage.setMinHeight(720);
|
stage.setMinHeight(800);
|
||||||
stage.setOnCloseRequest(event -> {
|
stage.setOnCloseRequest(event -> {
|
||||||
event.consume();
|
event.consume();
|
||||||
quit();
|
quit();
|
||||||
@@ -81,7 +84,7 @@ public final class App extends Application {
|
|||||||
|
|
||||||
AppSettings.applySettings();
|
AppSettings.applySettings();
|
||||||
|
|
||||||
setKeybinds(root);
|
setKeybinds(root);
|
||||||
|
|
||||||
LoadingWidget loading = new LoadingWidget(Primitive.text(
|
LoadingWidget loading = new LoadingWidget(Primitive.text(
|
||||||
"Loading...", false), 0, 0, Integer.MAX_VALUE, false, false // Just set a high default
|
"Loading...", false), 0, 0, Integer.MAX_VALUE, false, false // Just set a high default
|
||||||
@@ -89,7 +92,7 @@ public final class App extends Application {
|
|||||||
|
|
||||||
WidgetContainer.setCurrentView(loading);
|
WidgetContainer.setCurrentView(loading);
|
||||||
|
|
||||||
setOnLoadingSuccess(loading);
|
setOnLoadingSuccess(loading);
|
||||||
|
|
||||||
EventFlow loadingFlow = new EventFlow();
|
EventFlow loadingFlow = new EventFlow();
|
||||||
|
|
||||||
@@ -106,40 +109,54 @@ public final class App extends Application {
|
|||||||
Platform.runLater(() -> stage.setOpacity(1.0));
|
Platform.runLater(() -> stage.setOpacity(1.0));
|
||||||
}
|
}
|
||||||
|
|
||||||
Platform.runLater(() -> loading.setMaxAmount(e.isLoadingAmount()));
|
|
||||||
|
|
||||||
Platform.runLater(() -> {
|
Platform.runLater(() -> {
|
||||||
|
loading.setMaxAmount(e.isLoadingAmount());
|
||||||
try {
|
try {
|
||||||
loading.setAmount(e.hasLoadedAmount());
|
loading.setAmount(e.hasLoadedAmount());
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
throw new RuntimeException(ex);
|
throw new RuntimeException(ex);
|
||||||
}
|
}
|
||||||
|
if (e.hasLoadedAmount() >= e.isLoadingAmount()-1) {
|
||||||
|
Platform.runLater(loading::triggerSuccess);
|
||||||
|
loadingFlow.unsubscribe("init_loading");
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
if (e.hasLoadedAmount() >= e.isLoadingAmount()) {
|
|
||||||
Platform.runLater(loading::triggerSuccess);
|
|
||||||
loadingFlow.unsubscribe("init_loading");
|
|
||||||
}
|
|
||||||
|
|
||||||
}, false, "init_loading");
|
}, false, "init_loading");
|
||||||
|
|
||||||
// Start loading assets
|
ExecutorService executor = Executors.newSingleThreadExecutor();
|
||||||
new Thread(() -> ResourceManager.loadAssets(new ResourceLoader("app/src/main/resources/assets")))
|
try {
|
||||||
.start();
|
executor.submit(
|
||||||
|
() -> ResourceManager.loadAssets(new ResourceLoader("app/src/main/resources/assets")
|
||||||
|
));
|
||||||
|
} finally {
|
||||||
|
executor.shutdown();
|
||||||
|
}
|
||||||
|
|
||||||
stage.show();
|
stage.show();
|
||||||
|
}
|
||||||
}
|
|
||||||
|
|
||||||
private void setKeybinds(StackPane root) {
|
private void setKeybinds(StackPane root) {
|
||||||
root.addEventHandler(KeyEvent.KEY_PRESSED,event -> {
|
root.addEventHandler(KeyEvent.KEY_PRESSED,event -> {
|
||||||
if (event.getCode() == KeyCode.ESCAPE) {
|
if (event.getCode() == KeyCode.ESCAPE) {
|
||||||
escapePopup();
|
escapePopup();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
stage.setFullScreenExitKeyCombination(
|
||||||
|
new KeyCodeCombination(
|
||||||
|
KeyCode.F11
|
||||||
|
)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void escapePopup() {
|
public void escapePopup() {
|
||||||
|
|
||||||
|
if ( WidgetContainer.getCurrentView() == null
|
||||||
|
|| WidgetContainer.getCurrentView() instanceof MainView) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (!Objects.requireNonNull(
|
if (!Objects.requireNonNull(
|
||||||
WidgetContainer.find(widget -> widget instanceof QuitPopup || widget instanceof EscapePopup)
|
WidgetContainer.find(widget -> widget instanceof QuitPopup || widget instanceof EscapePopup)
|
||||||
).isEmpty()) {
|
).isEmpty()) {
|
||||||
@@ -154,8 +171,14 @@ public final class App extends Application {
|
|||||||
|
|
||||||
private void setOnLoadingSuccess(LoadingWidget loading) {
|
private void setOnLoadingSuccess(LoadingWidget loading) {
|
||||||
loading.setOnSuccess(() -> {
|
loading.setOnSuccess(() -> {
|
||||||
initSystems();
|
|
||||||
AppSettings.applyMusicVolumeSettings();
|
try {
|
||||||
|
initSystems();
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
|
||||||
|
AppSettings.applyMusicVolumeSettings();
|
||||||
new EventFlow().addPostEvent(new AudioEvents.StartBackgroundMusic()).postEvent();
|
new EventFlow().addPostEvent(new AudioEvents.StartBackgroundMusic()).postEvent();
|
||||||
loading.hide();
|
loading.hide();
|
||||||
WidgetContainer.add(Pos.CENTER, new MainView());
|
WidgetContainer.add(Pos.CENTER, new MainView());
|
||||||
@@ -172,36 +195,55 @@ public final class App extends Application {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private void initSystems() { // TODO Move to better place
|
private void initSystems() throws InterruptedException { // TODO Move to better place
|
||||||
new Thread(() -> new NetworkingClientEventListener(new NetworkingClientManager())).start();
|
|
||||||
|
|
||||||
new Thread(() -> {
|
final int THREAD_COUNT = 2;
|
||||||
MusicManager<MusicAsset> musicManager =
|
CountDownLatch latch = new CountDownLatch(THREAD_COUNT);
|
||||||
new MusicManager<>(ResourceManager.getAllOfTypeAndRemoveWrapper(MusicAsset.class), true);
|
|
||||||
|
|
||||||
SoundEffectManager<SoundEffectAsset> soundEffectManager =
|
@SuppressWarnings("resource")
|
||||||
new SoundEffectManager<>(ResourceManager.getAllOfType(SoundEffectAsset.class));
|
ExecutorService threads = Executors.newFixedThreadPool(THREAD_COUNT);
|
||||||
|
|
||||||
AudioVolumeManager audioVolumeManager = new AudioVolumeManager()
|
try {
|
||||||
.registerManager(VolumeControl.MASTERVOLUME, musicManager)
|
|
||||||
.registerManager(VolumeControl.MASTERVOLUME, soundEffectManager)
|
|
||||||
.registerManager(VolumeControl.FX, soundEffectManager)
|
|
||||||
.registerManager(VolumeControl.MUSIC, musicManager);
|
|
||||||
|
|
||||||
new AudioEventListener<>(
|
threads.submit(() -> {
|
||||||
musicManager,
|
new NetworkingClientEventListener(
|
||||||
soundEffectManager,
|
GlobalEventBus.get(),
|
||||||
audioVolumeManager
|
new NetworkingClientManager(GlobalEventBus.get()));
|
||||||
).initListeners("medium-button-click.wav");
|
|
||||||
|
|
||||||
}).start();
|
latch.countDown();
|
||||||
|
});
|
||||||
|
|
||||||
// Threads must be ready, before continue, TODO use latch instead
|
threads.submit(() -> {
|
||||||
try {
|
MusicManager<MusicAsset> musicManager =
|
||||||
Thread.sleep(200);
|
new MusicManager<>(
|
||||||
} catch (InterruptedException e) {
|
GlobalEventBus.get(),
|
||||||
throw new RuntimeException(e);
|
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<>(
|
||||||
|
GlobalEventBus.get(),
|
||||||
|
musicManager,
|
||||||
|
soundEffectManager,
|
||||||
|
audioVolumeManager
|
||||||
|
).initListeners("medium-button-click.wav");
|
||||||
|
|
||||||
|
latch.countDown();
|
||||||
|
});
|
||||||
|
|
||||||
|
} finally {
|
||||||
|
latch.await();
|
||||||
|
threads.shutdown();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void quit() {
|
public static void quit() {
|
||||||
|
|||||||
@@ -11,18 +11,19 @@ import org.toop.app.widget.popup.ErrorPopup;
|
|||||||
import org.toop.app.widget.popup.SendChallengePopup;
|
import org.toop.app.widget.popup.SendChallengePopup;
|
||||||
import org.toop.app.widget.view.ServerView;
|
import org.toop.app.widget.view.ServerView;
|
||||||
import org.toop.framework.eventbus.EventFlow;
|
import org.toop.framework.eventbus.EventFlow;
|
||||||
|
import org.toop.framework.game.players.ArtificialPlayer;
|
||||||
|
import org.toop.framework.game.players.OnlinePlayer;
|
||||||
import org.toop.framework.gameFramework.controller.GameController;
|
import org.toop.framework.gameFramework.controller.GameController;
|
||||||
|
import org.toop.framework.eventbus.GlobalEventBus;
|
||||||
import org.toop.framework.gameFramework.model.player.Player;
|
import org.toop.framework.gameFramework.model.player.Player;
|
||||||
import org.toop.framework.networking.clients.TournamentNetworkingClient;
|
import org.toop.framework.networking.connection.clients.TournamentNetworkingClient;
|
||||||
import org.toop.framework.networking.events.NetworkEvents;
|
import org.toop.framework.networking.connection.events.NetworkEvents;
|
||||||
import org.toop.framework.networking.types.NetworkingConnector;
|
import org.toop.framework.networking.connection.types.NetworkingConnector;
|
||||||
import org.toop.game.games.reversi.BitboardReversi;
|
import org.toop.framework.networking.server.gateway.NettyGatewayServer;
|
||||||
import org.toop.game.games.tictactoe.BitboardTicTacToe;
|
import org.toop.game.players.ai.mcts.MCTSAI3;
|
||||||
import org.toop.game.players.ArtificialPlayer;
|
|
||||||
import org.toop.game.players.OnlinePlayer;
|
|
||||||
import org.toop.game.players.RandomAI;
|
|
||||||
import org.toop.local.AppContext;
|
import org.toop.local.AppContext;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.concurrent.CopyOnWriteArrayList;
|
import java.util.concurrent.CopyOnWriteArrayList;
|
||||||
import java.util.concurrent.Executors;
|
import java.util.concurrent.Executors;
|
||||||
@@ -31,6 +32,8 @@ import java.util.concurrent.TimeUnit;
|
|||||||
import java.util.concurrent.atomic.AtomicBoolean;
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
|
||||||
public final class Server {
|
public final class Server {
|
||||||
|
private NettyGatewayServer nettyGatewayServer;
|
||||||
|
|
||||||
private String user = "";
|
private String user = "";
|
||||||
private long clientId = -1;
|
private long clientId = -1;
|
||||||
|
|
||||||
@@ -58,10 +61,13 @@ public final class Server {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Server(String ip, String port, String user) {
|
||||||
|
this(ip, port, user, null);
|
||||||
|
}
|
||||||
|
|
||||||
// Server has to deal with ALL network related listen events. This "server" can then interact with the manager to make stuff happen.
|
// 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.
|
// 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) {
|
public Server(String ip, String port, String user, NettyGatewayServer nettyGatewayServer) {
|
||||||
if (ip.split("\\.").length < 4) {
|
if (ip.split("\\.").length < 4) {
|
||||||
new ErrorPopup("\"" + ip + "\" " + AppContext.getString("is-not-a-valid-ip-address"));
|
new ErrorPopup("\"" + ip + "\" " + AppContext.getString("is-not-a-valid-ip-address"));
|
||||||
return;
|
return;
|
||||||
@@ -81,17 +87,19 @@ public final class Server {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
this.nettyGatewayServer = nettyGatewayServer;
|
||||||
|
|
||||||
final int reconnectAttempts = 10;
|
final int reconnectAttempts = 10;
|
||||||
|
|
||||||
LoadingWidget loading = new LoadingWidget(
|
LoadingWidget loading = new LoadingWidget(
|
||||||
Primitive.text("connecting"), 0, 0, reconnectAttempts, true, true
|
Primitive.text("connecting"), 0, 0, reconnectAttempts, true, true
|
||||||
);
|
);
|
||||||
|
|
||||||
WidgetContainer.getCurrentView().transitionNext(loading);
|
WidgetContainer.getCurrentView().transitionNextCustom(loading, "disconnect", this::disconnect);
|
||||||
|
|
||||||
var a = new EventFlow()
|
var a = new EventFlow()
|
||||||
.addPostEvent(NetworkEvents.StartClient.class,
|
.addPostEvent(NetworkEvents.StartClient.class,
|
||||||
new TournamentNetworkingClient(),
|
new TournamentNetworkingClient(GlobalEventBus.get()),
|
||||||
new NetworkingConnector(ip, parsedPort, reconnectAttempts, 1, TimeUnit.SECONDS)
|
new NetworkingConnector(ip, parsedPort, reconnectAttempts, 1, TimeUnit.SECONDS)
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -104,20 +112,21 @@ public final class Server {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
a.onResponse(NetworkEvents.StartClientResponse.class, e -> {
|
a.onResponse(NetworkEvents.CreatedIdForClient.class, e -> clientId = e.clientId(), true);
|
||||||
|
|
||||||
|
a.onResponse(NetworkEvents.StartClientResponse.class, e -> {
|
||||||
if (!e.successful()) {
|
if (!e.successful()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
primary = new ServerView(user, this::sendChallenge);
|
primary = new ServerView(user, this::sendChallenge, user, clientId);
|
||||||
|
|
||||||
WidgetContainer.getCurrentView().transitionNextCustom(primary, "disconnect", this::disconnect);
|
WidgetContainer.getCurrentView().transitionNextCustom(primary, "disconnect", this::disconnect);
|
||||||
|
|
||||||
a.unsubscribe("connecting");
|
a.unsubscribe("connecting");
|
||||||
a.unsubscribe("startclient");
|
a.unsubscribe("startclient");
|
||||||
|
|
||||||
this.user = user;
|
this.user = user;
|
||||||
clientId = e.clientId();
|
|
||||||
|
|
||||||
new EventFlow().addPostEvent(new NetworkEvents.SendLogin(clientId, user)).postEvent();
|
new EventFlow().addPostEvent(new NetworkEvents.SendLogin(clientId, user)).postEvent();
|
||||||
|
|
||||||
@@ -128,28 +137,33 @@ public final class Server {
|
|||||||
|
|
||||||
}, false, "startclient")
|
}, false, "startclient")
|
||||||
.listen(
|
.listen(
|
||||||
NetworkEvents.ConnectTry.class,
|
NetworkEvents.ConnectTry.class,
|
||||||
e -> Platform.runLater(
|
e -> {
|
||||||
() -> {
|
if (clientId != e.clientId()) return;
|
||||||
try {
|
Platform.runLater(
|
||||||
loading.setAmount(e.amount());
|
() -> {
|
||||||
if (e.amount() >= loading.getMaxAmount()) {
|
try {
|
||||||
loading.triggerFailure();
|
loading.setAmount(e.amount());
|
||||||
}
|
if (e.amount() >= loading.getMaxAmount()) {
|
||||||
} catch (Exception ex) {
|
loading.triggerFailure();
|
||||||
throw new RuntimeException(ex);
|
}
|
||||||
}
|
} catch (Exception ex) {
|
||||||
}
|
throw new RuntimeException(ex);
|
||||||
),
|
}
|
||||||
false, "connecting"
|
}
|
||||||
)
|
);
|
||||||
|
},
|
||||||
|
false, "connecting"
|
||||||
|
)
|
||||||
.postEvent();
|
.postEvent();
|
||||||
|
|
||||||
a.listen(NetworkEvents.ChallengeResponse.class, this::handleReceivedChallenge, false, "challenge")
|
a.listen(NetworkEvents.ChallengeResponse.class, this::handleReceivedChallenge, false, "challenge")
|
||||||
.listen(NetworkEvents.GameMatchResponse.class, this::handleMatchResponse, false, "match-response")
|
.listen(NetworkEvents.GameMatchResponse.class, this::handleMatchResponse, false, "match-response")
|
||||||
.listen(NetworkEvents.GameResultResponse.class, this::handleGameResult, false, "game-result")
|
.listen(NetworkEvents.GameResultResponse.class, this::handleGameResult, false, "game-result")
|
||||||
.listen(NetworkEvents.GameMoveResponse.class, this::handleReceivedMove, false, "game-move")
|
.listen(NetworkEvents.GameMoveResponse.class, this::handleReceivedMove, false, "game-move")
|
||||||
.listen(NetworkEvents.YourTurnResponse.class, this::handleYourTurn, false, "your-turn");
|
.listen(NetworkEvents.YourTurnResponse.class, this::handleYourTurn, false, "your-turn")
|
||||||
|
.listen(NetworkEvents.ClosedConnection.class, this::closedConnection, false, "closed-connection")
|
||||||
|
.listen(NetworkEvents.TournamentResultResponse.class, this::handleTournamentResult, false, "tournament-result");
|
||||||
|
|
||||||
connectFlow = a;
|
connectFlow = a;
|
||||||
}
|
}
|
||||||
@@ -173,7 +187,7 @@ public final class Server {
|
|||||||
|
|
||||||
gameController = null;
|
gameController = null;
|
||||||
|
|
||||||
//if (!isPolling) return;
|
// if (!isPolling) return;
|
||||||
|
|
||||||
String gameType = extractQuotedValue(response.gameType());
|
String gameType = extractQuotedValue(response.gameType());
|
||||||
if (response.clientId() == clientId) {
|
if (response.clientId() == clientId) {
|
||||||
@@ -186,45 +200,30 @@ public final class Server {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
final int myTurn = response.playerToMove().equalsIgnoreCase(response.opponent()) ? 1 : 0;
|
final String startingPlayer = response.playerToMove();
|
||||||
|
final int userStartingTurn = startingPlayer.equalsIgnoreCase(user) ? 0 : 1;
|
||||||
|
final int opponentStartingTurn = 1 - userStartingTurn;
|
||||||
|
|
||||||
final GameInformation information = new GameInformation(type);
|
final GameInformation information = new GameInformation(type);
|
||||||
//information.players[0] = playerInformation;
|
information.players[userStartingTurn].name = user;
|
||||||
information.players[0].name = user;
|
information.players[opponentStartingTurn].name = response.opponent();
|
||||||
information.players[0].isHuman = false;
|
|
||||||
information.players[0].computerDifficulty = 5;
|
|
||||||
information.players[0].computerThinkTime = 1;
|
|
||||||
information.players[1].name = response.opponent();
|
|
||||||
|
|
||||||
/*switch (type){
|
|
||||||
case TICTACTOE ->{
|
|
||||||
players[myTurn] = new ArtificialPlayer<>(new TicTacToeAIR(9), user);
|
|
||||||
}
|
|
||||||
case REVERSI ->{
|
|
||||||
players[myTurn] = new ArtificialPlayer<>(new ReversiAIR(), user);
|
|
||||||
}
|
|
||||||
}*/
|
|
||||||
|
|
||||||
|
Player[] players = new Player[2];
|
||||||
|
|
||||||
|
players[userStartingTurn] = new ArtificialPlayer(new MCTSAI3(1000, 8), user);
|
||||||
|
players[opponentStartingTurn] = new OnlinePlayer(response.opponent());
|
||||||
|
|
||||||
switch (type) {
|
switch (type) {
|
||||||
case TICTACTOE ->{
|
case TICTACTOE -> gameController = new TicTacToeBitController(players);
|
||||||
Player<BitboardTicTacToe>[] players = new Player[2];
|
case REVERSI -> gameController = new ReversiBitController(players);
|
||||||
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.");
|
default -> new ErrorPopup("Unsupported game type.");
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (gameController != null){
|
if (gameController != null) {
|
||||||
|
primary.reEnableButton(); // Re enable subscribe button
|
||||||
gameController.start();
|
gameController.start();
|
||||||
|
isPolling = true; // Fixes server getting stuck
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -244,6 +243,13 @@ public final class Server {
|
|||||||
gameController.gameFinished(response);
|
gameController.gameFinished(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void handleTournamentResult(NetworkEvents.TournamentResultResponse response) {
|
||||||
|
IO.println(response.gameType());
|
||||||
|
IO.println(Arrays.toString(response.names()));
|
||||||
|
IO.println(Arrays.toString(response.scoreTypes()));
|
||||||
|
IO.println(Arrays.toString(response.scores().toArray()));
|
||||||
|
}
|
||||||
|
|
||||||
private void handleReceivedMove(NetworkEvents.GameMoveResponse response) {
|
private void handleReceivedMove(NetworkEvents.GameMoveResponse response) {
|
||||||
if (gameController == null) {
|
if (gameController == null) {
|
||||||
return;
|
return;
|
||||||
@@ -258,7 +264,7 @@ public final class Server {
|
|||||||
String gameType = extractQuotedValue(response.gameType());
|
String gameType = extractQuotedValue(response.gameType());
|
||||||
final String finalGameType = gameType;
|
final String finalGameType = gameType;
|
||||||
var a = new ChallengePopup(challengerName, gameType, (playerInformation) -> {
|
var a = new ChallengePopup(challengerName, gameType, (playerInformation) -> {
|
||||||
final int challengeId = Integer.parseInt(response.challengeId().replaceAll("\\D", ""));
|
final long challengeId = Long.parseLong(response.challengeId().replaceAll("\\D", ""));
|
||||||
new EventFlow().addPostEvent(new NetworkEvents.SendAcceptChallenge(clientId, challengeId)).postEvent();
|
new EventFlow().addPostEvent(new NetworkEvents.SendAcceptChallenge(clientId, challengeId)).postEvent();
|
||||||
isSingleGame.set(true);
|
isSingleGame.set(true);
|
||||||
});
|
});
|
||||||
@@ -276,9 +282,27 @@ public final class Server {
|
|||||||
stopScheduler();
|
stopScheduler();
|
||||||
connectFlow.unsubscribeAll();
|
connectFlow.unsubscribeAll();
|
||||||
|
|
||||||
|
if (nettyGatewayServer != null) {
|
||||||
|
nettyGatewayServer.stop();
|
||||||
|
}
|
||||||
|
|
||||||
WidgetContainer.getCurrentView().transitionPrevious();
|
WidgetContainer.getCurrentView().transitionPrevious();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void closedConnection(NetworkEvents.ClosedConnection e) {
|
||||||
|
new EventFlow().addPostEvent(new NetworkEvents.CloseClient(clientId)).postEvent();
|
||||||
|
isPolling = false;
|
||||||
|
stopScheduler();
|
||||||
|
connectFlow.unsubscribeAll();
|
||||||
|
|
||||||
|
if (nettyGatewayServer != null) {
|
||||||
|
nettyGatewayServer.stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
WidgetContainer.getCurrentView().transitionPrevious();
|
||||||
|
WidgetContainer.add(Pos.CENTER, new ErrorPopup("Server closed connection."));
|
||||||
|
}
|
||||||
|
|
||||||
private void forfeitGame() {
|
private void forfeitGame() {
|
||||||
new EventFlow().addPostEvent(new NetworkEvents.SendForfeit(clientId)).postEvent();
|
new EventFlow().addPostEvent(new NetworkEvents.SendForfeit(clientId)).postEvent();
|
||||||
}
|
}
|
||||||
@@ -325,7 +349,10 @@ public final class Server {
|
|||||||
|
|
||||||
private void gamesListFromServerHandler(NetworkEvents.GamelistResponse event) {
|
private void gamesListFromServerHandler(NetworkEvents.GamelistResponse event) {
|
||||||
gameList.clear();
|
gameList.clear();
|
||||||
gameList.addAll(List.of(event.gamelist()));
|
var gl = new java.util.ArrayList<>(List.of(event.gamelist()));
|
||||||
|
gl.sort(String::compareTo);
|
||||||
|
gameList.addAll(gl);
|
||||||
|
primary.updateGameList(gl);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void populateGameList() {
|
public void populateGameList() {
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ import org.toop.framework.gameFramework.view.GUIEvents;
|
|||||||
|
|
||||||
import java.util.function.Consumer;
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
public abstract class BitGameCanvas<T extends TurnBasedGame<T>> implements GameCanvas<T> {
|
public abstract class BitGameCanvas implements GameCanvas {
|
||||||
protected record Cell(float x, float y, float width, float height) {
|
protected record Cell(float x, float y, float width, float height) {
|
||||||
public boolean isInside(double x, double y) {
|
public boolean isInside(double x, double y) {
|
||||||
return x >= this.x && x <= this.x + width &&
|
return x >= this.x && x <= this.x + width &&
|
||||||
@@ -78,6 +78,7 @@ public abstract class BitGameCanvas<T extends TurnBasedGame<T>> implements GameC
|
|||||||
}
|
}
|
||||||
|
|
||||||
canvas.setOnMouseClicked(event -> {
|
canvas.setOnMouseClicked(event -> {
|
||||||
|
|
||||||
if (event.getButton() != MouseButton.PRIMARY) {
|
if (event.getButton() != MouseButton.PRIMARY) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -93,9 +94,6 @@ public abstract class BitGameCanvas<T extends TurnBasedGame<T>> implements GameC
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
render();
|
render();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package org.toop.app.canvas;
|
|||||||
import javafx.scene.canvas.Canvas;
|
import javafx.scene.canvas.Canvas;
|
||||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||||
|
|
||||||
public interface GameCanvas<T extends TurnBasedGame<T>> extends GameDrawer<T>{
|
public interface GameCanvas {
|
||||||
Canvas getCanvas();
|
Canvas getCanvas();
|
||||||
|
void redraw(TurnBasedGame gameCopy);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +0,0 @@
|
|||||||
package org.toop.app.canvas;
|
|
||||||
|
|
||||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
|
||||||
|
|
||||||
public interface GameDrawer<T extends TurnBasedGame<T>> {
|
|
||||||
void redraw(T gameCopy);
|
|
||||||
}
|
|
||||||
@@ -2,12 +2,13 @@ package org.toop.app.canvas;
|
|||||||
|
|
||||||
import javafx.scene.paint.Color;
|
import javafx.scene.paint.Color;
|
||||||
import org.toop.app.App;
|
import org.toop.app.App;
|
||||||
import org.toop.game.games.reversi.BitboardReversi;
|
import org.toop.framework.game.games.reversi.BitboardReversi;
|
||||||
|
import org.toop.framework.game.players.LocalPlayer;
|
||||||
|
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||||
|
|
||||||
import java.util.Arrays;
|
public class ReversiBitCanvas extends BitGameCanvas {
|
||||||
import java.util.function.Consumer;
|
private TurnBasedGame gameCopy;
|
||||||
|
private int previousCell;
|
||||||
public class ReversiBitCanvas extends BitGameCanvas<BitboardReversi> {
|
|
||||||
public ReversiBitCanvas() {
|
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);
|
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 -> {
|
canvas.setOnMouseMoved(event -> {
|
||||||
@@ -23,6 +24,9 @@ public class ReversiBitCanvas extends BitGameCanvas<BitboardReversi> {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (hovered != null) {
|
||||||
|
checkHoverDots(hovered, cellId);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -33,10 +37,32 @@ public class ReversiBitCanvas extends BitGameCanvas<BitboardReversi> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void redraw(BitboardReversi gameCopy) {
|
public void redraw(TurnBasedGame gameCopy) {
|
||||||
|
this.gameCopy = gameCopy;
|
||||||
clearAll();
|
clearAll();
|
||||||
long[] board = gameCopy.getBoard();
|
long[] board = gameCopy.getBoard();
|
||||||
loopOverBoard(board[0], (i) -> drawDot(Color.WHITE, i));
|
loopOverBoard(board[0], (i) -> drawDot(Color.WHITE, i));
|
||||||
loopOverBoard(board[1], (i) -> drawDot(Color.BLACK, i));
|
loopOverBoard(board[1], (i) -> drawDot(Color.BLACK, i));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void drawLegalDots(TurnBasedGame gameCopy){
|
||||||
|
long legal = gameCopy.getLegalMoves();
|
||||||
|
loopOverBoard(legal, (i) -> drawInnerDot(gameCopy.getCurrentTurn()==0?new Color(1f,1f,1f,0.65f) :new Color(0f,0f,0f,0.65f), i,false));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void checkHoverDots(BitGameCanvas.Cell hovered, int cellId){
|
||||||
|
if (previousCell == cellId){
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
long backflips = ((BitboardReversi)gameCopy).getFlips(1L << previousCell);
|
||||||
|
loopOverBoard(backflips, (i) -> drawInnerDot(gameCopy.getCurrentTurn()==1?Color.WHITE:Color.BLACK, i,true));
|
||||||
|
previousCell = cellId;
|
||||||
|
if (gameCopy.getPlayer(gameCopy.getCurrentTurn()) instanceof LocalPlayer) {
|
||||||
|
long legal = gameCopy.getLegalMoves();
|
||||||
|
if ((legal & (1L << cellId)) != 0) {
|
||||||
|
long flips = ((BitboardReversi) gameCopy).getFlips(1L << cellId);
|
||||||
|
loopOverBoard(flips, (i) -> drawInnerDot(gameCopy.getCurrentTurn() == 0 ? Color.WHITE : Color.BLACK, i, false));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,12 +2,9 @@ package org.toop.app.canvas;
|
|||||||
|
|
||||||
import javafx.scene.paint.Color;
|
import javafx.scene.paint.Color;
|
||||||
import org.toop.app.App;
|
import org.toop.app.App;
|
||||||
import org.toop.game.games.tictactoe.BitboardTicTacToe;
|
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||||
|
|
||||||
import java.util.Arrays;
|
public class TicTacToeBitCanvas extends BitGameCanvas{
|
||||||
import java.util.function.Consumer;
|
|
||||||
|
|
||||||
public class TicTacToeBitCanvas extends BitGameCanvas<BitboardTicTacToe>{
|
|
||||||
public TicTacToeBitCanvas() {
|
public TicTacToeBitCanvas() {
|
||||||
super(
|
super(
|
||||||
Color.GRAY,
|
Color.GRAY,
|
||||||
@@ -22,7 +19,7 @@ public class TicTacToeBitCanvas extends BitGameCanvas<BitboardTicTacToe>{
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void redraw(BitboardTicTacToe gameCopy) {
|
public void redraw(TurnBasedGame gameCopy) {
|
||||||
clearAll();
|
clearAll();
|
||||||
drawMoves(gameCopy.getBoard());
|
drawMoves(gameCopy.getBoard());
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,24 +5,22 @@ import javafx.geometry.Pos;
|
|||||||
import org.apache.logging.log4j.LogManager;
|
import org.apache.logging.log4j.LogManager;
|
||||||
import org.apache.logging.log4j.Logger;
|
import org.apache.logging.log4j.Logger;
|
||||||
import org.toop.app.canvas.GameCanvas;
|
import org.toop.app.canvas.GameCanvas;
|
||||||
|
import org.toop.app.canvas.ReversiBitCanvas;
|
||||||
import org.toop.app.widget.WidgetContainer;
|
import org.toop.app.widget.WidgetContainer;
|
||||||
import org.toop.app.widget.view.GameView;
|
import org.toop.app.widget.view.GameView;
|
||||||
import org.toop.framework.eventbus.EventFlow;
|
import org.toop.framework.eventbus.EventFlow;
|
||||||
import org.toop.framework.eventbus.GlobalEventBus;
|
import org.toop.framework.eventbus.GlobalEventBus;
|
||||||
|
import org.toop.framework.game.games.reversi.BitboardReversi;
|
||||||
import org.toop.framework.gameFramework.controller.GameController;
|
import org.toop.framework.gameFramework.controller.GameController;
|
||||||
import org.toop.framework.gameFramework.model.game.SupportsOnlinePlay;
|
import org.toop.framework.gameFramework.model.game.threadBehaviour.SupportsOnlinePlay;
|
||||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||||
import org.toop.framework.gameFramework.model.game.threadBehaviour.ThreadBehaviour;
|
import org.toop.framework.gameFramework.model.game.threadBehaviour.ThreadBehaviour;
|
||||||
import org.toop.framework.gameFramework.model.player.Player;
|
import org.toop.framework.gameFramework.model.player.Player;
|
||||||
import org.toop.framework.gameFramework.view.GUIEvents;
|
import org.toop.framework.gameFramework.view.GUIEvents;
|
||||||
import org.toop.framework.networking.events.NetworkEvents;
|
import org.toop.framework.networking.connection.events.NetworkEvents;
|
||||||
import org.toop.game.players.LocalPlayer;
|
import org.toop.framework.game.players.LocalPlayer;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
public class GenericGameController implements GameController {
|
||||||
import java.util.List;
|
|
||||||
import java.util.function.Consumer;
|
|
||||||
|
|
||||||
public class GenericGameController<T extends TurnBasedGame<T>> implements GameController {
|
|
||||||
protected final EventFlow eventFlow = new EventFlow();
|
protected final EventFlow eventFlow = new EventFlow();
|
||||||
|
|
||||||
// Logger for logging
|
// Logger for logging
|
||||||
@@ -32,21 +30,23 @@ public class GenericGameController<T extends TurnBasedGame<T>> implements GameCo
|
|||||||
protected final GameView gameView;
|
protected final GameView gameView;
|
||||||
|
|
||||||
// Reference to game canvas
|
// Reference to game canvas
|
||||||
protected final GameCanvas<T> canvas;
|
protected final GameCanvas canvas;
|
||||||
|
|
||||||
protected final TurnBasedGame<T> game; // Reference to game instance
|
protected final TurnBasedGame game; // Reference to game instance
|
||||||
private final ThreadBehaviour gameThreadBehaviour;
|
private final ThreadBehaviour gameThreadBehaviour;
|
||||||
|
|
||||||
// TODO: Change gameType to automatically happen with either dependency injection or something else.
|
// TODO: Change gameType to automatically happen with either dependency injection or something else.
|
||||||
public GenericGameController(GameCanvas<T> canvas, T game, ThreadBehaviour gameThreadBehaviour, String gameType) {
|
public GenericGameController(GameCanvas canvas, TurnBasedGame game, ThreadBehaviour gameThreadBehaviour, String gameType) {
|
||||||
logger.info("Creating: " + this.getClass());
|
logger.info("Creating: {}", this.getClass());
|
||||||
|
|
||||||
this.canvas = canvas;
|
this.canvas = canvas;
|
||||||
this.game = game;
|
this.game = game;
|
||||||
this.gameThreadBehaviour = gameThreadBehaviour;
|
this.gameThreadBehaviour = gameThreadBehaviour;
|
||||||
|
|
||||||
// Tell thread how to send moves
|
// Tell thread how to send moves
|
||||||
this.gameThreadBehaviour.setOnSendMove((id, m) -> GlobalEventBus.postAsync(new NetworkEvents.SendMove(id, (short)translateMove(m))));
|
this.gameThreadBehaviour.setOnSendMove(
|
||||||
|
(id, m) -> GlobalEventBus.get().post(new NetworkEvents.SendMove(id, (short)translateMove(m)))
|
||||||
|
);
|
||||||
|
|
||||||
// Tell thread how to update UI
|
// Tell thread how to update UI
|
||||||
this.gameThreadBehaviour.setOnUpdateUI(() -> Platform.runLater(this::updateUI));
|
this.gameThreadBehaviour.setOnUpdateUI(() -> Platform.runLater(this::updateUI));
|
||||||
@@ -57,26 +57,42 @@ public class GenericGameController<T extends TurnBasedGame<T>> implements GameCo
|
|||||||
WidgetContainer.getCurrentView().transitionNext(gameView, true);
|
WidgetContainer.getCurrentView().transitionNext(gameView, true);
|
||||||
|
|
||||||
// Listen to updates
|
// Listen to updates
|
||||||
|
logger.info("Game controller started listening");
|
||||||
eventFlow
|
eventFlow
|
||||||
.listen(GUIEvents.GameEnded.class, this::onGameFinish, false)
|
.listen(GUIEvents.GameEnded.class, this::onGameFinish, false)
|
||||||
.listen(GUIEvents.PlayerAttemptedMove.class, event -> {if (getCurrentPlayer() instanceof LocalPlayer<T> lp){lp.setMove(event.move());}}, false);
|
.listen(GUIEvents.PlayerAttemptedMove.class, event -> {
|
||||||
|
logger.info("User attempting move {}", event.move());
|
||||||
|
logger.info("Current player's turn {}", getCurrentPlayer().getName());
|
||||||
|
logger.info("First player {}", game.getPlayer(0).getName());
|
||||||
|
logger.info("Username {}", getCurrentPlayer().getName());
|
||||||
|
logger.info("User is class {}, {}", getCurrentPlayer().getClass(), getCurrentPlayer() instanceof LocalPlayer);
|
||||||
|
if (getCurrentPlayer() instanceof LocalPlayer lp) {
|
||||||
|
try {
|
||||||
|
lp.setLastMove(event.move());
|
||||||
|
} catch (Exception e) {
|
||||||
|
IO.println(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void start(){
|
public void start(){
|
||||||
logger.info("Starting GameManager");
|
logger.info("Starting GameManager");
|
||||||
updateUI();
|
updateUI();
|
||||||
gameThreadBehaviour.start();
|
gameThreadBehaviour.start();
|
||||||
|
logger.info("GameManager started");
|
||||||
}
|
}
|
||||||
|
|
||||||
public void stop(){
|
public void stop(){
|
||||||
logger.info("Stopping GameManager");
|
logger.info("Stopping GameManager");
|
||||||
removeListeners();
|
removeListeners();
|
||||||
gameThreadBehaviour.stop();
|
gameThreadBehaviour.stop();
|
||||||
|
logger.info("GameManager stopped");
|
||||||
}
|
}
|
||||||
|
|
||||||
public Player<T> getCurrentPlayer(){
|
public Player getCurrentPlayer(){
|
||||||
return game.getPlayer(getCurrentPlayerIndex());
|
return game.getPlayer(getCurrentPlayerIndex());
|
||||||
};
|
}
|
||||||
|
|
||||||
public int getCurrentPlayerIndex(){
|
public int getCurrentPlayerIndex(){
|
||||||
return game.getCurrentTurn();
|
return game.getCurrentTurn();
|
||||||
@@ -95,14 +111,14 @@ public class GenericGameController<T extends TurnBasedGame<T>> implements GameCo
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void onGameFinish(GUIEvents.GameEnded event){
|
private void onGameFinish(GUIEvents.GameEnded event){
|
||||||
logger.info("Game Finished");
|
logger.info("OnlineTurnBasedGame Finished");
|
||||||
String name = event.winner() == -1 ? null : getPlayer(event.winner()).getName();
|
String name = event.winner() == -1 ? null : getPlayer(event.winner()).getName();
|
||||||
gameView.gameOver(event.winOrTie(), name);
|
gameView.gameOver(event.winOrTie(), name);
|
||||||
stop();
|
stop();
|
||||||
}
|
}
|
||||||
|
|
||||||
public Player<T> getPlayer(int player){
|
public Player getPlayer(int player){
|
||||||
if (player < 0 || player >= 2){ // TODO: Make game turn player count
|
if (player < 0 || player > game.getPlayerCount()-1){ // TODO: Make game turn player count
|
||||||
logger.error("Invalid player index");
|
logger.error("Invalid player index");
|
||||||
throw new IllegalArgumentException("player out of range");
|
throw new IllegalArgumentException("player out of range");
|
||||||
}
|
}
|
||||||
@@ -139,6 +155,18 @@ public class GenericGameController<T extends TurnBasedGame<T>> implements GameCo
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void updateUI() {
|
public void updateUI() {
|
||||||
canvas.redraw(game.deepCopy());
|
TurnBasedGame gameCopy = game.deepCopy();
|
||||||
|
canvas.redraw(gameCopy);
|
||||||
|
String gameType = game.getClass().getSimpleName().replace("Bitboard","");
|
||||||
|
gameView.nextPlayer(true, getCurrentPlayer().getName(), game.getPlayer(1-getCurrentPlayerIndex()).getName(),gameType);
|
||||||
|
if (gameType.equals("Reversi")) {
|
||||||
|
BitboardReversi reversiGame = (BitboardReversi) game;
|
||||||
|
BitboardReversi.Score reversiScore = reversiGame.getScore();
|
||||||
|
gameView.setPlayer1Score(reversiScore.black());
|
||||||
|
gameView.setPlayer2Score(reversiScore.white());
|
||||||
|
if (getCurrentPlayer() instanceof LocalPlayer) {
|
||||||
|
((ReversiBitCanvas)canvas).drawLegalDots(gameCopy);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,20 +3,27 @@ package org.toop.app.gameControllers;
|
|||||||
import org.toop.app.canvas.ReversiBitCanvas;
|
import org.toop.app.canvas.ReversiBitCanvas;
|
||||||
import org.toop.framework.gameFramework.model.game.threadBehaviour.ThreadBehaviour;
|
import org.toop.framework.gameFramework.model.game.threadBehaviour.ThreadBehaviour;
|
||||||
import org.toop.framework.gameFramework.model.player.Player;
|
import org.toop.framework.gameFramework.model.player.Player;
|
||||||
import org.toop.game.gameThreads.LocalThreadBehaviour;
|
import org.toop.framework.game.gameThreads.LocalThreadBehaviour;
|
||||||
import org.toop.game.gameThreads.OnlineThreadBehaviour;
|
import org.toop.framework.game.gameThreads.OnlineThreadBehaviour;
|
||||||
import org.toop.game.games.reversi.BitboardReversi;
|
import org.toop.framework.game.games.reversi.BitboardReversi;
|
||||||
import org.toop.game.players.OnlinePlayer;
|
import org.toop.framework.game.players.OnlinePlayer;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
public class ReversiBitController extends GenericGameController {
|
||||||
|
|
||||||
|
private BitboardReversi game;
|
||||||
|
|
||||||
|
public ReversiBitController(Player[] players) {
|
||||||
|
BitboardReversi game = new BitboardReversi();
|
||||||
|
game.init(players);
|
||||||
|
ThreadBehaviour thread = Arrays.stream(players).anyMatch(e -> e instanceof OnlinePlayer) ?
|
||||||
|
new OnlineThreadBehaviour(game) : new LocalThreadBehaviour(game);
|
||||||
|
|
||||||
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");
|
super(new ReversiBitCanvas(), game, thread, "Reversi");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public BitboardReversi.Score getScore() {
|
||||||
|
return game.getScore();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,21 +3,21 @@ package org.toop.app.gameControllers;
|
|||||||
import org.toop.app.canvas.TicTacToeBitCanvas;
|
import org.toop.app.canvas.TicTacToeBitCanvas;
|
||||||
import org.toop.framework.gameFramework.model.game.threadBehaviour.ThreadBehaviour;
|
import org.toop.framework.gameFramework.model.game.threadBehaviour.ThreadBehaviour;
|
||||||
import org.toop.framework.gameFramework.model.player.Player;
|
import org.toop.framework.gameFramework.model.player.Player;
|
||||||
import org.toop.game.gameThreads.LocalFixedRateThreadBehaviour;
|
import org.toop.framework.game.gameThreads.LocalThreadBehaviour;
|
||||||
import org.toop.game.gameThreads.LocalThreadBehaviour;
|
import org.toop.framework.game.gameThreads.OnlineThreadBehaviour;
|
||||||
import org.toop.game.gameThreads.OnlineThreadBehaviour;
|
import org.toop.framework.game.games.tictactoe.BitboardTicTacToe;
|
||||||
import org.toop.game.games.tictactoe.BitboardTicTacToe;
|
import org.toop.framework.game.players.OnlinePlayer;
|
||||||
import org.toop.game.players.OnlinePlayer;
|
|
||||||
|
|
||||||
public class TicTacToeBitController extends GenericGameController<BitboardTicTacToe> {
|
import java.util.Arrays;
|
||||||
public TicTacToeBitController(Player<BitboardTicTacToe>[] players) {
|
|
||||||
BitboardTicTacToe game = new BitboardTicTacToe(players);
|
public class TicTacToeBitController extends GenericGameController {
|
||||||
ThreadBehaviour thread = new LocalThreadBehaviour<>(game);
|
public TicTacToeBitController(Player[] players) {
|
||||||
for (Player<BitboardTicTacToe> player : players) {
|
BitboardTicTacToe game = new BitboardTicTacToe();
|
||||||
if (player instanceof OnlinePlayer<BitboardTicTacToe>){
|
game.init(players);
|
||||||
thread = new OnlineThreadBehaviour<>(game);
|
|
||||||
}
|
ThreadBehaviour thread = Arrays.stream(players).anyMatch(e -> e instanceof OnlinePlayer) ?
|
||||||
}
|
new OnlineThreadBehaviour(game) : new LocalThreadBehaviour(game);
|
||||||
super(new TicTacToeBitCanvas(), game, thread , "TicTacToe");
|
|
||||||
|
super(new TicTacToeBitCanvas(), game, thread, "TicTacToe");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import org.toop.framework.eventbus.EventFlow;
|
|||||||
import org.toop.framework.resource.resources.ImageAsset;
|
import org.toop.framework.resource.resources.ImageAsset;
|
||||||
import org.toop.local.AppContext;
|
import org.toop.local.AppContext;
|
||||||
|
|
||||||
import java.io.File;
|
|
||||||
import java.util.function.Consumer;
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
import javafx.collections.FXCollections;
|
import javafx.collections.FXCollections;
|
||||||
@@ -65,7 +64,7 @@ public final class Primitive {
|
|||||||
return imageView;
|
return imageView;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Button button(String key, Runnable onAction, boolean localize) {
|
public static Button button(String key, Runnable onAction, boolean localize, boolean disableOnClick) {
|
||||||
var button = new Button();
|
var button = new Button();
|
||||||
button.getStyleClass().add("button");
|
button.getStyleClass().add("button");
|
||||||
|
|
||||||
@@ -76,6 +75,7 @@ public final class Primitive {
|
|||||||
|
|
||||||
if (onAction != null) {
|
if (onAction != null) {
|
||||||
button.setOnAction(_ -> {
|
button.setOnAction(_ -> {
|
||||||
|
if (disableOnClick) button.setDisable(true);
|
||||||
onAction.run();
|
onAction.run();
|
||||||
playButtonSound();
|
playButtonSound();
|
||||||
});
|
});
|
||||||
@@ -84,8 +84,8 @@ public final class Primitive {
|
|||||||
return button;
|
return button;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Button button(String key, Runnable onAction) {
|
public static Button button(String key, Runnable onAction, boolean disableOnClick) {
|
||||||
return button(key, onAction, true);
|
return button(key, onAction, true, disableOnClick);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static TextField input(String promptKey, String text, Consumer<String> onValueChanged, boolean localize) {
|
public static TextField input(String promptKey, String text, Consumer<String> onValueChanged, boolean localize) {
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
package org.toop.app.widget;
|
package org.toop.app.widget;
|
||||||
|
|
||||||
import javafx.collections.ObservableList;
|
|
||||||
import javafx.scene.Node;
|
import javafx.scene.Node;
|
||||||
import org.toop.app.widget.complex.PopupWidget;
|
import org.toop.app.widget.complex.PopupWidget;
|
||||||
import org.toop.app.widget.complex.ViewWidget;
|
import org.toop.app.widget.complex.ViewWidget;
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ public class ConfirmWidget implements Widget {
|
|||||||
|
|
||||||
public void addButton(String key, Runnable onClick) {
|
public void addButton(String key, Runnable onClick) {
|
||||||
Platform.runLater(() -> {
|
Platform.runLater(() -> {
|
||||||
var button = Primitive.button(key, onClick);
|
var button = Primitive.button(key, onClick, false);
|
||||||
buttonsContainer.getChildren().add(button);
|
buttonsContainer.getChildren().add(button);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ package org.toop.app.widget.complex;
|
|||||||
import javafx.application.Platform;
|
import javafx.application.Platform;
|
||||||
import javafx.geometry.Pos;
|
import javafx.geometry.Pos;
|
||||||
import javafx.scene.Node;
|
import javafx.scene.Node;
|
||||||
import javafx.scene.control.Control;
|
|
||||||
import javafx.scene.control.ProgressBar;
|
import javafx.scene.control.ProgressBar;
|
||||||
import javafx.scene.control.ProgressIndicator;
|
import javafx.scene.control.ProgressIndicator;
|
||||||
import javafx.scene.layout.VBox;
|
import javafx.scene.layout.VBox;
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ public class PlayerInfoWidget {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private ToggleWidget buildToggle() {
|
private ToggleWidget buildToggle() {
|
||||||
return new ToggleWidget(
|
return new ToggleWidget(
|
||||||
"computer", "player",
|
"computer", "player",
|
||||||
information.isHuman,
|
information.isHuman,
|
||||||
isHuman -> {
|
isHuman -> {
|
||||||
@@ -37,7 +37,14 @@ public class PlayerInfoWidget {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private Node buildContent() {
|
private Node buildContent() {
|
||||||
|
|
||||||
if (information.isHuman) {
|
if (information.isHuman) {
|
||||||
|
var spacer = Primitive.vbox(
|
||||||
|
makeAIButton(0, 0, "zwartepiet"),
|
||||||
|
makeAIButton(0, 0, "sinterklaas"),
|
||||||
|
makeAIButton(0, 0, "santa")
|
||||||
|
); //todo make a better solution
|
||||||
|
spacer.setVisible(false);
|
||||||
var nameInput = new LabeledInputWidget(
|
var nameInput = new LabeledInputWidget(
|
||||||
"name",
|
"name",
|
||||||
"enter-your-name",
|
"enter-your-name",
|
||||||
@@ -45,7 +52,7 @@ public class PlayerInfoWidget {
|
|||||||
newName -> information.name = newName
|
newName -> information.name = newName
|
||||||
);
|
);
|
||||||
|
|
||||||
return nameInput.getNode();
|
return Primitive.vbox(spacer,nameInput.getNode());
|
||||||
} else {
|
} else {
|
||||||
var AIBox = Primitive.vbox(
|
var AIBox = Primitive.vbox(
|
||||||
makeAIButton(0, 1, "zwartepiet"),
|
makeAIButton(0, 1, "zwartepiet"),
|
||||||
@@ -84,7 +91,7 @@ public class PlayerInfoWidget {
|
|||||||
information.computerDifficulty = depth;
|
information.computerDifficulty = depth;
|
||||||
information.computerThinkTime = thinktime;
|
information.computerThinkTime = thinktime;
|
||||||
this.playerName.setText(getName(name));
|
this.playerName.setText(getName(name));
|
||||||
});
|
}, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
private String getName(String name) {
|
private String getName(String name) {
|
||||||
|
|||||||
@@ -0,0 +1,61 @@
|
|||||||
|
package org.toop.app.widget.complex;
|
||||||
|
|
||||||
|
import javafx.collections.FXCollections;
|
||||||
|
import javafx.collections.ObservableList;
|
||||||
|
import javafx.geometry.Pos;
|
||||||
|
import javafx.scene.control.TableColumn;
|
||||||
|
import javafx.scene.control.TableView;
|
||||||
|
import javafx.scene.control.cell.PropertyValueFactory;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class TableWidget<DATATYPE> extends PopupWidget {
|
||||||
|
private ObservableList<DATATYPE> serverList = FXCollections.observableArrayList();
|
||||||
|
private TableView<DATATYPE> table = new TableView<>();
|
||||||
|
|
||||||
|
|
||||||
|
public TableWidget(String... columns) {
|
||||||
|
var cols = new ArrayList<TableColumn<DATATYPE, String>>();
|
||||||
|
|
||||||
|
for (String column : columns) {
|
||||||
|
TableColumn<DATATYPE, String> col = new TableColumn<>(column.toUpperCase());
|
||||||
|
col.setCellValueFactory(new PropertyValueFactory<>(column));
|
||||||
|
cols.add(col);
|
||||||
|
}
|
||||||
|
|
||||||
|
table.getColumns().addAll(cols);
|
||||||
|
update();
|
||||||
|
onColumnClicked();
|
||||||
|
|
||||||
|
add(Pos.CENTER, table);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void add(DATATYPE serverFound) {
|
||||||
|
serverList.add(serverFound);
|
||||||
|
update();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void add(List<DATATYPE> serverFound) {
|
||||||
|
serverList.addAll(serverFound);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void remove(DATATYPE serverFound) {
|
||||||
|
serverList.remove(serverFound);
|
||||||
|
update();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void onColumnClicked() {
|
||||||
|
table.setOnMouseClicked(event -> {
|
||||||
|
DATATYPE selected = table.getSelectionModel().getSelectedItem();
|
||||||
|
if (selected == null) return;
|
||||||
|
IO.println(selected.toString());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void update() {
|
||||||
|
table.setItems(serverList);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
@@ -32,7 +32,7 @@ public abstract class ViewWidget extends StackWidget {
|
|||||||
|
|
||||||
var backButton = Primitive.button("back", () -> {
|
var backButton = Primitive.button("back", () -> {
|
||||||
view.transitionPrevious();
|
view.transitionPrevious();
|
||||||
});
|
}, false);
|
||||||
|
|
||||||
view.add(Pos.BOTTOM_LEFT, Primitive.vbox(backButton));
|
view.add(Pos.BOTTOM_LEFT, Primitive.vbox(backButton));
|
||||||
}
|
}
|
||||||
@@ -45,7 +45,7 @@ public abstract class ViewWidget extends StackWidget {
|
|||||||
var customButton = Primitive.button(key, () -> {
|
var customButton = Primitive.button(key, () -> {
|
||||||
runnable.run();
|
runnable.run();
|
||||||
view.transitionPrevious();
|
view.transitionPrevious();
|
||||||
});
|
}, false);
|
||||||
|
|
||||||
view.add(Pos.BOTTOM_LEFT, Primitive.vbox(customButton));
|
view.add(Pos.BOTTOM_LEFT, Primitive.vbox(customButton));
|
||||||
}
|
}
|
||||||
@@ -97,7 +97,7 @@ public abstract class ViewWidget extends StackWidget {
|
|||||||
|
|
||||||
var backButton = Primitive.button("back", () -> {
|
var backButton = Primitive.button("back", () -> {
|
||||||
view.transitionPrevious();
|
view.transitionPrevious();
|
||||||
});
|
}, false);
|
||||||
|
|
||||||
view.add(Pos.BOTTOM_LEFT, Primitive.vbox(backButton));
|
view.add(Pos.BOTTOM_LEFT, Primitive.vbox(backButton));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -49,11 +49,11 @@ public class SongDisplay extends VBox implements Widget {
|
|||||||
previousButton.getStyleClass().setAll("previous-button");
|
previousButton.getStyleClass().setAll("previous-button");
|
||||||
|
|
||||||
skipButton.setOnAction( event -> {
|
skipButton.setOnAction( event -> {
|
||||||
GlobalEventBus.post(new AudioEvents.SkipMusic());
|
GlobalEventBus.get().post(new AudioEvents.SkipMusic());
|
||||||
});
|
});
|
||||||
|
|
||||||
pauseButton.setOnAction(event -> {
|
pauseButton.setOnAction(event -> {
|
||||||
GlobalEventBus.post(new AudioEvents.PauseMusic());
|
GlobalEventBus.get().post(new AudioEvents.PauseMusic());
|
||||||
if (pauseButton.getText().equals("⏸")) {
|
if (pauseButton.getText().equals("⏸")) {
|
||||||
pauseButton.setText("▶");
|
pauseButton.setText("▶");
|
||||||
}
|
}
|
||||||
@@ -63,7 +63,7 @@ public class SongDisplay extends VBox implements Widget {
|
|||||||
});
|
});
|
||||||
|
|
||||||
previousButton.setOnAction( event -> {
|
previousButton.setOnAction( event -> {
|
||||||
GlobalEventBus.post(new AudioEvents.PreviousMusic());
|
GlobalEventBus.get().post(new AudioEvents.PreviousMusic());
|
||||||
});
|
});
|
||||||
|
|
||||||
HBox control = new HBox(10, previousButton, pauseButton, skipButton);
|
HBox control = new HBox(10, previousButton, pauseButton, skipButton);
|
||||||
|
|||||||
@@ -37,8 +37,8 @@ public final class ChallengePopup extends PopupWidget {
|
|||||||
var acceptButton = Primitive.button("accept", () -> {
|
var acceptButton = Primitive.button("accept", () -> {
|
||||||
onAccept.accept(playerInformation);
|
onAccept.accept(playerInformation);
|
||||||
this.hide();
|
this.hide();
|
||||||
});
|
}, false);
|
||||||
var denyButton = Primitive.button("deny", () -> hide());
|
var denyButton = Primitive.button("deny", () -> hide(), false);
|
||||||
|
|
||||||
var leftSection = Primitive.vbox(
|
var leftSection = Primitive.vbox(
|
||||||
challengeText,
|
challengeText,
|
||||||
|
|||||||
@@ -1,31 +1,48 @@
|
|||||||
package org.toop.app.widget.popup;
|
package org.toop.app.widget.popup;
|
||||||
|
|
||||||
import javafx.geometry.Pos;
|
import javafx.geometry.Pos;
|
||||||
import org.toop.app.App;
|
import javafx.scene.Node;
|
||||||
import org.toop.app.widget.Primitive;
|
import org.toop.app.widget.Primitive;
|
||||||
|
import org.toop.app.widget.Widget;
|
||||||
import org.toop.app.widget.WidgetContainer;
|
import org.toop.app.widget.WidgetContainer;
|
||||||
import org.toop.app.widget.complex.ConfirmWidget;
|
|
||||||
import org.toop.app.widget.complex.PopupWidget;
|
import org.toop.app.widget.complex.PopupWidget;
|
||||||
|
import org.toop.app.widget.complex.ViewWidget;
|
||||||
|
import org.toop.app.widget.view.GameView;
|
||||||
import org.toop.app.widget.view.OptionsView;
|
import org.toop.app.widget.view.OptionsView;
|
||||||
|
import org.toop.local.AppContext;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
|
||||||
public class EscapePopup extends PopupWidget {
|
public class EscapePopup extends PopupWidget {
|
||||||
public EscapePopup() {
|
public EscapePopup() {
|
||||||
var con = Primitive.button("Continue", this::hide, false); // TODO, localize
|
ViewWidget currentView = WidgetContainer.getCurrentView();
|
||||||
|
ArrayList<Node> nodes = new ArrayList<>();
|
||||||
|
|
||||||
var qui = Primitive.button("quit", () -> {
|
nodes.add(Primitive.button("Continue", this::hide, false, false)); // TODO, localize
|
||||||
hide();
|
|
||||||
WidgetContainer.add(Pos.CENTER, new QuitPopup());
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!(WidgetContainer.getCurrentView().getClass().isAssignableFrom(OptionsView.class))) {
|
if (!(currentView.getClass().isAssignableFrom(OptionsView.class))) {
|
||||||
var opt = Primitive.button("options", () -> {
|
var opt = Primitive.button("options", () -> {
|
||||||
hide();
|
hide();
|
||||||
WidgetContainer.getCurrentView().transitionNext(new OptionsView());
|
WidgetContainer.getCurrentView().transitionNext(new OptionsView());
|
||||||
});
|
}, false);
|
||||||
add(Pos.CENTER, Primitive.vbox(con, opt, qui));
|
nodes.add(opt);
|
||||||
} else {
|
|
||||||
add(Pos.CENTER, Primitive.vbox(con, qui));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (currentView.getClass().isAssignableFrom(GameView.class)) {
|
||||||
|
Widget tut = AppContext.currentTutorial();
|
||||||
|
if (tut != null) {
|
||||||
|
nodes.add(Primitive.button("tutorialstring", () -> {
|
||||||
|
WidgetContainer.getCurrentView().add(Pos.CENTER, tut);
|
||||||
|
}, false));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
nodes.add(Primitive.button("quit", () -> {
|
||||||
|
hide();
|
||||||
|
WidgetContainer.add(Pos.CENTER, new QuitPopup());
|
||||||
|
}, false));
|
||||||
|
|
||||||
|
add(Pos.CENTER, Primitive.vbox(nodes.toArray(new Node[0])));
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,9 +2,9 @@ package org.toop.app.widget.popup;
|
|||||||
|
|
||||||
import org.toop.app.widget.complex.ConfirmWidget;
|
import org.toop.app.widget.complex.ConfirmWidget;
|
||||||
import org.toop.app.widget.complex.PopupWidget;
|
import org.toop.app.widget.complex.PopupWidget;
|
||||||
import org.toop.local.AppContext;
|
|
||||||
|
|
||||||
import javafx.geometry.Pos;
|
import javafx.geometry.Pos;
|
||||||
|
import org.toop.framework.game.games.reversi.BitboardReversi;
|
||||||
|
|
||||||
public final class GameOverPopup extends PopupWidget {
|
public final class GameOverPopup extends PopupWidget {
|
||||||
public GameOverPopup(boolean winOrTie, String winner) {
|
public GameOverPopup(boolean winOrTie, String winner) {
|
||||||
@@ -16,7 +16,6 @@ public final class GameOverPopup extends PopupWidget {
|
|||||||
else{
|
else{
|
||||||
confirmWidget.setMessage("It was a tie!");
|
confirmWidget.setMessage("It was a tie!");
|
||||||
}
|
}
|
||||||
|
|
||||||
confirmWidget.addButton("ok", this::hide);
|
confirmWidget.addButton("ok", this::hide);
|
||||||
|
|
||||||
add(Pos.CENTER, confirmWidget);
|
add(Pos.CENTER, confirmWidget);
|
||||||
|
|||||||
@@ -62,9 +62,9 @@ public final class SendChallengePopup extends PopupWidget {
|
|||||||
var sendButton = Primitive.button(
|
var sendButton = Primitive.button(
|
||||||
"send",
|
"send",
|
||||||
() -> { onSend.accept(playerInformation, gameChoice.getValue()); this.hide(); }
|
() -> { onSend.accept(playerInformation, gameChoice.getValue()); this.hide(); }
|
||||||
);
|
, false);
|
||||||
|
|
||||||
var cancelButton = Primitive.button("cancel", () -> hide());
|
var cancelButton = Primitive.button("cancel", () -> hide(), false);
|
||||||
|
|
||||||
var leftSection = Primitive.vbox(
|
var leftSection = Primitive.vbox(
|
||||||
challengeText,
|
challengeText,
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import javafx.scene.text.Text;
|
|||||||
import org.apache.maven.surefire.shared.lang3.tuple.ImmutablePair;
|
import org.apache.maven.surefire.shared.lang3.tuple.ImmutablePair;
|
||||||
import org.toop.app.widget.Primitive;
|
import org.toop.app.widget.Primitive;
|
||||||
import org.toop.app.widget.Updatable;
|
import org.toop.app.widget.Updatable;
|
||||||
import org.toop.app.widget.WidgetContainer;
|
|
||||||
import org.toop.app.widget.complex.PopupWidget;
|
import org.toop.app.widget.complex.PopupWidget;
|
||||||
|
|
||||||
import org.toop.framework.resource.resources.ImageAsset;
|
import org.toop.framework.resource.resources.ImageAsset;
|
||||||
@@ -48,8 +47,8 @@ public class BaseTutorialWidget extends PopupWidget implements Updatable {
|
|||||||
this.pages = pages;
|
this.pages = pages;
|
||||||
this.nextScreen = nextScreen;
|
this.nextScreen = nextScreen;
|
||||||
|
|
||||||
previousButton = Primitive.button("goback", () -> { update(false); this.hide(); });
|
previousButton = Primitive.button("goback", () -> { update(false); this.hide(); }, false);
|
||||||
nextButton = Primitive.button(">", () -> update(true));
|
nextButton = Primitive.button(">", () -> update(true), false);
|
||||||
|
|
||||||
var w = Primitive.hbox(
|
var w = Primitive.hbox(
|
||||||
previousButton,
|
previousButton,
|
||||||
@@ -59,8 +58,6 @@ public class BaseTutorialWidget extends PopupWidget implements Updatable {
|
|||||||
var x = Primitive.vbox(imagery, tutorialText);
|
var x = Primitive.vbox(imagery, tutorialText);
|
||||||
|
|
||||||
add(Pos.CENTER, Primitive.vbox(x, w));
|
add(Pos.CENTER, Primitive.vbox(x, w));
|
||||||
|
|
||||||
WidgetContainer.add(Pos.CENTER, this);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -10,9 +10,9 @@ public class ShowEnableTutorialWidget extends PopupWidget {
|
|||||||
|
|
||||||
public ShowEnableTutorialWidget(Runnable tutorial, Runnable nextScreen, Runnable appSettingsSetter) {
|
public ShowEnableTutorialWidget(Runnable tutorial, Runnable nextScreen, Runnable appSettingsSetter) {
|
||||||
var a = Primitive.hbox(
|
var a = Primitive.hbox(
|
||||||
Primitive.button("ok", () -> { appSettingsSetter.run(); tutorial.run(); this.hide(); }),
|
Primitive.button("ok", () -> { appSettingsSetter.run(); tutorial.run(); this.hide(); }, false),
|
||||||
Primitive.button("no", () -> { appSettingsSetter.run(); nextScreen.run(); this.hide(); }),
|
Primitive.button("no", () -> { appSettingsSetter.run(); nextScreen.run(); this.hide(); }, false),
|
||||||
Primitive.button("never", () -> { AppSettings.getSettings().setTutorialFlag(false); nextScreen.run(); this.hide(); })
|
Primitive.button("never", () -> { AppSettings.getSettings().setTutorialFlag(false); nextScreen.run(); this.hide(); }, false)
|
||||||
);
|
);
|
||||||
|
|
||||||
var txt = Primitive.text("tutorial");
|
var txt = Primitive.text("tutorial");
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ import javafx.scene.text.Font;
|
|||||||
import org.toop.app.widget.Primitive;
|
import org.toop.app.widget.Primitive;
|
||||||
import org.toop.app.widget.complex.ViewWidget;
|
import org.toop.app.widget.complex.ViewWidget;
|
||||||
import org.toop.app.widget.popup.GameOverPopup;
|
import org.toop.app.widget.popup.GameOverPopup;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.function.Consumer;
|
import java.util.function.Consumer;
|
||||||
import javafx.application.Platform;
|
import javafx.application.Platform;
|
||||||
import javafx.geometry.Pos;
|
import javafx.geometry.Pos;
|
||||||
@@ -24,9 +26,10 @@ public final class GameView extends ViewWidget {
|
|||||||
private final Text player2Header;
|
private final Text player2Header;
|
||||||
private Circle player1Icon;
|
private Circle player1Icon;
|
||||||
private Circle player2Icon;
|
private Circle player2Icon;
|
||||||
|
private final Text player1Score;
|
||||||
|
private final Text player2Score;
|
||||||
private final Button forfeitButton;
|
private final Button forfeitButton;
|
||||||
private final Button exitButton;
|
private final Button exitButton;
|
||||||
private final Button tutorialButton;
|
|
||||||
private final TextField chatInput;
|
private final TextField chatInput;
|
||||||
private final Text keyThingy;
|
private final Text keyThingy;
|
||||||
private boolean hasSet = false;
|
private boolean hasSet = false;
|
||||||
@@ -39,9 +42,11 @@ public final class GameView extends ViewWidget {
|
|||||||
player2Header = Primitive.header("");
|
player2Header = Primitive.header("");
|
||||||
player1Icon = new Circle();
|
player1Icon = new Circle();
|
||||||
player2Icon = new Circle();
|
player2Icon = new Circle();
|
||||||
|
player1Score = Primitive.header("");
|
||||||
|
player2Score = Primitive.header("");
|
||||||
|
|
||||||
if (onForfeit != null) {
|
if (onForfeit != null) {
|
||||||
forfeitButton = Primitive.button("forfeit", () -> onForfeit.run());
|
forfeitButton = Primitive.button("forfeit", () -> onForfeit.run(), false);
|
||||||
} else {
|
} else {
|
||||||
forfeitButton = null;
|
forfeitButton = null;
|
||||||
}
|
}
|
||||||
@@ -49,7 +54,7 @@ public final class GameView extends ViewWidget {
|
|||||||
exitButton = Primitive.button("exit", () -> {
|
exitButton = Primitive.button("exit", () -> {
|
||||||
onExit.run();
|
onExit.run();
|
||||||
transitionPrevious();
|
transitionPrevious();
|
||||||
});
|
}, false);
|
||||||
|
|
||||||
if (onMessage != null) {
|
if (onMessage != null) {
|
||||||
chatInput = Primitive.input("enter-your-message", "", null);
|
chatInput = Primitive.input("enter-your-message", "", null);
|
||||||
@@ -61,15 +66,16 @@ public final class GameView extends ViewWidget {
|
|||||||
chatInput = null;
|
chatInput = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
switch(gameType) {
|
switch (gameType) {
|
||||||
case "TicTacToe":
|
case "TicTacToe":
|
||||||
this.tutorialButton = Primitive.button("tutorialstring", () -> new TicTacToeTutorialWidget(() -> {})); break;
|
AppContext.setCurrentTutorial(new TicTacToeTutorialWidget(() -> {}));
|
||||||
|
break;
|
||||||
case "Reversi":
|
case "Reversi":
|
||||||
this.tutorialButton = Primitive.button("tutorialstring", () -> new ReversiTutorialWidget(() -> {})); break;
|
AppContext.setCurrentTutorial(new ReversiTutorialWidget(() -> {}));
|
||||||
|
break;
|
||||||
case "Connect4":
|
case "Connect4":
|
||||||
this.tutorialButton = Primitive.button("tutorialstring", () -> new Connect4TutorialWidget(() -> {})); break;
|
AppContext.setCurrentTutorial(new Connect4TutorialWidget(() -> {}));
|
||||||
default:
|
break;
|
||||||
this.tutorialButton = null; break;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
setupLayout();
|
setupLayout();
|
||||||
@@ -92,13 +98,9 @@ public final class GameView extends ViewWidget {
|
|||||||
if (chatInput != null) {
|
if (chatInput != null) {
|
||||||
add(Pos.BOTTOM_RIGHT, Primitive.vbox(chatInput));
|
add(Pos.BOTTOM_RIGHT, Primitive.vbox(chatInput));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (tutorialButton != null) {
|
|
||||||
add(Pos.TOP_LEFT, tutorialButton);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void nextPlayer(boolean isMe, String currentPlayer, String currentMove, String nextPlayer, char GameType) {
|
public void nextPlayer(boolean isMe, String currentPlayer, String nextPlayer, String GameType) {
|
||||||
Platform.runLater(() -> {
|
Platform.runLater(() -> {
|
||||||
if (!(hasSet)) {
|
if (!(hasSet)) {
|
||||||
playerHeader.setText(currentPlayer + " vs. " + nextPlayer);
|
playerHeader.setText(currentPlayer + " vs. " + nextPlayer);
|
||||||
@@ -116,8 +118,8 @@ public final class GameView extends ViewWidget {
|
|||||||
new GameOverPopup(iWon, winner).show(Pos.CENTER);
|
new GameOverPopup(iWon, winner).show(Pos.CENTER);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void setPlayerHeaders(boolean isMe, String currentPlayer, String nextPlayer, char GameType) {
|
private void setPlayerHeaders(boolean isMe, String currentPlayer, String nextPlayer, String GameType) {
|
||||||
if (GameType == 'T') {
|
if (Objects.equals(GameType, "TicTacToe")) {
|
||||||
if (isMe) {
|
if (isMe) {
|
||||||
player1Header.setText("X: " + currentPlayer);
|
player1Header.setText("X: " + currentPlayer);
|
||||||
player2Header.setText("O: " + nextPlayer);
|
player2Header.setText("O: " + nextPlayer);
|
||||||
@@ -128,7 +130,7 @@ public final class GameView extends ViewWidget {
|
|||||||
}
|
}
|
||||||
setPlayerInfoTTT();
|
setPlayerInfoTTT();
|
||||||
}
|
}
|
||||||
else if (GameType == 'R') {
|
else if (Objects.equals(GameType, "Reversi")) {
|
||||||
if (isMe) {
|
if (isMe) {
|
||||||
player1Header.setText(currentPlayer);
|
player1Header.setText(currentPlayer);
|
||||||
player2Header.setText(nextPlayer);
|
player2Header.setText(nextPlayer);
|
||||||
@@ -155,14 +157,16 @@ public final class GameView extends ViewWidget {
|
|||||||
private void setPlayerInfoReversi() {
|
private void setPlayerInfoReversi() {
|
||||||
var player1box = Primitive.hbox(
|
var player1box = Primitive.hbox(
|
||||||
player1Icon,
|
player1Icon,
|
||||||
player1Header
|
player1Header,
|
||||||
|
player1Score
|
||||||
);
|
);
|
||||||
|
|
||||||
player1box.getStyleClass().add("hboxspacing");
|
player1box.getStyleClass().add("hboxspacing");
|
||||||
|
|
||||||
var player2box = Primitive.hbox(
|
var player2box = Primitive.hbox(
|
||||||
player2Icon,
|
player2Icon,
|
||||||
player2Header
|
player2Header,
|
||||||
|
player2Score
|
||||||
);
|
);
|
||||||
|
|
||||||
player2box.getStyleClass().add("hboxspacing");
|
player2box.getStyleClass().add("hboxspacing");
|
||||||
@@ -176,8 +180,16 @@ public final class GameView extends ViewWidget {
|
|||||||
|
|
||||||
player1Icon.setRadius(player1Header.fontProperty().map(Font::getSize).getValue());
|
player1Icon.setRadius(player1Header.fontProperty().map(Font::getSize).getValue());
|
||||||
player2Icon.setRadius(player2Header.fontProperty().map(Font::getSize).getValue());
|
player2Icon.setRadius(player2Header.fontProperty().map(Font::getSize).getValue());
|
||||||
player1Icon.setFill(Color.BLACK);
|
player1Icon.setFill(Color.WHITE);
|
||||||
player2Icon.setFill(Color.WHITE);
|
player2Icon.setFill(Color.BLACK);
|
||||||
add(Pos.TOP_RIGHT, playerInfo);
|
add(Pos.TOP_RIGHT, playerInfo);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void setPlayer1Score(int score) {
|
||||||
|
player1Score.setText("(" + Integer.toString(score) + ")");
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPlayer2Score(int score) {
|
||||||
|
player2Score.setText("(" + Integer.toString(score) + ")");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -2,24 +2,21 @@ package org.toop.app.widget.view;
|
|||||||
|
|
||||||
import javafx.application.Platform;
|
import javafx.application.Platform;
|
||||||
import org.toop.app.GameInformation;
|
import org.toop.app.GameInformation;
|
||||||
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.ReversiBitController;
|
||||||
import org.toop.app.gameControllers.TicTacToeBitController;
|
import org.toop.app.gameControllers.TicTacToeBitController;
|
||||||
|
import org.toop.framework.game.players.LocalPlayer;
|
||||||
import org.toop.framework.gameFramework.controller.GameController;
|
import org.toop.framework.gameFramework.controller.GameController;
|
||||||
import org.toop.framework.gameFramework.model.player.Player;
|
import org.toop.framework.gameFramework.model.player.Player;
|
||||||
import org.toop.game.games.reversi.BitboardReversi;
|
import org.toop.framework.game.players.ArtificialPlayer;
|
||||||
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.Primitive;
|
||||||
import org.toop.app.widget.complex.PlayerInfoWidget;
|
import org.toop.app.widget.complex.PlayerInfoWidget;
|
||||||
import org.toop.app.widget.complex.ViewWidget;
|
import org.toop.app.widget.complex.ViewWidget;
|
||||||
import org.toop.app.widget.popup.ErrorPopup;
|
import org.toop.app.widget.popup.ErrorPopup;
|
||||||
import org.toop.app.widget.tutorial.*;
|
import org.toop.app.widget.tutorial.*;
|
||||||
import org.toop.game.players.MiniMaxAI;
|
import org.toop.game.players.ai.MiniMaxAI;
|
||||||
import org.toop.game.players.RandomAI;
|
import org.toop.game.players.ai.mcts.MCTSAI1;
|
||||||
|
import org.toop.game.players.ai.mcts.MCTSAI3;
|
||||||
|
import org.toop.game.players.ai.mcts.MCTSAI4;
|
||||||
import org.toop.local.AppContext;
|
import org.toop.local.AppContext;
|
||||||
|
|
||||||
import javafx.geometry.Pos;
|
import javafx.geometry.Pos;
|
||||||
@@ -27,9 +24,6 @@ import javafx.scene.control.ScrollPane;
|
|||||||
import javafx.scene.layout.VBox;
|
import javafx.scene.layout.VBox;
|
||||||
import org.toop.local.AppSettings;
|
import org.toop.local.AppSettings;
|
||||||
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.Random;
|
|
||||||
|
|
||||||
public class LocalMultiplayerView extends ViewWidget {
|
public class LocalMultiplayerView extends ViewWidget {
|
||||||
private final GameInformation information;
|
private final GameInformation information;
|
||||||
|
|
||||||
@@ -58,14 +52,14 @@ public class LocalMultiplayerView extends ViewWidget {
|
|||||||
switch (information.type) {
|
switch (information.type) {
|
||||||
case TICTACTOE:
|
case TICTACTOE:
|
||||||
if (information.players[0].isHuman) {
|
if (information.players[0].isHuman) {
|
||||||
players[0] = new LocalPlayer<>(information.players[0].name);
|
players[0] = new LocalPlayer(information.players[0].name);
|
||||||
} else {
|
} else {
|
||||||
players[0] = new ArtificialPlayer<>(new RandomAI<BitboardTicTacToe>(), "Random AI");
|
players[0] = new ArtificialPlayer(new MCTSAI1(100), "MCTS AI");
|
||||||
}
|
}
|
||||||
if (information.players[1].isHuman) {
|
if (information.players[1].isHuman) {
|
||||||
players[1] = new LocalPlayer<>(information.players[1].name);
|
players[1] = new LocalPlayer(information.players[1].name);
|
||||||
} else {
|
} else {
|
||||||
players[1] = new ArtificialPlayer<>(new MiniMaxAI<BitboardTicTacToe>(9), "MiniMax AI");
|
players[1] = new ArtificialPlayer(new MiniMaxAI(9), "MiniMax AI");
|
||||||
}
|
}
|
||||||
if (AppSettings.getSettings().getTutorialFlag() && AppSettings.getSettings().getFirstTTT()) {
|
if (AppSettings.getSettings().getTutorialFlag() && AppSettings.getSettings().getFirstTTT()) {
|
||||||
new ShowEnableTutorialWidget(
|
new ShowEnableTutorialWidget(
|
||||||
@@ -86,14 +80,15 @@ public class LocalMultiplayerView extends ViewWidget {
|
|||||||
break;
|
break;
|
||||||
case REVERSI:
|
case REVERSI:
|
||||||
if (information.players[0].isHuman) {
|
if (information.players[0].isHuman) {
|
||||||
players[0] = new LocalPlayer<>(information.players[0].name);
|
players[0] = new LocalPlayer(information.players[0].name);
|
||||||
} else {
|
} else {
|
||||||
players[0] = new ArtificialPlayer<>(new RandomAI<BitboardReversi>(), "Random AI");
|
// players[0] = new ArtificialPlayer(new RandomAI(), "Random AI");
|
||||||
|
players[0] = new ArtificialPlayer(new MCTSAI1(100), "MCTS V1 AI");
|
||||||
}
|
}
|
||||||
if (information.players[1].isHuman) {
|
if (information.players[1].isHuman) {
|
||||||
players[1] = new LocalPlayer<>(information.players[1].name);
|
players[1] = new LocalPlayer(information.players[1].name);
|
||||||
} else {
|
} else {
|
||||||
players[1] = new ArtificialPlayer<>(new MiniMaxAI<BitboardReversi>(6), "MiniMax");
|
players[1] = new ArtificialPlayer(new MCTSAI4(100, 8), "MCTS V4 AI");
|
||||||
}
|
}
|
||||||
if (AppSettings.getSettings().getTutorialFlag() && AppSettings.getSettings().getFirstReversi()) {
|
if (AppSettings.getSettings().getTutorialFlag() && AppSettings.getSettings().getFirstReversi()) {
|
||||||
new ShowEnableTutorialWidget(
|
new ShowEnableTutorialWidget(
|
||||||
@@ -113,7 +108,7 @@ public class LocalMultiplayerView extends ViewWidget {
|
|||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
});
|
}, false);
|
||||||
|
|
||||||
var playerSection = setupPlayerSections();
|
var playerSection = setupPlayerSections();
|
||||||
|
|
||||||
|
|||||||
@@ -10,11 +10,11 @@ public class LocalView extends ViewWidget {
|
|||||||
public LocalView() {
|
public LocalView() {
|
||||||
var ticTacToeButton = Primitive.button("tic-tac-toe", () -> {
|
var ticTacToeButton = Primitive.button("tic-tac-toe", () -> {
|
||||||
transitionNext(new LocalMultiplayerView(GameInformation.Type.TICTACTOE));
|
transitionNext(new LocalMultiplayerView(GameInformation.Type.TICTACTOE));
|
||||||
});
|
}, false);
|
||||||
|
|
||||||
var reversiButton = Primitive.button("reversi", () -> {
|
var reversiButton = Primitive.button("reversi", () -> {
|
||||||
transitionNext(new LocalMultiplayerView(GameInformation.Type.REVERSI));
|
transitionNext(new LocalMultiplayerView(GameInformation.Type.REVERSI));
|
||||||
});
|
}, false);
|
||||||
|
|
||||||
add(Pos.CENTER, Primitive.vbox(
|
add(Pos.CENTER, Primitive.vbox(
|
||||||
ticTacToeButton,
|
ticTacToeButton,
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
package org.toop.app.widget.view;
|
package org.toop.app.widget.view;
|
||||||
|
|
||||||
import org.toop.app.App;
|
|
||||||
import org.toop.app.widget.Primitive;
|
import org.toop.app.widget.Primitive;
|
||||||
import org.toop.app.widget.complex.ViewWidget;
|
import org.toop.app.widget.complex.ViewWidget;
|
||||||
import javafx.geometry.Pos;
|
import javafx.geometry.Pos;
|
||||||
@@ -10,24 +9,24 @@ public class MainView extends ViewWidget {
|
|||||||
public MainView() {
|
public MainView() {
|
||||||
var localButton = Primitive.button("local", () -> {
|
var localButton = Primitive.button("local", () -> {
|
||||||
transitionNext(new LocalView());
|
transitionNext(new LocalView());
|
||||||
});
|
}, false);
|
||||||
|
|
||||||
var onlineButton = Primitive.button("online", () -> {
|
var onlineButton = Primitive.button("online", () -> {
|
||||||
transitionNext(new OnlineView());
|
transitionNext(new OnlineView());
|
||||||
});
|
}, false);
|
||||||
|
|
||||||
var creditsButton = Primitive.button("credits", () -> {
|
var creditsButton = Primitive.button("credits", () -> {
|
||||||
transitionNext(new CreditsView());
|
transitionNext(new CreditsView());
|
||||||
});
|
}, false);
|
||||||
|
|
||||||
var optionsButton = Primitive.button("options", () -> {
|
var optionsButton = Primitive.button("options", () -> {
|
||||||
transitionNext(new OptionsView());
|
transitionNext(new OptionsView());
|
||||||
});
|
}, false);
|
||||||
|
|
||||||
var quitButton = Primitive.button("quit", () -> {
|
var quitButton = Primitive.button("quit", () -> {
|
||||||
var a = new QuitPopup();
|
var a = new QuitPopup();
|
||||||
a.show(Pos.CENTER);
|
a.show(Pos.CENTER);
|
||||||
});
|
}, false);
|
||||||
|
|
||||||
add(Pos.CENTER, Primitive.vbox(
|
add(Pos.CENTER, Primitive.vbox(
|
||||||
localButton,
|
localButton,
|
||||||
|
|||||||
@@ -3,10 +3,17 @@ package org.toop.app.widget.view;
|
|||||||
import org.toop.app.Server;
|
import org.toop.app.Server;
|
||||||
import org.toop.app.widget.Primitive;
|
import org.toop.app.widget.Primitive;
|
||||||
import org.toop.app.widget.complex.LabeledInputWidget;
|
import org.toop.app.widget.complex.LabeledInputWidget;
|
||||||
import org.toop.app.widget.complex.LoadingWidget;
|
|
||||||
import org.toop.app.widget.complex.ViewWidget;
|
import org.toop.app.widget.complex.ViewWidget;
|
||||||
|
|
||||||
import javafx.geometry.Pos;
|
import javafx.geometry.Pos;
|
||||||
|
import org.toop.framework.game.games.reversi.BitboardReversi;
|
||||||
|
import org.toop.framework.game.games.tictactoe.BitboardTicTacToe;
|
||||||
|
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||||
|
import org.toop.framework.networking.server.gateway.NettyGatewayServer;
|
||||||
|
import org.toop.framework.networking.server.stores.TurnBasedGameTypeStore;
|
||||||
|
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
public class OnlineView extends ViewWidget {
|
public class OnlineView extends ViewWidget {
|
||||||
public OnlineView() {
|
public OnlineView() {
|
||||||
@@ -22,7 +29,31 @@ public class OnlineView extends ViewWidget {
|
|||||||
serverPortInput.getValue(),
|
serverPortInput.getValue(),
|
||||||
playerNameInput.getValue()
|
playerNameInput.getValue()
|
||||||
);
|
);
|
||||||
});
|
}, false);
|
||||||
|
|
||||||
|
var localHostButton = Primitive.button("host!", () -> {
|
||||||
|
|
||||||
|
var tps = new TurnBasedGameTypeStore();
|
||||||
|
tps.register("tic-tac-toe", BitboardTicTacToe::new);
|
||||||
|
tps.register("reversi", BitboardReversi::new);
|
||||||
|
|
||||||
|
var a = new NettyGatewayServer(6666, tps, Duration.ofSeconds(10));
|
||||||
|
|
||||||
|
new Thread(() -> {
|
||||||
|
try {
|
||||||
|
a.start();
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}).start();
|
||||||
|
|
||||||
|
new Server(
|
||||||
|
"127.0.0.1",
|
||||||
|
"6666",
|
||||||
|
"host",
|
||||||
|
a
|
||||||
|
);
|
||||||
|
}, false, false);
|
||||||
|
|
||||||
add(Pos.CENTER, Primitive.vbox(
|
add(Pos.CENTER, Primitive.vbox(
|
||||||
serverInformationHeader,
|
serverInformationHeader,
|
||||||
@@ -33,7 +64,9 @@ public class OnlineView extends ViewWidget {
|
|||||||
playerNameInput.getNode(),
|
playerNameInput.getNode(),
|
||||||
Primitive.separator(),
|
Primitive.separator(),
|
||||||
|
|
||||||
connectButton
|
connectButton,
|
||||||
|
Primitive.separator(),
|
||||||
|
localHostButton
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -74,7 +74,7 @@ public class OptionsView extends ViewWidget {
|
|||||||
AppSettings.getSettings().setVolume(val);
|
AppSettings.getSettings().setVolume(val);
|
||||||
new EventFlow()
|
new EventFlow()
|
||||||
.addPostEvent(new AudioEvents.ChangeVolume(val, VolumeControl.MASTERVOLUME))
|
.addPostEvent(new AudioEvents.ChangeVolume(val, VolumeControl.MASTERVOLUME))
|
||||||
.asyncPostEvent();
|
.postEvent();
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -86,7 +86,7 @@ public class OptionsView extends ViewWidget {
|
|||||||
AppSettings.getSettings().setFxVolume(val);
|
AppSettings.getSettings().setFxVolume(val);
|
||||||
new EventFlow()
|
new EventFlow()
|
||||||
.addPostEvent(new AudioEvents.ChangeVolume(val, VolumeControl.FX))
|
.addPostEvent(new AudioEvents.ChangeVolume(val, VolumeControl.FX))
|
||||||
.asyncPostEvent();
|
.postEvent();
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -98,7 +98,7 @@ public class OptionsView extends ViewWidget {
|
|||||||
AppSettings.getSettings().setMusicVolume(val);
|
AppSettings.getSettings().setMusicVolume(val);
|
||||||
new EventFlow()
|
new EventFlow()
|
||||||
.addPostEvent(new AudioEvents.ChangeVolume(val, VolumeControl.MUSIC))
|
.addPostEvent(new AudioEvents.ChangeVolume(val, VolumeControl.MUSIC))
|
||||||
.asyncPostEvent();
|
.postEvent();
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -1,47 +1,89 @@
|
|||||||
package org.toop.app.widget.view;
|
package org.toop.app.widget.view;
|
||||||
|
|
||||||
|
import javafx.collections.FXCollections;
|
||||||
|
import javafx.css.converter.StringConverter;
|
||||||
|
import javafx.scene.control.ComboBox;
|
||||||
import org.toop.app.widget.Primitive;
|
import org.toop.app.widget.Primitive;
|
||||||
import org.toop.app.widget.complex.ViewWidget;
|
import org.toop.app.widget.complex.ViewWidget;
|
||||||
|
|
||||||
|
import java.io.Reader;
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
import java.util.function.Consumer;
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
import javafx.application.Platform;
|
import javafx.application.Platform;
|
||||||
import javafx.geometry.Pos;
|
import javafx.geometry.Pos;
|
||||||
import javafx.scene.control.Button;
|
import javafx.scene.control.Button;
|
||||||
import javafx.scene.control.ListView;
|
import javafx.scene.control.ListView;
|
||||||
|
import org.toop.framework.eventbus.EventFlow;
|
||||||
|
import org.toop.framework.eventbus.GlobalEventBus;
|
||||||
|
import org.toop.framework.networking.connection.events.NetworkEvents;
|
||||||
|
|
||||||
public final class ServerView extends ViewWidget {
|
public final class ServerView extends ViewWidget {
|
||||||
private final String user;
|
private final String user;
|
||||||
private final Consumer<String> onPlayerClicked;
|
private final Consumer<String> onPlayerClicked;
|
||||||
|
private final long clientId;
|
||||||
|
|
||||||
|
private final ComboBox<String> gameListSub;
|
||||||
|
private final ComboBox<String> gameListTour;
|
||||||
private final ListView<Button> listView;
|
private final ListView<Button> listView;
|
||||||
|
private Button subscribeButton;
|
||||||
|
|
||||||
public ServerView(String user, Consumer<String> onPlayerClicked) {
|
public ServerView(String user, Consumer<String> onPlayerClicked, String userName, long clientId) {
|
||||||
this.user = user;
|
this.user = user;
|
||||||
this.onPlayerClicked = onPlayerClicked;
|
this.onPlayerClicked = onPlayerClicked;
|
||||||
|
this.clientId = clientId;
|
||||||
|
|
||||||
|
this.gameListSub = new ComboBox<>();
|
||||||
|
this.gameListTour = new ComboBox<>();
|
||||||
this.listView = new ListView<>();
|
this.listView = new ListView<>();
|
||||||
|
|
||||||
setupLayout();
|
setupLayout(userName);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void setupLayout() {
|
private void setupLayout(String userName) {
|
||||||
var playerHeader = Primitive.header(user, false);
|
var playerHeader = Primitive.header(user, false);
|
||||||
|
|
||||||
var playerListSection = Primitive.vbox(
|
if (userName.equals("host")) { // TODO is fragile
|
||||||
playerHeader,
|
var tournamentButton = Primitive.hbox(
|
||||||
Primitive.separator(),
|
gameListTour,
|
||||||
listView
|
Primitive.button(
|
||||||
);
|
"tournament",
|
||||||
|
() -> GlobalEventBus.get().post(new NetworkEvents.SendCommand(clientId, "tournament", "start", gameListTour.getValue())),
|
||||||
|
false,
|
||||||
|
false
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
add(Pos.CENTER, playerListSection);
|
add(Pos.BOTTOM_CENTER, tournamentButton);
|
||||||
|
} else {
|
||||||
|
subscribeButton = Primitive.button(
|
||||||
|
"subscribe",
|
||||||
|
() -> new EventFlow().addPostEvent(new NetworkEvents.SendSubscribe(clientId, gameListSub.getValue())).postEvent(),
|
||||||
|
false,
|
||||||
|
true
|
||||||
|
); // TODO localize
|
||||||
|
|
||||||
var disconnectButton = Primitive.button("disconnect", () -> {
|
var subscribe = Primitive.hbox(gameListSub, subscribeButton);
|
||||||
transitionPrevious();
|
|
||||||
});
|
|
||||||
|
|
||||||
add(Pos.BOTTOM_LEFT, Primitive.vbox(disconnectButton));
|
var playerListSection = Primitive.vbox(
|
||||||
|
playerHeader,
|
||||||
|
Primitive.separator(),
|
||||||
|
subscribe,
|
||||||
|
listView
|
||||||
|
);
|
||||||
|
|
||||||
|
add(Pos.CENTER, playerListSection);
|
||||||
|
|
||||||
|
var disconnectButton = Primitive.button(
|
||||||
|
"disconnect",
|
||||||
|
this::transitionPrevious,
|
||||||
|
false
|
||||||
|
);
|
||||||
|
|
||||||
|
add(Pos.BOTTOM_LEFT, Primitive.vbox(disconnectButton));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void update(List<String> players) {
|
public void update(List<String> players) {
|
||||||
@@ -49,9 +91,25 @@ public final class ServerView extends ViewWidget {
|
|||||||
listView.getItems().clear();
|
listView.getItems().clear();
|
||||||
|
|
||||||
for (String player : players) {
|
for (String player : players) {
|
||||||
var playerButton = Primitive.button(player, () -> onPlayerClicked.accept(player), false);
|
var playerButton = Primitive.button(player, () -> onPlayerClicked.accept(player), false, false);
|
||||||
listView.getItems().add(playerButton);
|
listView.getItems().add(playerButton);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void updateGameList(List<String> games) {
|
||||||
|
Platform.runLater(() -> {
|
||||||
|
gameListSub.getItems().clear();
|
||||||
|
gameListSub.setItems(FXCollections.observableArrayList(games));
|
||||||
|
gameListSub.getSelectionModel().select(0);
|
||||||
|
|
||||||
|
gameListTour.getItems().clear();
|
||||||
|
gameListTour.setItems(FXCollections.observableArrayList(games));
|
||||||
|
gameListTour.getSelectionModel().select(0);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public void reEnableButton() {
|
||||||
|
subscribeButton.setDisable(false);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
package org.toop.local;
|
package org.toop.local;
|
||||||
|
|
||||||
import java.util.Locale;
|
|
||||||
import java.util.MissingResourceException;
|
import java.util.MissingResourceException;
|
||||||
|
|
||||||
import org.apache.logging.log4j.LogManager;
|
import org.apache.logging.log4j.LogManager;
|
||||||
import org.apache.logging.log4j.Logger;
|
import org.apache.logging.log4j.Logger;
|
||||||
|
import org.toop.app.widget.tutorial.BaseTutorialWidget;
|
||||||
import org.toop.framework.resource.ResourceManager;
|
import org.toop.framework.resource.ResourceManager;
|
||||||
import org.toop.framework.resource.resources.LocalizationAsset;
|
import org.toop.framework.resource.resources.LocalizationAsset;
|
||||||
|
|
||||||
@@ -16,11 +16,13 @@ import javafx.beans.property.ObjectProperty;
|
|||||||
import javafx.beans.property.SimpleObjectProperty;
|
import javafx.beans.property.SimpleObjectProperty;
|
||||||
|
|
||||||
public class AppContext {
|
public class AppContext {
|
||||||
|
private static final Logger logger = LogManager.getLogger(AppContext.class);
|
||||||
|
|
||||||
private static final LocalizationAsset localization = ResourceManager.get("localization");
|
private static final LocalizationAsset localization = ResourceManager.get("localization");
|
||||||
private static Locale locale = Locale.forLanguageTag("en");
|
private static Locale locale = Locale.forLanguageTag("en");
|
||||||
|
|
||||||
private static final ObjectProperty<Locale> localeProperty = new SimpleObjectProperty<>(locale);
|
private static final ObjectProperty<Locale> localeProperty = new SimpleObjectProperty<>(locale);
|
||||||
private static final Logger logger = LogManager.getLogger(AppContext.class);
|
private static BaseTutorialWidget tutorialWidget;
|
||||||
|
|
||||||
public static LocalizationAsset getLocalization() {
|
public static LocalizationAsset getLocalization() {
|
||||||
return localization;
|
return localization;
|
||||||
@@ -73,4 +75,12 @@ public class AppContext {
|
|||||||
public static StringBinding bindToKey(String key) {
|
public static StringBinding bindToKey(String key) {
|
||||||
return bindToKey(key, true);
|
return bindToKey(key, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static void setCurrentTutorial(BaseTutorialWidget tutorial) {
|
||||||
|
AppContext.tutorialWidget = tutorial;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static BaseTutorialWidget currentTutorial() {
|
||||||
|
return AppContext.tutorialWidget;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -36,13 +36,13 @@ public class AppSettings {
|
|||||||
|
|
||||||
new EventFlow()
|
new EventFlow()
|
||||||
.addPostEvent(new AudioEvents.ChangeVolume(settingsData.volume, VolumeControl.MASTERVOLUME))
|
.addPostEvent(new AudioEvents.ChangeVolume(settingsData.volume, VolumeControl.MASTERVOLUME))
|
||||||
.asyncPostEvent();
|
.postEvent();
|
||||||
new EventFlow()
|
new EventFlow()
|
||||||
.addPostEvent(new AudioEvents.ChangeVolume(settingsData.fxVolume, VolumeControl.FX))
|
.addPostEvent(new AudioEvents.ChangeVolume(settingsData.fxVolume, VolumeControl.FX))
|
||||||
.asyncPostEvent();
|
.postEvent();
|
||||||
new EventFlow()
|
new EventFlow()
|
||||||
.addPostEvent(new AudioEvents.ChangeVolume(settingsData.musicVolume, VolumeControl.MUSIC))
|
.addPostEvent(new AudioEvents.ChangeVolume(settingsData.musicVolume, VolumeControl.MUSIC))
|
||||||
.asyncPostEvent();
|
.postEvent();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static SettingsAsset getPath() {
|
public static SettingsAsset getPath() {
|
||||||
|
|||||||
@@ -147,7 +147,6 @@
|
|||||||
<version>2.42.0</version>
|
<version>2.42.0</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
<plugin>
|
||||||
|
|||||||
@@ -5,26 +5,29 @@ import org.toop.framework.audio.interfaces.MusicManager;
|
|||||||
import org.toop.framework.audio.interfaces.SoundEffectManager;
|
import org.toop.framework.audio.interfaces.SoundEffectManager;
|
||||||
import org.toop.framework.audio.interfaces.VolumeManager;
|
import org.toop.framework.audio.interfaces.VolumeManager;
|
||||||
import org.toop.framework.eventbus.EventFlow;
|
import org.toop.framework.eventbus.EventFlow;
|
||||||
import org.toop.framework.eventbus.GlobalEventBus;
|
import org.toop.framework.eventbus.bus.EventBus;
|
||||||
import org.toop.framework.resource.types.AudioResource;
|
import org.toop.framework.resource.types.AudioResource;
|
||||||
|
|
||||||
public class AudioEventListener<T extends AudioResource, K extends AudioResource> {
|
public class AudioEventListener<T extends AudioResource, K extends AudioResource> {
|
||||||
|
private final EventBus eventBus;
|
||||||
private final MusicManager<T> musicManager;
|
private final MusicManager<T> musicManager;
|
||||||
private final SoundEffectManager<K> soundEffectManager;
|
private final SoundEffectManager<K> soundEffectManager;
|
||||||
private final VolumeManager audioVolumeManager;
|
private final VolumeManager audioVolumeManager;
|
||||||
|
|
||||||
public AudioEventListener(
|
public AudioEventListener(
|
||||||
|
EventBus eventBus,
|
||||||
MusicManager<T> musicManager,
|
MusicManager<T> musicManager,
|
||||||
SoundEffectManager<K> soundEffectManager,
|
SoundEffectManager<K> soundEffectManager,
|
||||||
VolumeManager audioVolumeManager
|
VolumeManager audioVolumeManager
|
||||||
) {
|
) {
|
||||||
|
this.eventBus = eventBus;
|
||||||
this.musicManager = musicManager;
|
this.musicManager = musicManager;
|
||||||
this.soundEffectManager = soundEffectManager;
|
this.soundEffectManager = soundEffectManager;
|
||||||
this.audioVolumeManager = audioVolumeManager;
|
this.audioVolumeManager = audioVolumeManager;
|
||||||
}
|
}
|
||||||
|
|
||||||
public AudioEventListener<?, ?> initListeners(String buttonSoundToPlay) {
|
public AudioEventListener<?, ?> initListeners(String buttonSoundToPlay) {
|
||||||
new EventFlow()
|
new EventFlow(eventBus)
|
||||||
.listen(AudioEvents.StopAudioManager.class, this::handleStopMusicManager, false)
|
.listen(AudioEvents.StopAudioManager.class, this::handleStopMusicManager, false)
|
||||||
.listen(AudioEvents.PlayEffect.class, this::handlePlaySound, false)
|
.listen(AudioEvents.PlayEffect.class, this::handlePlaySound, false)
|
||||||
.listen(AudioEvents.SkipMusic.class, this::handleSkipSong, false)
|
.listen(AudioEvents.SkipMusic.class, this::handleSkipSong, false)
|
||||||
@@ -73,7 +76,7 @@ public class AudioEventListener<T extends AudioResource, K extends AudioResource
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void handleGetVolume(AudioEvents.GetVolume event) {
|
private void handleGetVolume(AudioEvents.GetVolume event) {
|
||||||
GlobalEventBus.postAsync(new AudioEvents.GetVolumeResponse(
|
eventBus.post(new AudioEvents.GetVolumeResponse(
|
||||||
audioVolumeManager.getVolume(event.controlType()),
|
audioVolumeManager.getVolume(event.controlType()),
|
||||||
event.identifier()));
|
event.identifier()));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,8 +6,7 @@ import org.toop.framework.audio.events.AudioEvents;
|
|||||||
import org.toop.framework.dispatch.interfaces.Dispatcher;
|
import org.toop.framework.dispatch.interfaces.Dispatcher;
|
||||||
import org.toop.framework.dispatch.JavaFXDispatcher;
|
import org.toop.framework.dispatch.JavaFXDispatcher;
|
||||||
import org.toop.annotations.TestsOnly;
|
import org.toop.annotations.TestsOnly;
|
||||||
import org.toop.framework.eventbus.EventFlow;
|
import org.toop.framework.eventbus.bus.EventBus;
|
||||||
import org.toop.framework.eventbus.GlobalEventBus;
|
|
||||||
import org.toop.framework.resource.types.AudioResource;
|
import org.toop.framework.resource.types.AudioResource;
|
||||||
|
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
@@ -18,6 +17,7 @@ import java.util.concurrent.TimeUnit;
|
|||||||
public class MusicManager<T extends AudioResource> implements org.toop.framework.audio.interfaces.MusicManager<T> {
|
public class MusicManager<T extends AudioResource> implements org.toop.framework.audio.interfaces.MusicManager<T> {
|
||||||
private static final Logger logger = LogManager.getLogger(MusicManager.class);
|
private static final Logger logger = LogManager.getLogger(MusicManager.class);
|
||||||
|
|
||||||
|
private final EventBus eventBus;
|
||||||
private final List<T> backgroundMusic = new ArrayList<>();
|
private final List<T> backgroundMusic = new ArrayList<>();
|
||||||
private final Dispatcher dispatcher;
|
private final Dispatcher dispatcher;
|
||||||
private final List<T> resources;
|
private final List<T> resources;
|
||||||
@@ -27,7 +27,8 @@ public class MusicManager<T extends AudioResource> implements org.toop.framework
|
|||||||
private ScheduledExecutorService scheduler;
|
private ScheduledExecutorService scheduler;
|
||||||
|
|
||||||
|
|
||||||
public MusicManager(List<T> resources, boolean shuffleMusic) {
|
public MusicManager(EventBus eventbus, List<T> resources, boolean shuffleMusic) {
|
||||||
|
this.eventBus = eventbus;
|
||||||
this.dispatcher = new JavaFXDispatcher();
|
this.dispatcher = new JavaFXDispatcher();
|
||||||
this.resources = resources;
|
this.resources = resources;
|
||||||
// Shuffle if wanting to shuffle
|
// Shuffle if wanting to shuffle
|
||||||
@@ -40,7 +41,8 @@ public class MusicManager<T extends AudioResource> implements org.toop.framework
|
|||||||
* {@code @TestsOnly} DO NOT USE
|
* {@code @TestsOnly} DO NOT USE
|
||||||
*/
|
*/
|
||||||
@TestsOnly
|
@TestsOnly
|
||||||
public MusicManager(List<T> resources, Dispatcher dispatcher) {
|
public MusicManager(EventBus eventBus, List<T> resources, Dispatcher dispatcher) {
|
||||||
|
this.eventBus = eventBus;
|
||||||
this.dispatcher = dispatcher;
|
this.dispatcher = dispatcher;
|
||||||
this.resources = new ArrayList<>(resources);
|
this.resources = new ArrayList<>(resources);
|
||||||
backgroundMusic.addAll(resources);
|
backgroundMusic.addAll(resources);
|
||||||
@@ -124,7 +126,7 @@ public class MusicManager<T extends AudioResource> implements org.toop.framework
|
|||||||
Runnable currentMusicTask = new Runnable() {
|
Runnable currentMusicTask = new Runnable() {
|
||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
GlobalEventBus.post(new AudioEvents.PlayingMusic(track.getName(), track.currentPosition(), track.duration()));
|
eventBus.post(new AudioEvents.PlayingMusic(track.getName(), track.currentPosition(), track.duration()));
|
||||||
scheduler.schedule(this, 1, TimeUnit.SECONDS);
|
scheduler.schedule(this, 1, TimeUnit.SECONDS);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -2,18 +2,10 @@ package org.toop.framework.audio;
|
|||||||
|
|
||||||
import org.apache.logging.log4j.LogManager;
|
import org.apache.logging.log4j.LogManager;
|
||||||
import org.apache.logging.log4j.Logger;
|
import org.apache.logging.log4j.Logger;
|
||||||
import org.toop.framework.resource.ResourceManager;
|
|
||||||
import org.toop.framework.resource.ResourceMeta;
|
import org.toop.framework.resource.ResourceMeta;
|
||||||
import org.toop.framework.resource.resources.BaseResource;
|
import org.toop.framework.resource.resources.BaseResource;
|
||||||
import org.toop.framework.resource.resources.MusicAsset;
|
|
||||||
import org.toop.framework.resource.resources.SoundEffectAsset;
|
|
||||||
import org.toop.framework.resource.types.AudioResource;
|
import org.toop.framework.resource.types.AudioResource;
|
||||||
|
|
||||||
import javax.sound.sampled.Clip;
|
|
||||||
import javax.sound.sampled.LineEvent;
|
|
||||||
import javax.sound.sampled.LineUnavailableException;
|
|
||||||
import javax.sound.sampled.UnsupportedAudioFileException;
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
|||||||
@@ -2,8 +2,6 @@ package org.toop.framework.audio.events;
|
|||||||
|
|
||||||
import org.toop.framework.audio.VolumeControl;
|
import org.toop.framework.audio.VolumeControl;
|
||||||
import org.toop.framework.eventbus.events.*;
|
import org.toop.framework.eventbus.events.*;
|
||||||
import org.toop.framework.eventbus.events.ResponseToUniqueEvent;
|
|
||||||
import org.toop.framework.eventbus.events.UniqueEvent;
|
|
||||||
|
|
||||||
public class AudioEvents extends EventsBase {
|
public class AudioEvents extends EventsBase {
|
||||||
/** Stops the audio manager. */
|
/** Stops the audio manager. */
|
||||||
|
|||||||
@@ -1,12 +1,7 @@
|
|||||||
package org.toop.framework.audio.interfaces;
|
package org.toop.framework.audio.interfaces;
|
||||||
|
|
||||||
import org.toop.framework.resource.resources.SoundEffectAsset;
|
|
||||||
import org.toop.framework.resource.types.AudioResource;
|
import org.toop.framework.resource.types.AudioResource;
|
||||||
|
|
||||||
import javax.sound.sampled.LineUnavailableException;
|
|
||||||
import javax.sound.sampled.UnsupportedAudioFileException;
|
|
||||||
import java.io.IOException;
|
|
||||||
|
|
||||||
public interface SoundEffectManager<T extends AudioResource> extends AudioManager<T> {
|
public interface SoundEffectManager<T extends AudioResource> extends AudioManager<T> {
|
||||||
void play(String name, boolean loop);
|
void play(String name, boolean loop);
|
||||||
void stop(String name);
|
void stop(String name);
|
||||||
|
|||||||
@@ -13,10 +13,14 @@ import org.toop.framework.SnowflakeGenerator;
|
|||||||
import org.toop.framework.eventbus.events.EventType;
|
import org.toop.framework.eventbus.events.EventType;
|
||||||
import org.toop.framework.eventbus.events.ResponseToUniqueEvent;
|
import org.toop.framework.eventbus.events.ResponseToUniqueEvent;
|
||||||
import org.toop.framework.eventbus.events.UniqueEvent;
|
import org.toop.framework.eventbus.events.UniqueEvent;
|
||||||
|
import org.toop.framework.eventbus.bus.EventBus;
|
||||||
|
import org.toop.framework.eventbus.subscriber.DefaultNamedSubscriber;
|
||||||
|
import org.toop.framework.eventbus.subscriber.NamedSubscriber;
|
||||||
|
import org.toop.framework.eventbus.subscriber.Subscriber;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* EventFlow is a utility class for creating, posting, and optionally subscribing to events in a
|
* EventFlow is a utility class for creating, posting, and optionally subscribing to events in a
|
||||||
* type-safe and chainable manner. It is designed to work with the {@link GlobalEventBus}.
|
* type-safe and chainable manner. It is designed to work with the {@link EventBus}.
|
||||||
*
|
*
|
||||||
* <p>This class supports automatic UUID assignment for {@link UniqueEvent} events, and
|
* <p>This class supports automatic UUID assignment for {@link UniqueEvent} events, and
|
||||||
* allows filtering subscribers so they only respond to events with a specific UUID. All
|
* allows filtering subscribers so they only respond to events with a specific UUID. All
|
||||||
@@ -31,6 +35,8 @@ public class EventFlow {
|
|||||||
/** Cache of constructor handles for event classes to avoid repeated reflection lookups. */
|
/** Cache of constructor handles for event classes to avoid repeated reflection lookups. */
|
||||||
private static final Map<Class<?>, MethodHandle> CONSTRUCTOR_CACHE = new ConcurrentHashMap<>();
|
private static final Map<Class<?>, MethodHandle> CONSTRUCTOR_CACHE = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
private final EventBus eventBus;
|
||||||
|
|
||||||
/** Automatically assigned UUID for {@link UniqueEvent} events. */
|
/** Automatically assigned UUID for {@link UniqueEvent} events. */
|
||||||
private long eventSnowflake = -1;
|
private long eventSnowflake = -1;
|
||||||
|
|
||||||
@@ -38,13 +44,19 @@ public class EventFlow {
|
|||||||
private EventType event = null;
|
private EventType event = null;
|
||||||
|
|
||||||
/** The listener returned by GlobalEventBus subscription. Used for unsubscription. */
|
/** The listener returned by GlobalEventBus subscription. Used for unsubscription. */
|
||||||
private final List<ListenerHandler<?>> listeners = new ArrayList<>();
|
private final List<NamedSubscriber<?>> listeners = new ArrayList<>();
|
||||||
|
|
||||||
/** Holds the results returned from the subscribed event, if any. */
|
/** Holds the results returned from the subscribed event, if any. */
|
||||||
private Map<String, ?> result = null;
|
private Map<String, ?> result = null;
|
||||||
|
|
||||||
/** Empty constructor (event must be added via {@link #addPostEvent(Class, Object...)}). */
|
/** Empty constructor (event must be added via {@link #addPostEvent(Class, Object...)}). */
|
||||||
public EventFlow() {}
|
public EventFlow(EventBus eventBus) {
|
||||||
|
this.eventBus = eventBus;
|
||||||
|
}
|
||||||
|
|
||||||
|
public EventFlow() {
|
||||||
|
this.eventBus = GlobalEventBus.get();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
@@ -145,21 +157,19 @@ public class EventFlow {
|
|||||||
|
|
||||||
action.accept(eventClass);
|
action.accept(eventClass);
|
||||||
|
|
||||||
if (unsubscribeAfterSuccess) unsubscribe(id);
|
if (unsubscribeAfterSuccess) unsubscribe(String.valueOf(id));
|
||||||
|
|
||||||
this.result = eventClass.result();
|
this.result = eventClass.result();
|
||||||
};
|
};
|
||||||
|
|
||||||
// TODO Remove casts
|
var subscriber = new DefaultNamedSubscriber<>(
|
||||||
var listener = new ListenerHandler<>(
|
|
||||||
id,
|
|
||||||
name,
|
name,
|
||||||
(Class<ResponseToUniqueEvent>) event,
|
event,
|
||||||
(Consumer<ResponseToUniqueEvent>) newAction
|
newAction
|
||||||
);
|
);
|
||||||
|
|
||||||
GlobalEventBus.subscribe(listener);
|
eventBus.subscribe(subscriber);
|
||||||
this.listeners.add(listener);
|
this.listeners.add(subscriber);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -227,7 +237,7 @@ public class EventFlow {
|
|||||||
TT typedEvent = (TT) uuidEvent;
|
TT typedEvent = (TT) uuidEvent;
|
||||||
action.accept(typedEvent);
|
action.accept(typedEvent);
|
||||||
|
|
||||||
if (unsubscribeAfterSuccess) unsubscribe(id);
|
if (unsubscribeAfterSuccess) unsubscribe(String.valueOf(id));
|
||||||
|
|
||||||
this.result = typedEvent.result();
|
this.result = typedEvent.result();
|
||||||
} catch (ClassCastException _) {
|
} catch (ClassCastException _) {
|
||||||
@@ -239,14 +249,13 @@ public class EventFlow {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
var listener = new ListenerHandler<>(
|
var listener = new DefaultNamedSubscriber<>(
|
||||||
id,
|
|
||||||
name,
|
name,
|
||||||
(Class<TT>) action.getClass().getDeclaredMethods()[0].getParameterTypes()[0],
|
(Class<TT>) action.getClass().getDeclaredMethods()[0].getParameterTypes()[0],
|
||||||
newAction
|
newAction
|
||||||
);
|
);
|
||||||
|
|
||||||
GlobalEventBus.subscribe(listener);
|
eventBus.subscribe(listener);
|
||||||
this.listeners.add(listener);
|
this.listeners.add(listener);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
@@ -284,17 +293,16 @@ public class EventFlow {
|
|||||||
Consumer<TT> newAction = eventc -> {
|
Consumer<TT> newAction = eventc -> {
|
||||||
action.accept(eventc);
|
action.accept(eventc);
|
||||||
|
|
||||||
if (unsubscribeAfterSuccess) unsubscribe(id);
|
if (unsubscribeAfterSuccess) unsubscribe(String.valueOf(id));
|
||||||
};
|
};
|
||||||
|
|
||||||
var listener = new ListenerHandler<>(
|
var listener = new DefaultNamedSubscriber<>(
|
||||||
id,
|
|
||||||
name,
|
name,
|
||||||
event,
|
event,
|
||||||
newAction
|
newAction
|
||||||
);
|
);
|
||||||
|
|
||||||
GlobalEventBus.subscribe(listener);
|
eventBus.subscribe(listener);
|
||||||
this.listeners.add(listener);
|
this.listeners.add(listener);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
@@ -362,7 +370,7 @@ public class EventFlow {
|
|||||||
try {
|
try {
|
||||||
TT typedEvent = (TT) nonUuidEvent;
|
TT typedEvent = (TT) nonUuidEvent;
|
||||||
action.accept(typedEvent);
|
action.accept(typedEvent);
|
||||||
if (unsubscribeAfterSuccess) unsubscribe(id);
|
if (unsubscribeAfterSuccess) unsubscribe(String.valueOf(id));
|
||||||
} catch (ClassCastException _) {
|
} catch (ClassCastException _) {
|
||||||
throw new ClassCastException(
|
throw new ClassCastException(
|
||||||
"Cannot cast "
|
"Cannot cast "
|
||||||
@@ -371,14 +379,13 @@ public class EventFlow {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
var listener = new ListenerHandler<>(
|
var listener = new DefaultNamedSubscriber<>(
|
||||||
id,
|
|
||||||
name,
|
name,
|
||||||
eventClass,
|
eventClass,
|
||||||
newAction
|
newAction
|
||||||
);
|
);
|
||||||
|
|
||||||
GlobalEventBus.subscribe(listener);
|
eventBus.subscribe(listener);
|
||||||
this.listeners.add(listener);
|
this.listeners.add(listener);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
@@ -401,15 +408,16 @@ public class EventFlow {
|
|||||||
* Posts the event added through {@link #addPostEvent}.
|
* Posts the event added through {@link #addPostEvent}.
|
||||||
*/
|
*/
|
||||||
public EventFlow postEvent() {
|
public EventFlow postEvent() {
|
||||||
GlobalEventBus.post(this.event);
|
eventBus.post(this.event);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Posts the event added through {@link #addPostEvent} asynchronously.
|
* Posts the event added through {@link #addPostEvent} asynchronously.
|
||||||
|
*
|
||||||
*/
|
*/
|
||||||
public EventFlow asyncPostEvent() {
|
public EventFlow asyncPostEvent() {
|
||||||
GlobalEventBus.postAsync(this.event);
|
GlobalEventBus.get().post(this.event);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -417,28 +425,12 @@ public class EventFlow {
|
|||||||
*
|
*
|
||||||
* Unsubscribe from an event.
|
* Unsubscribe from an event.
|
||||||
*
|
*
|
||||||
* @param listenerObject The listener object to remove and unsubscribe.
|
* @param action The listener object to remove and unsubscribe.
|
||||||
*/
|
*/
|
||||||
public void unsubscribe(Object listenerObject) {
|
public void unsubscribe(Consumer<?> action) {
|
||||||
this.listeners.removeIf(handler -> {
|
this.listeners.removeIf(handler -> {
|
||||||
if (handler.getListener() == listenerObject) {
|
if (handler.handler().equals(action)) {
|
||||||
GlobalEventBus.unsubscribe(handler);
|
eventBus.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 true;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
@@ -452,8 +444,8 @@ public class EventFlow {
|
|||||||
*/
|
*/
|
||||||
public void unsubscribe(String name) {
|
public void unsubscribe(String name) {
|
||||||
this.listeners.removeIf(handler -> {
|
this.listeners.removeIf(handler -> {
|
||||||
if (handler.getName().equals(name)) {
|
if (handler.id().equals(name)) {
|
||||||
GlobalEventBus.unsubscribe(handler);
|
eventBus.unsubscribe(handler);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
@@ -465,7 +457,7 @@ public class EventFlow {
|
|||||||
*/
|
*/
|
||||||
public void unsubscribeAll() {
|
public void unsubscribeAll() {
|
||||||
listeners.removeIf(handler -> {
|
listeners.removeIf(handler -> {
|
||||||
GlobalEventBus.unsubscribe(handler);
|
eventBus.unsubscribe(handler);
|
||||||
return true;
|
return true;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -503,8 +495,8 @@ public class EventFlow {
|
|||||||
*
|
*
|
||||||
* @return Copy of the list of listeners.
|
* @return Copy of the list of listeners.
|
||||||
*/
|
*/
|
||||||
public ListenerHandler[] getListeners() {
|
public Subscriber<?>[] getListeners() {
|
||||||
return listeners.toArray(new ListenerHandler[0]);
|
return listeners.toArray(new Subscriber[0]);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,193 +1,57 @@
|
|||||||
package org.toop.framework.eventbus;
|
package org.toop.framework.eventbus;
|
||||||
|
|
||||||
import com.lmax.disruptor.*;
|
|
||||||
import com.lmax.disruptor.dsl.Disruptor;
|
|
||||||
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.LogManager;
|
||||||
import org.apache.logging.log4j.Logger;
|
import org.toop.framework.eventbus.bus.AsyncEventBus;
|
||||||
|
import org.toop.framework.eventbus.bus.DefaultEventBus;
|
||||||
|
import org.toop.framework.eventbus.bus.DisruptorEventBus;
|
||||||
|
import org.toop.framework.eventbus.bus.EventBus;
|
||||||
import org.toop.framework.eventbus.events.EventType;
|
import org.toop.framework.eventbus.events.EventType;
|
||||||
import org.toop.framework.eventbus.events.UniqueEvent;
|
import org.toop.framework.eventbus.store.DefaultSubscriberStore;
|
||||||
|
import org.toop.framework.eventbus.subscriber.Subscriber;
|
||||||
|
|
||||||
/**
|
import java.util.concurrent.ExecutorService;
|
||||||
* GlobalEventBus backed by the LMAX Disruptor for ultra-low latency, high-throughput event
|
import java.util.concurrent.Executors;
|
||||||
* publishing.
|
|
||||||
*/
|
|
||||||
public final class GlobalEventBus {
|
|
||||||
private static final Logger logger = LogManager.getLogger(GlobalEventBus.class);
|
|
||||||
|
|
||||||
/** Map of event class to type-specific listeners. */
|
public class GlobalEventBus implements AsyncEventBus {
|
||||||
private static final Map<Class<?>, CopyOnWriteArrayList<ListenerHandler<?>>>
|
private static final AsyncEventBus INSTANCE = new DefaultEventBus(
|
||||||
LISTENERS = new ConcurrentHashMap<>();
|
LogManager.getLogger(DefaultEventBus.class),
|
||||||
|
new DefaultSubscriberStore()
|
||||||
|
);
|
||||||
|
|
||||||
/** Map of event class to Snowflake-ID-specific listeners. */
|
|
||||||
private static final Map<
|
|
||||||
Class<?>, ConcurrentHashMap<Long, Consumer<? extends UniqueEvent>>>
|
|
||||||
UUID_LISTENERS = new ConcurrentHashMap<>();
|
|
||||||
|
|
||||||
/** Disruptor ring buffer size (must be power of two). */
|
|
||||||
private static final int RING_BUFFER_SIZE = 1024 * 64;
|
|
||||||
|
|
||||||
/** Disruptor instance. */
|
|
||||||
private static final Disruptor<EventHolder> DISRUPTOR;
|
|
||||||
|
|
||||||
/** Ring buffer used for publishing events. */
|
|
||||||
private static final RingBuffer<EventHolder> RING_BUFFER;
|
|
||||||
|
|
||||||
static {
|
|
||||||
ThreadFactory threadFactory =
|
|
||||||
r -> {
|
|
||||||
Thread t = new Thread(r, "EventBus-Disruptor");
|
|
||||||
t.setDaemon(true);
|
|
||||||
return t;
|
|
||||||
};
|
|
||||||
|
|
||||||
DISRUPTOR =
|
|
||||||
new Disruptor<>(
|
|
||||||
EventHolder::new,
|
|
||||||
RING_BUFFER_SIZE,
|
|
||||||
threadFactory,
|
|
||||||
ProducerType.MULTI,
|
|
||||||
new BusySpinWaitStrategy());
|
|
||||||
|
|
||||||
DISRUPTOR.handleEventsWith(
|
|
||||||
(holder, seq, endOfBatch) -> {
|
|
||||||
if (holder.event != null) {
|
|
||||||
dispatchEvent(holder.event);
|
|
||||||
holder.event = null;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
DISRUPTOR.start();
|
|
||||||
RING_BUFFER = DISRUPTOR.getRingBuffer();
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Prevent instantiation. */
|
|
||||||
private GlobalEventBus() {}
|
private GlobalEventBus() {}
|
||||||
|
|
||||||
/** Wrapper used inside the ring buffer. */
|
public static EventBus get() {
|
||||||
private static class EventHolder {
|
return INSTANCE;
|
||||||
EventType event;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------------------
|
@Override
|
||||||
// Subscription
|
public void subscribe(Subscriber<? extends EventType> listener) {
|
||||||
// ------------------------------------------------------------------------
|
INSTANCE.subscribe(listener);
|
||||||
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
|
@Override
|
||||||
public static <T extends UniqueEvent> void subscribeById(
|
public void unsubscribe(Subscriber<? extends EventType> listener) {
|
||||||
Class<T> eventClass, long eventId, Consumer<T> listener) {
|
INSTANCE.unsubscribe(listener);
|
||||||
UUID_LISTENERS
|
|
||||||
.computeIfAbsent(eventClass, _ -> new ConcurrentHashMap<>())
|
|
||||||
.put(eventId, listener);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void unsubscribe(ListenerHandler<?> listener) {
|
@Override
|
||||||
logger.debug("Unsubscribing from {}: {}", listener.getListenerClass().getSimpleName(), listener.getListener().getClass().getSimpleName());
|
public <T extends EventType> void post(T event) {
|
||||||
LISTENERS.getOrDefault(listener.getListenerClass(), new CopyOnWriteArrayList<>())
|
INSTANCE.post(event);
|
||||||
.remove(listener);
|
|
||||||
LISTENERS.entrySet().removeIf(entry -> entry.getValue().isEmpty());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO
|
@Override
|
||||||
public static <T extends UniqueEvent> void unsubscribeById(
|
public <T extends EventType> void asyncPost(T event) {
|
||||||
Class<T> eventClass, long eventId) {
|
INSTANCE.asyncPost(event);
|
||||||
Map<Long, Consumer<? extends UniqueEvent>> map = UUID_LISTENERS.get(eventClass);
|
|
||||||
if (map != null) map.remove(eventId);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------------------
|
@Override
|
||||||
// Posting
|
public void shutdown() {
|
||||||
// ------------------------------------------------------------------------
|
INSTANCE.shutdown();
|
||||||
public static <T extends EventType> void post(T event) {
|
|
||||||
dispatchEvent(event); // synchronous
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static <T extends EventType> void postAsync(T event) {
|
@Override
|
||||||
long seq = RING_BUFFER.next();
|
public void reset() {
|
||||||
try {
|
INSTANCE.reset();
|
||||||
EventHolder holder = RING_BUFFER.get(seq);
|
|
||||||
holder.event = event;
|
|
||||||
} finally {
|
|
||||||
RING_BUFFER.publish(seq);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@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();
|
|
||||||
|
|
||||||
logger.debug("Triggered event: {}", event.getClass().getSimpleName());
|
|
||||||
|
|
||||||
CopyOnWriteArrayList<ListenerHandler<?>> classListeners = LISTENERS.get(clazz);
|
|
||||||
if (classListeners != null) {
|
|
||||||
for (ListenerHandler<?> listener : classListeners) {
|
|
||||||
try {
|
|
||||||
callListener(listener, event);
|
|
||||||
} catch (Throwable e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
CopyOnWriteArrayList<ListenerHandler<?>> genericListeners = LISTENERS.get(Object.class);
|
|
||||||
if (genericListeners != null) {
|
|
||||||
for (ListenerHandler<?> listener : genericListeners) {
|
|
||||||
try {
|
|
||||||
callListener(listener, event);
|
|
||||||
} catch (Throwable e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (event instanceof UniqueEvent snowflakeEvent) {
|
|
||||||
Map<Long, Consumer<? extends UniqueEvent>> map = UUID_LISTENERS.get(clazz);
|
|
||||||
if (map != null) {
|
|
||||||
Consumer<UniqueEvent> listener =
|
|
||||||
(Consumer<UniqueEvent>) map.remove(snowflakeEvent.getIdentifier());
|
|
||||||
if (listener != null) {
|
|
||||||
try {
|
|
||||||
listener.accept(snowflakeEvent);
|
|
||||||
} catch (Throwable ignored) {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ------------------------------------------------------------------------
|
|
||||||
// Lifecycle
|
|
||||||
// ------------------------------------------------------------------------
|
|
||||||
public static void shutdown() {
|
|
||||||
DISRUPTOR.shutdown();
|
|
||||||
LISTENERS.clear();
|
|
||||||
UUID_LISTENERS.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
public static void reset() {
|
|
||||||
LISTENERS.clear();
|
|
||||||
UUID_LISTENERS.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
public static Map<Class<?>, CopyOnWriteArrayList<ListenerHandler<?>>> getAllListeners() {
|
|
||||||
return LISTENERS;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,48 +0,0 @@
|
|||||||
package org.toop.framework.eventbus;
|
|
||||||
|
|
||||||
import org.toop.framework.SnowflakeGenerator;
|
|
||||||
import org.toop.framework.eventbus.events.EventType;
|
|
||||||
|
|
||||||
import java.util.function.Consumer;
|
|
||||||
|
|
||||||
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(long id, String name, Class<T> clazz, Consumer<T> listener) {
|
|
||||||
this.id = id;
|
|
||||||
this.name = name;
|
|
||||||
this.clazz = clazz;
|
|
||||||
this.listener = listener;
|
|
||||||
}
|
|
||||||
|
|
||||||
public ListenerHandler(String name, Class<T> clazz, Consumer<T> listener) {
|
|
||||||
this(SnowflakeGenerator.nextId(), name, clazz, listener);
|
|
||||||
}
|
|
||||||
|
|
||||||
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,7 @@
|
|||||||
|
package org.toop.framework.eventbus.bus;
|
||||||
|
|
||||||
|
import org.toop.framework.eventbus.events.EventType;
|
||||||
|
|
||||||
|
public interface AsyncEventBus extends EventBus {
|
||||||
|
<T extends EventType> void asyncPost(T event);
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
package org.toop.framework.eventbus.bus;
|
||||||
|
|
||||||
|
import org.apache.logging.log4j.Logger;
|
||||||
|
import org.toop.framework.eventbus.events.EventType;
|
||||||
|
import org.toop.framework.eventbus.store.SubscriberStore;
|
||||||
|
import org.toop.framework.eventbus.subscriber.Subscriber;
|
||||||
|
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
|
public class DefaultEventBus implements AsyncEventBus {
|
||||||
|
private final Logger logger;
|
||||||
|
private final SubscriberStore eventsHolder;
|
||||||
|
|
||||||
|
private final ExecutorService asyncExecutor = Executors.newCachedThreadPool();
|
||||||
|
|
||||||
|
public DefaultEventBus(Logger logger, SubscriberStore eventsHolder) {
|
||||||
|
this.logger = logger;
|
||||||
|
this.eventsHolder = eventsHolder;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void subscribe(Subscriber<? extends EventType> subscriber) {
|
||||||
|
eventsHolder.add(subscriber);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void unsubscribe(Subscriber<? extends EventType> subscriber) {
|
||||||
|
eventsHolder.remove(subscriber);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public <T extends EventType> void post(T event) {
|
||||||
|
Class<T> eventType = (Class<T>) event.getClass();
|
||||||
|
var subs = eventsHolder.get(eventType);
|
||||||
|
if (subs != null) {
|
||||||
|
for (Subscriber<?> subscriber : subs) {
|
||||||
|
Class<T> eventClass = (Class<T>) subscriber.event();
|
||||||
|
Consumer<EventType> action = (Consumer<EventType>) subscriber.handler();
|
||||||
|
|
||||||
|
action.accept(eventClass.cast(event));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public <T extends EventType> void asyncPost(T event) {
|
||||||
|
asyncExecutor.submit(() -> post(event));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void shutdown() {
|
||||||
|
eventsHolder.reset();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void reset() {
|
||||||
|
eventsHolder.reset();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
package org.toop.framework.eventbus.bus;
|
||||||
|
|
||||||
|
import com.lmax.disruptor.BusySpinWaitStrategy;
|
||||||
|
import com.lmax.disruptor.RingBuffer;
|
||||||
|
import com.lmax.disruptor.dsl.Disruptor;
|
||||||
|
import com.lmax.disruptor.dsl.ProducerType;
|
||||||
|
import org.apache.logging.log4j.Logger;
|
||||||
|
import org.toop.framework.eventbus.subscriber.Subscriber;
|
||||||
|
import org.toop.framework.eventbus.events.EventType;
|
||||||
|
import org.toop.framework.eventbus.store.SubscriberStore;
|
||||||
|
|
||||||
|
import java.util.concurrent.ThreadFactory;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
|
public class DisruptorEventBus implements EventBus {
|
||||||
|
/** Wrapper used inside the ring buffer. */
|
||||||
|
private static class EventHolder<T> {
|
||||||
|
T event;
|
||||||
|
}
|
||||||
|
|
||||||
|
private final Logger logger;
|
||||||
|
private final SubscriberStore eventsHolder;
|
||||||
|
|
||||||
|
private final Disruptor<EventHolder<? extends EventType>> disruptor;
|
||||||
|
private final RingBuffer<EventHolder<? extends EventType>> ringBuffer;
|
||||||
|
|
||||||
|
public DisruptorEventBus(Logger logger, SubscriberStore eventsHolder) {
|
||||||
|
this.logger = logger;
|
||||||
|
this.eventsHolder = eventsHolder;
|
||||||
|
|
||||||
|
ThreadFactory threadFactory =
|
||||||
|
r -> {
|
||||||
|
Thread t = new Thread(r, "EventBus-Disruptor");
|
||||||
|
t.setDaemon(true);
|
||||||
|
return t;
|
||||||
|
};
|
||||||
|
|
||||||
|
disruptor = getEventHolderDisruptor(threadFactory);
|
||||||
|
|
||||||
|
disruptor.start();
|
||||||
|
this.ringBuffer = disruptor.getRingBuffer();
|
||||||
|
}
|
||||||
|
|
||||||
|
private Disruptor<EventHolder<? extends EventType>> getEventHolderDisruptor(ThreadFactory threadFactory) {
|
||||||
|
int RING_BUFFER_SIZE = 1024 * 64;
|
||||||
|
Disruptor<EventHolder<? extends EventType>> disruptor = new Disruptor<>(
|
||||||
|
EventHolder::new,
|
||||||
|
RING_BUFFER_SIZE,
|
||||||
|
threadFactory,
|
||||||
|
ProducerType.MULTI,
|
||||||
|
new BusySpinWaitStrategy());
|
||||||
|
|
||||||
|
disruptor.handleEventsWith(
|
||||||
|
(holder, _, _) -> {
|
||||||
|
if (holder.event != null) {
|
||||||
|
dispatchEvent(holder.event);
|
||||||
|
holder.event = null;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return disruptor;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void subscribe(Subscriber<? extends EventType> listener) {
|
||||||
|
eventsHolder.add(listener);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void unsubscribe(Subscriber<? extends EventType> listener) {
|
||||||
|
eventsHolder.remove(listener);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public <T extends EventType> void post(T event) {
|
||||||
|
long seq = ringBuffer.next();
|
||||||
|
try {
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
EventHolder<T> holder = (EventHolder<T>) ringBuffer.get(seq);
|
||||||
|
holder.event = event;
|
||||||
|
} finally {
|
||||||
|
ringBuffer.publish(seq);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void shutdown() {
|
||||||
|
disruptor.shutdown();
|
||||||
|
eventsHolder.reset();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void reset() {
|
||||||
|
eventsHolder.reset();
|
||||||
|
}
|
||||||
|
|
||||||
|
private <T extends EventType> void dispatchEvent(T event) {
|
||||||
|
var classListeners = eventsHolder.get(event.getClass());
|
||||||
|
if (classListeners != null) {
|
||||||
|
for (Subscriber<?> listener : classListeners) {
|
||||||
|
try {
|
||||||
|
callListener(listener, event);
|
||||||
|
} catch (Throwable e) {
|
||||||
|
logger.warn("Exception while handling event: {}", event, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private <T> void callListener(Subscriber<?> subscriber, T event) {
|
||||||
|
Class<T> eventClass = (Class<T>) subscriber.event();
|
||||||
|
Consumer<EventType> action = (Consumer<EventType>) subscriber.handler();
|
||||||
|
|
||||||
|
action.accept((EventType) eventClass.cast(event));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package org.toop.framework.eventbus.bus;
|
||||||
|
|
||||||
|
import org.toop.framework.eventbus.events.EventType;
|
||||||
|
import org.toop.framework.eventbus.subscriber.Subscriber;
|
||||||
|
|
||||||
|
public interface EventBus {
|
||||||
|
void subscribe(Subscriber<? extends EventType> subscriber);
|
||||||
|
void unsubscribe(Subscriber<? extends EventType> subscriber);
|
||||||
|
<T extends EventType> void post(T event);
|
||||||
|
void shutdown();
|
||||||
|
void reset();
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package org.toop.framework.eventbus.store;
|
||||||
|
|
||||||
|
import org.toop.framework.eventbus.events.EventType;
|
||||||
|
import org.toop.framework.eventbus.subscriber.Subscriber;
|
||||||
|
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||||
|
|
||||||
|
public class AsyncSubscriberStore implements SubscriberStore {
|
||||||
|
private final ConcurrentHashMap<Class<? extends EventType>, ConcurrentLinkedQueue<Subscriber<? extends EventType>>> queues = new ConcurrentHashMap<>();
|
||||||
|
private final ConcurrentHashMap<Class<? extends EventType>, Subscriber<? extends EventType>[]> snapshots = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void add(Subscriber<? extends EventType> sub) {
|
||||||
|
queues.computeIfAbsent(sub.event(), _ -> new ConcurrentLinkedQueue<>()).add(sub);
|
||||||
|
rebuildSnapshot(sub.event());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void remove(Subscriber<? extends EventType> sub) {
|
||||||
|
ConcurrentLinkedQueue<Subscriber<?>> queue = queues.get(sub.event());
|
||||||
|
if (queue != null) {
|
||||||
|
queue.remove(sub);
|
||||||
|
rebuildSnapshot(sub.event());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Subscriber<? extends EventType>[] get(Class<? extends EventType> event) {
|
||||||
|
return snapshots.getOrDefault(event, new Subscriber<?>[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void reset() {
|
||||||
|
queues.clear();
|
||||||
|
snapshots.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void rebuildSnapshot(Class<? extends EventType> event) {
|
||||||
|
ConcurrentLinkedQueue<Subscriber<?>> queue = queues.get(event);
|
||||||
|
if (queue != null) {
|
||||||
|
snapshots.put(event, queue.toArray(new Subscriber<?>[0]));
|
||||||
|
} else {
|
||||||
|
snapshots.put(event, new Subscriber<?>[0]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
package org.toop.framework.eventbus.store;
|
||||||
|
|
||||||
|
import org.toop.framework.eventbus.events.EventType;
|
||||||
|
import org.toop.framework.eventbus.subscriber.NamedSubscriber;
|
||||||
|
import org.toop.framework.eventbus.subscriber.Subscriber;
|
||||||
|
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
|
public class DefaultSubscriberStore implements SubscriberStore {
|
||||||
|
|
||||||
|
private static final Subscriber<? extends EventType>[] EMPTY = new Subscriber<?>[0];
|
||||||
|
|
||||||
|
private final ConcurrentHashMap<Class<? extends EventType>, Subscriber<? extends EventType>[]>
|
||||||
|
listeners = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void add(Subscriber<? extends EventType> sub) {
|
||||||
|
listeners.compute(sub.event(), (_, arr) -> {
|
||||||
|
if (arr == null || arr.length == 0) {
|
||||||
|
return new Subscriber<?>[]{sub};
|
||||||
|
}
|
||||||
|
|
||||||
|
int len = arr.length;
|
||||||
|
Subscriber<?>[] newArr = new Subscriber[len + 1];
|
||||||
|
System.arraycopy(arr, 0, newArr, 0, len);
|
||||||
|
newArr[len] = sub;
|
||||||
|
return newArr;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void remove(Subscriber<? extends EventType> sub) {
|
||||||
|
listeners.computeIfPresent(sub.event(), (_, arr) -> {
|
||||||
|
int len = arr.length;
|
||||||
|
|
||||||
|
if (len == 1) {
|
||||||
|
return arr[0].equals(sub) ? null : arr;
|
||||||
|
}
|
||||||
|
|
||||||
|
int keep = 0;
|
||||||
|
for (Subscriber<?> s : arr) {
|
||||||
|
if (!s.equals(sub)) keep++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (keep == len) {
|
||||||
|
return arr;
|
||||||
|
}
|
||||||
|
if (keep == 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
Subscriber<?>[] newArr = new Subscriber[keep];
|
||||||
|
int i = 0;
|
||||||
|
for (Subscriber<?> s : arr) {
|
||||||
|
if (!s.equals(sub)) {
|
||||||
|
newArr[i++] = s;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return newArr;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Subscriber<? extends EventType>[] get(Class<? extends EventType> event) {
|
||||||
|
return listeners.getOrDefault(event, EMPTY);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void reset() {
|
||||||
|
listeners.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package org.toop.framework.eventbus.store;
|
||||||
|
|
||||||
|
import org.toop.framework.eventbus.events.EventType;
|
||||||
|
import org.toop.framework.eventbus.subscriber.Subscriber;
|
||||||
|
|
||||||
|
public interface SubscriberStore {
|
||||||
|
void add(Subscriber<? extends EventType> subscriber);
|
||||||
|
void remove(Subscriber<? extends EventType> subscriber);
|
||||||
|
Subscriber<? extends EventType>[] get(Class<? extends EventType> event);
|
||||||
|
void reset();
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package org.toop.framework.eventbus.store;
|
||||||
|
|
||||||
|
import org.toop.framework.eventbus.events.EventType;
|
||||||
|
import org.toop.framework.eventbus.subscriber.Subscriber;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
|
public class SyncSubscriberStore implements SubscriberStore {
|
||||||
|
private final Map<Class<? extends EventType>, List<Subscriber<? extends EventType>>> LISTENERS = new ConcurrentHashMap<>();
|
||||||
|
private static final Subscriber<? extends EventType>[] EMPTY = new Subscriber<?>[0];
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void add(Subscriber<? extends EventType> sub) {
|
||||||
|
LISTENERS.computeIfAbsent(sub.event(), _ -> new ArrayList<>()).add(sub);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void remove(Subscriber<? extends EventType> sub) {
|
||||||
|
LISTENERS.getOrDefault(sub.event(), new ArrayList<>()).remove(sub);
|
||||||
|
LISTENERS.entrySet().removeIf(entry -> entry.getValue().isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Subscriber<? extends EventType>[] get(Class<? extends EventType> event) {
|
||||||
|
List<Subscriber<? extends EventType>> list = LISTENERS.get(event);
|
||||||
|
if (list == null || list.isEmpty()) return EMPTY;
|
||||||
|
return list.toArray(EMPTY);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void reset() {
|
||||||
|
LISTENERS.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package org.toop.framework.eventbus.subscriber;
|
||||||
|
|
||||||
|
import org.toop.framework.eventbus.events.EventType;
|
||||||
|
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
|
public record DefaultNamedSubscriber<K extends EventType>(String id, Class<K> event, Consumer<K> handler)
|
||||||
|
implements NamedSubscriber<K> {}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package org.toop.framework.eventbus.subscriber;
|
||||||
|
|
||||||
|
import org.toop.framework.eventbus.events.EventType;
|
||||||
|
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
|
public record DefaultSubscriber<K extends EventType>(Class<K> event, Consumer<K> handler) implements Subscriber<K> {}
|
||||||
|
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
package org.toop.framework.eventbus.subscriber;
|
||||||
|
|
||||||
|
public interface HasId<ID> {
|
||||||
|
ID id();
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
package org.toop.framework.eventbus.subscriber;
|
||||||
|
|
||||||
|
import org.toop.framework.eventbus.events.EventType;
|
||||||
|
|
||||||
|
public interface IdSubscriber<K extends EventType> extends Subscriber<K>, HasId<Long> {}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package org.toop.framework.eventbus.subscriber;
|
||||||
|
|
||||||
|
import org.toop.framework.eventbus.events.EventType;
|
||||||
|
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
|
public record LongIdSubscriber<K extends EventType>(Long id, Class<K> event, Consumer<K> handler)
|
||||||
|
implements IdSubscriber<K> {}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
package org.toop.framework.eventbus.subscriber;
|
||||||
|
|
||||||
|
import org.toop.framework.eventbus.events.EventType;
|
||||||
|
|
||||||
|
public interface NamedSubscriber<K extends EventType> extends Subscriber<K>, HasId<String> {}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package org.toop.framework.eventbus.subscriber;
|
||||||
|
|
||||||
|
import org.toop.framework.eventbus.events.EventType;
|
||||||
|
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
|
public interface Subscriber<K extends EventType> {
|
||||||
|
Class<K> event();
|
||||||
|
Consumer<K> handler();
|
||||||
|
}
|
||||||
@@ -1,40 +1,57 @@
|
|||||||
package org.toop.game;
|
package org.toop.framework.game;
|
||||||
|
|
||||||
|
import org.toop.framework.gameFramework.GameState;
|
||||||
|
import org.toop.framework.gameFramework.model.game.PlayResult;
|
||||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||||
import org.toop.framework.gameFramework.model.player.Player;
|
import org.toop.framework.gameFramework.model.player.Player;
|
||||||
|
|
||||||
import java.util.Arrays;
|
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
|
// 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> {
|
public abstract class BitboardGame implements TurnBasedGame {
|
||||||
private final int columnSize;
|
private final int columnSize;
|
||||||
private final int rowSize;
|
private final int rowSize;
|
||||||
|
|
||||||
private Player<T>[] players;
|
protected PlayResult state;
|
||||||
|
|
||||||
|
private Player[] players;
|
||||||
|
|
||||||
// long is 64 bits. Every game has a limit of 64 cells maximum.
|
// long is 64 bits. Every game has a limit of 64 cells maximum.
|
||||||
private final long[] playerBitboard;
|
protected final long[] playerBitboard;
|
||||||
private int currentTurn = 0;
|
protected int currentTurn = 0;
|
||||||
|
private final int playerCount;
|
||||||
|
|
||||||
public BitboardGame(int columnSize, int rowSize, int playerCount, Player<T>[] players) {
|
public BitboardGame(int columnSize, int rowSize, int playerCount) {
|
||||||
this.columnSize = columnSize;
|
this.columnSize = columnSize;
|
||||||
this.rowSize = rowSize;
|
this.rowSize = rowSize;
|
||||||
this.players = players;
|
this.playerCount = playerCount;
|
||||||
|
this.state = new PlayResult(GameState.NORMAL, -1);
|
||||||
|
|
||||||
this.playerBitboard = new long[playerCount];
|
this.playerBitboard = new long[playerCount];
|
||||||
|
|
||||||
Arrays.fill(playerBitboard, 0L);
|
Arrays.fill(playerBitboard, 0L);
|
||||||
}
|
}
|
||||||
|
|
||||||
public BitboardGame(BitboardGame<T> other) {
|
@Override
|
||||||
|
public void init(Player[] players) {
|
||||||
|
this.players = players;
|
||||||
|
|
||||||
|
Arrays.fill(playerBitboard, 0L);
|
||||||
|
}
|
||||||
|
|
||||||
|
public BitboardGame(BitboardGame other) {
|
||||||
this.columnSize = other.columnSize;
|
this.columnSize = other.columnSize;
|
||||||
this.rowSize = other.rowSize;
|
this.rowSize = other.rowSize;
|
||||||
|
this.playerCount = other.playerCount;
|
||||||
|
this.state = other.state;
|
||||||
|
|
||||||
this.playerBitboard = other.playerBitboard.clone();
|
this.playerBitboard = other.playerBitboard.clone();
|
||||||
this.currentTurn = other.currentTurn;
|
this.currentTurn = other.currentTurn;
|
||||||
this.players = Arrays.stream(other.players)
|
this.players = other.players;
|
||||||
.map(Player<T>::deepCopy)
|
// TODO: Players are not deep copied, which is bad. I don't know why but deepcopying breaks it. Fix it
|
||||||
.toArray(Player[]::new);
|
//this.players = Arrays.stream(other.players)
|
||||||
|
// .map(Player::deepCopy)
|
||||||
|
// .toArray(Player[]::new);
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getColumnSize() {
|
public int getColumnSize() {
|
||||||
@@ -57,11 +74,13 @@ public abstract class BitboardGame<T extends BitboardGame<T>> implements TurnBas
|
|||||||
return playerBitboard.length;
|
return playerBitboard.length;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public int getAmountOfTurns() { return currentTurn; }
|
||||||
|
|
||||||
public int getCurrentTurn() {
|
public int getCurrentTurn() {
|
||||||
return getCurrentPlayerIndex();
|
return getCurrentPlayerIndex();
|
||||||
}
|
}
|
||||||
|
|
||||||
public Player<T> getPlayer(int index) {return players[index];}
|
public Player getPlayer(int index) {return players[index];}
|
||||||
|
|
||||||
public int getCurrentPlayerIndex() {
|
public int getCurrentPlayerIndex() {
|
||||||
return currentTurn % playerBitboard.length;
|
return currentTurn % playerBitboard.length;
|
||||||
@@ -71,13 +90,21 @@ public abstract class BitboardGame<T extends BitboardGame<T>> implements TurnBas
|
|||||||
return (currentTurn + 1) % playerBitboard.length;
|
return (currentTurn + 1) % playerBitboard.length;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Player<T> getCurrentPlayer(){
|
public Player getCurrentPlayer(){
|
||||||
return players[getCurrentPlayerIndex()];
|
return players[getCurrentPlayerIndex()];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PlayResult getState() {
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isTerminal() {
|
||||||
|
return state.state() == GameState.WIN || state.state() == GameState.DRAW;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public long[] getBoard() {return this.playerBitboard;}
|
public long[] getBoard() {return this.playerBitboard;}
|
||||||
|
|
||||||
public void nextTurn() {
|
public void nextTurn() {
|
||||||
@@ -1,3 +1,3 @@
|
|||||||
package org.toop.game;
|
package org.toop.framework.game;
|
||||||
// TODO: Remove this, only used in ReversiCanvas. Needs to not
|
// TODO: Remove this, only used in ReversiCanvas. Needs to not
|
||||||
public record Move(int position, char value) {}
|
public record Move(int position, char value) {}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package org.toop.game.gameThreads;
|
package org.toop.framework.game.gameThreads;
|
||||||
|
|
||||||
import org.toop.framework.eventbus.EventFlow;
|
import org.toop.framework.eventbus.EventFlow;
|
||||||
import org.toop.framework.gameFramework.GameState;
|
import org.toop.framework.gameFramework.GameState;
|
||||||
@@ -16,7 +16,7 @@ import java.util.function.Consumer;
|
|||||||
* Runs a separate thread that executes game turns at a fixed frequency (default 60 updates/sec),
|
* 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.
|
* applying player moves, updating the game state, and dispatching UI events.
|
||||||
*/
|
*/
|
||||||
public class LocalFixedRateThreadBehaviour<T extends TurnBasedGame<T>> extends AbstractThreadBehaviour<T> implements Runnable {
|
public class LocalFixedRateThreadBehaviour extends AbstractThreadBehaviour implements Runnable {
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -24,7 +24,7 @@ public class LocalFixedRateThreadBehaviour<T extends TurnBasedGame<T>> extends A
|
|||||||
*
|
*
|
||||||
* @param game the game instance
|
* @param game the game instance
|
||||||
*/
|
*/
|
||||||
public LocalFixedRateThreadBehaviour(T game) {
|
public LocalFixedRateThreadBehaviour(TurnBasedGame game) {
|
||||||
super(game);
|
super(game);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -59,7 +59,7 @@ public class LocalFixedRateThreadBehaviour<T extends TurnBasedGame<T>> extends A
|
|||||||
if (now >= nextUpdate) {
|
if (now >= nextUpdate) {
|
||||||
nextUpdate += UPDATE_INTERVAL;
|
nextUpdate += UPDATE_INTERVAL;
|
||||||
|
|
||||||
Player<T> currentPlayer = game.getPlayer(game.getCurrentTurn());
|
Player currentPlayer = game.getPlayer(game.getCurrentTurn());
|
||||||
long move = currentPlayer.getMove(game.deepCopy());
|
long move = currentPlayer.getMove(game.deepCopy());
|
||||||
PlayResult result = game.play(move);
|
PlayResult result = game.play(move);
|
||||||
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package org.toop.game.gameThreads;
|
package org.toop.framework.game.gameThreads;
|
||||||
|
|
||||||
import org.toop.framework.eventbus.EventFlow;
|
import org.toop.framework.eventbus.EventFlow;
|
||||||
import org.toop.framework.gameFramework.model.game.threadBehaviour.AbstractThreadBehaviour;
|
import org.toop.framework.gameFramework.model.game.threadBehaviour.AbstractThreadBehaviour;
|
||||||
@@ -16,14 +16,14 @@ import java.util.function.Consumer;
|
|||||||
* Repeatedly gets the current player's move, applies it to the game,
|
* 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.
|
* 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 {
|
public class LocalThreadBehaviour extends AbstractThreadBehaviour implements Runnable {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a new behaviour for a local turn-based game.
|
* Creates a new behaviour for a local turn-based game.
|
||||||
*
|
*
|
||||||
* @param game the game instance
|
* @param game the game instance
|
||||||
*/
|
*/
|
||||||
public LocalThreadBehaviour(T game) {
|
public LocalThreadBehaviour(TurnBasedGame game) {
|
||||||
super(game);
|
super(game);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -48,7 +48,7 @@ public class LocalThreadBehaviour<T extends TurnBasedGame<T>> extends AbstractTh
|
|||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
while (isRunning.get()) {
|
while (isRunning.get()) {
|
||||||
Player<T> currentPlayer = game.getPlayer(game.getCurrentTurn());
|
Player currentPlayer = game.getPlayer(game.getCurrentTurn());
|
||||||
long move = currentPlayer.getMove(game.deepCopy());
|
long move = currentPlayer.getMove(game.deepCopy());
|
||||||
PlayResult result = game.play(move);
|
PlayResult result = game.play(move);
|
||||||
|
|
||||||
@@ -1,12 +1,15 @@
|
|||||||
package org.toop.game.gameThreads;
|
package org.toop.framework.game.gameThreads;
|
||||||
|
|
||||||
import org.toop.framework.eventbus.EventFlow;
|
import org.toop.framework.eventbus.EventFlow;
|
||||||
import org.toop.framework.gameFramework.model.game.threadBehaviour.AbstractThreadBehaviour;
|
import org.toop.framework.gameFramework.model.game.threadBehaviour.AbstractThreadBehaviour;
|
||||||
import org.toop.framework.gameFramework.view.GUIEvents;
|
import org.toop.framework.gameFramework.view.GUIEvents;
|
||||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||||
import org.toop.framework.gameFramework.model.game.SupportsOnlinePlay;
|
import org.toop.framework.gameFramework.model.game.threadBehaviour.SupportsOnlinePlay;
|
||||||
import org.toop.framework.gameFramework.model.player.Player;
|
import org.toop.framework.gameFramework.model.player.Player;
|
||||||
import org.toop.game.players.OnlinePlayer;
|
import org.toop.framework.game.players.OnlinePlayer;
|
||||||
|
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handles online multiplayer game logic.
|
* Handles online multiplayer game logic.
|
||||||
@@ -14,17 +17,20 @@ import org.toop.game.players.OnlinePlayer;
|
|||||||
* Reacts to server events, sending moves and updating the game state
|
* Reacts to server events, sending moves and updating the game state
|
||||||
* for the local player while receiving moves from other players.
|
* for the local player while receiving moves from other players.
|
||||||
*/
|
*/
|
||||||
public class OnlineThreadBehaviour<T extends TurnBasedGame<T>> extends AbstractThreadBehaviour<T> implements SupportsOnlinePlay {
|
public class OnlineThreadBehaviour extends AbstractThreadBehaviour implements SupportsOnlinePlay {
|
||||||
|
|
||||||
|
private ExecutorService moveExecutor = Executors.newSingleThreadExecutor();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates behaviour and sets the first local player
|
* Creates behaviour and sets the first local player
|
||||||
* (non-online player) from the given array.
|
* (non-online player) from the given array.
|
||||||
*/
|
*/
|
||||||
public OnlineThreadBehaviour(T game) {
|
public OnlineThreadBehaviour(TurnBasedGame game) {
|
||||||
super(game);
|
super(game);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Finds the first non-online player in the array. */
|
/** Finds the first non-online player in the array. */
|
||||||
private int getFirstNotOnlinePlayer(Player<T>[] players) {
|
private int getFirstNotOnlinePlayer(Player[] players) {
|
||||||
for (int i = 0; i < players.length; i++) {
|
for (int i = 0; i < players.length; i++) {
|
||||||
if (!(players[i] instanceof OnlinePlayer)) {
|
if (!(players[i] instanceof OnlinePlayer)) {
|
||||||
return i;
|
return i;
|
||||||
@@ -51,8 +57,30 @@ public class OnlineThreadBehaviour<T extends TurnBasedGame<T>> extends AbstractT
|
|||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public void onYourTurn(long clientId) {
|
public void onYourTurn(long clientId) {
|
||||||
if (!isRunning.get()) return;
|
logger.info("Yourturn");
|
||||||
long move = game.getPlayer(game.getCurrentTurn()).getMove(game.deepCopy());
|
if (!isRunning.get()) {
|
||||||
|
logger.warn("Game is not running!");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
TurnBasedGame gameCopy = game.deepCopy();
|
||||||
|
if (gameCopy == null) {
|
||||||
|
logger.error("Could not deep copy game");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
logger.info("Successfully collected game copy");
|
||||||
|
|
||||||
|
Player player = gameCopy.getPlayer(game.getCurrentTurn());
|
||||||
|
if (player == null) {
|
||||||
|
logger.error("Could not find current turn's player");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
logger.info("Successfully collected current turn's player");
|
||||||
|
|
||||||
|
long move = player.getMove(gameCopy);
|
||||||
|
logger.info("Move set: {}", move);
|
||||||
|
logger.info("Completed onYourTurn");
|
||||||
|
|
||||||
sendMove(clientId, move);
|
sendMove(clientId, move);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
package org.toop.game.gameThreads;
|
package org.toop.framework.game.gameThreads;
|
||||||
|
|
||||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
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
|
* Online thread behaviour that adds a fixed delay before processing
|
||||||
@@ -10,14 +9,14 @@ import org.toop.framework.networking.events.NetworkEvents;
|
|||||||
* This is identical to {@link OnlineThreadBehaviour}, but inserts a
|
* This is identical to {@link OnlineThreadBehaviour}, but inserts a
|
||||||
* short sleep before delegating to the base implementation.
|
* short sleep before delegating to the base implementation.
|
||||||
*/
|
*/
|
||||||
public class OnlineWithSleepThreadBehaviour<T extends TurnBasedGame<T>> extends OnlineThreadBehaviour<T> {
|
public class OnlineWithSleepThreadBehaviour extends OnlineThreadBehaviour {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates the behaviour and forwards the players to the base class.
|
* Creates the behaviour and forwards the players to the base class.
|
||||||
*
|
*
|
||||||
* @param game the online-capable turn-based game
|
* @param game the online-capable turn-based game
|
||||||
*/
|
*/
|
||||||
public OnlineWithSleepThreadBehaviour(T game) {
|
public OnlineWithSleepThreadBehaviour(TurnBasedGame game) {
|
||||||
super(game);
|
super(game);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
package org.toop.framework.game.gameThreads;
|
||||||
|
|
||||||
|
import org.toop.framework.gameFramework.GameState;
|
||||||
|
import org.toop.framework.gameFramework.model.game.PlayResult;
|
||||||
|
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||||
|
import org.toop.framework.gameFramework.model.game.threadBehaviour.AbstractThreadBehaviour;
|
||||||
|
import org.toop.framework.gameFramework.model.player.Player;
|
||||||
|
import org.toop.framework.utils.ImmutablePair;
|
||||||
|
import org.toop.framework.utils.Pair;
|
||||||
|
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.concurrent.*;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
|
public class ServerThreadBehaviour extends AbstractThreadBehaviour implements Runnable {
|
||||||
|
private final Consumer<ImmutablePair<String, Integer>> onPlayerMove;
|
||||||
|
private final Consumer<Pair<GameState, Integer>> onGameEnd;
|
||||||
|
|
||||||
|
private final ExecutorService moveExecutor = Executors.newSingleThreadExecutor();
|
||||||
|
|
||||||
|
private final Duration timeOut;
|
||||||
|
/**
|
||||||
|
* Creates a new base behaviour for the specified game.
|
||||||
|
*
|
||||||
|
* @param game the turn-based game to control
|
||||||
|
*/
|
||||||
|
public ServerThreadBehaviour(
|
||||||
|
TurnBasedGame game,
|
||||||
|
Consumer<ImmutablePair<String,
|
||||||
|
Integer>> onPlayerMove,
|
||||||
|
Consumer<Pair<GameState, Integer>> onGameEnd,
|
||||||
|
Duration timeOut
|
||||||
|
) {
|
||||||
|
this.onPlayerMove = onPlayerMove;
|
||||||
|
this.onGameEnd = onGameEnd;
|
||||||
|
this.timeOut = timeOut;
|
||||||
|
super(game);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void notifyPlayerMove(ImmutablePair<String, Integer> pair) {
|
||||||
|
if (onPlayerMove != null) {
|
||||||
|
onPlayerMove.accept(pair);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void notifyGameEnd(ImmutablePair<GameState, Integer> pair) {
|
||||||
|
if (onGameEnd != null) {
|
||||||
|
onGameEnd.accept(pair);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
while (isRunning.get()) {
|
||||||
|
Player currentPlayer = game.getPlayer(game.getCurrentTurn());
|
||||||
|
|
||||||
|
Future<Long> move = moveExecutor.submit(() -> currentPlayer.getMove(game.deepCopy()));
|
||||||
|
|
||||||
|
PlayResult result;
|
||||||
|
try {
|
||||||
|
long moveResult = move.get(timeOut.toMillis(), TimeUnit.MILLISECONDS);
|
||||||
|
result = game.play(moveResult);
|
||||||
|
|
||||||
|
GameState state = result.state();
|
||||||
|
notifyPlayerMove(new ImmutablePair<>(currentPlayer.getName(), Long.numberOfTrailingZeros(moveResult)));
|
||||||
|
|
||||||
|
switch (state) {
|
||||||
|
case WIN, DRAW -> {
|
||||||
|
isRunning.set(false);
|
||||||
|
moveExecutor.shutdown();
|
||||||
|
notifyGameEnd(new ImmutablePair<>(state, game.getWinner()));
|
||||||
|
}
|
||||||
|
case NORMAL, TURN_SKIPPED -> { /* continue normally */ }
|
||||||
|
default -> {
|
||||||
|
logger.error("Unexpected state {}", state);
|
||||||
|
isRunning.set(false);
|
||||||
|
moveExecutor.shutdown();
|
||||||
|
throw new RuntimeException("Unknown state: " + state);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (InterruptedException | ExecutionException e) {
|
||||||
|
isRunning.set(false);
|
||||||
|
notifyGameEnd(new ImmutablePair<>(GameState.DRAW, 0));
|
||||||
|
moveExecutor.shutdown();
|
||||||
|
return;
|
||||||
|
} catch (TimeoutException e) {
|
||||||
|
isRunning.set(false);
|
||||||
|
notifyGameEnd(new ImmutablePair<>(GameState.WIN, 1+game.getWinner()%2));
|
||||||
|
moveExecutor.shutdown();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,377 @@
|
|||||||
|
package org.toop.framework.game.games.reversi;
|
||||||
|
|
||||||
|
import org.toop.framework.game.BitboardGame;
|
||||||
|
import org.toop.framework.gameFramework.GameState;
|
||||||
|
import org.toop.framework.gameFramework.model.game.PlayResult;
|
||||||
|
import org.toop.framework.gameFramework.model.player.Player;
|
||||||
|
|
||||||
|
public class BitboardReversi extends BitboardGame {
|
||||||
|
|
||||||
|
public record Score(int black, int white) {}
|
||||||
|
|
||||||
|
private final long notAFile = 0xfefefefefefefefeL;
|
||||||
|
private final long notHFile = 0x7f7f7f7f7f7f7f7fL;
|
||||||
|
|
||||||
|
public BitboardReversi() {
|
||||||
|
super(8, 8, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void init(Player[] players) {
|
||||||
|
super.init(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() {
|
||||||
|
long legalMoves = 0L;
|
||||||
|
|
||||||
|
final long player = getPlayerBitboard(getCurrentPlayerIndex());
|
||||||
|
final long opponent = getPlayerBitboard(getNextPlayer());
|
||||||
|
|
||||||
|
final long empty = ~(player | opponent);
|
||||||
|
|
||||||
|
long mask;
|
||||||
|
long direction;
|
||||||
|
|
||||||
|
// north
|
||||||
|
mask = opponent;
|
||||||
|
direction = (player << 8) & mask;
|
||||||
|
|
||||||
|
direction |= (direction << 8) & mask;
|
||||||
|
direction |= (direction << 8) & mask;
|
||||||
|
direction |= (direction << 8) & mask;
|
||||||
|
direction |= (direction << 8) & mask;
|
||||||
|
direction |= (direction << 8) & mask;
|
||||||
|
legalMoves |= (direction << 8) & empty;
|
||||||
|
|
||||||
|
// south
|
||||||
|
mask = opponent;
|
||||||
|
direction = (player >>> 8) & mask;
|
||||||
|
|
||||||
|
direction |= (direction >>> 8) & mask;
|
||||||
|
direction |= (direction >>> 8) & mask;
|
||||||
|
direction |= (direction >>> 8) & mask;
|
||||||
|
direction |= (direction >>> 8) & mask;
|
||||||
|
direction |= (direction >>> 8) & mask;
|
||||||
|
legalMoves |= (direction >>> 8) & empty;
|
||||||
|
|
||||||
|
// east
|
||||||
|
mask = opponent & notAFile;
|
||||||
|
direction = (player << 1) & mask;
|
||||||
|
|
||||||
|
direction |= (direction << 1) & mask;
|
||||||
|
direction |= (direction << 1) & mask;
|
||||||
|
direction |= (direction << 1) & mask;
|
||||||
|
direction |= (direction << 1) & mask;
|
||||||
|
direction |= (direction << 1) & mask;
|
||||||
|
legalMoves |= (direction << 1) & empty & notAFile;
|
||||||
|
|
||||||
|
// west
|
||||||
|
mask = opponent & notHFile;
|
||||||
|
direction = (player >>> 1) & mask;
|
||||||
|
|
||||||
|
direction |= (direction >>> 1) & mask;
|
||||||
|
direction |= (direction >>> 1) & mask;
|
||||||
|
direction |= (direction >>> 1) & mask;
|
||||||
|
direction |= (direction >>> 1) & mask;
|
||||||
|
direction |= (direction >>> 1) & mask;
|
||||||
|
legalMoves |= (direction >>> 1) & empty & notHFile;
|
||||||
|
|
||||||
|
// north-east
|
||||||
|
mask = opponent & notAFile;
|
||||||
|
direction = (player << 9) & mask;
|
||||||
|
|
||||||
|
direction |= (direction << 9) & mask;
|
||||||
|
direction |= (direction << 9) & mask;
|
||||||
|
direction |= (direction << 9) & mask;
|
||||||
|
direction |= (direction << 9) & mask;
|
||||||
|
direction |= (direction << 9) & mask;
|
||||||
|
legalMoves |= (direction << 9) & empty & notAFile;
|
||||||
|
|
||||||
|
// north-west
|
||||||
|
mask = opponent & notHFile;
|
||||||
|
direction = (player << 7) & mask;
|
||||||
|
|
||||||
|
direction |= (direction << 7) & mask;
|
||||||
|
direction |= (direction << 7) & mask;
|
||||||
|
direction |= (direction << 7) & mask;
|
||||||
|
direction |= (direction << 7) & mask;
|
||||||
|
direction |= (direction << 7) & mask;
|
||||||
|
legalMoves |= (direction << 7) & empty & notHFile;
|
||||||
|
|
||||||
|
// south-east
|
||||||
|
mask = opponent & notAFile;
|
||||||
|
direction = (player >>> 7) & mask;
|
||||||
|
|
||||||
|
direction |= (direction >>> 7) & mask;
|
||||||
|
direction |= (direction >>> 7) & mask;
|
||||||
|
direction |= (direction >>> 7) & mask;
|
||||||
|
direction |= (direction >>> 7) & mask;
|
||||||
|
direction |= (direction >>> 7) & mask;
|
||||||
|
legalMoves |= (direction >>> 7) & empty & notAFile;
|
||||||
|
|
||||||
|
// south-west
|
||||||
|
mask = opponent & notHFile;
|
||||||
|
direction = (player >>> 9) & mask;
|
||||||
|
|
||||||
|
direction |= (direction >>> 9) & mask;
|
||||||
|
direction |= (direction >>> 9) & mask;
|
||||||
|
direction |= (direction >>> 9) & mask;
|
||||||
|
direction |= (direction >>> 9) & mask;
|
||||||
|
direction |= (direction >>> 9) & mask;
|
||||||
|
legalMoves |= (direction >>> 9) & empty & notHFile;
|
||||||
|
|
||||||
|
return legalMoves;
|
||||||
|
}
|
||||||
|
|
||||||
|
public long getFlips(long move) {
|
||||||
|
long flips = 0L;
|
||||||
|
|
||||||
|
final long player = getPlayerBitboard(getCurrentPlayerIndex());
|
||||||
|
final long opponent = getPlayerBitboard(getNextPlayer());
|
||||||
|
|
||||||
|
long mask;
|
||||||
|
long direction;
|
||||||
|
|
||||||
|
// north
|
||||||
|
mask = opponent;
|
||||||
|
direction = (move << 8) & mask;
|
||||||
|
|
||||||
|
direction |= (direction << 8) & mask;
|
||||||
|
direction |= (direction << 8) & mask;
|
||||||
|
direction |= (direction << 8) & mask;
|
||||||
|
direction |= (direction << 8) & mask;
|
||||||
|
direction |= (direction << 8) & mask;
|
||||||
|
|
||||||
|
if (((direction << 8) & player) != 0) {
|
||||||
|
flips |= direction;
|
||||||
|
}
|
||||||
|
|
||||||
|
// south
|
||||||
|
mask = opponent;
|
||||||
|
direction = (move >>> 8) & mask;
|
||||||
|
|
||||||
|
direction |= (direction >>> 8) & mask;
|
||||||
|
direction |= (direction >>> 8) & mask;
|
||||||
|
direction |= (direction >>> 8) & mask;
|
||||||
|
direction |= (direction >>> 8) & mask;
|
||||||
|
direction |= (direction >>> 8) & mask;
|
||||||
|
|
||||||
|
if (((direction >>> 8) & player) != 0) {
|
||||||
|
flips |= direction;
|
||||||
|
}
|
||||||
|
|
||||||
|
// east
|
||||||
|
mask = opponent & notAFile;
|
||||||
|
direction = (move << 1) & mask;
|
||||||
|
|
||||||
|
direction |= (direction << 1) & mask;
|
||||||
|
direction |= (direction << 1) & mask;
|
||||||
|
direction |= (direction << 1) & mask;
|
||||||
|
direction |= (direction << 1) & mask;
|
||||||
|
direction |= (direction << 1) & mask;
|
||||||
|
|
||||||
|
if (((direction << 1) & player & notAFile) != 0) {
|
||||||
|
flips |= direction;
|
||||||
|
}
|
||||||
|
|
||||||
|
// west
|
||||||
|
mask = opponent & notHFile;
|
||||||
|
direction = (move >>> 1) & mask;
|
||||||
|
|
||||||
|
direction |= (direction >>> 1) & mask;
|
||||||
|
direction |= (direction >>> 1) & mask;
|
||||||
|
direction |= (direction >>> 1) & mask;
|
||||||
|
direction |= (direction >>> 1) & mask;
|
||||||
|
direction |= (direction >>> 1) & mask;
|
||||||
|
|
||||||
|
if (((direction >>> 1) & player & notHFile) != 0) {
|
||||||
|
flips |= direction;
|
||||||
|
}
|
||||||
|
|
||||||
|
// north-east
|
||||||
|
mask = opponent & notAFile;
|
||||||
|
direction = (move << 9) & mask;
|
||||||
|
|
||||||
|
direction |= (direction << 9) & mask;
|
||||||
|
direction |= (direction << 9) & mask;
|
||||||
|
direction |= (direction << 9) & mask;
|
||||||
|
direction |= (direction << 9) & mask;
|
||||||
|
direction |= (direction << 9) & mask;
|
||||||
|
|
||||||
|
if (((direction << 9) & player & notAFile) != 0) {
|
||||||
|
flips |= direction;
|
||||||
|
}
|
||||||
|
|
||||||
|
// north-west
|
||||||
|
mask = opponent & notHFile;
|
||||||
|
direction = (move << 7) & mask;
|
||||||
|
|
||||||
|
direction |= (direction << 7) & mask;
|
||||||
|
direction |= (direction << 7) & mask;
|
||||||
|
direction |= (direction << 7) & mask;
|
||||||
|
direction |= (direction << 7) & mask;
|
||||||
|
direction |= (direction << 7) & mask;
|
||||||
|
|
||||||
|
if (((direction << 7) & player & notHFile) != 0) {
|
||||||
|
flips |= direction;
|
||||||
|
}
|
||||||
|
|
||||||
|
// south-east
|
||||||
|
mask = opponent & notAFile;
|
||||||
|
direction = (move >>> 7) & mask;
|
||||||
|
|
||||||
|
direction |= (direction >>> 7) & mask;
|
||||||
|
direction |= (direction >>> 7) & mask;
|
||||||
|
direction |= (direction >>> 7) & mask;
|
||||||
|
direction |= (direction >>> 7) & mask;
|
||||||
|
direction |= (direction >>> 7) & mask;
|
||||||
|
|
||||||
|
if (((direction >>> 7) & player & notAFile) != 0) {
|
||||||
|
flips |= direction;
|
||||||
|
}
|
||||||
|
|
||||||
|
// south-west
|
||||||
|
mask = opponent & notHFile;
|
||||||
|
direction = (move >>> 9) & mask;
|
||||||
|
|
||||||
|
direction |= (direction >>> 9) & mask;
|
||||||
|
direction |= (direction >>> 9) & mask;
|
||||||
|
direction |= (direction >>> 9) & mask;
|
||||||
|
direction |= (direction >>> 9) & mask;
|
||||||
|
direction |= (direction >>> 9) & mask;
|
||||||
|
|
||||||
|
if (((direction >>> 9) & player & notHFile) != 0) {
|
||||||
|
flips |= direction;
|
||||||
|
}
|
||||||
|
|
||||||
|
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) {
|
||||||
|
state = new PlayResult(GameState.DRAW, -1);
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
state = new PlayResult(GameState.WIN, winner);
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
state = new PlayResult(GameState.TURN_SKIPPED, getCurrentPlayerIndex());
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
state = new PlayResult(GameState.NORMAL, getCurrentPlayerIndex());
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public float rateMove(long move) {
|
||||||
|
final long corners = 0x8100000000000081L;
|
||||||
|
|
||||||
|
if ((move & corners) != 0L) {
|
||||||
|
return 0.4f;
|
||||||
|
}
|
||||||
|
|
||||||
|
final long xSquares = 0x0042000000004200L;
|
||||||
|
|
||||||
|
if ((move & xSquares) != 0) {
|
||||||
|
return -0.4f;
|
||||||
|
}
|
||||||
|
|
||||||
|
final long cSquares = 0x4281000000008142L;
|
||||||
|
|
||||||
|
if ((move & cSquares) != 0) {
|
||||||
|
return -0.1f;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0.0f;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public long heuristicMove(long legalMoves) {
|
||||||
|
long bestMove = 0L;
|
||||||
|
float bestMoveRate = Float.NEGATIVE_INFINITY;
|
||||||
|
|
||||||
|
while (legalMoves != 0L) {
|
||||||
|
final long move = legalMoves & -legalMoves;
|
||||||
|
final float moveRate = rateMove(move);
|
||||||
|
|
||||||
|
if (moveRate > bestMoveRate) {
|
||||||
|
bestMove = move;
|
||||||
|
bestMoveRate = moveRate;
|
||||||
|
}
|
||||||
|
|
||||||
|
legalMoves &= ~move;
|
||||||
|
}
|
||||||
|
|
||||||
|
return bestMove;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void setFrom(long player1, long player2, int turn) {
|
||||||
|
this.playerBitboard[0] = player1;
|
||||||
|
this.playerBitboard[1] = player2;
|
||||||
|
this.currentTurn = turn;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +1,12 @@
|
|||||||
package org.toop.game.games.tictactoe;
|
package org.toop.framework.game.games.tictactoe;
|
||||||
|
|
||||||
import org.toop.framework.gameFramework.GameState;
|
import org.toop.framework.gameFramework.GameState;
|
||||||
import org.toop.framework.gameFramework.model.game.PlayResult;
|
import org.toop.framework.gameFramework.model.game.PlayResult;
|
||||||
|
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||||
import org.toop.framework.gameFramework.model.player.Player;
|
import org.toop.framework.gameFramework.model.player.Player;
|
||||||
import org.toop.game.BitboardGame;
|
import org.toop.framework.game.BitboardGame;
|
||||||
|
|
||||||
public class BitboardTicTacToe extends BitboardGame<BitboardTicTacToe> {
|
public class BitboardTicTacToe extends BitboardGame {
|
||||||
private final long[] winningLines = {
|
private final long[] winningLines = {
|
||||||
0b111000000L, // top row
|
0b111000000L, // top row
|
||||||
0b000111000L, // middle row
|
0b000111000L, // middle row
|
||||||
@@ -17,9 +18,15 @@ public class BitboardTicTacToe extends BitboardGame<BitboardTicTacToe> {
|
|||||||
0b001010100L // anti-diagonal
|
0b001010100L // anti-diagonal
|
||||||
};
|
};
|
||||||
|
|
||||||
public BitboardTicTacToe(Player<BitboardTicTacToe>[] players) {
|
public BitboardTicTacToe() {
|
||||||
super(3, 3, 2, players);
|
super(3, 3, 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void init(Player[] players) {
|
||||||
|
super.init(players);
|
||||||
|
}
|
||||||
|
|
||||||
public BitboardTicTacToe(BitboardTicTacToe other) {
|
public BitboardTicTacToe(BitboardTicTacToe other) {
|
||||||
super(other);
|
super(other);
|
||||||
}
|
}
|
||||||
@@ -39,7 +46,8 @@ public class BitboardTicTacToe extends BitboardGame<BitboardTicTacToe> {
|
|||||||
public PlayResult play(long move) {
|
public PlayResult play(long move) {
|
||||||
// Player loses if move is invalid
|
// Player loses if move is invalid
|
||||||
if ((move & getLegalMoves()) == 0 || Long.bitCount(move) != 1){
|
if ((move & getLegalMoves()) == 0 || Long.bitCount(move) != 1){
|
||||||
return new PlayResult(GameState.WIN, getNextPlayer());
|
state = new PlayResult(GameState.WIN, getNextPlayer());
|
||||||
|
return state;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Move is legal, make move
|
// Move is legal, make move
|
||||||
@@ -50,7 +58,8 @@ public class BitboardTicTacToe extends BitboardGame<BitboardTicTacToe> {
|
|||||||
|
|
||||||
// Check if current player won
|
// Check if current player won
|
||||||
if (checkWin(playerBitboard)) {
|
if (checkWin(playerBitboard)) {
|
||||||
return new PlayResult(GameState.WIN, getCurrentPlayerIndex());
|
state = new PlayResult(GameState.WIN, getCurrentPlayerIndex());
|
||||||
|
return state;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Proceed to next turn
|
// Proceed to next turn
|
||||||
@@ -59,11 +68,13 @@ public class BitboardTicTacToe extends BitboardGame<BitboardTicTacToe> {
|
|||||||
|
|
||||||
// Check for early draw
|
// Check for early draw
|
||||||
if (getLegalMoves() == 0L || checkEarlyDraw()) {
|
if (getLegalMoves() == 0L || checkEarlyDraw()) {
|
||||||
return new PlayResult(GameState.DRAW, -1);
|
state = new PlayResult(GameState.DRAW, -1);
|
||||||
|
return state;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Nothing weird happened, continue on as normal
|
// Nothing weird happened, continue on as normal
|
||||||
return new PlayResult(GameState.NORMAL, -1);
|
state = new PlayResult(GameState.NORMAL, -1);
|
||||||
|
return state;
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean checkWin(long board) {
|
private boolean checkWin(long board) {
|
||||||
@@ -100,4 +111,18 @@ public class BitboardTicTacToe extends BitboardGame<BitboardTicTacToe> {
|
|||||||
public BitboardTicTacToe deepCopy() {
|
public BitboardTicTacToe deepCopy() {
|
||||||
return new BitboardTicTacToe(this);
|
return new BitboardTicTacToe(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public float rateMove(long move) {
|
||||||
|
return 0.0f;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public long heuristicMove(long legalMoves) {
|
||||||
|
return legalMoves;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void setFrom(long player1, long player2, int turn) {
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package org.toop.game.players;
|
package org.toop.framework.game.players;
|
||||||
|
|
||||||
import org.toop.framework.gameFramework.model.player.*;
|
import org.toop.framework.gameFramework.model.player.*;
|
||||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||||
@@ -12,22 +12,24 @@ import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
|||||||
*
|
*
|
||||||
* @param <T> the specific type of game this AI player can play
|
* @param <T> the specific type of game this AI player can play
|
||||||
*/
|
*/
|
||||||
public class ArtificialPlayer<T extends TurnBasedGame<T>> extends AbstractPlayer<T> {
|
public class ArtificialPlayer extends AbstractPlayer {
|
||||||
|
|
||||||
/** The AI instance used to calculate moves. */
|
/**
|
||||||
private final AI<T> ai;
|
* The AI instance used to calculate moves.
|
||||||
|
*/
|
||||||
|
private final AI ai;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs a new ArtificialPlayer using the specified AI.
|
* Constructs a new ArtificialPlayer using the specified AI.
|
||||||
*
|
*
|
||||||
* @param ai the AI instance that determines moves for this player
|
* @param ai the AI instance that determines moves for this player
|
||||||
*/
|
*/
|
||||||
public ArtificialPlayer(AI<T> ai, String name) {
|
public ArtificialPlayer(AI ai, String name) {
|
||||||
super(name);
|
super(name);
|
||||||
this.ai = ai;
|
this.ai = ai;
|
||||||
}
|
}
|
||||||
|
|
||||||
public ArtificialPlayer(ArtificialPlayer<T> other) {
|
public ArtificialPlayer(ArtificialPlayer other) {
|
||||||
super(other);
|
super(other);
|
||||||
this.ai = other.ai.deepCopy();
|
this.ai = other.ai.deepCopy();
|
||||||
}
|
}
|
||||||
@@ -44,12 +46,21 @@ public class ArtificialPlayer<T extends TurnBasedGame<T>> extends AbstractPlayer
|
|||||||
* @return the integer representing the chosen move
|
* @return the integer representing the chosen move
|
||||||
* @throws ClassCastException if {@code gameCopy} is not of type {@code T}
|
* @throws ClassCastException if {@code gameCopy} is not of type {@code T}
|
||||||
*/
|
*/
|
||||||
public long getMove(T gameCopy) {
|
protected long determineMove(TurnBasedGame gameCopy) {
|
||||||
return ai.getMove(gameCopy);
|
return ai.getMove(gameCopy);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a deep copy of this AI player.
|
||||||
|
*
|
||||||
|
* @return a copy of this player
|
||||||
|
*/
|
||||||
@Override
|
@Override
|
||||||
public ArtificialPlayer<T> deepCopy() {
|
public ArtificialPlayer deepCopy() {
|
||||||
return new ArtificialPlayer<T>(this);
|
return new ArtificialPlayer(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
public AI getAi() {
|
||||||
|
return ai;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
package org.toop.framework.game.players;
|
||||||
|
|
||||||
|
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||||
|
import org.toop.framework.gameFramework.model.player.AbstractPlayer;
|
||||||
|
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.concurrent.ExecutionException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Represents a local player who provides moves manually.
|
||||||
|
*
|
||||||
|
* @param <T> the type of turn-based game
|
||||||
|
*/
|
||||||
|
public class LocalPlayer extends AbstractPlayer {
|
||||||
|
|
||||||
|
private CompletableFuture<Long> LastMove = new CompletableFuture<>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a new local player with the given name.
|
||||||
|
*
|
||||||
|
* @param name the player's name
|
||||||
|
*/
|
||||||
|
public LocalPlayer(String name) {
|
||||||
|
super(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a copy of another local player.
|
||||||
|
*
|
||||||
|
* @param other the player to copy
|
||||||
|
*/
|
||||||
|
public LocalPlayer(LocalPlayer other) {
|
||||||
|
super(other);
|
||||||
|
this.LastMove = other.LastMove;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Waits for and returns the player's next legal move.
|
||||||
|
*
|
||||||
|
* @param gameCopy a copy of the current game
|
||||||
|
* @return the chosen move
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
protected long determineMove(TurnBasedGame gameCopy) {
|
||||||
|
long legalMoves = gameCopy.getLegalMoves();
|
||||||
|
long move;
|
||||||
|
|
||||||
|
try {
|
||||||
|
do {
|
||||||
|
move = getLastMove();
|
||||||
|
IO.println("GETTING MOVE");
|
||||||
|
} while ((legalMoves & move) == 0);
|
||||||
|
return move;
|
||||||
|
} catch (Exception e) {
|
||||||
|
IO.println(e);
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the player's last move.
|
||||||
|
*
|
||||||
|
* @param move the move to set
|
||||||
|
*/
|
||||||
|
public void setLastMove(long move) {
|
||||||
|
LastMove.complete(move);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Waits for the next move from the player.
|
||||||
|
*
|
||||||
|
* @return the chosen move or 0 if interrupted
|
||||||
|
*/
|
||||||
|
private long getLastMove() {
|
||||||
|
LastMove = new CompletableFuture<>(); // Reset the future
|
||||||
|
try {
|
||||||
|
return LastMove.get();
|
||||||
|
} catch (ExecutionException | InterruptedException e) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a deep copy of this local player.
|
||||||
|
*
|
||||||
|
* @return a copy of this player
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public LocalPlayer deepCopy() {
|
||||||
|
return new LocalPlayer(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*public void register() {
|
||||||
|
// Listening to PlayerAttemptedMove
|
||||||
|
new EventFlow().listen(GUIEvents.PlayerAttemptedMove.class, event -> {
|
||||||
|
if (!LastMove.isDone()) {
|
||||||
|
LastMove.complete(event.move()); // complete the future
|
||||||
|
}
|
||||||
|
}, true); // auto-unsubscribe
|
||||||
|
}
|
||||||
|
|
||||||
|
// This blocks until the next move arrives
|
||||||
|
public int take() throws ExecutionException, InterruptedException {
|
||||||
|
int move = LastMove.get(); // blocking
|
||||||
|
LastMove = new CompletableFuture<>(); // reset for next move
|
||||||
|
return move;
|
||||||
|
}*/
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
package org.toop.framework.game.players;
|
||||||
|
|
||||||
|
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||||
|
import org.toop.framework.gameFramework.model.player.AbstractPlayer;
|
||||||
|
import org.toop.framework.gameFramework.model.player.Player;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Represents a player that participates online.
|
||||||
|
*
|
||||||
|
* @param <T> the type of turn-based game
|
||||||
|
*/
|
||||||
|
public class OnlinePlayer extends AbstractPlayer {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a new online player with the given name.
|
||||||
|
*
|
||||||
|
* @param name the name of the player
|
||||||
|
*/
|
||||||
|
public OnlinePlayer(String name) {
|
||||||
|
super(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a copy of another online player.
|
||||||
|
*
|
||||||
|
* @param other the player to copy
|
||||||
|
*/
|
||||||
|
public OnlinePlayer(OnlinePlayer other) {
|
||||||
|
super(other);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@inheritDoc}
|
||||||
|
* <p>
|
||||||
|
* This method is not supported for online players.
|
||||||
|
*
|
||||||
|
* @throws UnsupportedOperationException always
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
protected long determineMove(TurnBasedGame gameCopy) {
|
||||||
|
throw new UnsupportedOperationException("An online player does not support determining move");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@inheritDoc}
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public Player deepCopy() {
|
||||||
|
return new OnlinePlayer(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package org.toop.framework.game.players;
|
||||||
|
|
||||||
|
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||||
|
import org.toop.framework.gameFramework.model.player.AbstractPlayer;
|
||||||
|
import org.toop.framework.gameFramework.model.player.Player;
|
||||||
|
import org.toop.framework.networking.server.client.NettyClient;
|
||||||
|
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.concurrent.ExecutionException;
|
||||||
|
|
||||||
|
public class ServerPlayer extends AbstractPlayer {
|
||||||
|
private NettyClient client;
|
||||||
|
private CompletableFuture<Long> lastMove;
|
||||||
|
|
||||||
|
public ServerPlayer(NettyClient client) {
|
||||||
|
super(client.name());
|
||||||
|
this.client = client;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setMove(long move) {
|
||||||
|
lastMove.complete(move);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Player deepCopy() {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public long determineMove(TurnBasedGame game) {
|
||||||
|
lastMove = new CompletableFuture<>();
|
||||||
|
|
||||||
|
client.send("SVR GAME YOURTURN {TURNMESSAGE: \"<bericht voor deze beurt>\"}");
|
||||||
|
return lastMove.join();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,13 +4,13 @@ package org.toop.framework.gameFramework;
|
|||||||
* Represents the current state of a turn-based game.
|
* Represents the current state of a turn-based game.
|
||||||
*/
|
*/
|
||||||
public enum GameState {
|
public enum GameState {
|
||||||
/** Game is ongoing and no special condition applies. */
|
/** OnlineTurnBasedGame is ongoing and no special condition applies. */
|
||||||
NORMAL,
|
NORMAL,
|
||||||
|
|
||||||
/** Game ended in a draw. */
|
/** OnlineTurnBasedGame ended in a draw. */
|
||||||
DRAW,
|
DRAW,
|
||||||
|
|
||||||
/** Game ended with a win for a player. */
|
/** OnlineTurnBasedGame ended with a win for a player. */
|
||||||
WIN,
|
WIN,
|
||||||
|
|
||||||
/** Next player's turn was skipped. */
|
/** Next player's turn was skipped. */
|
||||||
|
|||||||
@@ -1,10 +1,8 @@
|
|||||||
package org.toop.framework.gameFramework.controller;
|
package org.toop.framework.gameFramework.controller;
|
||||||
|
|
||||||
import org.toop.framework.gameFramework.model.game.SupportsOnlinePlay;
|
import org.toop.framework.networking.connection.events.NetworkEvents;
|
||||||
import org.toop.framework.gameFramework.model.game.threadBehaviour.Controllable;
|
|
||||||
import org.toop.framework.networking.events.NetworkEvents;
|
|
||||||
|
|
||||||
public interface GameController extends Controllable, UpdatesGameUI {
|
public interface GameController {
|
||||||
/** Called when it is this player's turn to make a move. */
|
/** Called when it is this player's turn to make a move. */
|
||||||
void onYourTurn(NetworkEvents.YourTurnResponse event);
|
void onYourTurn(NetworkEvents.YourTurnResponse event);
|
||||||
|
|
||||||
@@ -14,5 +12,12 @@ public interface GameController extends Controllable, UpdatesGameUI {
|
|||||||
/** Called when the game has finished, with the final result. */
|
/** Called when the game has finished, with the final result. */
|
||||||
void gameFinished(NetworkEvents.GameResultResponse event);
|
void gameFinished(NetworkEvents.GameResultResponse event);
|
||||||
|
|
||||||
|
void start();
|
||||||
|
|
||||||
|
void stop();
|
||||||
|
|
||||||
|
/** Called to refresh or update the game UI. */
|
||||||
|
void updateUI();
|
||||||
|
|
||||||
void sendMove(long clientId, long move);
|
void sendMove(long clientId, long move);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +0,0 @@
|
|||||||
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();
|
|
||||||
}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
package org.toop.framework.gameFramework.model.game;
|
|
||||||
|
|
||||||
public interface BoardProvider {
|
|
||||||
long[] getBoard();
|
|
||||||
}
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
||||||
@@ -1,7 +1,21 @@
|
|||||||
package org.toop.framework.gameFramework.model.game;
|
package org.toop.framework.gameFramework.model.game;
|
||||||
|
|
||||||
public interface TurnBasedGame<T extends TurnBasedGame<T>> extends Playable, DeepCopyable<T>, PlayerProvider<T>, BoardProvider {
|
import org.toop.framework.gameFramework.model.player.Player;
|
||||||
|
|
||||||
|
public interface TurnBasedGame extends DeepCopyable<TurnBasedGame> {
|
||||||
|
void init(Player[] players);
|
||||||
|
long[] getBoard();
|
||||||
int getCurrentTurn();
|
int getCurrentTurn();
|
||||||
int getPlayerCount();
|
int getPlayerCount();
|
||||||
|
Player getPlayer(int index);
|
||||||
int getWinner();
|
int getWinner();
|
||||||
|
long getLegalMoves();
|
||||||
|
PlayResult play(long move);
|
||||||
|
PlayResult getState();
|
||||||
|
boolean isTerminal();
|
||||||
|
|
||||||
|
float rateMove(long move);
|
||||||
|
long heuristicMove(long legalMoves);
|
||||||
|
|
||||||
|
void setFrom(long player1, long player2, int turn);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,9 +3,7 @@ package org.toop.framework.gameFramework.model.game.threadBehaviour;
|
|||||||
import org.apache.logging.log4j.LogManager;
|
import org.apache.logging.log4j.LogManager;
|
||||||
import org.apache.logging.log4j.Logger;
|
import org.apache.logging.log4j.Logger;
|
||||||
import org.toop.framework.gameFramework.LongPairConsumer;
|
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.game.TurnBasedGame;
|
||||||
import org.toop.framework.gameFramework.model.player.Player;
|
|
||||||
|
|
||||||
import java.util.concurrent.atomic.AtomicBoolean;
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
import java.util.function.Consumer;
|
import java.util.function.Consumer;
|
||||||
@@ -17,14 +15,14 @@ import java.util.function.Consumer;
|
|||||||
* a running flag, a game reference, and a logger.
|
* a running flag, a game reference, and a logger.
|
||||||
* Subclasses implement the actual game-loop logic.
|
* Subclasses implement the actual game-loop logic.
|
||||||
*/
|
*/
|
||||||
public abstract class AbstractThreadBehaviour<T extends TurnBasedGame<T>> implements ThreadBehaviour {
|
public abstract class AbstractThreadBehaviour implements ThreadBehaviour {
|
||||||
private LongPairConsumer onSendMove;
|
private LongPairConsumer onSendMove;
|
||||||
private Runnable onUpdateUI;
|
private Runnable onUpdateUI;
|
||||||
/** Indicates whether the game loop or event processing is active. */
|
/** Indicates whether the game loop or event processing is active. */
|
||||||
protected final AtomicBoolean isRunning = new AtomicBoolean();
|
protected final AtomicBoolean isRunning = new AtomicBoolean();
|
||||||
|
|
||||||
/** The game instance controlled by this behaviour. */
|
/** The game instance controlled by this behaviour. */
|
||||||
protected final T game;
|
protected final TurnBasedGame game;
|
||||||
|
|
||||||
/** Logger for the subclass to report errors or debug info. */
|
/** Logger for the subclass to report errors or debug info. */
|
||||||
protected final Logger logger = LogManager.getLogger(this.getClass());
|
protected final Logger logger = LogManager.getLogger(this.getClass());
|
||||||
@@ -34,7 +32,7 @@ public abstract class AbstractThreadBehaviour<T extends TurnBasedGame<T>> implem
|
|||||||
*
|
*
|
||||||
* @param game the turn-based game to control
|
* @param game the turn-based game to control
|
||||||
*/
|
*/
|
||||||
public AbstractThreadBehaviour(T game) {
|
public AbstractThreadBehaviour(TurnBasedGame game) {
|
||||||
this.game = game;
|
this.game = game;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +0,0 @@
|
|||||||
package org.toop.framework.gameFramework.model.game.threadBehaviour;
|
|
||||||
|
|
||||||
public interface Controllable {
|
|
||||||
void start();
|
|
||||||
|
|
||||||
void stop();
|
|
||||||
}
|
|
||||||
@@ -1,6 +1,4 @@
|
|||||||
package org.toop.framework.gameFramework.model.game;
|
package org.toop.framework.gameFramework.model.game.threadBehaviour;
|
||||||
|
|
||||||
import org.toop.framework.networking.events.NetworkEvents;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Interface for games that support online multiplayer play.
|
* Interface for games that support online multiplayer play.
|
||||||
@@ -3,8 +3,6 @@ package org.toop.framework.gameFramework.model.game.threadBehaviour;
|
|||||||
import org.toop.framework.gameFramework.LongPairConsumer;
|
import org.toop.framework.gameFramework.LongPairConsumer;
|
||||||
import org.toop.framework.gameFramework.controller.GameController;
|
import org.toop.framework.gameFramework.controller.GameController;
|
||||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
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;
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
@@ -13,8 +11,11 @@ import java.util.function.Consumer;
|
|||||||
* <p>
|
* <p>
|
||||||
* Defines how a game's execution is started, stopped, and which player is active.
|
* Defines how a game's execution is started, stopped, and which player is active.
|
||||||
*/
|
*/
|
||||||
public interface ThreadBehaviour extends Controllable {
|
public interface ThreadBehaviour {
|
||||||
void setOnUpdateUI(Runnable onUpdateUI);
|
void setOnUpdateUI(Runnable onUpdateUI);
|
||||||
void setOnSendMove(LongPairConsumer onSendMove);
|
void setOnSendMove(LongPairConsumer onSendMove);
|
||||||
|
void start();
|
||||||
|
void stop();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,5 +3,6 @@ package org.toop.framework.gameFramework.model.player;
|
|||||||
import org.toop.framework.gameFramework.model.game.DeepCopyable;
|
import org.toop.framework.gameFramework.model.game.DeepCopyable;
|
||||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||||
|
|
||||||
public interface AI<T extends TurnBasedGame<T>> extends MoveProvider<T>, DeepCopyable<AI<T>> {
|
public interface AI extends DeepCopyable<AI> {
|
||||||
|
long getMove(TurnBasedGame game);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,6 +12,6 @@ import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
|||||||
*
|
*
|
||||||
* @param <T> the specific type of game this AI can play, extending {@link GameR}
|
* @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> {
|
public abstract class AbstractAI implements AI {
|
||||||
// Concrete AI implementations should override findBestMove(T game, int depth)
|
// Concrete AI implementations should override findBestMove(T game, int depth)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,16 +15,17 @@ import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
|||||||
* specific move logic.
|
* specific move logic.
|
||||||
* </p>
|
* </p>
|
||||||
*/
|
*/
|
||||||
public abstract class AbstractPlayer<T extends TurnBasedGame<T>> implements Player<T> {
|
public abstract class AbstractPlayer implements Player {
|
||||||
private final Logger logger = LogManager.getLogger(this.getClass());
|
private final Logger logger = LogManager.getLogger(this.getClass());
|
||||||
|
|
||||||
private final String name;
|
private final String name;
|
||||||
|
|
||||||
protected AbstractPlayer(String name) {
|
protected AbstractPlayer(String name) {
|
||||||
|
System.out.println("Player " + name + " has been created");
|
||||||
this.name = name;
|
this.name = name;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected AbstractPlayer(AbstractPlayer<T> other) {
|
protected AbstractPlayer(AbstractPlayer other) {
|
||||||
this.name = other.name;
|
this.name = other.name;
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
@@ -39,12 +40,29 @@ public abstract class AbstractPlayer<T extends TurnBasedGame<T>> implements Play
|
|||||||
* @return an integer representing the chosen move
|
* @return an integer representing the chosen move
|
||||||
* @throws UnsupportedOperationException if the method is not overridden
|
* @throws UnsupportedOperationException if the method is not overridden
|
||||||
*/
|
*/
|
||||||
public long getMove(T gameCopy) {
|
public final long getMove(TurnBasedGame game) {
|
||||||
logger.error("Method getMove not implemented.");
|
return determineMove(game.deepCopy());
|
||||||
throw new UnsupportedOperationException("Not supported yet.");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getName(){
|
|
||||||
|
/**
|
||||||
|
* Determines the player's move using a safe copy of the game.
|
||||||
|
* <p>
|
||||||
|
* This method is called by {@link #getMove(T)} and should contain
|
||||||
|
* the player's strategy for choosing a move.
|
||||||
|
*
|
||||||
|
* @param gameCopy a deep copy of the game
|
||||||
|
* @return the chosen move
|
||||||
|
*/
|
||||||
|
protected abstract long determineMove(TurnBasedGame gameCopy);
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the player's name.
|
||||||
|
*
|
||||||
|
* @return the name
|
||||||
|
*/
|
||||||
|
public String getName() {
|
||||||
return this.name;
|
return this.name;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
package org.toop.framework.gameFramework.model.player;
|
|
||||||
|
|
||||||
public interface NameProvider {
|
|
||||||
String getName();
|
|
||||||
}
|
|
||||||
@@ -3,5 +3,7 @@ package org.toop.framework.gameFramework.model.player;
|
|||||||
import org.toop.framework.gameFramework.model.game.DeepCopyable;
|
import org.toop.framework.gameFramework.model.game.DeepCopyable;
|
||||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||||
|
|
||||||
public interface Player<T extends TurnBasedGame<T>> extends NameProvider, MoveProvider<T>, DeepCopyable<Player<T>> {
|
public interface Player extends DeepCopyable<Player> {
|
||||||
|
String getName();
|
||||||
|
long getMove(TurnBasedGame game);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,22 +1,23 @@
|
|||||||
package org.toop.framework.networking;
|
package org.toop.framework.networking.connection;
|
||||||
|
|
||||||
import org.apache.logging.log4j.LogManager;
|
import org.apache.logging.log4j.LogManager;
|
||||||
import org.apache.logging.log4j.Logger;
|
import org.apache.logging.log4j.Logger;
|
||||||
import org.toop.framework.SnowflakeGenerator;
|
import org.toop.framework.SnowflakeGenerator;
|
||||||
import org.toop.framework.eventbus.EventFlow;
|
import org.toop.framework.eventbus.EventFlow;
|
||||||
import org.toop.framework.networking.events.NetworkEvents;
|
import org.toop.framework.eventbus.bus.EventBus;
|
||||||
import org.toop.framework.networking.exceptions.ClientNotFoundException;
|
import org.toop.framework.networking.connection.events.NetworkEvents;
|
||||||
import org.toop.framework.networking.interfaces.NetworkingClientManager;
|
import org.toop.framework.networking.connection.exceptions.ClientNotFoundException;
|
||||||
|
import org.toop.framework.networking.connection.interfaces.NetworkingClientManager;
|
||||||
|
|
||||||
public class NetworkingClientEventListener {
|
public class NetworkingClientEventListener {
|
||||||
|
|
||||||
private static final Logger logger = LogManager.getLogger(NetworkingClientEventListener.class);
|
private static final Logger logger = LogManager.getLogger(NetworkingClientEventListener.class);
|
||||||
|
|
||||||
private final NetworkingClientManager clientManager;
|
private final NetworkingClientManager clientManager;
|
||||||
|
|
||||||
/** Starts a connection manager, to manage, connections. */
|
/** Starts a connection manager, to manage, connections. */
|
||||||
public NetworkingClientEventListener(NetworkingClientManager clientManager) {
|
public NetworkingClientEventListener(EventBus eventBus, NetworkingClientManager clientManager) {
|
||||||
this.clientManager = clientManager;
|
this.clientManager = clientManager;
|
||||||
new EventFlow()
|
new EventFlow(eventBus)
|
||||||
.listen(NetworkEvents.StartClient.class, this::handleStartClient, false)
|
.listen(NetworkEvents.StartClient.class, this::handleStartClient, false)
|
||||||
.listen(NetworkEvents.SendCommand.class, this::handleCommand, false)
|
.listen(NetworkEvents.SendCommand.class, this::handleCommand, false)
|
||||||
.listen(NetworkEvents.SendLogin.class, this::handleSendLogin, false)
|
.listen(NetworkEvents.SendLogin.class, this::handleSendLogin, false)
|
||||||
@@ -40,6 +41,7 @@ public class NetworkingClientEventListener {
|
|||||||
|
|
||||||
void handleStartClient(NetworkEvents.StartClient event) {
|
void handleStartClient(NetworkEvents.StartClient event) {
|
||||||
long clientId = SnowflakeGenerator.nextId();
|
long clientId = SnowflakeGenerator.nextId();
|
||||||
|
new EventFlow().addPostEvent(new NetworkEvents.CreatedIdForClient(clientId, event.identifier())).postEvent();
|
||||||
clientManager.startClient(
|
clientManager.startClient(
|
||||||
clientId,
|
clientId,
|
||||||
event.networkingClient(),
|
event.networkingClient(),
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package org.toop.framework.networking;
|
package org.toop.framework.networking.connection;
|
||||||
|
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
@@ -8,18 +8,23 @@ import java.util.concurrent.TimeUnit;
|
|||||||
|
|
||||||
import org.apache.logging.log4j.LogManager;
|
import org.apache.logging.log4j.LogManager;
|
||||||
import org.apache.logging.log4j.Logger;
|
import org.apache.logging.log4j.Logger;
|
||||||
import org.toop.framework.eventbus.GlobalEventBus;
|
import org.toop.framework.eventbus.EventFlow;
|
||||||
import org.toop.framework.networking.events.NetworkEvents;
|
import org.toop.framework.eventbus.bus.EventBus;
|
||||||
import org.toop.framework.networking.exceptions.ClientNotFoundException;
|
import org.toop.framework.networking.connection.events.NetworkEvents;
|
||||||
import org.toop.framework.networking.exceptions.CouldNotConnectException;
|
import org.toop.framework.networking.connection.exceptions.ClientNotFoundException;
|
||||||
import org.toop.framework.networking.interfaces.NetworkingClient;
|
import org.toop.framework.networking.connection.exceptions.CouldNotConnectException;
|
||||||
import org.toop.framework.networking.types.NetworkingConnector;
|
import org.toop.framework.networking.connection.interfaces.NetworkingClient;
|
||||||
|
import org.toop.framework.networking.connection.types.NetworkingConnector;
|
||||||
|
|
||||||
public class NetworkingClientManager implements org.toop.framework.networking.interfaces.NetworkingClientManager {
|
public class NetworkingClientManager implements org.toop.framework.networking.connection.interfaces.NetworkingClientManager {
|
||||||
private static final Logger logger = LogManager.getLogger(NetworkingClientManager.class);
|
private static final Logger logger = LogManager.getLogger(NetworkingClientManager.class);
|
||||||
|
|
||||||
|
private final EventBus eventBus;
|
||||||
private final Map<Long, NetworkingClient> networkClients = new ConcurrentHashMap<>();
|
private final Map<Long, NetworkingClient> networkClients = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
public NetworkingClientManager() {}
|
public NetworkingClientManager(EventBus eventBus) {
|
||||||
|
this.eventBus = eventBus;
|
||||||
|
}
|
||||||
|
|
||||||
private void connectHelper(
|
private void connectHelper(
|
||||||
long id,
|
long id,
|
||||||
@@ -28,8 +33,16 @@ public class NetworkingClientManager implements org.toop.framework.networking.in
|
|||||||
Runnable onSuccess,
|
Runnable onSuccess,
|
||||||
Runnable onFailure
|
Runnable onFailure
|
||||||
) {
|
) {
|
||||||
|
|
||||||
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
|
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
|
||||||
|
|
||||||
|
EventFlow closeEvent = new EventFlow()
|
||||||
|
.listen(
|
||||||
|
NetworkEvents.CloseClient.class,
|
||||||
|
e -> {
|
||||||
|
if (e.clientId() == id) scheduler.shutdownNow();
|
||||||
|
}, "close");
|
||||||
|
|
||||||
Runnable connectTask = new Runnable() {
|
Runnable connectTask = new Runnable() {
|
||||||
int attempts = 0;
|
int attempts = 0;
|
||||||
|
|
||||||
@@ -46,7 +59,7 @@ public class NetworkingClientManager implements org.toop.framework.networking.in
|
|||||||
nClient.connect(id, nConnector.host(), nConnector.port());
|
nClient.connect(id, nConnector.host(), nConnector.port());
|
||||||
networkClients.put(id, nClient);
|
networkClients.put(id, nClient);
|
||||||
logger.info("New client started successfully for {}:{}", nConnector.host(), nConnector.port());
|
logger.info("New client started successfully for {}:{}", nConnector.host(), nConnector.port());
|
||||||
GlobalEventBus.post(new NetworkEvents.ConnectTry(id, attempts, nConnector.reconnectAttempts(), true));
|
eventBus.post(new NetworkEvents.ConnectTry(id, attempts, nConnector.reconnectAttempts(), true));
|
||||||
onSuccess.run();
|
onSuccess.run();
|
||||||
scheduler.shutdown();
|
scheduler.shutdown();
|
||||||
} catch (CouldNotConnectException e) {
|
} catch (CouldNotConnectException e) {
|
||||||
@@ -54,17 +67,17 @@ public class NetworkingClientManager implements org.toop.framework.networking.in
|
|||||||
if (attempts < nConnector.reconnectAttempts()) {
|
if (attempts < nConnector.reconnectAttempts()) {
|
||||||
logger.warn("Could not connect to {}:{}. Retrying in {} {}",
|
logger.warn("Could not connect to {}:{}. Retrying in {} {}",
|
||||||
nConnector.host(), nConnector.port(), nConnector.timeout(), nConnector.timeUnit());
|
nConnector.host(), nConnector.port(), nConnector.timeout(), nConnector.timeUnit());
|
||||||
GlobalEventBus.post(new NetworkEvents.ConnectTry(id, attempts, nConnector.reconnectAttempts(), false));
|
eventBus.post(new NetworkEvents.ConnectTry(id, attempts, nConnector.reconnectAttempts(), false));
|
||||||
scheduler.schedule(this, nConnector.timeout(), nConnector.timeUnit());
|
scheduler.schedule(this, nConnector.timeout(), nConnector.timeUnit());
|
||||||
} else {
|
} else {
|
||||||
logger.error("Failed to start client for {}:{} after {} attempts", nConnector.host(), nConnector.port(), attempts);
|
logger.error("Failed to start client for {}:{} after {} attempts", nConnector.host(), nConnector.port(), attempts);
|
||||||
GlobalEventBus.post(new NetworkEvents.ConnectTry(id, -1, nConnector.reconnectAttempts(), false));
|
eventBus.post(new NetworkEvents.ConnectTry(id, -1, nConnector.reconnectAttempts(), false));
|
||||||
onFailure.run();
|
onFailure.run();
|
||||||
scheduler.shutdown();
|
scheduler.shutdown();
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error("Unexpected exception during startClient", e);
|
logger.error("Unexpected exception during startClient", e);
|
||||||
GlobalEventBus.post(new NetworkEvents.ConnectTry(id, -1, nConnector.reconnectAttempts(), false));
|
eventBus.post(new NetworkEvents.ConnectTry(id, -1, nConnector.reconnectAttempts(), false));
|
||||||
onFailure.run();
|
onFailure.run();
|
||||||
scheduler.shutdown();
|
scheduler.shutdown();
|
||||||
}
|
}
|
||||||
@@ -72,6 +85,8 @@ public class NetworkingClientManager implements org.toop.framework.networking.in
|
|||||||
};
|
};
|
||||||
|
|
||||||
scheduler.schedule(connectTask, 0, TimeUnit.MILLISECONDS);
|
scheduler.schedule(connectTask, 0, TimeUnit.MILLISECONDS);
|
||||||
|
//
|
||||||
|
// closeEvent.unsubscribe("close");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package org.toop.framework.networking.clients;
|
package org.toop.framework.networking.connection.clients;
|
||||||
|
|
||||||
import io.netty.bootstrap.Bootstrap;
|
import io.netty.bootstrap.Bootstrap;
|
||||||
import io.netty.channel.*;
|
import io.netty.channel.*;
|
||||||
@@ -11,17 +11,24 @@ import io.netty.handler.codec.string.StringEncoder;
|
|||||||
import io.netty.util.CharsetUtil;
|
import io.netty.util.CharsetUtil;
|
||||||
import org.apache.logging.log4j.LogManager;
|
import org.apache.logging.log4j.LogManager;
|
||||||
import org.apache.logging.log4j.Logger;
|
import org.apache.logging.log4j.Logger;
|
||||||
import org.toop.framework.networking.exceptions.CouldNotConnectException;
|
import org.toop.framework.eventbus.bus.EventBus;
|
||||||
import org.toop.framework.networking.handlers.NetworkingGameClientHandler;
|
import org.toop.framework.networking.connection.events.NetworkEvents;
|
||||||
import org.toop.framework.networking.interfaces.NetworkingClient;
|
import org.toop.framework.networking.connection.exceptions.CouldNotConnectException;
|
||||||
|
import org.toop.framework.networking.connection.handlers.NetworkingGameClientHandler;
|
||||||
|
import org.toop.framework.networking.connection.interfaces.NetworkingClient;
|
||||||
|
|
||||||
import java.net.InetSocketAddress;
|
import java.net.InetSocketAddress;
|
||||||
|
|
||||||
public class TournamentNetworkingClient implements NetworkingClient {
|
public class TournamentNetworkingClient implements NetworkingClient {
|
||||||
private static final Logger logger = LogManager.getLogger(TournamentNetworkingClient.class);
|
private static final Logger logger = LogManager.getLogger(TournamentNetworkingClient.class);
|
||||||
private Channel channel;
|
|
||||||
|
|
||||||
public TournamentNetworkingClient() {}
|
private final EventBus eventBus;
|
||||||
|
private Channel channel;
|
||||||
|
private long clientId;
|
||||||
|
|
||||||
|
public TournamentNetworkingClient(EventBus eventBus) {
|
||||||
|
this.eventBus = eventBus;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public InetSocketAddress getAddress() {
|
public InetSocketAddress getAddress() {
|
||||||
@@ -30,6 +37,7 @@ public class TournamentNetworkingClient implements NetworkingClient {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void connect(long clientId, String host, int port) throws CouldNotConnectException {
|
public void connect(long clientId, String host, int port) throws CouldNotConnectException {
|
||||||
|
this.clientId = clientId;
|
||||||
try {
|
try {
|
||||||
Bootstrap bootstrap = new Bootstrap();
|
Bootstrap bootstrap = new Bootstrap();
|
||||||
EventLoopGroup workerGroup = new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory());
|
EventLoopGroup workerGroup = new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory());
|
||||||
@@ -40,7 +48,7 @@ public class TournamentNetworkingClient implements NetworkingClient {
|
|||||||
new ChannelInitializer<SocketChannel>() {
|
new ChannelInitializer<SocketChannel>() {
|
||||||
@Override
|
@Override
|
||||||
public void initChannel(SocketChannel ch) {
|
public void initChannel(SocketChannel ch) {
|
||||||
NetworkingGameClientHandler handler = new NetworkingGameClientHandler(clientId);
|
NetworkingGameClientHandler handler = new NetworkingGameClientHandler(eventBus, clientId);
|
||||||
|
|
||||||
ChannelPipeline pipeline = ch.pipeline();
|
ChannelPipeline pipeline = ch.pipeline();
|
||||||
pipeline.addLast(new LineBasedFrameDecoder(1024)); // split at \n
|
pipeline.addLast(new LineBasedFrameDecoder(1024)); // split at \n
|
||||||
@@ -70,6 +78,7 @@ public class TournamentNetworkingClient implements NetworkingClient {
|
|||||||
logger.info("Connection {} sent message: '{}' ", this.channel.remoteAddress(), literalMsg);
|
logger.info("Connection {} sent message: '{}' ", this.channel.remoteAddress(), literalMsg);
|
||||||
} else {
|
} else {
|
||||||
logger.warn("Cannot send message: '{}', connection inactive. ", literalMsg);
|
logger.warn("Cannot send message: '{}', connection inactive. ", literalMsg);
|
||||||
|
eventBus.post(new NetworkEvents.ClosedConnection(clientId));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1,17 +1,18 @@
|
|||||||
package org.toop.framework.networking.events;
|
package org.toop.framework.networking.connection.events;
|
||||||
|
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
import java.util.concurrent.CompletableFuture;
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
|
||||||
import org.toop.annotations.AutoResponseResult;
|
import org.toop.annotations.AutoResponseResult;
|
||||||
|
import org.toop.framework.eventbus.GlobalEventBus;
|
||||||
import org.toop.framework.eventbus.events.*;
|
import org.toop.framework.eventbus.events.*;
|
||||||
import org.toop.framework.networking.interfaces.NetworkingClient;
|
import org.toop.framework.networking.connection.interfaces.NetworkingClient;
|
||||||
import org.toop.framework.networking.types.NetworkingConnector;
|
import org.toop.framework.networking.connection.types.NetworkingConnector;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Defines all event types related to the networking subsystem.
|
* Defines all event types related to the networking subsystem.
|
||||||
* <p>
|
* <p>
|
||||||
* These events are used in conjunction with the {@link org.toop.framework.eventbus.GlobalEventBus}
|
* These events are used in conjunction with the {@link GlobalEventBus}
|
||||||
* and {@link org.toop.framework.eventbus.EventFlow} to communicate between components
|
* and {@link org.toop.framework.eventbus.EventFlow} to communicate between components
|
||||||
* such as networking clients, managers, and listeners.
|
* such as networking clients, managers, and listeners.
|
||||||
* </p>
|
* </p>
|
||||||
@@ -64,6 +65,9 @@ public class NetworkEvents extends EventsBase {
|
|||||||
public record GameResultResponse(long clientId, String condition)
|
public record GameResultResponse(long clientId, String condition)
|
||||||
implements GenericEvent {}
|
implements GenericEvent {}
|
||||||
|
|
||||||
|
public record TournamentResultResponse(long clientId, String gameType, String[] names, String[] scoreTypes, List<Integer[]> scores)
|
||||||
|
implements GenericEvent {}
|
||||||
|
|
||||||
/** Indicates that a game move has been processed or received. */
|
/** Indicates that a game move has been processed or received. */
|
||||||
public record GameMoveResponse(long clientId, String player, String move, String details)
|
public record GameMoveResponse(long clientId, String player, String move, String details)
|
||||||
implements GenericEvent {}
|
implements GenericEvent {}
|
||||||
@@ -101,7 +105,7 @@ public class NetworkEvents extends EventsBase {
|
|||||||
implements GenericEvent {}
|
implements GenericEvent {}
|
||||||
|
|
||||||
/** Requests to accept an existing challenge. */
|
/** Requests to accept an existing challenge. */
|
||||||
public record SendAcceptChallenge(long clientId, int challengeId)
|
public record SendAcceptChallenge(long clientId, long challengeId)
|
||||||
implements GenericEvent {}
|
implements GenericEvent {}
|
||||||
|
|
||||||
/** Requests to forfeit the current game. */
|
/** Requests to forfeit the current game. */
|
||||||
@@ -166,6 +170,10 @@ public class NetworkEvents extends EventsBase {
|
|||||||
long identifier)
|
long identifier)
|
||||||
implements UniqueEvent {}
|
implements UniqueEvent {}
|
||||||
|
|
||||||
|
public record CreatedIdForClient(long clientId, long identifier) implements ResponseToUniqueEvent {}
|
||||||
|
|
||||||
|
public record ConnectTry(long clientId, int amount, int maxAmount, boolean success) implements GenericEvent {}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Response confirming that a client has been successfully started.
|
* Response confirming that a client has been successfully started.
|
||||||
* <p>
|
* <p>
|
||||||
@@ -181,8 +189,6 @@ public class NetworkEvents extends EventsBase {
|
|||||||
public record StartClientResponse(long clientId, boolean successful, long identifier)
|
public record StartClientResponse(long clientId, boolean successful, long identifier)
|
||||||
implements ResponseToUniqueEvent {}
|
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.
|
* Requests reconnection of an existing client using its previous configuration.
|
||||||
* <p>
|
* <p>
|
||||||
@@ -216,4 +222,5 @@ public class NetworkEvents extends EventsBase {
|
|||||||
/** Response to a {@link ChangeAddress} event, carrying the success result. */
|
/** Response to a {@link ChangeAddress} event, carrying the success result. */
|
||||||
public record ChangeAddressResponse(boolean successful, long identifier)
|
public record ChangeAddressResponse(boolean successful, long identifier)
|
||||||
implements ResponseToUniqueEvent {}
|
implements ResponseToUniqueEvent {}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package org.toop.framework.networking.exceptions;
|
package org.toop.framework.networking.connection.exceptions;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Thrown when an operation is attempted on a networking client
|
* Thrown when an operation is attempted on a networking client
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package org.toop.framework.networking.exceptions;
|
package org.toop.framework.networking.connection.exceptions;
|
||||||
|
|
||||||
public class CouldNotConnectException extends RuntimeException {
|
public class CouldNotConnectException extends RuntimeException {
|
||||||
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package org.toop.framework.networking.exceptions;
|
package org.toop.framework.networking.connection.exceptions;
|
||||||
|
|
||||||
public class NetworkingInitializationException extends RuntimeException {
|
public class NetworkingInitializationException extends RuntimeException {
|
||||||
public NetworkingInitializationException(String message, Throwable cause) {
|
public NetworkingInitializationException(String message, Throwable cause) {
|
||||||
@@ -1,22 +1,27 @@
|
|||||||
package org.toop.framework.networking.handlers;
|
package org.toop.framework.networking.connection.handlers;
|
||||||
|
|
||||||
import io.netty.channel.ChannelHandlerContext;
|
import io.netty.channel.ChannelHandlerContext;
|
||||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
import java.util.regex.MatchResult;
|
import java.util.regex.MatchResult;
|
||||||
import java.util.regex.Matcher;
|
import java.util.regex.Matcher;
|
||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
import org.apache.logging.log4j.LogManager;
|
import org.apache.logging.log4j.LogManager;
|
||||||
import org.apache.logging.log4j.Logger;
|
import org.apache.logging.log4j.Logger;
|
||||||
import org.toop.framework.eventbus.EventFlow;
|
import org.toop.framework.eventbus.bus.EventBus;
|
||||||
import org.toop.framework.networking.events.NetworkEvents;
|
import org.toop.framework.networking.connection.events.NetworkEvents;
|
||||||
|
|
||||||
public class NetworkingGameClientHandler extends ChannelInboundHandlerAdapter {
|
public class NetworkingGameClientHandler extends ChannelInboundHandlerAdapter {
|
||||||
private static final Logger logger = LogManager.getLogger(NetworkingGameClientHandler.class);
|
private static final Logger logger = LogManager.getLogger(NetworkingGameClientHandler.class);
|
||||||
|
|
||||||
|
private final EventBus eventBus;
|
||||||
private final long connectionId;
|
private final long connectionId;
|
||||||
|
|
||||||
public NetworkingGameClientHandler(long connectionId) {
|
public NetworkingGameClientHandler(EventBus eventBus, long connectionId) {
|
||||||
|
this.eventBus = eventBus;
|
||||||
this.connectionId = connectionId;
|
this.connectionId = connectionId;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -40,9 +45,7 @@ public class NetworkingGameClientHandler extends ChannelInboundHandlerAdapter {
|
|||||||
"Received SVR message from server-{}, data: {}",
|
"Received SVR message from server-{}, data: {}",
|
||||||
ctx.channel().remoteAddress(),
|
ctx.channel().remoteAddress(),
|
||||||
msg);
|
msg);
|
||||||
new EventFlow()
|
eventBus.post(new NetworkEvents.ServerResponse(this.connectionId));
|
||||||
.addPostEvent(new NetworkEvents.ServerResponse(this.connectionId))
|
|
||||||
.asyncPostEvent();
|
|
||||||
parseServerReturn(rec);
|
parseServerReturn(rec);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -94,6 +97,9 @@ public class NetworkingGameClientHandler extends ChannelInboundHandlerAdapter {
|
|||||||
case "HELP":
|
case "HELP":
|
||||||
helpHandler(recSrvRemoved);
|
helpHandler(recSrvRemoved);
|
||||||
return;
|
return;
|
||||||
|
case "RESULTS":
|
||||||
|
resultsHandler(recSrvRemoved);
|
||||||
|
return;
|
||||||
default:
|
default:
|
||||||
// return
|
// return
|
||||||
}
|
}
|
||||||
@@ -103,6 +109,66 @@ public class NetworkingGameClientHandler extends ChannelInboundHandlerAdapter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static String extract(String input, String key) {
|
||||||
|
Pattern p = Pattern.compile(
|
||||||
|
key + "\\s*:\\s*(\\[[^]]*]|\"[^\"]*\")",
|
||||||
|
Pattern.CASE_INSENSITIVE
|
||||||
|
);
|
||||||
|
Matcher m = p.matcher(input);
|
||||||
|
return m.find() ? m.group(1) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void resultsHandler(String rec) {
|
||||||
|
// TODO all of this
|
||||||
|
|
||||||
|
IO.println(rec);
|
||||||
|
|
||||||
|
String gameTypeRaw = extract(rec, "GAMETYPE");
|
||||||
|
String usersRaw = extract(rec, "USERS");
|
||||||
|
String scoreTypesRaw = extract(rec, "SCORETYPES");
|
||||||
|
String scoresRaw = extract(rec, "SCORES");
|
||||||
|
|
||||||
|
if (usersRaw == null) return;
|
||||||
|
|
||||||
|
String[] users;
|
||||||
|
if (usersRaw.length() > 2) {
|
||||||
|
users = Arrays.stream(usersRaw.substring(1, usersRaw.length() - 1).split(","))
|
||||||
|
.map(s -> s.trim().replace("\"", ""))
|
||||||
|
.toArray(String[]::new);
|
||||||
|
} else {
|
||||||
|
users = new String[]{};
|
||||||
|
}
|
||||||
|
|
||||||
|
String[] scoreTypes;
|
||||||
|
if (scoreTypesRaw.length() > 2) {
|
||||||
|
scoreTypes = Arrays.stream(scoreTypesRaw.substring(1, usersRaw.length() - 1).split(","))
|
||||||
|
.map(s -> s.trim().replace("\"", ""))
|
||||||
|
.toArray(String[]::new);
|
||||||
|
} else {
|
||||||
|
scoreTypes = new String[]{};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (scoresRaw == null) return;
|
||||||
|
if (scoresRaw.length() > 2) {
|
||||||
|
List<Integer[]> scores = Arrays.stream(
|
||||||
|
scoresRaw.substring(1, scoresRaw.length() - 1) // remove outer []
|
||||||
|
.split("\\],\\[")
|
||||||
|
)
|
||||||
|
.map(part -> part.replace("[", "").replace("]", ""))
|
||||||
|
.map(part -> Arrays.stream(part.split(","))
|
||||||
|
.map(String::trim)
|
||||||
|
.map(Integer::parseInt)
|
||||||
|
.toArray(Integer[]::new)
|
||||||
|
)
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
eventBus.post(new NetworkEvents.TournamentResultResponse(this.connectionId, gameTypeRaw, users, scoreTypes, scores));
|
||||||
|
} else {
|
||||||
|
eventBus.post(new NetworkEvents.TournamentResultResponse(this.connectionId, gameTypeRaw, users, scoreTypes, new ArrayList<>()));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
private void gameMoveHandler(String rec) {
|
private void gameMoveHandler(String rec) {
|
||||||
String[] msg =
|
String[] msg =
|
||||||
Pattern.compile(
|
Pattern.compile(
|
||||||
@@ -113,11 +179,7 @@ public class NetworkingGameClientHandler extends ChannelInboundHandlerAdapter {
|
|||||||
.map(m -> m.group(1).trim())
|
.map(m -> m.group(1).trim())
|
||||||
.toArray(String[]::new);
|
.toArray(String[]::new);
|
||||||
|
|
||||||
new EventFlow()
|
eventBus.post(new NetworkEvents.GameMoveResponse(this.connectionId, msg[0], msg[1], msg[2]));
|
||||||
.addPostEvent(
|
|
||||||
new NetworkEvents.GameMoveResponse(
|
|
||||||
this.connectionId, msg[0], msg[1], msg[2]))
|
|
||||||
.asyncPostEvent();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void gameWinConditionHandler(String rec) {
|
private void gameWinConditionHandler(String rec) {
|
||||||
@@ -128,9 +190,7 @@ public class NetworkingGameClientHandler extends ChannelInboundHandlerAdapter {
|
|||||||
.findFirst()
|
.findFirst()
|
||||||
.orElse("");
|
.orElse("");
|
||||||
|
|
||||||
new EventFlow()
|
eventBus.post(new NetworkEvents.GameResultResponse(this.connectionId, condition));
|
||||||
.addPostEvent(new NetworkEvents.GameResultResponse(this.connectionId, condition))
|
|
||||||
.asyncPostEvent();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void gameChallengeHandler(String rec) {
|
private void gameChallengeHandler(String rec) {
|
||||||
@@ -145,17 +205,9 @@ public class NetworkingGameClientHandler extends ChannelInboundHandlerAdapter {
|
|||||||
.toArray(String[]::new);
|
.toArray(String[]::new);
|
||||||
|
|
||||||
if (isCancelled)
|
if (isCancelled)
|
||||||
new EventFlow()
|
eventBus.post(new NetworkEvents.GameResultResponse(this.connectionId, msg[0]));
|
||||||
.addPostEvent(
|
|
||||||
new NetworkEvents.ChallengeCancelledResponse(
|
|
||||||
this.connectionId, msg[0]))
|
|
||||||
.asyncPostEvent();
|
|
||||||
else
|
else
|
||||||
new EventFlow()
|
eventBus.post(new NetworkEvents.ChallengeResponse(this.connectionId, msg[0], msg[1], msg[2]));
|
||||||
.addPostEvent(
|
|
||||||
new NetworkEvents.ChallengeResponse(
|
|
||||||
this.connectionId, msg[0], msg[1], msg[2]))
|
|
||||||
.asyncPostEvent();
|
|
||||||
} catch (ArrayIndexOutOfBoundsException e) {
|
} catch (ArrayIndexOutOfBoundsException e) {
|
||||||
logger.error("Array out of bounds for: {}", rec, e);
|
logger.error("Array out of bounds for: {}", rec, e);
|
||||||
}
|
}
|
||||||
@@ -171,11 +223,7 @@ public class NetworkingGameClientHandler extends ChannelInboundHandlerAdapter {
|
|||||||
.toArray(String[]::new);
|
.toArray(String[]::new);
|
||||||
|
|
||||||
// [0] playerToMove, [1] gameType, [2] opponent
|
// [0] playerToMove, [1] gameType, [2] opponent
|
||||||
new EventFlow()
|
eventBus.post(new NetworkEvents.GameMatchResponse(this.connectionId, msg[0], msg[1], msg[2]));
|
||||||
.addPostEvent(
|
|
||||||
new NetworkEvents.GameMatchResponse(
|
|
||||||
this.connectionId, msg[0], msg[1], msg[2]))
|
|
||||||
.asyncPostEvent();
|
|
||||||
} catch (ArrayIndexOutOfBoundsException e) {
|
} catch (ArrayIndexOutOfBoundsException e) {
|
||||||
logger.error("Array out of bounds for: {}", rec, e);
|
logger.error("Array out of bounds for: {}", rec, e);
|
||||||
}
|
}
|
||||||
@@ -190,9 +238,7 @@ public class NetworkingGameClientHandler extends ChannelInboundHandlerAdapter {
|
|||||||
.toString()
|
.toString()
|
||||||
.trim();
|
.trim();
|
||||||
|
|
||||||
new EventFlow()
|
eventBus.post(new NetworkEvents.YourTurnResponse(this.connectionId, msg));
|
||||||
.addPostEvent(new NetworkEvents.YourTurnResponse(this.connectionId, msg))
|
|
||||||
.asyncPostEvent();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void playerlistHandler(String rec) {
|
private void playerlistHandler(String rec) {
|
||||||
@@ -203,9 +249,7 @@ public class NetworkingGameClientHandler extends ChannelInboundHandlerAdapter {
|
|||||||
.map(m -> m.group(1).trim())
|
.map(m -> m.group(1).trim())
|
||||||
.toArray(String[]::new);
|
.toArray(String[]::new);
|
||||||
|
|
||||||
new EventFlow()
|
eventBus.post(new NetworkEvents.PlayerlistResponse(this.connectionId, players));
|
||||||
.addPostEvent(new NetworkEvents.PlayerlistResponse(this.connectionId, players))
|
|
||||||
.asyncPostEvent();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void gamelistHandler(String rec) {
|
private void gamelistHandler(String rec) {
|
||||||
@@ -216,9 +260,7 @@ public class NetworkingGameClientHandler extends ChannelInboundHandlerAdapter {
|
|||||||
.map(m -> m.group(1).trim())
|
.map(m -> m.group(1).trim())
|
||||||
.toArray(String[]::new);
|
.toArray(String[]::new);
|
||||||
|
|
||||||
new EventFlow()
|
eventBus.post(new NetworkEvents.GamelistResponse(this.connectionId, gameTypes));
|
||||||
.addPostEvent(new NetworkEvents.GamelistResponse(this.connectionId, gameTypes))
|
|
||||||
.asyncPostEvent();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void helpHandler(String rec) {
|
private void helpHandler(String rec) {
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
package org.toop.framework.networking.interfaces;
|
package org.toop.framework.networking.connection.interfaces;
|
||||||
|
|
||||||
import org.toop.framework.networking.exceptions.CouldNotConnectException;
|
import org.toop.framework.networking.connection.exceptions.CouldNotConnectException;
|
||||||
|
|
||||||
import java.net.InetSocketAddress;
|
import java.net.InetSocketAddress;
|
||||||
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user