mirror of
https://github.com/2OOP/pism.git
synced 2026-02-04 19:04:49 +00:00
Compare commits
112 Commits
b2e4e7d810
...
289-server
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fe57e53d2e | ||
|
|
43fb9e2faf | ||
|
|
4dfe503584 | ||
|
|
d2e1edab5c | ||
|
|
94e3fc71b8 | ||
|
|
9fcbe7d298 | ||
|
|
848d257b9c | ||
|
|
7ce000c795 | ||
|
|
07a3e22dc9 | ||
|
|
a1f0d48477 | ||
|
|
5caf6900d1 | ||
|
|
94d85bf78d | ||
|
|
c9ea8f5e5b | ||
|
|
cc7acf9f0c | ||
|
|
955cb6109c | ||
|
|
013dd90705 | ||
|
|
c77499c36d | ||
|
|
28791fcc8a | ||
|
|
97657b01c9 | ||
|
|
a5bf6ca9fb | ||
|
|
fc25c15736 | ||
|
|
d4cad3311e | ||
|
|
96afc9543a | ||
|
|
0c1b106da5 | ||
|
|
aca0b2dcc0 | ||
|
|
75963a891b | ||
|
|
6b644ed8fa | ||
|
|
6a395cc40b | ||
|
|
5e5948d1fe | ||
|
|
35f7a4fd13 | ||
|
|
e2132b549d | ||
|
|
9aefcb9b7b | ||
|
|
9c01aabbe1 | ||
|
|
0cb52b042f | ||
|
|
56a8d12e46 | ||
| 65220d9649 | |||
|
|
c64a2e2c65 | ||
| 58a9ce78fe | |||
| 230f7480e4 | |||
|
|
6aa0eb952a | ||
|
|
df93b44d19 | ||
|
|
67f39c3f3b | ||
| 6e6a383708 | |||
| b7dec7798b | |||
| 2caa4fc79f | |||
| e72d888d84 | |||
|
|
e149588b60 | ||
|
|
a7d1a964c2 | ||
|
|
380e219c08 | ||
|
|
dccf428bb8 | ||
|
|
4ad922423c | ||
|
|
6e2ea82a32 | ||
|
|
34c85ec472 | ||
| 2d9b34b7f6 | |||
|
|
8867d5a1ea | ||
|
|
b94d1b6c9d | ||
|
|
8cb0a86d4e | ||
|
|
c2f1df7143 | ||
|
|
0956286616 | ||
| 55de6b5b18 | |||
| 73d71f2a2d | |||
|
|
cbcce29780 | ||
|
|
afcd9be71e | ||
| a9145d44cf | |||
| c015100ebf | |||
|
|
cd5736afc8 | ||
|
|
89a9cb1e55 | ||
|
|
22270e58dc | ||
|
|
edd2c24b65 | ||
| c929abc4b8 | |||
|
|
8b85915c74 | ||
|
|
150fb2986f | ||
|
|
9c20fcbc39 | ||
|
|
4d31a8ed44 | ||
|
|
fc47d81b8e | ||
|
|
a60c702306 | ||
|
|
c30c118c04 | ||
| 4b8edf1585 | |||
| fa9c2ce32b | |||
|
|
2599f9fa40 | ||
|
|
84e411fa38 | ||
|
|
66cb000fad | ||
|
|
1ae79daef0 | ||
|
|
cd8eb99559 | ||
|
|
8146be16ed | ||
|
|
0132981d94 | ||
|
|
322197494c | ||
|
|
a9c99df5d2 | ||
|
|
d702f82194 | ||
|
|
912d25c01f | ||
|
|
adc7b1a8f3 | ||
|
|
3a8b1c2454 | ||
|
|
846898988f | ||
|
|
ecd0fd26be | ||
|
|
a838973e67 | ||
|
|
a4f2a67d9c | ||
|
|
12bccb8854 | ||
|
|
80d3e47ad9 | ||
|
|
38f50cc16d | ||
|
|
f4678edf2f | ||
|
|
9a0bfc4fce | ||
|
|
0b750d5c0d | ||
|
|
07f3319675 | ||
|
|
1dfa6a7c6e | ||
| 144de5100e | |||
| 40ddf08e2d | |||
| 2936cc0b72 | |||
|
|
d24feef73e | ||
|
|
59d46cb73c | ||
|
|
38681c5db0 | ||
|
|
cbe01fbca5 | ||
|
|
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>
|
||||||
|
|||||||
@@ -4,6 +4,50 @@ import org.toop.app.App;
|
|||||||
|
|
||||||
public final class Main {
|
public final class Main {
|
||||||
static void main(String[] args) {
|
static void main(String[] args) {
|
||||||
App.run(args);
|
App.run(args);
|
||||||
|
// testMCTS(10);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Voor onderzoek
|
||||||
|
// private static void testMCTS(int games) {
|
||||||
|
// var random = new ArtificialPlayer<>(new RandomAI<BitboardReversi>(), "Random AI");
|
||||||
|
// var v1 = new ArtificialPlayer<>(new MCTSAI<BitboardTicTacToe>(10), "MCTS V1 AI");
|
||||||
|
// var v2 = new ArtificialPlayer<>(new MCTSAI2<BitboardTicTacToe>(10), "MCTS V2 AI");
|
||||||
|
// var v2_2 = new ArtificialPlayer<>(new MCTSAI2<BitboardTicTacToe>(100), "MCTS V2_2 AI");
|
||||||
|
// var v3 = new ArtificialPlayer<>(new MCTSAI3<BitboardTicTacToe>(10), "MCTS V3 AI");
|
||||||
|
|
||||||
|
// testAI(games, new Player[]{ v1, v2 });
|
||||||
|
// // testAI(games, new Player[]{ v1, v3 });
|
||||||
|
|
||||||
|
// // testAI(games, new Player[]{ random, v3 });
|
||||||
|
// // testAI(games, new Player[]{ v2, v3 });
|
||||||
|
// testAI(games, new Player[]{ v2, v3 });
|
||||||
|
// // testAI(games, new Player[]{ v3, v2 });
|
||||||
|
// }
|
||||||
|
|
||||||
|
// private static void testAI(int games, Player<BitboardReversi>[] ais) {
|
||||||
|
// int wins = 0;
|
||||||
|
// int ties = 0;
|
||||||
|
|
||||||
|
// for (int i = 0; i < games; i++) {
|
||||||
|
// final BitboardReversi match = new BitboardReversi(ais);
|
||||||
|
|
||||||
|
// while (!match.isTerminal()) {
|
||||||
|
// final int currentAI = match.getCurrentTurn();
|
||||||
|
// final long move = ais[currentAI].getMove(match);
|
||||||
|
|
||||||
|
// match.play(move);
|
||||||
|
// }
|
||||||
|
|
||||||
|
// if (match.getWinner() < 0) {
|
||||||
|
// ties++;
|
||||||
|
// continue;
|
||||||
|
// }
|
||||||
|
|
||||||
|
// wins += match.getWinner() == 0? 1 : 0;
|
||||||
|
// }
|
||||||
|
|
||||||
|
// System.out.printf("Out of %d games, %s won %d -- tied %d -- lost %d, games against %s\n", games, ais[0].getName(), wins, ties, games - wins - ties, ais[1].getName());
|
||||||
|
// System.out.printf("Average win rate was: %.2f\n\n", wins / (float)games);
|
||||||
|
// }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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;
|
||||||
@@ -15,8 +20,8 @@ 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.eventbus.GlobalEventBus;
|
import org.toop.framework.eventbus.GlobalEventBus;
|
||||||
import org.toop.framework.networking.NetworkingClientEventListener;
|
import org.toop.framework.networking.connection.NetworkingClientEventListener;
|
||||||
import org.toop.framework.networking.NetworkingClientManager;
|
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;
|
||||||
@@ -26,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;
|
||||||
@@ -46,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"));
|
||||||
@@ -64,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();
|
||||||
@@ -82,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
|
||||||
@@ -90,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();
|
||||||
|
|
||||||
@@ -107,30 +109,33 @@ 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 -> {
|
||||||
@@ -138,6 +143,11 @@ public final class App extends Application {
|
|||||||
escapePopup();
|
escapePopup();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
stage.setFullScreenExitKeyCombination(
|
||||||
|
new KeyCodeCombination(
|
||||||
|
KeyCode.F11
|
||||||
|
)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void escapePopup() {
|
public void escapePopup() {
|
||||||
@@ -161,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());
|
||||||
@@ -179,44 +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(
|
|
||||||
GlobalEventBus.get(),
|
|
||||||
new NetworkingClientManager(GlobalEventBus.get()))
|
|
||||||
).start();
|
|
||||||
|
|
||||||
new Thread(() -> {
|
final int THREAD_COUNT = 2;
|
||||||
MusicManager<MusicAsset> musicManager =
|
CountDownLatch latch = new CountDownLatch(THREAD_COUNT);
|
||||||
new MusicManager<>(
|
|
||||||
GlobalEventBus.get(),
|
|
||||||
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(() -> {
|
||||||
GlobalEventBus.get(),
|
new NetworkingClientEventListener(
|
||||||
musicManager,
|
GlobalEventBus.get(),
|
||||||
soundEffectManager,
|
new NetworkingClientManager(GlobalEventBus.get()));
|
||||||
audioVolumeManager
|
|
||||||
).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() {
|
||||||
|
|||||||
@@ -2,9 +2,7 @@ package org.toop.app;
|
|||||||
|
|
||||||
import javafx.application.Platform;
|
import javafx.application.Platform;
|
||||||
import javafx.geometry.Pos;
|
import javafx.geometry.Pos;
|
||||||
import org.toop.app.gameControllers.AbstractGameController;
|
import org.toop.app.gameControllers.*;
|
||||||
import org.toop.app.gameControllers.ReversiController;
|
|
||||||
import org.toop.app.gameControllers.TicTacToeController;
|
|
||||||
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;
|
||||||
@@ -13,18 +11,20 @@ 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.eventbus.GlobalEventBus;
|
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.players.ArtificialPlayer;
|
import org.toop.framework.networking.server.gateway.NettyGatewayServer;
|
||||||
import org.toop.game.players.OnlinePlayer;
|
import org.toop.framework.game.players.LocalPlayer;
|
||||||
import org.toop.game.games.reversi.ReversiAIR;
|
import org.toop.game.players.ai.MCTSAI3;
|
||||||
import org.toop.game.games.reversi.ReversiR;
|
|
||||||
import org.toop.game.games.tictactoe.TicTacToeAIR;
|
|
||||||
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;
|
||||||
@@ -33,6 +33,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;
|
||||||
|
|
||||||
@@ -42,7 +44,7 @@ public final class Server {
|
|||||||
private ServerView primary;
|
private ServerView primary;
|
||||||
private boolean isPolling = true;
|
private boolean isPolling = true;
|
||||||
|
|
||||||
private AbstractGameController<?> gameController;
|
private GameController gameController;
|
||||||
|
|
||||||
private final AtomicBoolean isSingleGame = new AtomicBoolean(false);
|
private final AtomicBoolean isSingleGame = new AtomicBoolean(false);
|
||||||
|
|
||||||
@@ -60,10 +62,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;
|
||||||
@@ -83,6 +88,8 @@ 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(
|
||||||
@@ -113,7 +120,8 @@ public final class Server {
|
|||||||
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");
|
||||||
@@ -154,7 +162,9 @@ public final class Server {
|
|||||||
.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;
|
||||||
}
|
}
|
||||||
@@ -178,7 +188,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) {
|
||||||
@@ -191,40 +201,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();
|
|
||||||
|
|
||||||
Player[] players = new Player[2];
|
Player[] players = new Player[2];
|
||||||
|
|
||||||
players[(myTurn + 1) % 2] = new OnlinePlayer<ReversiR>(response.opponent());
|
players[userStartingTurn] = new ArtificialPlayer(new MCTSAI3(1000), user);
|
||||||
|
players[opponentStartingTurn] = new OnlinePlayer(response.opponent());
|
||||||
switch (type){
|
|
||||||
case TICTACTOE ->{
|
|
||||||
players[myTurn] = new ArtificialPlayer<>(new TicTacToeAIR(9), user);
|
|
||||||
}
|
|
||||||
case REVERSI ->{
|
|
||||||
players[myTurn] = new ArtificialPlayer<>(new ReversiAIR(), user);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
switch (type) {
|
switch (type) {
|
||||||
case TICTACTOE ->{
|
case TICTACTOE -> gameController = new TicTacToeBitController(players);
|
||||||
gameController = new TicTacToeController(players, false);
|
case REVERSI -> gameController = new ReversiBitController(players);
|
||||||
}
|
|
||||||
case REVERSI ->
|
|
||||||
gameController = new ReversiController(players, false);
|
|
||||||
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 +244,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 +265,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 +283,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 +350,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() {
|
||||||
|
|||||||
245
app/src/main/java/org/toop/app/canvas/BitGameCanvas.java
Normal file
245
app/src/main/java/org/toop/app/canvas/BitGameCanvas.java
Normal file
@@ -0,0 +1,245 @@
|
|||||||
|
package org.toop.app.canvas;
|
||||||
|
|
||||||
|
import javafx.animation.KeyFrame;
|
||||||
|
import javafx.animation.Timeline;
|
||||||
|
import javafx.scene.canvas.Canvas;
|
||||||
|
import javafx.scene.canvas.GraphicsContext;
|
||||||
|
import javafx.scene.input.MouseButton;
|
||||||
|
import javafx.scene.paint.Color;
|
||||||
|
import javafx.scene.text.Font;
|
||||||
|
import javafx.util.Duration;
|
||||||
|
import org.toop.framework.eventbus.EventFlow;
|
||||||
|
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||||
|
import org.toop.framework.gameFramework.view.GUIEvents;
|
||||||
|
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
|
public abstract class BitGameCanvas implements GameCanvas {
|
||||||
|
protected record Cell(float x, float y, float width, float height) {
|
||||||
|
public boolean isInside(double x, double y) {
|
||||||
|
return x >= this.x && x <= this.x + width &&
|
||||||
|
y >= this.y && y <= this.y + height;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected final Canvas canvas;
|
||||||
|
protected final GraphicsContext graphics;
|
||||||
|
|
||||||
|
protected final Color color;
|
||||||
|
protected final Color backgroundColor;
|
||||||
|
|
||||||
|
protected final int width;
|
||||||
|
protected final int height;
|
||||||
|
|
||||||
|
protected final int rowSize;
|
||||||
|
protected final int columnSize;
|
||||||
|
|
||||||
|
protected final int gapSize;
|
||||||
|
protected final boolean edges;
|
||||||
|
|
||||||
|
protected final Cell[] cells;
|
||||||
|
|
||||||
|
private Consumer<Long> onCellCLicked;
|
||||||
|
|
||||||
|
public void setOnCellClicked(Consumer<Long> onClick) {
|
||||||
|
this.onCellCLicked = onClick;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected BitGameCanvas(Color color, Color backgroundColor, int width, int height, int rowSize, int columnSize, int gapSize, boolean edges) {
|
||||||
|
canvas = new Canvas(width, height);
|
||||||
|
graphics = canvas.getGraphicsContext2D();
|
||||||
|
|
||||||
|
this.onCellCLicked = (c) -> new EventFlow().addPostEvent(GUIEvents.PlayerAttemptedMove.class, c).postEvent();
|
||||||
|
|
||||||
|
this.color = color;
|
||||||
|
this.backgroundColor = backgroundColor;
|
||||||
|
|
||||||
|
this.width = width;
|
||||||
|
this.height = height;
|
||||||
|
|
||||||
|
this.rowSize = rowSize;
|
||||||
|
this.columnSize = columnSize;
|
||||||
|
|
||||||
|
this.gapSize = gapSize;
|
||||||
|
this.edges = edges;
|
||||||
|
|
||||||
|
cells = new Cell[rowSize * columnSize];
|
||||||
|
|
||||||
|
final float cellWidth = ((float) width - gapSize * rowSize - gapSize) / rowSize;
|
||||||
|
final float cellHeight = ((float) height - gapSize * columnSize - gapSize) / columnSize;
|
||||||
|
|
||||||
|
for (int y = 0; y < columnSize; y++) {
|
||||||
|
final float startY = y * cellHeight + y * gapSize + gapSize;
|
||||||
|
|
||||||
|
for (int x = 0; x < rowSize; x++) {
|
||||||
|
final float startX = x * cellWidth + x * gapSize + gapSize;
|
||||||
|
cells[x + y * rowSize] = new Cell(startX, startY, cellWidth, cellHeight);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
canvas.setOnMouseClicked(event -> {
|
||||||
|
|
||||||
|
if (event.getButton() != MouseButton.PRIMARY) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
final int column = (int) ((event.getX() / this.width) * rowSize);
|
||||||
|
final int row = (int) ((event.getY() / this.height) * columnSize);
|
||||||
|
|
||||||
|
final Cell cell = cells[column + row * rowSize];
|
||||||
|
|
||||||
|
if (cell.isInside(event.getX(), event.getY())) {
|
||||||
|
event.consume();
|
||||||
|
this.onCellCLicked.accept(1L << (column + row * rowSize));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
render();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void loopOverBoard(long bb, Consumer<Integer> onCell){
|
||||||
|
while (bb != 0) {
|
||||||
|
int idx = Long.numberOfTrailingZeros(bb); // index of least-significant 1-bit
|
||||||
|
onCell.accept(idx);
|
||||||
|
|
||||||
|
bb &= bb - 1; // clear LSB 1-bit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void render() {
|
||||||
|
graphics.setFill(backgroundColor);
|
||||||
|
graphics.fillRect(0, 0, width, height);
|
||||||
|
|
||||||
|
graphics.setFill(color);
|
||||||
|
|
||||||
|
for (int x = 0; x < rowSize - 1; x++) {
|
||||||
|
final float start = cells[x].x + cells[x].width;
|
||||||
|
graphics.fillRect(start, gapSize, gapSize, height - gapSize * 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int y = 0; y < columnSize - 1; y++) {
|
||||||
|
final float start = cells[y * rowSize].y + cells[y * rowSize].height;
|
||||||
|
graphics.fillRect(gapSize, start, width - gapSize * 2, gapSize);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (edges) {
|
||||||
|
graphics.fillRect(0, 0, width, gapSize);
|
||||||
|
graphics.fillRect(0, 0, gapSize, height);
|
||||||
|
|
||||||
|
graphics.fillRect(width - gapSize, 0, gapSize, height);
|
||||||
|
graphics.fillRect(0, height - gapSize, width, gapSize);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void fill(Color color, int cell) {
|
||||||
|
final float x = cells[cell].x();
|
||||||
|
final float y = cells[cell].y();
|
||||||
|
|
||||||
|
final float width = cells[cell].width();
|
||||||
|
final float height = cells[cell].height();
|
||||||
|
|
||||||
|
graphics.setFill(color);
|
||||||
|
graphics.fillRect(x, y, width, height);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void clear(int cell) {
|
||||||
|
final float x = cells[cell].x();
|
||||||
|
final float y = cells[cell].y();
|
||||||
|
|
||||||
|
final float width = cells[cell].width();
|
||||||
|
final float height = cells[cell].height();
|
||||||
|
|
||||||
|
graphics.clearRect(x, y, width, height);
|
||||||
|
|
||||||
|
graphics.setFill(backgroundColor);
|
||||||
|
graphics.fillRect(x, y, width, height);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void clearAll() {
|
||||||
|
for (int i = 0; i < cells.length; i++) {
|
||||||
|
clear(i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void drawPlayerMove(int player, int move) {
|
||||||
|
final float x = cells[move].x() + gapSize;
|
||||||
|
final float y = cells[move].y() + gapSize;
|
||||||
|
|
||||||
|
final float width = cells[move].width() - gapSize * 2;
|
||||||
|
final float height = cells[move].height() - gapSize * 2;
|
||||||
|
|
||||||
|
graphics.setFill(color);
|
||||||
|
graphics.setFont(Font.font("Arial", 40)); // TODO different font and size
|
||||||
|
graphics.fillText(String.valueOf(player), x + width, y + height);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void drawDot(Color color, int cell) {
|
||||||
|
final float x = cells[cell].x() + gapSize;
|
||||||
|
final float y = cells[cell].y() + gapSize;
|
||||||
|
|
||||||
|
final float width = cells[cell].width() - gapSize * 2;
|
||||||
|
final float height = cells[cell].height() - gapSize * 2;
|
||||||
|
|
||||||
|
graphics.setFill(color);
|
||||||
|
graphics.fillOval(x, y, width, height);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void drawInnerDot(Color color, int cell, boolean slightlyBigger) {
|
||||||
|
final float x = cells[cell].x() + gapSize;
|
||||||
|
final float y = cells[cell].y() + gapSize;
|
||||||
|
|
||||||
|
float multiplier = slightlyBigger?1.4f:1.5f;
|
||||||
|
|
||||||
|
final float width = (cells[cell].width() - gapSize * 2)/multiplier;
|
||||||
|
final float height = (cells[cell].height() - gapSize * 2)/multiplier;
|
||||||
|
|
||||||
|
float offset = slightlyBigger?5f:4f;
|
||||||
|
|
||||||
|
graphics.setFill(color);
|
||||||
|
graphics.fillOval(x + width/offset, y + height/offset, width, height);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void drawDotScaled(Color color, int cell, double scale) {
|
||||||
|
final float cx = cells[cell].x() + gapSize;
|
||||||
|
final float cy = cells[cell].y() + gapSize;
|
||||||
|
|
||||||
|
final float fullWidth = cells[cell].width() - gapSize * 2;
|
||||||
|
final float height = cells[cell].height() - gapSize * 2;
|
||||||
|
|
||||||
|
final float scaledWidth = (float)(fullWidth * scale);
|
||||||
|
final float offsetX = (fullWidth - scaledWidth) / 2;
|
||||||
|
|
||||||
|
graphics.setFill(color);
|
||||||
|
graphics.fillOval(cx + offsetX, cy, scaledWidth, height);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Timeline flipDot(Color fromColor, Color toColor, int cell) {
|
||||||
|
final int steps = 60;
|
||||||
|
final long duration = 250;
|
||||||
|
final double interval = duration / (double) steps;
|
||||||
|
|
||||||
|
final Timeline timeline = new Timeline();
|
||||||
|
|
||||||
|
for (int i = 0; i <= steps; i++) {
|
||||||
|
final double t = i / (double) steps;
|
||||||
|
final KeyFrame keyFrame = new KeyFrame(Duration.millis(i * interval),
|
||||||
|
_ -> {
|
||||||
|
clear(cell);
|
||||||
|
|
||||||
|
final double scale = t <= 0.5 ? 1 - 2 * t : 2 * t - 1;
|
||||||
|
final Color currentColor = t < 0.5 ? fromColor : toColor;
|
||||||
|
|
||||||
|
drawDotScaled(currentColor, cell, scale);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
timeline.getKeyFrames().add(keyFrame);
|
||||||
|
}
|
||||||
|
|
||||||
|
return timeline;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Canvas getCanvas() {
|
||||||
|
return canvas;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
package org.toop.app.canvas;
|
|
||||||
|
|
||||||
import javafx.scene.paint.Color;
|
|
||||||
import org.toop.framework.gameFramework.model.game.AbstractGame;
|
|
||||||
|
|
||||||
import java.util.function.Consumer;
|
|
||||||
|
|
||||||
public class Connect4Canvas extends GameCanvas {
|
|
||||||
public Connect4Canvas(Color color, int width, int height, Consumer<Integer> onCellClicked) {
|
|
||||||
super(color, Color.TRANSPARENT, width, height, 7, 6, 10, true, onCellClicked,null);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void drawPlayerHover(int player, int move, AbstractGame game) {
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
package org.toop.app.canvas;
|
package org.toop.app.canvas;
|
||||||
|
|
||||||
import org.toop.framework.gameFramework.model.game.AbstractGame;
|
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||||
|
|
||||||
public interface DrawPlayerHover {
|
public interface DrawPlayerHover {
|
||||||
void drawPlayerHover(int player, int move, AbstractGame game);
|
void drawPlayerHover(int player, int move, TurnBasedGame game);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,237 +1,9 @@
|
|||||||
package org.toop.app.canvas;
|
package org.toop.app.canvas;
|
||||||
|
|
||||||
import javafx.animation.KeyFrame;
|
|
||||||
import javafx.animation.Timeline;
|
|
||||||
import javafx.scene.canvas.Canvas;
|
import javafx.scene.canvas.Canvas;
|
||||||
import javafx.scene.canvas.GraphicsContext;
|
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||||
import javafx.scene.input.MouseButton;
|
|
||||||
import javafx.scene.paint.Color;
|
|
||||||
import javafx.scene.text.Font;
|
|
||||||
import javafx.util.Duration;
|
|
||||||
import org.toop.framework.gameFramework.model.game.AbstractGame;
|
|
||||||
|
|
||||||
import java.util.function.Consumer;
|
public interface GameCanvas {
|
||||||
|
Canvas getCanvas();
|
||||||
public abstract class GameCanvas<T extends AbstractGame> implements DrawPlayerMove, DrawPlayerHover {
|
void redraw(TurnBasedGame gameCopy);
|
||||||
protected record Cell(float x, float y, float width, float height) {
|
|
||||||
public boolean isInside(double x, double y) {
|
|
||||||
return x >= this.x && x <= this.x + width &&
|
|
||||||
y >= this.y && y <= this.y + height;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
protected final Canvas canvas;
|
|
||||||
protected final GraphicsContext graphics;
|
|
||||||
|
|
||||||
protected final Color color;
|
|
||||||
protected final Color backgroundColor;
|
|
||||||
|
|
||||||
protected final int width;
|
|
||||||
protected final int height;
|
|
||||||
|
|
||||||
protected final int rowSize;
|
|
||||||
protected final int columnSize;
|
|
||||||
|
|
||||||
protected final int gapSize;
|
|
||||||
protected final boolean edges;
|
|
||||||
|
|
||||||
protected final Cell[] cells;
|
|
||||||
|
|
||||||
private Consumer<Integer> onCellCLicked;
|
|
||||||
|
|
||||||
public void setOnCellClicked(Consumer<Integer> onClick) {
|
|
||||||
this.onCellCLicked = onClick;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected GameCanvas(Color color, Color backgroundColor, int width, int height, int rowSize, int columnSize, int gapSize, boolean edges, Consumer<Integer> onCellClicked, Consumer<Integer> newCellEntered) {
|
|
||||||
canvas = new Canvas(width, height);
|
|
||||||
graphics = canvas.getGraphicsContext2D();
|
|
||||||
|
|
||||||
this.onCellCLicked = onCellClicked;
|
|
||||||
|
|
||||||
this.color = color;
|
|
||||||
this.backgroundColor = backgroundColor;
|
|
||||||
|
|
||||||
this.width = width;
|
|
||||||
this.height = height;
|
|
||||||
|
|
||||||
this.rowSize = rowSize;
|
|
||||||
this.columnSize = columnSize;
|
|
||||||
|
|
||||||
this.gapSize = gapSize;
|
|
||||||
this.edges = edges;
|
|
||||||
|
|
||||||
cells = new Cell[rowSize * columnSize];
|
|
||||||
|
|
||||||
final float cellWidth = ((float) width - gapSize * rowSize - gapSize) / rowSize;
|
|
||||||
final float cellHeight = ((float) height - gapSize * columnSize - gapSize) / columnSize;
|
|
||||||
|
|
||||||
for (int y = 0; y < columnSize; y++) {
|
|
||||||
final float startY = y * cellHeight + y * gapSize + gapSize;
|
|
||||||
|
|
||||||
for (int x = 0; x < rowSize; x++) {
|
|
||||||
final float startX = x * cellWidth + x * gapSize + gapSize;
|
|
||||||
cells[x + y * rowSize] = new Cell(startX, startY, cellWidth, cellHeight);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
canvas.setOnMouseClicked(event -> {
|
|
||||||
if (event.getButton() != MouseButton.PRIMARY) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
final int column = (int) ((event.getX() / this.width) * rowSize);
|
|
||||||
final int row = (int) ((event.getY() / this.height) * columnSize);
|
|
||||||
|
|
||||||
final Cell cell = cells[column + row * rowSize];
|
|
||||||
|
|
||||||
if (cell.isInside(event.getX(), event.getY())) {
|
|
||||||
event.consume();
|
|
||||||
this.onCellCLicked.accept(column + row * rowSize);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
render();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void render() {
|
|
||||||
graphics.setFill(backgroundColor);
|
|
||||||
graphics.fillRect(0, 0, width, height);
|
|
||||||
|
|
||||||
graphics.setFill(color);
|
|
||||||
|
|
||||||
for (int x = 0; x < rowSize - 1; x++) {
|
|
||||||
final float start = cells[x].x + cells[x].width;
|
|
||||||
graphics.fillRect(start, gapSize, gapSize, height - gapSize * 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
for (int y = 0; y < columnSize - 1; y++) {
|
|
||||||
final float start = cells[y * rowSize].y + cells[y * rowSize].height;
|
|
||||||
graphics.fillRect(gapSize, start, width - gapSize * 2, gapSize);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (edges) {
|
|
||||||
graphics.fillRect(0, 0, width, gapSize);
|
|
||||||
graphics.fillRect(0, 0, gapSize, height);
|
|
||||||
|
|
||||||
graphics.fillRect(width - gapSize, 0, gapSize, height);
|
|
||||||
graphics.fillRect(0, height - gapSize, width, gapSize);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void fill(Color color, int cell) {
|
|
||||||
final float x = cells[cell].x();
|
|
||||||
final float y = cells[cell].y();
|
|
||||||
|
|
||||||
final float width = cells[cell].width();
|
|
||||||
final float height = cells[cell].height();
|
|
||||||
|
|
||||||
graphics.setFill(color);
|
|
||||||
graphics.fillRect(x, y, width, height);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void clear(int cell) {
|
|
||||||
final float x = cells[cell].x();
|
|
||||||
final float y = cells[cell].y();
|
|
||||||
|
|
||||||
final float width = cells[cell].width();
|
|
||||||
final float height = cells[cell].height();
|
|
||||||
|
|
||||||
graphics.clearRect(x, y, width, height);
|
|
||||||
|
|
||||||
graphics.setFill(backgroundColor);
|
|
||||||
graphics.fillRect(x, y, width, height);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void clearAll() {
|
|
||||||
for (int i = 0; i < cells.length; i++) {
|
|
||||||
clear(i);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void drawPlayerMove(int player, int move) {
|
|
||||||
final float x = cells[move].x() + gapSize;
|
|
||||||
final float y = cells[move].y() + gapSize;
|
|
||||||
|
|
||||||
final float width = cells[move].width() - gapSize * 2;
|
|
||||||
final float height = cells[move].height() - gapSize * 2;
|
|
||||||
|
|
||||||
graphics.setFill(color);
|
|
||||||
graphics.setFont(Font.font("Arial", 40)); // TODO different font and size
|
|
||||||
graphics.fillText(String.valueOf(player), x + width, y + height);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void drawDot(Color color, int cell) {
|
|
||||||
final float x = cells[cell].x() + gapSize;
|
|
||||||
final float y = cells[cell].y() + gapSize;
|
|
||||||
|
|
||||||
final float width = cells[cell].width() - gapSize * 2;
|
|
||||||
final float height = cells[cell].height() - gapSize * 2;
|
|
||||||
|
|
||||||
graphics.setFill(color);
|
|
||||||
graphics.fillOval(x, y, width, height);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void drawInnerDot(Color color, int cell, boolean slightlyBigger) {
|
|
||||||
final float x = cells[cell].x() + gapSize;
|
|
||||||
final float y = cells[cell].y() + gapSize;
|
|
||||||
|
|
||||||
float multiplier = slightlyBigger?1.4f:1.5f;
|
|
||||||
|
|
||||||
final float width = (cells[cell].width() - gapSize * 2)/multiplier;
|
|
||||||
final float height = (cells[cell].height() - gapSize * 2)/multiplier;
|
|
||||||
|
|
||||||
float offset = slightlyBigger?5f:4f;
|
|
||||||
|
|
||||||
graphics.setFill(color);
|
|
||||||
graphics.fillOval(x + width/offset, y + height/offset, width, height);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void drawDotScaled(Color color, int cell, double scale) {
|
|
||||||
final float cx = cells[cell].x() + gapSize;
|
|
||||||
final float cy = cells[cell].y() + gapSize;
|
|
||||||
|
|
||||||
final float fullWidth = cells[cell].width() - gapSize * 2;
|
|
||||||
final float height = cells[cell].height() - gapSize * 2;
|
|
||||||
|
|
||||||
final float scaledWidth = (float)(fullWidth * scale);
|
|
||||||
final float offsetX = (fullWidth - scaledWidth) / 2;
|
|
||||||
|
|
||||||
graphics.setFill(color);
|
|
||||||
graphics.fillOval(cx + offsetX, cy, scaledWidth, height);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Timeline flipDot(Color fromColor, Color toColor, int cell) {
|
|
||||||
final int steps = 60;
|
|
||||||
final long duration = 250;
|
|
||||||
final double interval = duration / (double) steps;
|
|
||||||
|
|
||||||
final Timeline timeline = new Timeline();
|
|
||||||
|
|
||||||
for (int i = 0; i <= steps; i++) {
|
|
||||||
final double t = i / (double) steps;
|
|
||||||
final KeyFrame keyFrame = new KeyFrame(Duration.millis(i * interval),
|
|
||||||
_ -> {
|
|
||||||
clear(cell);
|
|
||||||
|
|
||||||
final double scale = t <= 0.5 ? 1 - 2 * t : 2 * t - 1;
|
|
||||||
final Color currentColor = t < 0.5 ? fromColor : toColor;
|
|
||||||
|
|
||||||
drawDotScaled(currentColor, cell, scale);
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
timeline.getKeyFrames().add(keyFrame);
|
|
||||||
}
|
|
||||||
|
|
||||||
return timeline;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Canvas getCanvas() {
|
|
||||||
return canvas;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
68
app/src/main/java/org/toop/app/canvas/ReversiBitCanvas.java
Normal file
68
app/src/main/java/org/toop/app/canvas/ReversiBitCanvas.java
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
package org.toop.app.canvas;
|
||||||
|
|
||||||
|
import javafx.scene.paint.Color;
|
||||||
|
import org.toop.app.App;
|
||||||
|
import org.toop.framework.game.games.reversi.BitboardReversi;
|
||||||
|
import org.toop.framework.game.players.LocalPlayer;
|
||||||
|
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||||
|
|
||||||
|
public class ReversiBitCanvas extends BitGameCanvas {
|
||||||
|
private TurnBasedGame gameCopy;
|
||||||
|
private int previousCell;
|
||||||
|
public ReversiBitCanvas() {
|
||||||
|
super(Color.GRAY, new Color(0f, 0.4f, 0.2f, 1f), (App.getHeight() / 4) * 3, (App.getHeight() / 4) * 3, 8, 8, 5, true);
|
||||||
|
canvas.setOnMouseMoved(event -> {
|
||||||
|
double mouseX = event.getX();
|
||||||
|
double mouseY = event.getY();
|
||||||
|
int cellId = -1;
|
||||||
|
|
||||||
|
BitGameCanvas.Cell hovered = null;
|
||||||
|
for (BitGameCanvas.Cell cell : cells) {
|
||||||
|
if (cell.isInside(mouseX, mouseY)) {
|
||||||
|
hovered = cell;
|
||||||
|
cellId = turnCoordsIntoCellId(mouseX, mouseY);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (hovered != null) {
|
||||||
|
checkHoverDots(hovered, cellId);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private int turnCoordsIntoCellId(double x, double y) {
|
||||||
|
final int column = (int) ((x / this.width) * rowSize);
|
||||||
|
final int row = (int) ((y / this.height) * columnSize);
|
||||||
|
return column + row * rowSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void redraw(TurnBasedGame gameCopy) {
|
||||||
|
this.gameCopy = gameCopy;
|
||||||
|
clearAll();
|
||||||
|
long[] board = gameCopy.getBoard();
|
||||||
|
loopOverBoard(board[0], (i) -> drawDot(Color.WHITE, 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));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,96 +0,0 @@
|
|||||||
package org.toop.app.canvas;
|
|
||||||
|
|
||||||
import javafx.scene.paint.Color;
|
|
||||||
import org.toop.framework.gameFramework.model.game.AbstractGame;
|
|
||||||
import org.toop.game.Move;
|
|
||||||
import org.toop.game.games.reversi.ReversiR;
|
|
||||||
|
|
||||||
import java.util.concurrent.atomic.AtomicReference;
|
|
||||||
import java.util.function.Consumer;
|
|
||||||
|
|
||||||
public final class ReversiCanvas extends GameCanvas<ReversiR> {
|
|
||||||
private Move[] currentlyHighlightedMoves = null;
|
|
||||||
public ReversiCanvas(Color color, int width, int height, Consumer<Integer> onCellClicked, Consumer<Integer> newCellEntered) {
|
|
||||||
super(color, new Color(0f,0.4f,0.2f,1f), width, height, 8, 8, 5, true, onCellClicked, newCellEntered);
|
|
||||||
drawStartingDots();
|
|
||||||
|
|
||||||
final AtomicReference<Cell> lastHoveredCell = new AtomicReference<>(null);
|
|
||||||
|
|
||||||
canvas.setOnMouseMoved(event -> {
|
|
||||||
double mouseX = event.getX();
|
|
||||||
double mouseY = event.getY();
|
|
||||||
int cellId = -1;
|
|
||||||
|
|
||||||
Cell hovered = null;
|
|
||||||
for (Cell cell : cells) {
|
|
||||||
if (cell.isInside(mouseX, mouseY)) {
|
|
||||||
hovered = cell;
|
|
||||||
cellId = turnCoordsIntoCellId(mouseX, mouseY);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Cell previous = lastHoveredCell.get();
|
|
||||||
|
|
||||||
if (hovered != previous) {
|
|
||||||
lastHoveredCell.set(hovered);
|
|
||||||
newCellEntered.accept(cellId);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setCurrentlyHighlightedMovesNull() {
|
|
||||||
currentlyHighlightedMoves = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void drawHighlightDots(Move[] moves){
|
|
||||||
if (currentlyHighlightedMoves != null){
|
|
||||||
for (final Move move : currentlyHighlightedMoves){
|
|
||||||
Color color = move.value() == 'W'? Color.BLACK: Color.WHITE;
|
|
||||||
drawInnerDot(color, move.position(), true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
currentlyHighlightedMoves = moves;
|
|
||||||
if (moves != null) {
|
|
||||||
for (Move move : moves) {
|
|
||||||
Color color = move.value() == 'B' ? Color.BLACK : Color.WHITE;
|
|
||||||
drawInnerDot(color, move.position(), false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private int turnCoordsIntoCellId(double x, double y) {
|
|
||||||
final int column = (int) ((x / this.width) * rowSize);
|
|
||||||
final int row = (int) ((y / this.height) * columnSize);
|
|
||||||
return column + row * rowSize;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void drawStartingDots() {
|
|
||||||
drawDot(Color.BLACK, 28);
|
|
||||||
drawDot(Color.WHITE, 36);
|
|
||||||
drawDot(Color.BLACK, 35);
|
|
||||||
drawDot(Color.WHITE, 27);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void drawLegalPosition(int cell, char player) {
|
|
||||||
|
|
||||||
Color innerColor;
|
|
||||||
if (player == 'B') {
|
|
||||||
innerColor = new Color(0.0f, 0.0f, 0.0f, 0.6f);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
innerColor = new Color(1.0f, 1.0f, 1.0f, 0.75f);
|
|
||||||
}
|
|
||||||
drawInnerDot(innerColor, cell,false);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void drawPlayerMove(int player ,int move){
|
|
||||||
super.drawPlayerMove(player, move);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void drawPlayerHover(int player, int move, AbstractGame game) {
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
package org.toop.app.canvas;
|
||||||
|
|
||||||
|
import javafx.scene.paint.Color;
|
||||||
|
import org.toop.app.App;
|
||||||
|
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||||
|
|
||||||
|
public class TicTacToeBitCanvas extends BitGameCanvas{
|
||||||
|
public TicTacToeBitCanvas() {
|
||||||
|
super(
|
||||||
|
Color.GRAY,
|
||||||
|
Color.TRANSPARENT,
|
||||||
|
(App.getHeight() / 4) * 3,
|
||||||
|
(App.getHeight() / 4) * 3,
|
||||||
|
3,
|
||||||
|
3,
|
||||||
|
30,
|
||||||
|
false
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void redraw(TurnBasedGame gameCopy) {
|
||||||
|
clearAll();
|
||||||
|
drawMoves(gameCopy.getBoard());
|
||||||
|
}
|
||||||
|
|
||||||
|
private void drawMoves(long[] gameBoard){
|
||||||
|
loopOverBoard(gameBoard[0], (i) -> drawX(Color.RED, i));
|
||||||
|
loopOverBoard(gameBoard[1], (i) -> drawO(Color.BLUE, i));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public void drawX(Color color, int cell) {
|
||||||
|
graphics.setStroke(color);
|
||||||
|
graphics.setLineWidth(gapSize);
|
||||||
|
|
||||||
|
final float x = cells[cell].x() + gapSize;
|
||||||
|
final float y = cells[cell].y() + gapSize;
|
||||||
|
|
||||||
|
final float width = cells[cell].width() - gapSize * 2;
|
||||||
|
final float height = cells[cell].height() - gapSize * 2;
|
||||||
|
|
||||||
|
graphics.strokeLine(x, y, x + width, y + height);
|
||||||
|
graphics.strokeLine(x + width, y, x, y + height);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void drawO(Color color, int cell) {
|
||||||
|
graphics.setStroke(color);
|
||||||
|
graphics.setLineWidth(gapSize);
|
||||||
|
|
||||||
|
final float x = cells[cell].x() + gapSize;
|
||||||
|
final float y = cells[cell].y() + gapSize;
|
||||||
|
|
||||||
|
final float width = cells[cell].width() - gapSize * 2;
|
||||||
|
final float height = cells[cell].height() - gapSize * 2;
|
||||||
|
|
||||||
|
graphics.strokeOval(x, y, width, height);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
package org.toop.app.canvas;
|
|
||||||
|
|
||||||
import javafx.scene.paint.Color;
|
|
||||||
import org.toop.framework.gameFramework.model.game.AbstractGame;
|
|
||||||
import org.toop.game.games.tictactoe.TicTacToeR;
|
|
||||||
|
|
||||||
import java.util.function.Consumer;
|
|
||||||
|
|
||||||
public final class TicTacToeCanvas extends GameCanvas<TicTacToeR> {
|
|
||||||
public TicTacToeCanvas(Color color, int width, int height, Consumer<Integer> onCellClicked) {
|
|
||||||
super(color, Color.TRANSPARENT, width, height, 3, 3, 30, false, onCellClicked,null);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void drawPlayerMove(int player, int move) {
|
|
||||||
switch (player) {
|
|
||||||
case 0 -> drawX(Color.RED, move);
|
|
||||||
case 1 -> drawO(Color.BLUE, move);
|
|
||||||
default -> super.drawPlayerMove(player, move);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void drawX(Color color, int cell) {
|
|
||||||
graphics.setStroke(color);
|
|
||||||
graphics.setLineWidth(gapSize);
|
|
||||||
|
|
||||||
final float x = cells[cell].x() + gapSize;
|
|
||||||
final float y = cells[cell].y() + gapSize;
|
|
||||||
|
|
||||||
final float width = cells[cell].width() - gapSize * 2;
|
|
||||||
final float height = cells[cell].height() - gapSize * 2;
|
|
||||||
|
|
||||||
graphics.strokeLine(x, y, x + width, y + height);
|
|
||||||
graphics.strokeLine(x + width, y, x, y + height);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void drawO(Color color, int cell) {
|
|
||||||
graphics.setStroke(color);
|
|
||||||
graphics.setLineWidth(gapSize);
|
|
||||||
|
|
||||||
final float x = cells[cell].x() + gapSize;
|
|
||||||
final float y = cells[cell].y() + gapSize;
|
|
||||||
|
|
||||||
final float width = cells[cell].width() - gapSize * 2;
|
|
||||||
final float height = cells[cell].height() - gapSize * 2;
|
|
||||||
|
|
||||||
graphics.strokeOval(x, y, width, height);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void drawPlayerHover(int player, int move, AbstractGame game) {
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,127 +0,0 @@
|
|||||||
package org.toop.app.gameControllers;
|
|
||||||
|
|
||||||
import org.apache.logging.log4j.LogManager;
|
|
||||||
import org.apache.logging.log4j.Logger;
|
|
||||||
import org.toop.framework.gameFramework.controller.UpdatesGameUI;
|
|
||||||
import org.toop.framework.gameFramework.view.GUIEvents;
|
|
||||||
import org.toop.app.canvas.GameCanvas;
|
|
||||||
import org.toop.framework.networking.events.NetworkEvents;
|
|
||||||
import org.toop.framework.gameFramework.model.game.threadBehaviour.ThreadBehaviour;
|
|
||||||
import org.toop.app.widget.view.GameView;
|
|
||||||
import org.toop.framework.eventbus.EventFlow;
|
|
||||||
import org.toop.game.gameThreads.OnlineThreadBehaviour;
|
|
||||||
import org.toop.framework.gameFramework.model.game.AbstractGame;
|
|
||||||
import org.toop.framework.gameFramework.model.game.SupportsOnlinePlay;
|
|
||||||
import org.toop.framework.gameFramework.model.player.Player;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.function.Consumer;
|
|
||||||
|
|
||||||
public abstract class AbstractGameController<T extends AbstractGame<T>> implements UpdatesGameUI, ThreadBehaviour<T> {
|
|
||||||
protected final EventFlow eventFlow = new EventFlow();
|
|
||||||
|
|
||||||
protected final List<Consumer<?>> listeners = new ArrayList<>();
|
|
||||||
|
|
||||||
// Logger for logging ofcourse
|
|
||||||
protected final Logger logger = LogManager.getLogger(this.getClass());
|
|
||||||
|
|
||||||
// Reference to primary view
|
|
||||||
protected final GameView primary;
|
|
||||||
|
|
||||||
// Reference to game canvas
|
|
||||||
protected final GameCanvas<T> canvas;
|
|
||||||
|
|
||||||
private final Player<T>[] players; // List of players, can't be changed.
|
|
||||||
protected final T game; // Reference to game instance
|
|
||||||
private final ThreadBehaviour<T> gameThreadBehaviour;
|
|
||||||
|
|
||||||
// TODO: Change gameType to automatically happen with either dependency injection or something else.
|
|
||||||
// TODO: Make visualisation of moves a behaviour.
|
|
||||||
protected AbstractGameController(GameCanvas<T> canvas, Player<T>[] players, T game, ThreadBehaviour<T> gameThreadBehaviour, String gameType) {
|
|
||||||
logger.info("Creating AbstractGameController");
|
|
||||||
// Make sure player list matches expected size
|
|
||||||
if (players.length != game.getPlayerCount()){
|
|
||||||
logger.error("Player count mismatch");
|
|
||||||
throw new IllegalArgumentException("players and game's players must have same length");
|
|
||||||
}
|
|
||||||
|
|
||||||
this.canvas = canvas;
|
|
||||||
this.players = players;
|
|
||||||
this.game = game;
|
|
||||||
this.gameThreadBehaviour = gameThreadBehaviour;
|
|
||||||
|
|
||||||
primary = new GameView(null, null, null, gameType);
|
|
||||||
addListeners();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void start(){
|
|
||||||
logger.info("Starting GameManager");
|
|
||||||
gameThreadBehaviour.start();;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void stop(){
|
|
||||||
logger.info("Stopping GameManager");
|
|
||||||
removeListeners();
|
|
||||||
gameThreadBehaviour.stop();
|
|
||||||
}
|
|
||||||
|
|
||||||
public Player<T> getCurrentPlayer(){
|
|
||||||
return game.getPlayer(getCurrentPlayerIndex());
|
|
||||||
};
|
|
||||||
|
|
||||||
public int getCurrentPlayerIndex(){
|
|
||||||
return game.getCurrentTurn();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void addListeners(){
|
|
||||||
eventFlow
|
|
||||||
.listen(GUIEvents.RefreshGameCanvas.class, this::onUpdateGameUI, false)
|
|
||||||
.listen(GUIEvents.GameEnded.class, this::onGameFinish, false);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void removeListeners(){
|
|
||||||
eventFlow.unsubscribeAll();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void onUpdateGameUI(GUIEvents.RefreshGameCanvas event){
|
|
||||||
this.updateUI();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void onGameFinish(GUIEvents.GameEnded event){
|
|
||||||
logger.info("Game Finished");
|
|
||||||
String name = event.winner() == -1 ? null : getPlayer(event.winner()).getName();
|
|
||||||
primary.gameOver(event.winOrTie(), name);
|
|
||||||
stop();
|
|
||||||
}
|
|
||||||
|
|
||||||
public Player<T> getPlayer(int player){
|
|
||||||
if (player < 0 || player >= players.length){
|
|
||||||
logger.error("Invalid player index");
|
|
||||||
throw new IllegalArgumentException("player out of range");
|
|
||||||
}
|
|
||||||
return players[player];
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean isOnline(){
|
|
||||||
return this.gameThreadBehaviour instanceof SupportsOnlinePlay;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void onYourTurn(NetworkEvents.YourTurnResponse event){
|
|
||||||
if (isOnline()){
|
|
||||||
((OnlineThreadBehaviour<T>) this.gameThreadBehaviour).onYourTurn(event);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void onMoveReceived(NetworkEvents.GameMoveResponse event){
|
|
||||||
if (isOnline()){
|
|
||||||
((OnlineThreadBehaviour<T>) this.gameThreadBehaviour).onMoveReceived(event);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void gameFinished(NetworkEvents.GameResultResponse event){
|
|
||||||
if (isOnline()){
|
|
||||||
((OnlineThreadBehaviour<T>) this.gameThreadBehaviour).gameFinished(event);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
package org.toop.app.gameControllers;
|
||||||
|
|
||||||
|
import javafx.application.Platform;
|
||||||
|
import javafx.geometry.Pos;
|
||||||
|
import org.apache.logging.log4j.LogManager;
|
||||||
|
import org.apache.logging.log4j.Logger;
|
||||||
|
import org.toop.app.canvas.GameCanvas;
|
||||||
|
import org.toop.app.canvas.ReversiBitCanvas;
|
||||||
|
import org.toop.app.widget.WidgetContainer;
|
||||||
|
import org.toop.app.widget.view.GameView;
|
||||||
|
import org.toop.framework.eventbus.EventFlow;
|
||||||
|
import org.toop.framework.eventbus.GlobalEventBus;
|
||||||
|
import org.toop.framework.gameFramework.controller.GameController;
|
||||||
|
import org.toop.framework.gameFramework.model.game.threadBehaviour.SupportsOnlinePlay;
|
||||||
|
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||||
|
import org.toop.framework.gameFramework.model.game.threadBehaviour.ThreadBehaviour;
|
||||||
|
import org.toop.framework.gameFramework.model.player.Player;
|
||||||
|
import org.toop.framework.gameFramework.view.GUIEvents;
|
||||||
|
import org.toop.framework.networking.connection.events.NetworkEvents;
|
||||||
|
import org.toop.framework.game.players.LocalPlayer;
|
||||||
|
|
||||||
|
public class GenericGameController implements GameController {
|
||||||
|
protected final EventFlow eventFlow = new EventFlow();
|
||||||
|
|
||||||
|
// Logger for logging
|
||||||
|
protected final Logger logger = LogManager.getLogger(this.getClass());
|
||||||
|
|
||||||
|
// Reference to gameView view
|
||||||
|
protected final GameView gameView;
|
||||||
|
|
||||||
|
// Reference to game canvas
|
||||||
|
protected final GameCanvas canvas;
|
||||||
|
|
||||||
|
protected final TurnBasedGame game; // Reference to game instance
|
||||||
|
private final ThreadBehaviour gameThreadBehaviour;
|
||||||
|
|
||||||
|
// TODO: Change gameType to automatically happen with either dependency injection or something else.
|
||||||
|
public GenericGameController(GameCanvas canvas, TurnBasedGame game, ThreadBehaviour gameThreadBehaviour, String gameType) {
|
||||||
|
logger.info("Creating: {}", this.getClass());
|
||||||
|
|
||||||
|
this.canvas = canvas;
|
||||||
|
this.game = game;
|
||||||
|
this.gameThreadBehaviour = gameThreadBehaviour;
|
||||||
|
|
||||||
|
// Tell thread how to send moves
|
||||||
|
this.gameThreadBehaviour.setOnSendMove(
|
||||||
|
(id, m) -> GlobalEventBus.get().post(new NetworkEvents.SendMove(id, (short)translateMove(m)))
|
||||||
|
);
|
||||||
|
|
||||||
|
// Tell thread how to update UI
|
||||||
|
this.gameThreadBehaviour.setOnUpdateUI(() -> Platform.runLater(this::updateUI));
|
||||||
|
|
||||||
|
// Change scene to game view
|
||||||
|
gameView = new GameView(null, null, null, gameType);
|
||||||
|
gameView.add(Pos.CENTER, canvas.getCanvas());
|
||||||
|
WidgetContainer.getCurrentView().transitionNext(gameView, true);
|
||||||
|
|
||||||
|
// Listen to updates
|
||||||
|
logger.info("Game controller started listening");
|
||||||
|
eventFlow
|
||||||
|
.listen(GUIEvents.GameEnded.class, this::onGameFinish, 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(){
|
||||||
|
logger.info("Starting GameManager");
|
||||||
|
updateUI();
|
||||||
|
gameThreadBehaviour.start();
|
||||||
|
logger.info("GameManager started");
|
||||||
|
}
|
||||||
|
|
||||||
|
public void stop(){
|
||||||
|
logger.info("Stopping GameManager");
|
||||||
|
removeListeners();
|
||||||
|
gameThreadBehaviour.stop();
|
||||||
|
logger.info("GameManager stopped");
|
||||||
|
}
|
||||||
|
|
||||||
|
public Player getCurrentPlayer(){
|
||||||
|
return game.getPlayer(getCurrentPlayerIndex());
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getCurrentPlayerIndex(){
|
||||||
|
return game.getCurrentTurn();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected long translateMove(int move){
|
||||||
|
return 1L << move;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected int translateMove(long move){
|
||||||
|
return Long.numberOfTrailingZeros(move);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void removeListeners(){
|
||||||
|
eventFlow.unsubscribeAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void onGameFinish(GUIEvents.GameEnded event){
|
||||||
|
logger.info("OnlineTurnBasedGame Finished");
|
||||||
|
String name = event.winner() == -1 ? null : getPlayer(event.winner()).getName();
|
||||||
|
gameView.gameOver(event.winOrTie(), name);
|
||||||
|
stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Player getPlayer(int player){
|
||||||
|
if (player < 0 || player > game.getPlayerCount()-1){ // TODO: Make game turn player count
|
||||||
|
logger.error("Invalid player index");
|
||||||
|
throw new IllegalArgumentException("player out of range");
|
||||||
|
}
|
||||||
|
return game.getPlayer(player);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isOnline(){
|
||||||
|
return this.gameThreadBehaviour instanceof SupportsOnlinePlay;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void onYourTurn(NetworkEvents.YourTurnResponse event){
|
||||||
|
if (isOnline()){
|
||||||
|
((SupportsOnlinePlay) this.gameThreadBehaviour).onYourTurn(event.clientId());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void onMoveReceived(NetworkEvents.GameMoveResponse event){
|
||||||
|
if (isOnline()){
|
||||||
|
((SupportsOnlinePlay) this.gameThreadBehaviour).onMoveReceived(
|
||||||
|
translateMove(Integer.parseInt(event.move())));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void gameFinished(NetworkEvents.GameResultResponse event){
|
||||||
|
if (isOnline()){
|
||||||
|
((SupportsOnlinePlay) this.gameThreadBehaviour).gameFinished(event.condition());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void sendMove(long clientId, long move) {
|
||||||
|
new EventFlow().addPostEvent(NetworkEvents.SendMove.class, clientId, (short) Long.numberOfTrailingZeros(move)).asyncPostEvent();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void updateUI() {
|
||||||
|
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 (getCurrentPlayer() instanceof LocalPlayer && gameType.equals("Reversi")){
|
||||||
|
((ReversiBitCanvas)canvas).drawLegalDots(gameCopy);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package org.toop.app.gameControllers;
|
||||||
|
|
||||||
|
import org.toop.app.canvas.ReversiBitCanvas;
|
||||||
|
import org.toop.framework.gameFramework.model.game.threadBehaviour.ThreadBehaviour;
|
||||||
|
import org.toop.framework.gameFramework.model.player.Player;
|
||||||
|
import org.toop.framework.game.gameThreads.LocalThreadBehaviour;
|
||||||
|
import org.toop.framework.game.gameThreads.OnlineThreadBehaviour;
|
||||||
|
import org.toop.framework.game.games.reversi.BitboardReversi;
|
||||||
|
import org.toop.framework.game.players.OnlinePlayer;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
public class ReversiBitController extends GenericGameController {
|
||||||
|
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);
|
||||||
|
|
||||||
|
super(new ReversiBitCanvas(), game, thread, "Reversi");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,138 +0,0 @@
|
|||||||
package org.toop.app.gameControllers;
|
|
||||||
|
|
||||||
import javafx.animation.SequentialTransition;
|
|
||||||
import javafx.geometry.Pos;
|
|
||||||
import javafx.scene.paint.Color;
|
|
||||||
import org.toop.app.App;
|
|
||||||
import org.toop.app.canvas.ReversiCanvas;
|
|
||||||
import org.toop.app.widget.WidgetContainer;
|
|
||||||
import org.toop.framework.eventbus.EventFlow;
|
|
||||||
import org.toop.framework.gameFramework.model.game.AbstractGame;
|
|
||||||
import org.toop.framework.gameFramework.view.GUIEvents;
|
|
||||||
import org.toop.game.gameThreads.LocalFixedRateThreadBehaviour;
|
|
||||||
import org.toop.game.gameThreads.OnlineThreadBehaviour;
|
|
||||||
import org.toop.game.players.LocalPlayer;
|
|
||||||
import org.toop.framework.gameFramework.model.player.Player;
|
|
||||||
import org.toop.game.games.reversi.ReversiR;
|
|
||||||
|
|
||||||
public class ReversiController extends AbstractGameController<ReversiR> {
|
|
||||||
// TODO: Refactor GUI update methods to follow designed system
|
|
||||||
public ReversiController(Player<ReversiR>[] players, boolean local) {
|
|
||||||
ReversiR ReversiR = new ReversiR(players);
|
|
||||||
super(
|
|
||||||
new ReversiCanvas(Color.GRAY, (App.getHeight() / 4) * 3, (App.getHeight() / 4) * 3,(c) -> {new EventFlow().addPostEvent(GUIEvents.PlayerAttemptedMove.class, c).postEvent();}, (c) -> {new EventFlow().addPostEvent(GUIEvents.PlayerMoveHovered.class, c).postEvent();}),
|
|
||||||
players,
|
|
||||||
ReversiR,
|
|
||||||
local ? new LocalFixedRateThreadBehaviour<>(ReversiR, players) : new OnlineThreadBehaviour<>(ReversiR, players), // TODO: Player order matters here, this won't work atm
|
|
||||||
"Reversi");
|
|
||||||
eventFlow.listen(GUIEvents.PlayerAttemptedMove.class, event -> {if (getCurrentPlayer() instanceof LocalPlayer lp){lp.setMove(event.move());}}, false);
|
|
||||||
eventFlow.listen(GUIEvents.PlayerMoveHovered.class, this::onHoverMove, false);
|
|
||||||
initUI();
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
private void onHoverMove(GUIEvents.PlayerMoveHovered event){
|
|
||||||
int cellEntered = event.move();
|
|
||||||
canvas.drawPlayerHover(-1, cellEntered, game);
|
|
||||||
/*// (information.players[game.getCurrentTurn()].isHuman) {
|
|
||||||
int[] legalMoves = game.getLegalMoves();
|
|
||||||
boolean isLegalMove = false;
|
|
||||||
for (int move : legalMoves) {
|
|
||||||
if (move == cellEntered){
|
|
||||||
isLegalMove = true;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (cellEntered >= 0){
|
|
||||||
int[] moves = null;
|
|
||||||
if (isLegalMove) {
|
|
||||||
moves = game.getFlipsForPotentialMove(
|
|
||||||
new Point(cellEntered%game.getColumnSize(),cellEntered/game.getRowSize()),
|
|
||||||
game.getCurrentPlayer());
|
|
||||||
}
|
|
||||||
canvas.drawHighlightDots(moves);
|
|
||||||
}
|
|
||||||
//}*/
|
|
||||||
}
|
|
||||||
|
|
||||||
public ReversiController(Player<ReversiR>[] players) {
|
|
||||||
this(players, true);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void updateCanvas(boolean animate) {
|
|
||||||
// Todo: this is very inefficient. still very fast but if the grid is bigger it might cause issues. improve.
|
|
||||||
canvas.clearAll();
|
|
||||||
|
|
||||||
for (int i = 0; i < game.getBoard().length; i++) {
|
|
||||||
if (game.getBoard()[i] == 0) {
|
|
||||||
canvas.drawDot(Color.WHITE, i);
|
|
||||||
} else if (game.getBoard()[i] == 1) {
|
|
||||||
canvas.drawDot(Color.BLACK, i);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
final int[] flipped = game.getMostRecentlyFlippedPieces();
|
|
||||||
|
|
||||||
final SequentialTransition animation = new SequentialTransition();
|
|
||||||
|
|
||||||
final Color fromColor = getCurrentPlayerIndex() == 0? Color.WHITE : Color.BLACK;
|
|
||||||
final Color toColor = getCurrentPlayerIndex() == 0? Color.BLACK : Color.WHITE;
|
|
||||||
|
|
||||||
if (animate && flipped != null) {
|
|
||||||
for (final int flip : flipped) {
|
|
||||||
canvas.clear(flip);
|
|
||||||
canvas.drawDot(fromColor, flip);
|
|
||||||
animation.getChildren().addFirst(canvas.flipDot(fromColor, toColor, flip));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
animation.setOnFinished(_ -> {
|
|
||||||
|
|
||||||
if (getCurrentPlayer() instanceof LocalPlayer) {
|
|
||||||
final int[] legalMoves = game.getLegalMoves();
|
|
||||||
|
|
||||||
for (final int legalMove : legalMoves) {
|
|
||||||
drawLegalPosition(legalMove, getCurrentPlayerIndex());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
animation.play();
|
|
||||||
primary.nextPlayer(true, getCurrentPlayer().getName(), game.getCurrentTurn() == 0 ? "X" : "O", getPlayer((game.getCurrentTurn() + 1) % 2).getName(), 'R');
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void updateUI() {
|
|
||||||
updateCanvas(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void drawLegalPosition(int cell, int player) {
|
|
||||||
Color innerColor;
|
|
||||||
if (player == 1) {
|
|
||||||
innerColor = new Color(0.0f, 0.0f, 0.0f, 0.6f);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
innerColor = new Color(1.0f, 1.0f, 1.0f, 0.75f);
|
|
||||||
}
|
|
||||||
canvas.drawInnerDot(innerColor, cell,false);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void initUI(){
|
|
||||||
primary.add(Pos.CENTER, canvas.getCanvas());
|
|
||||||
WidgetContainer.getCurrentView().transitionNext(primary, true);
|
|
||||||
updateCanvas(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void drawMoves(){
|
|
||||||
int[] board = game.getBoard();
|
|
||||||
|
|
||||||
// Draw each square
|
|
||||||
for (int i = 0; i < board.length; i++){
|
|
||||||
// If square isn't empty, draw player move
|
|
||||||
if (board[i] != AbstractGame.EMPTY){
|
|
||||||
canvas.drawPlayerMove(board[i], i);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package org.toop.app.gameControllers;
|
||||||
|
|
||||||
|
import org.toop.app.canvas.TicTacToeBitCanvas;
|
||||||
|
import org.toop.framework.gameFramework.model.game.threadBehaviour.ThreadBehaviour;
|
||||||
|
import org.toop.framework.gameFramework.model.player.Player;
|
||||||
|
import org.toop.framework.game.gameThreads.LocalThreadBehaviour;
|
||||||
|
import org.toop.framework.game.gameThreads.OnlineThreadBehaviour;
|
||||||
|
import org.toop.framework.game.games.tictactoe.BitboardTicTacToe;
|
||||||
|
import org.toop.framework.game.players.OnlinePlayer;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
public class TicTacToeBitController extends GenericGameController {
|
||||||
|
public TicTacToeBitController(Player[] players) {
|
||||||
|
BitboardTicTacToe game = new BitboardTicTacToe();
|
||||||
|
game.init(players);
|
||||||
|
|
||||||
|
ThreadBehaviour thread = Arrays.stream(players).anyMatch(e -> e instanceof OnlinePlayer) ?
|
||||||
|
new OnlineThreadBehaviour(game) : new LocalThreadBehaviour(game);
|
||||||
|
|
||||||
|
super(new TicTacToeBitCanvas(), game, thread, "TicTacToe");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,63 +0,0 @@
|
|||||||
package org.toop.app.gameControllers;
|
|
||||||
|
|
||||||
import javafx.geometry.Pos;
|
|
||||||
import javafx.scene.paint.Color;
|
|
||||||
import org.toop.app.App;
|
|
||||||
import org.toop.app.canvas.TicTacToeCanvas;
|
|
||||||
import org.toop.framework.eventbus.EventFlow;
|
|
||||||
import org.toop.framework.gameFramework.model.player.Player;
|
|
||||||
import org.toop.framework.gameFramework.view.GUIEvents;
|
|
||||||
import org.toop.framework.gameFramework.model.game.AbstractGame;
|
|
||||||
import org.toop.game.gameThreads.LocalThreadBehaviour;
|
|
||||||
import org.toop.game.gameThreads.OnlineThreadBehaviour;
|
|
||||||
import org.toop.game.players.LocalPlayer;
|
|
||||||
import org.toop.app.widget.WidgetContainer;
|
|
||||||
import org.toop.game.games.tictactoe.TicTacToeR;
|
|
||||||
|
|
||||||
public class TicTacToeController extends AbstractGameController<TicTacToeR> {
|
|
||||||
|
|
||||||
public TicTacToeController(Player<TicTacToeR>[] players, boolean local) {
|
|
||||||
TicTacToeR ticTacToeR = new TicTacToeR(players);
|
|
||||||
super(
|
|
||||||
new TicTacToeCanvas(Color.GRAY, (App.getHeight() / 4) * 3, (App.getHeight() / 4) * 3,(c) -> {new EventFlow().addPostEvent(GUIEvents.PlayerAttemptedMove.class, c).postEvent();}),
|
|
||||||
players,
|
|
||||||
ticTacToeR,
|
|
||||||
local ? new LocalThreadBehaviour(ticTacToeR, players) : new OnlineThreadBehaviour<>(ticTacToeR, players), // TODO: Player order matters here, this won't work atm
|
|
||||||
"TicTacToe");
|
|
||||||
|
|
||||||
initUI();
|
|
||||||
eventFlow.listen(GUIEvents.PlayerAttemptedMove.class, event -> {if (getCurrentPlayer() instanceof LocalPlayer lp){lp.setMove(event.move());}}, false);
|
|
||||||
//addListener(GlobalEventBus.subscribe(GUIEvents.PlayerAttemptedMove.class, event -> {if (getCurrentPlayer() instanceof LocalPlayer lp){lp.setMove(event.move());}}));
|
|
||||||
//new EventFlow().listen(GUIEvents.PlayerAttemptedMove.class, event -> {if (getCurrentPlayer() instanceof LocalPlayer lp){lp.setMove(event.move());}});
|
|
||||||
}
|
|
||||||
|
|
||||||
public TicTacToeController(Player<TicTacToeR>[] players) {
|
|
||||||
this(players, true);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void updateUI() {
|
|
||||||
canvas.clearAll();
|
|
||||||
// TODO: wtf is even this pile of poop temp fix
|
|
||||||
primary.nextPlayer(true, getCurrentPlayer().getName(), game.getCurrentTurn() == 0 ? "X" : "O", getPlayer((game.getCurrentTurn() + 1) % 2).getName(), 'T');
|
|
||||||
drawMoves();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void initUI(){
|
|
||||||
primary.add(Pos.CENTER, canvas.getCanvas());
|
|
||||||
WidgetContainer.getCurrentView().transitionNext(primary, true);
|
|
||||||
updateUI();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void drawMoves(){
|
|
||||||
int[] board = game.getBoard();
|
|
||||||
|
|
||||||
// Draw each square
|
|
||||||
for (int i = 0; i < board.length; i++){
|
|
||||||
// If square isn't empty, draw player move
|
|
||||||
if (board[i] != AbstractGame.EMPTY){
|
|
||||||
canvas.drawPlayerMove(board[i], i);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -18,13 +18,13 @@ public class EscapePopup extends PopupWidget {
|
|||||||
ViewWidget currentView = WidgetContainer.getCurrentView();
|
ViewWidget currentView = WidgetContainer.getCurrentView();
|
||||||
ArrayList<Node> nodes = new ArrayList<>();
|
ArrayList<Node> nodes = new ArrayList<>();
|
||||||
|
|
||||||
nodes.add(Primitive.button("Continue", this::hide, false)); // TODO, localize
|
nodes.add(Primitive.button("Continue", this::hide, false, false)); // TODO, localize
|
||||||
|
|
||||||
if (!(currentView.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);
|
||||||
nodes.add(opt);
|
nodes.add(opt);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -33,14 +33,14 @@ public class EscapePopup extends PopupWidget {
|
|||||||
if (tut != null) {
|
if (tut != null) {
|
||||||
nodes.add(Primitive.button("tutorialstring", () -> {
|
nodes.add(Primitive.button("tutorialstring", () -> {
|
||||||
WidgetContainer.getCurrentView().add(Pos.CENTER, tut);
|
WidgetContainer.getCurrentView().add(Pos.CENTER, tut);
|
||||||
}));
|
}, false));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
nodes.add(Primitive.button("quit", () -> {
|
nodes.add(Primitive.button("quit", () -> {
|
||||||
hide();
|
hide();
|
||||||
WidgetContainer.add(Pos.CENTER, new QuitPopup());
|
WidgetContainer.add(Pos.CENTER, new QuitPopup());
|
||||||
}));
|
}, false));
|
||||||
|
|
||||||
add(Pos.CENTER, Primitive.vbox(nodes.toArray(new Node[0])));
|
add(Pos.CENTER, Primitive.vbox(nodes.toArray(new Node[0])));
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ 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;
|
||||||
|
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -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;
|
||||||
@@ -40,7 +42,7 @@ public final class GameView extends ViewWidget {
|
|||||||
player2Icon = new Circle();
|
player2Icon = new Circle();
|
||||||
|
|
||||||
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;
|
||||||
}
|
}
|
||||||
@@ -48,7 +50,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);
|
||||||
@@ -94,7 +96,7 @@ public final class GameView extends ViewWidget {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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);
|
||||||
@@ -112,8 +114,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);
|
||||||
@@ -124,7 +126,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);
|
||||||
@@ -172,8 +174,8 @@ 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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2,20 +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.gameControllers.AbstractGameController;
|
import org.toop.app.gameControllers.ReversiBitController;
|
||||||
import org.toop.app.gameControllers.ReversiController;
|
import org.toop.app.gameControllers.TicTacToeBitController;
|
||||||
import org.toop.app.gameControllers.TicTacToeController;
|
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.tictactoe.TicTacToeAIRSleep;
|
import org.toop.framework.game.players.ArtificialPlayer;
|
||||||
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.game.games.reversi.ReversiAIR;
|
|
||||||
import org.toop.game.games.tictactoe.TicTacToeAIR;
|
|
||||||
import org.toop.app.widget.tutorial.*;
|
import org.toop.app.widget.tutorial.*;
|
||||||
|
import org.toop.framework.game.players.LocalPlayer;
|
||||||
|
import org.toop.game.players.ai.MCTSAI;
|
||||||
|
import org.toop.game.players.ai.MCTSAI2;
|
||||||
|
import org.toop.game.players.ai.MCTSAI3;
|
||||||
|
import org.toop.game.players.ai.MiniMaxAI;
|
||||||
import org.toop.local.AppContext;
|
import org.toop.local.AppContext;
|
||||||
|
|
||||||
import javafx.geometry.Pos;
|
import javafx.geometry.Pos;
|
||||||
@@ -26,7 +27,7 @@ import org.toop.local.AppSettings;
|
|||||||
public class LocalMultiplayerView extends ViewWidget {
|
public class LocalMultiplayerView extends ViewWidget {
|
||||||
private final GameInformation information;
|
private final GameInformation information;
|
||||||
|
|
||||||
private AbstractGameController<?> gameController;
|
private GameController gameController;
|
||||||
|
|
||||||
public LocalMultiplayerView(GameInformation.Type type) {
|
public LocalMultiplayerView(GameInformation.Type type) {
|
||||||
this(new GameInformation(type));
|
this(new GameInformation(type));
|
||||||
@@ -45,68 +46,69 @@ public class LocalMultiplayerView extends ViewWidget {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Fix this temporary ass way of setting the players (Only works for TicTacToe)
|
// TODO: Fix this temporary ass way of setting the players
|
||||||
Player[] players = new Player[2];
|
Player[] players = new Player[2];
|
||||||
|
|
||||||
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 TicTacToeAIRSleep(information.players[0].computerDifficulty, information.players[1].computerThinkTime), information.players[0].name);
|
players[0] = new ArtificialPlayer(new MCTSAI(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 TicTacToeAIRSleep(information.players[1].computerDifficulty, information.players[1].computerThinkTime), information.players[1].name);
|
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(
|
||||||
() -> new TicTacToeTutorialWidget(() -> {
|
() -> new TicTacToeTutorialWidget(() -> {
|
||||||
gameController = new TicTacToeController(players);
|
gameController = new TicTacToeBitController(players);
|
||||||
gameController.start();
|
gameController.start();
|
||||||
}),
|
}),
|
||||||
() -> Platform.runLater(() -> {
|
() -> Platform.runLater(() -> {
|
||||||
gameController = new TicTacToeController(players);
|
gameController = new TicTacToeBitController(players);
|
||||||
gameController.start();
|
gameController.start();
|
||||||
}),
|
}),
|
||||||
() -> AppSettings.getSettings().setFirstTTT(false)
|
() -> AppSettings.getSettings().setFirstTTT(false)
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
gameController = new TicTacToeController(players);
|
gameController = new TicTacToeBitController(players);
|
||||||
gameController.start();
|
gameController.start();
|
||||||
}
|
}
|
||||||
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 ReversiAIR(), information.players[0].name);
|
// players[0] = new ArtificialPlayer(new RandomAI<BitboardReversi>(), "Random AI");
|
||||||
|
players[0] = new ArtificialPlayer(new MCTSAI3(50), "MCTS V3 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 ReversiAIR(), information.players[1].name);
|
players[1] = new ArtificialPlayer(new MCTSAI(50), "MCTS V1 AI");
|
||||||
}
|
}
|
||||||
if (AppSettings.getSettings().getTutorialFlag() && AppSettings.getSettings().getFirstReversi()) {
|
if (AppSettings.getSettings().getTutorialFlag() && AppSettings.getSettings().getFirstReversi()) {
|
||||||
new ShowEnableTutorialWidget(
|
new ShowEnableTutorialWidget(
|
||||||
() -> new ReversiTutorialWidget(() -> {
|
() -> new ReversiTutorialWidget(() -> {
|
||||||
gameController = new ReversiController(players);
|
gameController = new ReversiBitController(players);
|
||||||
gameController.start();
|
gameController.start();
|
||||||
}),
|
}),
|
||||||
() -> Platform.runLater(() -> {
|
() -> Platform.runLater(() -> {
|
||||||
gameController = new ReversiController(players);
|
gameController = new ReversiBitController(players);
|
||||||
gameController.start();
|
gameController.start();
|
||||||
}),
|
}),
|
||||||
() -> AppSettings.getSettings().setFirstReversi(false)
|
() -> AppSettings.getSettings().setFirstReversi(false)
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
gameController = new ReversiController(players);
|
gameController = new ReversiBitController(players);
|
||||||
gameController.start();
|
gameController.start();
|
||||||
}
|
}
|
||||||
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,6 +1,5 @@
|
|||||||
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;
|
||||||
|
|||||||
@@ -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,7 +5,6 @@ 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.eventbus.bus.EventBus;
|
||||||
import org.toop.framework.resource.types.AudioResource;
|
import org.toop.framework.resource.types.AudioResource;
|
||||||
|
|
||||||
|
|||||||
@@ -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);
|
||||||
|
|||||||
@@ -14,7 +14,8 @@ 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.bus.EventBus;
|
||||||
import org.toop.framework.eventbus.subscriber.DefaultSubscriber;
|
import org.toop.framework.eventbus.subscriber.DefaultNamedSubscriber;
|
||||||
|
import org.toop.framework.eventbus.subscriber.NamedSubscriber;
|
||||||
import org.toop.framework.eventbus.subscriber.Subscriber;
|
import org.toop.framework.eventbus.subscriber.Subscriber;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -43,7 +44,7 @@ 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<Subscriber<?, ?>> 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;
|
||||||
@@ -161,7 +162,7 @@ public class EventFlow {
|
|||||||
this.result = eventClass.result();
|
this.result = eventClass.result();
|
||||||
};
|
};
|
||||||
|
|
||||||
var subscriber = new DefaultSubscriber<>(
|
var subscriber = new DefaultNamedSubscriber<>(
|
||||||
name,
|
name,
|
||||||
event,
|
event,
|
||||||
newAction
|
newAction
|
||||||
@@ -248,7 +249,7 @@ public class EventFlow {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
var listener = new DefaultSubscriber<>(
|
var listener = new DefaultNamedSubscriber<>(
|
||||||
name,
|
name,
|
||||||
(Class<TT>) action.getClass().getDeclaredMethods()[0].getParameterTypes()[0],
|
(Class<TT>) action.getClass().getDeclaredMethods()[0].getParameterTypes()[0],
|
||||||
newAction
|
newAction
|
||||||
@@ -295,7 +296,7 @@ public class EventFlow {
|
|||||||
if (unsubscribeAfterSuccess) unsubscribe(String.valueOf(id));
|
if (unsubscribeAfterSuccess) unsubscribe(String.valueOf(id));
|
||||||
};
|
};
|
||||||
|
|
||||||
var listener = new DefaultSubscriber<>(
|
var listener = new DefaultNamedSubscriber<>(
|
||||||
name,
|
name,
|
||||||
event,
|
event,
|
||||||
newAction
|
newAction
|
||||||
@@ -378,7 +379,7 @@ public class EventFlow {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
var listener = new DefaultSubscriber<>(
|
var listener = new DefaultNamedSubscriber<>(
|
||||||
name,
|
name,
|
||||||
eventClass,
|
eventClass,
|
||||||
newAction
|
newAction
|
||||||
@@ -414,11 +415,9 @@ public class EventFlow {
|
|||||||
/**
|
/**
|
||||||
* Posts the event added through {@link #addPostEvent} asynchronously.
|
* Posts the event added through {@link #addPostEvent} asynchronously.
|
||||||
*
|
*
|
||||||
* @deprecated use {@link #postEvent()} instead.
|
|
||||||
*/
|
*/
|
||||||
@Deprecated
|
|
||||||
public EventFlow asyncPostEvent() {
|
public EventFlow asyncPostEvent() {
|
||||||
eventBus.post(this.event);
|
GlobalEventBus.get().post(this.event);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -430,7 +429,7 @@ public class EventFlow {
|
|||||||
*/
|
*/
|
||||||
public void unsubscribe(Consumer<?> action) {
|
public void unsubscribe(Consumer<?> action) {
|
||||||
this.listeners.removeIf(handler -> {
|
this.listeners.removeIf(handler -> {
|
||||||
if (handler.getAction().equals(action)) {
|
if (handler.handler().equals(action)) {
|
||||||
eventBus.unsubscribe(handler);
|
eventBus.unsubscribe(handler);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -445,7 +444,7 @@ public class EventFlow {
|
|||||||
*/
|
*/
|
||||||
public void unsubscribe(String name) {
|
public void unsubscribe(String name) {
|
||||||
this.listeners.removeIf(handler -> {
|
this.listeners.removeIf(handler -> {
|
||||||
if (handler.getId().equals(name)) {
|
if (handler.id().equals(name)) {
|
||||||
eventBus.unsubscribe(handler);
|
eventBus.unsubscribe(handler);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -496,7 +495,7 @@ public class EventFlow {
|
|||||||
*
|
*
|
||||||
* @return Copy of the list of listeners.
|
* @return Copy of the list of listeners.
|
||||||
*/
|
*/
|
||||||
public Subscriber<?, ?>[] getListeners() {
|
public Subscriber<?>[] getListeners() {
|
||||||
return listeners.toArray(new Subscriber[0]);
|
return listeners.toArray(new Subscriber[0]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,15 +1,21 @@
|
|||||||
package org.toop.framework.eventbus;
|
package org.toop.framework.eventbus;
|
||||||
|
|
||||||
import org.apache.logging.log4j.LogManager;
|
import org.apache.logging.log4j.LogManager;
|
||||||
|
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.DisruptorEventBus;
|
||||||
import org.toop.framework.eventbus.bus.EventBus;
|
import org.toop.framework.eventbus.bus.EventBus;
|
||||||
import org.toop.framework.eventbus.holder.AsyncArraySubscriberStore;
|
import org.toop.framework.eventbus.events.EventType;
|
||||||
|
import org.toop.framework.eventbus.store.DefaultSubscriberStore;
|
||||||
import org.toop.framework.eventbus.subscriber.Subscriber;
|
import org.toop.framework.eventbus.subscriber.Subscriber;
|
||||||
|
|
||||||
public class GlobalEventBus implements EventBus {
|
import java.util.concurrent.ExecutorService;
|
||||||
private static final EventBus INSTANCE = new DisruptorEventBus(
|
import java.util.concurrent.Executors;
|
||||||
LogManager.getLogger(DisruptorEventBus.class),
|
|
||||||
new AsyncArraySubscriberStore()
|
public class GlobalEventBus implements AsyncEventBus {
|
||||||
|
private static final AsyncEventBus INSTANCE = new DefaultEventBus(
|
||||||
|
LogManager.getLogger(DefaultEventBus.class),
|
||||||
|
new DefaultSubscriberStore()
|
||||||
);
|
);
|
||||||
|
|
||||||
private GlobalEventBus() {}
|
private GlobalEventBus() {}
|
||||||
@@ -19,20 +25,25 @@ public class GlobalEventBus implements EventBus {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void subscribe(Subscriber<?, ?> listener) {
|
public void subscribe(Subscriber<? extends EventType> listener) {
|
||||||
INSTANCE.subscribe(listener);
|
INSTANCE.subscribe(listener);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void unsubscribe(Subscriber<?, ?> listener) {
|
public void unsubscribe(Subscriber<? extends EventType> listener) {
|
||||||
INSTANCE.unsubscribe(listener);
|
INSTANCE.unsubscribe(listener);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public <T> void post(T event) {
|
public <T extends EventType> void post(T event) {
|
||||||
INSTANCE.post(event);
|
INSTANCE.post(event);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public <T extends EventType> void asyncPost(T event) {
|
||||||
|
INSTANCE.asyncPost(event);
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void shutdown() {
|
public void shutdown() {
|
||||||
INSTANCE.shutdown();
|
INSTANCE.shutdown();
|
||||||
@@ -42,4 +53,5 @@ public class GlobalEventBus implements EventBus {
|
|||||||
public void reset() {
|
public void reset() {
|
||||||
INSTANCE.reset();
|
INSTANCE.reset();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
@@ -2,45 +2,54 @@ package org.toop.framework.eventbus.bus;
|
|||||||
|
|
||||||
import org.apache.logging.log4j.Logger;
|
import org.apache.logging.log4j.Logger;
|
||||||
import org.toop.framework.eventbus.events.EventType;
|
import org.toop.framework.eventbus.events.EventType;
|
||||||
import org.toop.framework.eventbus.holder.SubscriberStore;
|
import org.toop.framework.eventbus.store.SubscriberStore;
|
||||||
import org.toop.framework.eventbus.subscriber.Subscriber;
|
import org.toop.framework.eventbus.subscriber.Subscriber;
|
||||||
|
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
import java.util.function.Consumer;
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
public class DefaultEventBus implements EventBus {
|
public class DefaultEventBus implements AsyncEventBus {
|
||||||
private final Logger logger;
|
private final Logger logger;
|
||||||
private final SubscriberStore eventsHolder;
|
private final SubscriberStore eventsHolder;
|
||||||
|
|
||||||
|
private final ExecutorService asyncExecutor = Executors.newCachedThreadPool();
|
||||||
|
|
||||||
public DefaultEventBus(Logger logger, SubscriberStore eventsHolder) {
|
public DefaultEventBus(Logger logger, SubscriberStore eventsHolder) {
|
||||||
this.logger = logger;
|
this.logger = logger;
|
||||||
this.eventsHolder = eventsHolder;
|
this.eventsHolder = eventsHolder;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void subscribe(Subscriber<?, ?> subscriber) {
|
public void subscribe(Subscriber<? extends EventType> subscriber) {
|
||||||
eventsHolder.add(subscriber);
|
eventsHolder.add(subscriber);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void unsubscribe(Subscriber<?, ?> subscriber) {
|
public void unsubscribe(Subscriber<? extends EventType> subscriber) {
|
||||||
eventsHolder.remove(subscriber);
|
eventsHolder.remove(subscriber);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
public <T> void post(T event) {
|
public <T extends EventType> void post(T event) {
|
||||||
Class<T> eventType = (Class<T>) event.getClass();
|
Class<T> eventType = (Class<T>) event.getClass();
|
||||||
var subs = eventsHolder.get(eventType);
|
var subs = eventsHolder.get(eventType);
|
||||||
if (subs != null) {
|
if (subs != null) {
|
||||||
for (Subscriber<?, ?> subscriber : subs) {
|
for (Subscriber<?> subscriber : subs) {
|
||||||
Class<T> eventClass = (Class<T>) subscriber.getEvent();
|
Class<T> eventClass = (Class<T>) subscriber.event();
|
||||||
Consumer<EventType> action = (Consumer<EventType>) subscriber.getAction();
|
Consumer<EventType> action = (Consumer<EventType>) subscriber.handler();
|
||||||
|
|
||||||
action.accept((EventType) eventClass.cast(event));
|
action.accept(eventClass.cast(event));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public <T extends EventType> void asyncPost(T event) {
|
||||||
|
asyncExecutor.submit(() -> post(event));
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void shutdown() {
|
public void shutdown() {
|
||||||
eventsHolder.reset();
|
eventsHolder.reset();
|
||||||
@@ -50,4 +59,5 @@ public class DefaultEventBus implements EventBus {
|
|||||||
public void reset() {
|
public void reset() {
|
||||||
eventsHolder.reset();
|
eventsHolder.reset();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import com.lmax.disruptor.dsl.ProducerType;
|
|||||||
import org.apache.logging.log4j.Logger;
|
import org.apache.logging.log4j.Logger;
|
||||||
import org.toop.framework.eventbus.subscriber.Subscriber;
|
import org.toop.framework.eventbus.subscriber.Subscriber;
|
||||||
import org.toop.framework.eventbus.events.EventType;
|
import org.toop.framework.eventbus.events.EventType;
|
||||||
import org.toop.framework.eventbus.holder.SubscriberStore;
|
import org.toop.framework.eventbus.store.SubscriberStore;
|
||||||
|
|
||||||
import java.util.concurrent.ThreadFactory;
|
import java.util.concurrent.ThreadFactory;
|
||||||
import java.util.function.Consumer;
|
import java.util.function.Consumer;
|
||||||
@@ -21,8 +21,8 @@ public class DisruptorEventBus implements EventBus {
|
|||||||
private final Logger logger;
|
private final Logger logger;
|
||||||
private final SubscriberStore eventsHolder;
|
private final SubscriberStore eventsHolder;
|
||||||
|
|
||||||
private final Disruptor<EventHolder<?>> disruptor;
|
private final Disruptor<EventHolder<? extends EventType>> disruptor;
|
||||||
private final RingBuffer<EventHolder<?>> ringBuffer;
|
private final RingBuffer<EventHolder<? extends EventType>> ringBuffer;
|
||||||
|
|
||||||
public DisruptorEventBus(Logger logger, SubscriberStore eventsHolder) {
|
public DisruptorEventBus(Logger logger, SubscriberStore eventsHolder) {
|
||||||
this.logger = logger;
|
this.logger = logger;
|
||||||
@@ -41,9 +41,9 @@ public class DisruptorEventBus implements EventBus {
|
|||||||
this.ringBuffer = disruptor.getRingBuffer();
|
this.ringBuffer = disruptor.getRingBuffer();
|
||||||
}
|
}
|
||||||
|
|
||||||
private Disruptor<EventHolder<?>> getEventHolderDisruptor(ThreadFactory threadFactory) {
|
private Disruptor<EventHolder<? extends EventType>> getEventHolderDisruptor(ThreadFactory threadFactory) {
|
||||||
int RING_BUFFER_SIZE = 1024 * 64;
|
int RING_BUFFER_SIZE = 1024 * 64;
|
||||||
Disruptor<EventHolder<?>> disruptor = new Disruptor<>(
|
Disruptor<EventHolder<? extends EventType>> disruptor = new Disruptor<>(
|
||||||
EventHolder::new,
|
EventHolder::new,
|
||||||
RING_BUFFER_SIZE,
|
RING_BUFFER_SIZE,
|
||||||
threadFactory,
|
threadFactory,
|
||||||
@@ -61,17 +61,17 @@ public class DisruptorEventBus implements EventBus {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void subscribe(Subscriber<?, ?> listener) {
|
public void subscribe(Subscriber<? extends EventType> listener) {
|
||||||
eventsHolder.add(listener);
|
eventsHolder.add(listener);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void unsubscribe(Subscriber<?, ?> listener) {
|
public void unsubscribe(Subscriber<? extends EventType> listener) {
|
||||||
eventsHolder.remove(listener);
|
eventsHolder.remove(listener);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public <T> void post(T event) {
|
public <T extends EventType> void post(T event) {
|
||||||
long seq = ringBuffer.next();
|
long seq = ringBuffer.next();
|
||||||
try {
|
try {
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
@@ -93,10 +93,10 @@ public class DisruptorEventBus implements EventBus {
|
|||||||
eventsHolder.reset();
|
eventsHolder.reset();
|
||||||
}
|
}
|
||||||
|
|
||||||
private <T> void dispatchEvent(T event) {
|
private <T extends EventType> void dispatchEvent(T event) {
|
||||||
var classListeners = eventsHolder.get(event.getClass());
|
var classListeners = eventsHolder.get(event.getClass());
|
||||||
if (classListeners != null) {
|
if (classListeners != null) {
|
||||||
for (Subscriber<?, ?> listener : classListeners) {
|
for (Subscriber<?> listener : classListeners) {
|
||||||
try {
|
try {
|
||||||
callListener(listener, event);
|
callListener(listener, event);
|
||||||
} catch (Throwable e) {
|
} catch (Throwable e) {
|
||||||
@@ -108,9 +108,9 @@ public class DisruptorEventBus implements EventBus {
|
|||||||
|
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
private <T> void callListener(Subscriber<?, ?> subscriber, T event) {
|
private <T> void callListener(Subscriber<?> subscriber, T event) {
|
||||||
Class<T> eventClass = (Class<T>) subscriber.getEvent();
|
Class<T> eventClass = (Class<T>) subscriber.event();
|
||||||
Consumer<EventType> action = (Consumer<EventType>) subscriber.getAction();
|
Consumer<EventType> action = (Consumer<EventType>) subscriber.handler();
|
||||||
|
|
||||||
action.accept((EventType) eventClass.cast(event));
|
action.accept((EventType) eventClass.cast(event));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,9 +4,9 @@ import org.toop.framework.eventbus.events.EventType;
|
|||||||
import org.toop.framework.eventbus.subscriber.Subscriber;
|
import org.toop.framework.eventbus.subscriber.Subscriber;
|
||||||
|
|
||||||
public interface EventBus {
|
public interface EventBus {
|
||||||
void subscribe(Subscriber<?, ?> subscriber);
|
void subscribe(Subscriber<? extends EventType> subscriber);
|
||||||
void unsubscribe(Subscriber<?, ?> subscriber);
|
void unsubscribe(Subscriber<? extends EventType> subscriber);
|
||||||
<T> void post(T event);
|
<T extends EventType> void post(T event);
|
||||||
void shutdown();
|
void shutdown();
|
||||||
void reset();
|
void reset();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,46 +0,0 @@
|
|||||||
package org.toop.framework.eventbus.holder;
|
|
||||||
|
|
||||||
import org.toop.framework.eventbus.subscriber.Subscriber;
|
|
||||||
|
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
|
||||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
|
||||||
|
|
||||||
public class AsyncSubscriberStore implements SubscriberStore {
|
|
||||||
private final ConcurrentHashMap<Class<?>, ConcurrentLinkedQueue<Subscriber<?, ?>>> queues = new ConcurrentHashMap<>();
|
|
||||||
private final ConcurrentHashMap<Class<?>, Subscriber<?, ?>[]> snapshots = new ConcurrentHashMap<>();
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void add(Subscriber<?, ?> sub) {
|
|
||||||
queues.computeIfAbsent(sub.getEvent(), _ -> new ConcurrentLinkedQueue<>()).add(sub);
|
|
||||||
rebuildSnapshot(sub.getEvent());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void remove(Subscriber<?, ?> sub) {
|
|
||||||
ConcurrentLinkedQueue<Subscriber<?, ?>> queue = queues.get(sub.getEvent());
|
|
||||||
if (queue != null) {
|
|
||||||
queue.remove(sub);
|
|
||||||
rebuildSnapshot(sub.getEvent());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Subscriber<?, ?>[] get(Class<?> event) {
|
|
||||||
return snapshots.getOrDefault(event, new Subscriber[0]);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void reset() {
|
|
||||||
queues.clear();
|
|
||||||
snapshots.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void rebuildSnapshot(Class<?> 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]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
package org.toop.framework.eventbus.holder;
|
|
||||||
|
|
||||||
import org.toop.framework.eventbus.subscriber.Subscriber;
|
|
||||||
|
|
||||||
public interface SubscriberStore {
|
|
||||||
void add(Subscriber<?, ?> subscriber);
|
|
||||||
void remove(Subscriber<?, ?> subscriber);
|
|
||||||
Subscriber<?, ?>[] get(Class<?> event);
|
|
||||||
void reset();
|
|
||||||
}
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
package org.toop.framework.eventbus.holder;
|
|
||||||
|
|
||||||
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<?>, List<Subscriber<?, ?>>> LISTENERS = new ConcurrentHashMap<>();
|
|
||||||
private static final Subscriber<?, ?>[] EMPTY = new Subscriber[0];
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void add(Subscriber<?, ?> sub) {
|
|
||||||
LISTENERS.computeIfAbsent(sub.getEvent(), _ -> new ArrayList<>()).add(sub);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void remove(Subscriber<?, ?> sub) {
|
|
||||||
LISTENERS.getOrDefault(sub.getEvent(), new ArrayList<>()).remove(sub);
|
|
||||||
LISTENERS.entrySet().removeIf(entry -> entry.getValue().isEmpty());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Subscriber<?, ?>[] get(Class<?> event) {
|
|
||||||
List<Subscriber<?, ?>> list = LISTENERS.get(event);
|
|
||||||
if (list == null || list.isEmpty()) return EMPTY;
|
|
||||||
return list.toArray(EMPTY);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void reset() {
|
|
||||||
LISTENERS.clear();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,25 +1,27 @@
|
|||||||
package org.toop.framework.eventbus.holder;
|
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 org.toop.framework.eventbus.subscriber.Subscriber;
|
||||||
|
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
public class AsyncArraySubscriberStore implements SubscriberStore {
|
public class DefaultSubscriberStore implements SubscriberStore {
|
||||||
|
|
||||||
private static final Subscriber<?, ?>[] EMPTY = new Subscriber[0];
|
private static final Subscriber<? extends EventType>[] EMPTY = new Subscriber<?>[0];
|
||||||
|
|
||||||
private final ConcurrentHashMap<Class<?>, Subscriber<?, ?>[]> listeners =
|
private final ConcurrentHashMap<Class<? extends EventType>, Subscriber<? extends EventType>[]>
|
||||||
new ConcurrentHashMap<>();
|
listeners = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void add(Subscriber<?, ?> sub) {
|
public void add(Subscriber<? extends EventType> sub) {
|
||||||
listeners.compute(sub.getEvent(), (_, arr) -> {
|
listeners.compute(sub.event(), (_, arr) -> {
|
||||||
if (arr == null || arr.length == 0) {
|
if (arr == null || arr.length == 0) {
|
||||||
return new Subscriber<?, ?>[]{sub};
|
return new Subscriber<?>[]{sub};
|
||||||
}
|
}
|
||||||
|
|
||||||
int len = arr.length;
|
int len = arr.length;
|
||||||
Subscriber<?, ?>[] newArr = new Subscriber[len + 1];
|
Subscriber<?>[] newArr = new Subscriber[len + 1];
|
||||||
System.arraycopy(arr, 0, newArr, 0, len);
|
System.arraycopy(arr, 0, newArr, 0, len);
|
||||||
newArr[len] = sub;
|
newArr[len] = sub;
|
||||||
return newArr;
|
return newArr;
|
||||||
@@ -27,8 +29,8 @@ public class AsyncArraySubscriberStore implements SubscriberStore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void remove(Subscriber<?, ?> sub) {
|
public void remove(Subscriber<? extends EventType> sub) {
|
||||||
listeners.computeIfPresent(sub.getEvent(), (_, arr) -> {
|
listeners.computeIfPresent(sub.event(), (_, arr) -> {
|
||||||
int len = arr.length;
|
int len = arr.length;
|
||||||
|
|
||||||
if (len == 1) {
|
if (len == 1) {
|
||||||
@@ -36,7 +38,7 @@ public class AsyncArraySubscriberStore implements SubscriberStore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
int keep = 0;
|
int keep = 0;
|
||||||
for (Subscriber<?, ?> s : arr) {
|
for (Subscriber<?> s : arr) {
|
||||||
if (!s.equals(sub)) keep++;
|
if (!s.equals(sub)) keep++;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -47,9 +49,9 @@ public class AsyncArraySubscriberStore implements SubscriberStore {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
Subscriber<?, ?>[] newArr = new Subscriber[keep];
|
Subscriber<?>[] newArr = new Subscriber[keep];
|
||||||
int i = 0;
|
int i = 0;
|
||||||
for (Subscriber<?, ?> s : arr) {
|
for (Subscriber<?> s : arr) {
|
||||||
if (!s.equals(sub)) {
|
if (!s.equals(sub)) {
|
||||||
newArr[i++] = s;
|
newArr[i++] = s;
|
||||||
}
|
}
|
||||||
@@ -60,7 +62,7 @@ public class AsyncArraySubscriberStore implements SubscriberStore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Subscriber<?, ?>[] get(Class<?> event) {
|
public Subscriber<? extends EventType>[] get(Class<? extends EventType> event) {
|
||||||
return listeners.getOrDefault(event, EMPTY);
|
return listeners.getOrDefault(event, EMPTY);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -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> {}
|
||||||
@@ -1,30 +1,8 @@
|
|||||||
package org.toop.framework.eventbus.subscriber;
|
package org.toop.framework.eventbus.subscriber;
|
||||||
|
|
||||||
|
import org.toop.framework.eventbus.events.EventType;
|
||||||
|
|
||||||
import java.util.function.Consumer;
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
public class DefaultSubscriber<T, K> implements Subscriber<K, T> {
|
public record DefaultSubscriber<K extends EventType>(Class<K> event, Consumer<K> handler) implements Subscriber<K> {}
|
||||||
private final K id;
|
|
||||||
private final Class<T> event;
|
|
||||||
private final Consumer<T> action;
|
|
||||||
|
|
||||||
public DefaultSubscriber(K id, Class<T> eventClass, Consumer<T> action) {
|
|
||||||
this.id = id;
|
|
||||||
this.event = eventClass;
|
|
||||||
this.action = action;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public K getId() {
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Class<T> getEvent() {
|
|
||||||
return event;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Consumer<T> getAction() {
|
|
||||||
return action;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -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> {}
|
||||||
@@ -1,9 +1,10 @@
|
|||||||
package org.toop.framework.eventbus.subscriber;
|
package org.toop.framework.eventbus.subscriber;
|
||||||
|
|
||||||
|
import org.toop.framework.eventbus.events.EventType;
|
||||||
|
|
||||||
import java.util.function.Consumer;
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
public interface Subscriber<T, K> {
|
public interface Subscriber<K extends EventType> {
|
||||||
T getId();
|
Class<K> event();
|
||||||
Class<K> getEvent();
|
Consumer<K> handler();
|
||||||
Consumer<K> getAction();
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,111 @@
|
|||||||
|
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.player.Player;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
// There is AI performance to be gained by getting rid of non-primitives and thus speeding up deepCopy
|
||||||
|
public abstract class BitboardGame implements TurnBasedGame {
|
||||||
|
private final int columnSize;
|
||||||
|
private final int rowSize;
|
||||||
|
|
||||||
|
protected PlayResult state;
|
||||||
|
|
||||||
|
private Player[] players;
|
||||||
|
|
||||||
|
// long is 64 bits. Every game has a limit of 64 cells maximum.
|
||||||
|
private final long[] playerBitboard;
|
||||||
|
private int currentTurn = 0;
|
||||||
|
private final int playerCount;
|
||||||
|
|
||||||
|
public BitboardGame(int columnSize, int rowSize, int playerCount) {
|
||||||
|
this.columnSize = columnSize;
|
||||||
|
this.rowSize = rowSize;
|
||||||
|
this.playerCount = playerCount;
|
||||||
|
this.state = new PlayResult(GameState.NORMAL, -1);
|
||||||
|
|
||||||
|
this.playerBitboard = new long[playerCount];
|
||||||
|
|
||||||
|
Arrays.fill(playerBitboard, 0L);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void init(Player[] players) {
|
||||||
|
this.players = players;
|
||||||
|
|
||||||
|
Arrays.fill(playerBitboard, 0L);
|
||||||
|
}
|
||||||
|
|
||||||
|
public BitboardGame(BitboardGame other) {
|
||||||
|
this.columnSize = other.columnSize;
|
||||||
|
this.rowSize = other.rowSize;
|
||||||
|
this.playerCount = other.playerCount;
|
||||||
|
this.state = other.state;
|
||||||
|
|
||||||
|
this.playerBitboard = other.playerBitboard.clone();
|
||||||
|
this.currentTurn = other.currentTurn;
|
||||||
|
this.players = other.players;
|
||||||
|
// TODO: Players are not deep copied, which is bad. I don't know why but deepcopying breaks it. Fix it
|
||||||
|
//this.players = Arrays.stream(other.players)
|
||||||
|
// .map(Player::deepCopy)
|
||||||
|
// .toArray(Player[]::new);
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getColumnSize() {
|
||||||
|
return this.columnSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getRowSize() {
|
||||||
|
return this.rowSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
public long getPlayerBitboard(int player) {
|
||||||
|
return this.playerBitboard[player];
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPlayerBitboard(int player, long bitboard) {
|
||||||
|
this.playerBitboard[player] = bitboard;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getPlayerCount() {
|
||||||
|
return playerBitboard.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getCurrentTurn() {
|
||||||
|
return getCurrentPlayerIndex();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Player getPlayer(int index) {return players[index];}
|
||||||
|
|
||||||
|
public int getCurrentPlayerIndex() {
|
||||||
|
return currentTurn % playerBitboard.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getNextPlayer() {
|
||||||
|
return (currentTurn + 1) % playerBitboard.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Player getCurrentPlayer(){
|
||||||
|
return players[getCurrentPlayerIndex()];
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PlayResult getState() {
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isTerminal() {
|
||||||
|
return state.state() == GameState.WIN || state.state() == GameState.DRAW;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public long[] getBoard() {return this.playerBitboard;}
|
||||||
|
|
||||||
|
public void nextTurn() {
|
||||||
|
currentTurn++;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
@@ -8,26 +8,24 @@ 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.player.Player;
|
import org.toop.framework.gameFramework.model.player.Player;
|
||||||
|
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handles local turn-based game logic at a fixed update rate.
|
* Handles local turn-based game logic at a fixed update rate.
|
||||||
* <p>
|
* <p>
|
||||||
* 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 {
|
||||||
|
|
||||||
/** All players participating in the game. */
|
|
||||||
private final Player<T>[] players;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a fixed-rate behaviour for a local turn-based game.
|
* Creates a fixed-rate behaviour for a local turn-based game.
|
||||||
*
|
*
|
||||||
* @param game the game instance
|
* @param game the game instance
|
||||||
* @param players the list of players in turn order
|
|
||||||
*/
|
*/
|
||||||
public LocalFixedRateThreadBehaviour(T game, Player<T>[] players) {
|
public LocalFixedRateThreadBehaviour(TurnBasedGame game) {
|
||||||
super(game);
|
super(game);
|
||||||
this.players = players;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Starts the game loop thread if not already running. */
|
/** Starts the game loop thread if not already running. */
|
||||||
@@ -52,7 +50,7 @@ public class LocalFixedRateThreadBehaviour<T extends TurnBasedGame<T>> extends A
|
|||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
final int UPS = 60;
|
final int UPS = 1;
|
||||||
final long UPDATE_INTERVAL = 1_000_000_000L / UPS;
|
final long UPDATE_INTERVAL = 1_000_000_000L / UPS;
|
||||||
long nextUpdate = System.nanoTime();
|
long nextUpdate = System.nanoTime();
|
||||||
|
|
||||||
@@ -61,10 +59,11 @@ 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());
|
||||||
int move = currentPlayer.getMove(game.deepCopy());
|
long move = currentPlayer.getMove(game.deepCopy());
|
||||||
PlayResult result = game.play(move);
|
PlayResult result = game.play(move);
|
||||||
new EventFlow().addPostEvent(GUIEvents.RefreshGameCanvas.class).postEvent();
|
|
||||||
|
updateUI();
|
||||||
|
|
||||||
GameState state = result.state();
|
GameState state = result.state();
|
||||||
switch (state) {
|
switch (state) {
|
||||||
@@ -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;
|
||||||
@@ -8,21 +8,22 @@ import org.toop.framework.gameFramework.GameState;
|
|||||||
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.function.Consumer;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handles local turn-based game logic in its own thread.
|
* Handles local turn-based game logic in its own thread.
|
||||||
* <p>
|
* <p>
|
||||||
* 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
|
||||||
* @param players the list of players in turn order
|
|
||||||
*/
|
*/
|
||||||
public LocalThreadBehaviour(T game, Player<T>[] players) {
|
public LocalThreadBehaviour(TurnBasedGame game) {
|
||||||
super(game);
|
super(game);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -47,10 +48,11 @@ 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());
|
||||||
int move = currentPlayer.getMove(game.deepCopy());
|
long move = currentPlayer.getMove(game.deepCopy());
|
||||||
PlayResult result = game.play(move);
|
PlayResult result = game.play(move);
|
||||||
new EventFlow().addPostEvent(GUIEvents.RefreshGameCanvas.class).postEvent();
|
|
||||||
|
updateUI();
|
||||||
|
|
||||||
GameState state = result.state();
|
GameState state = result.state();
|
||||||
switch (state) {
|
switch (state) {
|
||||||
@@ -1,14 +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.AbstractGame;
|
|
||||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||||
import org.toop.framework.networking.events.NetworkEvents;
|
import org.toop.framework.gameFramework.model.game.threadBehaviour.SupportsOnlinePlay;
|
||||||
import org.toop.framework.gameFramework.model.game.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.
|
||||||
@@ -16,24 +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 {
|
||||||
|
|
||||||
/** The local player controlled by this client. */
|
private ExecutorService moveExecutor = Executors.newSingleThreadExecutor();
|
||||||
private final Player<T> mainPlayer;
|
|
||||||
private final int playerTurn;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 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, Player<T>[] players) {
|
public OnlineThreadBehaviour(TurnBasedGame game) {
|
||||||
super(game);
|
super(game);
|
||||||
this.playerTurn = getFirstNotOnlinePlayer(players);
|
|
||||||
this.mainPlayer = players[this.playerTurn];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 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;
|
||||||
@@ -59,33 +56,53 @@ public class OnlineThreadBehaviour<T extends TurnBasedGame<T>> extends AbstractT
|
|||||||
* Sends the generated move back to the server.
|
* Sends the generated move back to the server.
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public void onYourTurn(NetworkEvents.YourTurnResponse event) {
|
public void onYourTurn(long clientId) {
|
||||||
if (!isRunning.get()) return;
|
logger.info("Yourturn");
|
||||||
int move = mainPlayer.getMove(game.deepCopy());
|
if (!isRunning.get()) {
|
||||||
new EventFlow().addPostEvent(NetworkEvents.SendMove.class, event.clientId(), (short) move).postEvent();
|
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);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handles a move received from the server for any player.
|
* Handles a move received from the server for any player.
|
||||||
* Updates the game state and triggers a UI refresh.
|
* Updates the game state and triggers a UI refresh.
|
||||||
*/
|
*/
|
||||||
@Override
|
public void onMoveReceived(long move) {
|
||||||
public void onMoveReceived(NetworkEvents.GameMoveResponse event) {
|
|
||||||
if (!isRunning.get()) return;
|
if (!isRunning.get()) return;
|
||||||
game.play(Integer.parseInt(event.move()));
|
game.play(move);
|
||||||
new EventFlow().addPostEvent(GUIEvents.RefreshGameCanvas.class).postEvent();
|
|
||||||
|
updateUI();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handles the end of the game as notified by the server.
|
* Handles the end of the game as notified by the server.
|
||||||
* Updates the UI to show a win or draw result for the local player.
|
* Updates the UI to show a win or draw result for the local player.
|
||||||
*/
|
*/
|
||||||
@Override
|
public void gameFinished(String condition) {
|
||||||
public void gameFinished(NetworkEvents.GameResultResponse event) {
|
switch(condition.toUpperCase()){
|
||||||
switch(event.condition().toUpperCase()){
|
case "WIN", "LOSS" -> new EventFlow().addPostEvent(GUIEvents.GameEnded.class, true, game.getWinner()).postEvent();
|
||||||
case "WIN" -> new EventFlow().addPostEvent(GUIEvents.GameEnded.class, true, playerTurn).postEvent();
|
case "DRAW" -> new EventFlow().addPostEvent(GUIEvents.GameEnded.class, false, -1).postEvent();
|
||||||
case "DRAW" -> new EventFlow().addPostEvent(GUIEvents.GameEnded.class, false, AbstractGame.EMPTY).postEvent();
|
|
||||||
case "LOSS" -> new EventFlow().addPostEvent(GUIEvents.GameEnded.class, true, (playerTurn + 1)%2).postEvent();
|
|
||||||
default -> {
|
default -> {
|
||||||
logger.error("Invalid condition");
|
logger.error("Invalid condition");
|
||||||
throw new RuntimeException("Unknown condition");
|
throw new RuntimeException("Unknown condition");
|
||||||
@@ -1,8 +1,6 @@
|
|||||||
package org.toop.game.gameThreads;
|
package org.toop.framework.game.gameThreads;
|
||||||
|
|
||||||
import org.toop.framework.gameFramework.model.game.AbstractGame;
|
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||||
import org.toop.framework.networking.events.NetworkEvents;
|
|
||||||
import org.toop.framework.gameFramework.model.player.AbstractPlayer;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Online thread behaviour that adds a fixed delay before processing
|
* Online thread behaviour that adds a fixed delay before processing
|
||||||
@@ -16,11 +14,10 @@ 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
|
||||||
* @param players the list of local and remote players
|
|
||||||
*/
|
*/
|
||||||
public OnlineWithSleepThreadBehaviour(AbstractGame game, AbstractPlayer[] players) {
|
public OnlineWithSleepThreadBehaviour(TurnBasedGame game) {
|
||||||
super(game, players);
|
super(game);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -29,14 +26,14 @@ public class OnlineWithSleepThreadBehaviour extends OnlineThreadBehaviour {
|
|||||||
* @param event the network event indicating it's this client's turn
|
* @param event the network event indicating it's this client's turn
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public void onYourTurn(NetworkEvents.YourTurnResponse event) {
|
public void onYourTurn(long clientId) {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
Thread.sleep(1000);
|
Thread.sleep(50);
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
|
|
||||||
super.onYourTurn(event);
|
super.onYourTurn(clientId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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,328 @@
|
|||||||
|
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;
|
||||||
|
import org.toop.framework.game.BitboardGame;
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
package org.toop.framework.game.games.tictactoe;
|
||||||
|
|
||||||
|
import org.toop.framework.gameFramework.GameState;
|
||||||
|
import org.toop.framework.gameFramework.model.game.PlayResult;
|
||||||
|
import org.toop.framework.gameFramework.model.player.Player;
|
||||||
|
import org.toop.framework.game.BitboardGame;
|
||||||
|
|
||||||
|
public class BitboardTicTacToe extends BitboardGame {
|
||||||
|
private final long[] winningLines = {
|
||||||
|
0b111000000L, // top row
|
||||||
|
0b000111000L, // middle row
|
||||||
|
0b000000111L, // bottom row
|
||||||
|
0b100100100L, // left column
|
||||||
|
0b010010010L, // middle column
|
||||||
|
0b001001001L, // right column
|
||||||
|
0b100010001L, // diagonal
|
||||||
|
0b001010100L // anti-diagonal
|
||||||
|
};
|
||||||
|
|
||||||
|
public BitboardTicTacToe() {
|
||||||
|
super(3, 3, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void init(Player[] players) {
|
||||||
|
super.init(players);
|
||||||
|
}
|
||||||
|
|
||||||
|
public BitboardTicTacToe(BitboardTicTacToe other) {
|
||||||
|
super(other);
|
||||||
|
}
|
||||||
|
|
||||||
|
public long getLegalMoves() {
|
||||||
|
final long xBitboard = getPlayerBitboard(0);
|
||||||
|
final long oBitboard = getPlayerBitboard(1);
|
||||||
|
|
||||||
|
final long taken = (xBitboard | oBitboard);
|
||||||
|
return (~taken) & 0x1ffL;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getWinner(){
|
||||||
|
return getCurrentPlayerIndex();
|
||||||
|
}
|
||||||
|
|
||||||
|
public PlayResult play(long move) {
|
||||||
|
// Player loses if move is invalid
|
||||||
|
if ((move & getLegalMoves()) == 0 || Long.bitCount(move) != 1){
|
||||||
|
state = new PlayResult(GameState.WIN, getNextPlayer());
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Move is legal, make move
|
||||||
|
long playerBitboard = getPlayerBitboard(getCurrentPlayerIndex());
|
||||||
|
playerBitboard |= move;
|
||||||
|
|
||||||
|
setPlayerBitboard(getCurrentPlayerIndex(), playerBitboard);
|
||||||
|
|
||||||
|
// Check if current player won
|
||||||
|
if (checkWin(playerBitboard)) {
|
||||||
|
state = new PlayResult(GameState.WIN, getCurrentPlayerIndex());
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Proceed to next turn
|
||||||
|
nextTurn();
|
||||||
|
|
||||||
|
|
||||||
|
// Check for early draw
|
||||||
|
if (getLegalMoves() == 0L || checkEarlyDraw()) {
|
||||||
|
state = new PlayResult(GameState.DRAW, -1);
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Nothing weird happened, continue on as normal
|
||||||
|
state = new PlayResult(GameState.NORMAL, -1);
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean checkWin(long board) {
|
||||||
|
for (final long line : winningLines) {
|
||||||
|
if ((board & line) == line) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean checkEarlyDraw() {
|
||||||
|
final long xBitboard = getPlayerBitboard(0);
|
||||||
|
final long oBitboard = getPlayerBitboard(1);
|
||||||
|
|
||||||
|
final long taken = (xBitboard | oBitboard);
|
||||||
|
final long empty = (~taken) & 0x1FFL;
|
||||||
|
|
||||||
|
for (final long line : winningLines) {
|
||||||
|
if (((line & xBitboard) != 0 && (line & oBitboard) != 0)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((line & empty) != 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public BitboardTicTacToe deepCopy() {
|
||||||
|
return new BitboardTicTacToe(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,8 +1,6 @@
|
|||||||
package org.toop.game.players;
|
package org.toop.framework.game.players;
|
||||||
|
|
||||||
import org.toop.framework.gameFramework.model.player.AbstractAI;
|
import org.toop.framework.gameFramework.model.player.*;
|
||||||
import org.toop.framework.gameFramework.model.player.AbstractPlayer;
|
|
||||||
import org.toop.framework.gameFramework.model.player.MoveProvider;
|
|
||||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -14,21 +12,26 @@ 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. */
|
/** The AI instance used to calculate moves. */
|
||||||
private final MoveProvider<T> ai;
|
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(MoveProvider<T> ai, String name) {
|
public ArtificialPlayer(AI ai, String name) {
|
||||||
super(name);
|
super(name);
|
||||||
this.ai = ai;
|
this.ai = ai;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public ArtificialPlayer(ArtificialPlayer other) {
|
||||||
|
super(other);
|
||||||
|
this.ai = other.ai.deepCopy();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Determines the next move for this player using its AI.
|
* Determines the next move for this player using its AI.
|
||||||
* <p>
|
* <p>
|
||||||
@@ -41,7 +44,17 @@ 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 int 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
|
||||||
|
public ArtificialPlayer deepCopy() {
|
||||||
|
return new ArtificialPlayer(this);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -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. */
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package org.toop.framework.gameFramework;
|
||||||
|
|
||||||
|
@FunctionalInterface
|
||||||
|
public interface LongPairConsumer {
|
||||||
|
void accept(long a, long b);
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package org.toop.framework.gameFramework.controller;
|
||||||
|
|
||||||
|
import org.toop.framework.networking.connection.events.NetworkEvents;
|
||||||
|
|
||||||
|
public interface GameController {
|
||||||
|
/** Called when it is this player's turn to make a move. */
|
||||||
|
void onYourTurn(NetworkEvents.YourTurnResponse event);
|
||||||
|
|
||||||
|
/** Called when a move from another player is received. */
|
||||||
|
void onMoveReceived(NetworkEvents.GameMoveResponse event);
|
||||||
|
|
||||||
|
/** Called when the game has finished, with the final result. */
|
||||||
|
void gameFinished(NetworkEvents.GameResultResponse event);
|
||||||
|
|
||||||
|
void start();
|
||||||
|
|
||||||
|
void stop();
|
||||||
|
|
||||||
|
/** Called to refresh or update the game UI. */
|
||||||
|
void updateUI();
|
||||||
|
|
||||||
|
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,108 +0,0 @@
|
|||||||
package org.toop.framework.gameFramework.model.game;
|
|
||||||
|
|
||||||
import org.toop.framework.gameFramework.model.player.Player;
|
|
||||||
|
|
||||||
import java.util.Arrays;
|
|
||||||
|
|
||||||
public abstract class AbstractGame<T extends TurnBasedGame<T>> implements TurnBasedGame<T> {
|
|
||||||
private final int playerCount; // How many players are playing
|
|
||||||
private final Player<T>[] players;
|
|
||||||
private int turn = 0; // What turn it is in the game
|
|
||||||
|
|
||||||
/** Constant representing an empty position on the board. */
|
|
||||||
public static final int EMPTY = -1;
|
|
||||||
|
|
||||||
/** Number of rows in the game board. */
|
|
||||||
private final int rowSize;
|
|
||||||
|
|
||||||
/** Number of columns in the game board. */
|
|
||||||
private final int columnSize;
|
|
||||||
|
|
||||||
/** The game board stored as a one-dimensional array. */
|
|
||||||
private final int[] board;
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
protected AbstractGame(int rowSize, int columnSize, int playerCount, Player<T>[] players) {
|
|
||||||
assert rowSize > 0 && columnSize > 0;
|
|
||||||
|
|
||||||
this.rowSize = rowSize;
|
|
||||||
this.columnSize = columnSize;
|
|
||||||
|
|
||||||
this.players = players;
|
|
||||||
|
|
||||||
board = new int[rowSize * columnSize];
|
|
||||||
Arrays.fill(board, EMPTY);
|
|
||||||
|
|
||||||
this.playerCount = playerCount;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected AbstractGame(AbstractGame<T> other){
|
|
||||||
this.rowSize = other.rowSize;
|
|
||||||
this.columnSize = other.columnSize;
|
|
||||||
this.board = other.board.clone();
|
|
||||||
this.playerCount = other.playerCount;
|
|
||||||
this.turn = other.turn;
|
|
||||||
// TODO: Make this a deep copy, add deep copy interface to Player
|
|
||||||
this.players = other.players;
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
public static boolean contains(int[] array, int value) {
|
|
||||||
// O(n)
|
|
||||||
for (int element : array){
|
|
||||||
if (element == value) return true;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Player<T> getPlayer(int index) {
|
|
||||||
return players[index];
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getPlayerCount(){return this.playerCount;}
|
|
||||||
|
|
||||||
protected void nextTurn() {
|
|
||||||
turn += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getCurrentTurn() {
|
|
||||||
return turn % playerCount;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected void setBoard(int position) {
|
|
||||||
setBoard(position, getCurrentTurn());
|
|
||||||
}
|
|
||||||
|
|
||||||
protected void setBoard(int position, int player) {
|
|
||||||
this.board[position] = player;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the number of rows in the board.
|
|
||||||
*
|
|
||||||
* @return number of rows
|
|
||||||
*/
|
|
||||||
public int getRowSize() {
|
|
||||||
return this.rowSize;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the number of columns in the board.
|
|
||||||
*
|
|
||||||
* @return number of columns
|
|
||||||
*/
|
|
||||||
public int getColumnSize() {
|
|
||||||
return this.columnSize;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns a copy of the current board state.
|
|
||||||
*
|
|
||||||
* @return a cloned array representing the board
|
|
||||||
*/
|
|
||||||
public int[] getBoard() {
|
|
||||||
return this.board.clone();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
package org.toop.framework.gameFramework.model.game;
|
package org.toop.framework.gameFramework.model.game;
|
||||||
|
|
||||||
public interface DeepCopyable<T extends TurnBasedGame<T>> {
|
public interface DeepCopyable<T> {
|
||||||
T deepCopy();
|
T deepCopy();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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
|
|
||||||
*/
|
|
||||||
int[] 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(int 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,5 +1,16 @@
|
|||||||
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> {
|
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();
|
||||||
|
Player getPlayer(int index);
|
||||||
|
int getWinner();
|
||||||
|
long getLegalMoves();
|
||||||
|
PlayResult play(long move);
|
||||||
|
PlayResult getState();
|
||||||
|
boolean isTerminal();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,10 +2,11 @@ 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.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;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Base class for thread-based game behaviours.
|
* Base class for thread-based game behaviours.
|
||||||
@@ -14,13 +15,14 @@ import java.util.concurrent.atomic.AtomicBoolean;
|
|||||||
* 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<T> {
|
public abstract class AbstractThreadBehaviour implements ThreadBehaviour {
|
||||||
|
private LongPairConsumer onSendMove;
|
||||||
|
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());
|
||||||
@@ -30,7 +32,29 @@ 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected void updateUI(){
|
||||||
|
if (onUpdateUI != null) {
|
||||||
|
onUpdateUI.run();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void sendMove(long clientId, long move){
|
||||||
|
if (onSendMove != null) {
|
||||||
|
onSendMove.accept(clientId, move);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void setOnUpdateUI(Runnable onUpdateUI) {
|
||||||
|
this.onUpdateUI = onUpdateUI;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void setOnSendMove(LongPairConsumer onSendMove) {
|
||||||
|
this.onSendMove = onSendMove;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,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.
|
||||||
@@ -10,11 +8,11 @@ import org.toop.framework.networking.events.NetworkEvents;
|
|||||||
public interface SupportsOnlinePlay {
|
public interface SupportsOnlinePlay {
|
||||||
|
|
||||||
/** 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(long clientId);
|
||||||
|
|
||||||
/** Called when a move from another player is received. */
|
/** Called when a move from another player is received. */
|
||||||
void onMoveReceived(NetworkEvents.GameMoveResponse event);
|
void onMoveReceived(long move);
|
||||||
|
|
||||||
/** Called when the game has finished, with the final result. */
|
/** Called when the game has finished, with the final result. */
|
||||||
void gameFinished(NetworkEvents.GameResultResponse event);
|
void gameFinished(String condition);
|
||||||
}
|
}
|
||||||
@@ -1,13 +1,21 @@
|
|||||||
package org.toop.framework.gameFramework.model.game.threadBehaviour;
|
package org.toop.framework.gameFramework.model.game.threadBehaviour;
|
||||||
|
|
||||||
|
import org.toop.framework.gameFramework.LongPairConsumer;
|
||||||
|
import org.toop.framework.gameFramework.controller.GameController;
|
||||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||||
import org.toop.framework.gameFramework.model.player.AbstractPlayer;
|
|
||||||
import org.toop.framework.gameFramework.model.player.Player;
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Strategy interface for controlling game thread behavior.
|
* Strategy interface for controlling game thread behavior.
|
||||||
* <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<T extends TurnBasedGame<T>> extends Controllable {
|
public interface ThreadBehaviour {
|
||||||
|
void setOnUpdateUI(Runnable onUpdateUI);
|
||||||
|
void setOnSendMove(LongPairConsumer onSendMove);
|
||||||
|
void start();
|
||||||
|
void stop();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package org.toop.framework.gameFramework.model.player;
|
||||||
|
|
||||||
|
import org.toop.framework.gameFramework.model.game.DeepCopyable;
|
||||||
|
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||||
|
|
||||||
|
public interface AI 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> implements MoveProvider<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,19 @@ 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 int playerIndex = -1;
|
private final Logger logger = LogManager.getLogger(this.getClass());
|
||||||
|
|
||||||
private 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 other) {
|
||||||
|
this.name = other.name;
|
||||||
|
}
|
||||||
/**
|
/**
|
||||||
* Determines the next move based on the provided game state.
|
* Determines the next move based on the provided game state.
|
||||||
* <p>
|
* <p>
|
||||||
@@ -37,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 int 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> {
|
|
||||||
int getMove(T game);
|
|
||||||
}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
package org.toop.framework.gameFramework.model.player;
|
|
||||||
|
|
||||||
public interface NameProvider {
|
|
||||||
String getName();
|
|
||||||
}
|
|
||||||
@@ -1,6 +1,9 @@
|
|||||||
package org.toop.framework.gameFramework.model.player;
|
package org.toop.framework.gameFramework.model.player;
|
||||||
|
|
||||||
|
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> {
|
public interface Player extends DeepCopyable<Player> {
|
||||||
|
String getName();
|
||||||
|
long getMove(TurnBasedGame game);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,10 +10,6 @@ import org.toop.framework.eventbus.events.GenericEvent;
|
|||||||
* player actions, and game completion.
|
* player actions, and game completion.
|
||||||
*/
|
*/
|
||||||
public class GUIEvents extends EventsBase {
|
public class GUIEvents extends EventsBase {
|
||||||
|
|
||||||
/** Event to refresh or redraw the game canvas. */
|
|
||||||
public record RefreshGameCanvas() implements GenericEvent {}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Event indicating the game has ended.
|
* Event indicating the game has ended.
|
||||||
*
|
*
|
||||||
@@ -23,8 +19,8 @@ public class GUIEvents extends EventsBase {
|
|||||||
public record GameEnded(boolean winOrTie, int winner) implements GenericEvent {}
|
public record GameEnded(boolean winOrTie, int winner) implements GenericEvent {}
|
||||||
|
|
||||||
/** Event indicating a player has attempted a move. */
|
/** Event indicating a player has attempted a move. */
|
||||||
public record PlayerAttemptedMove(int move) implements GenericEvent {}
|
public record PlayerAttemptedMove(long move) implements GenericEvent {}
|
||||||
|
|
||||||
/** Event indicating a player is hovering over a move (for UI feedback). */
|
/** Event indicating a player is hovering over a move (for UI feedback). */
|
||||||
public record PlayerMoveHovered(int move) implements GenericEvent {}
|
public record PlayerMoveHovered(long move) implements GenericEvent {}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
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.eventbus.bus.EventBus;
|
import org.toop.framework.eventbus.bus.EventBus;
|
||||||
import org.toop.framework.networking.events.NetworkEvents;
|
import org.toop.framework.networking.connection.events.NetworkEvents;
|
||||||
import org.toop.framework.networking.exceptions.ClientNotFoundException;
|
import org.toop.framework.networking.connection.exceptions.ClientNotFoundException;
|
||||||
import org.toop.framework.networking.interfaces.NetworkingClientManager;
|
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);
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user