mirror of
https://github.com/2OOP/pism.git
synced 2026-02-04 10:54:51 +00:00
Compare commits
25 Commits
ea179eb0e2
...
UnitTests
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
153e6343e1 | ||
|
|
e5e79bb9b0 | ||
|
|
a982345791 | ||
|
|
d1176f2151 | ||
|
|
39df1be6ee | ||
|
|
4b80072042 | ||
|
|
e6e931b565 | ||
|
|
e5ad144783 | ||
|
|
550ee5874b | ||
|
|
1ae79daef0 | ||
|
|
cd8eb99559 | ||
|
|
0132981d94 | ||
|
|
322197494c | ||
|
|
a9c99df5d2 | ||
|
|
912d25c01f | ||
|
|
adc7b1a8f3 | ||
|
|
3a8b1c2454 | ||
|
|
846898988f | ||
|
|
ecd0fd26be | ||
|
|
a838973e67 | ||
|
|
a4f2a67d9c | ||
|
|
12bccb8854 | ||
|
|
80d3e47ad9 | ||
|
|
38f50cc16d | ||
|
|
afb4844084 |
80
.github/workflows/checks.yaml
vendored
80
.github/workflows/checks.yaml
vendored
@@ -1,42 +1,42 @@
|
||||
name: Checks
|
||||
#name: Checks
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- 'main'
|
||||
pull_request:
|
||||
branches:
|
||||
- 'main'
|
||||
#on:
|
||||
# push:
|
||||
# branches:
|
||||
# - 'main'
|
||||
# pull_request:
|
||||
# branches:
|
||||
# - 'main'
|
||||
#
|
||||
#jobs:
|
||||
# formatting-check:
|
||||
# name: Follow Google Formatting Guidelines
|
||||
# runs-on: ubuntu-latest
|
||||
# steps:
|
||||
# - uses: actions/checkout@v5
|
||||
# with:
|
||||
# fetch-depth: 0 # Fix for incremental formatting
|
||||
# - uses: actions/setup-java@v5
|
||||
# with:
|
||||
# java-version: '25'
|
||||
# distribution: 'temurin'
|
||||
# cache: maven
|
||||
# - name: Run Format Check
|
||||
# run: mvn spotless:check
|
||||
|
||||
jobs:
|
||||
formatting-check:
|
||||
name: Follow Google Formatting Guidelines
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0 # Fix for incremental formatting
|
||||
- uses: actions/setup-java@v5
|
||||
with:
|
||||
java-version: '25'
|
||||
distribution: 'temurin'
|
||||
cache: maven
|
||||
- name: Run Format Check
|
||||
run: mvn spotless:check
|
||||
|
||||
tests:
|
||||
name: Unittests
|
||||
runs-on: ${{ matrix.os }}
|
||||
needs: formatting-check
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-latest] #windows-latest, macos-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/setup-java@v5
|
||||
with:
|
||||
java-version: '25'
|
||||
distribution: 'temurin'
|
||||
cache: maven
|
||||
- name: Run Unittests
|
||||
run: mvn -B test
|
||||
# tests:
|
||||
# name: Unittests
|
||||
# runs-on: ${{ matrix.os }}
|
||||
# needs: formatting-check
|
||||
# strategy:
|
||||
# matrix:
|
||||
# os: [ubuntu-latest] #windows-latest, macos-latest
|
||||
# steps:
|
||||
# - uses: actions/checkout@v5
|
||||
# - uses: actions/setup-java@v5
|
||||
# with:
|
||||
# java-version: '25'
|
||||
# distribution: 'temurin'
|
||||
# cache: maven
|
||||
# - name: Run Unittests
|
||||
# run: mvn -B test
|
||||
|
||||
3
.idea/inspectionProfiles/Project_Default.xml
generated
3
.idea/inspectionProfiles/Project_Default.xml
generated
@@ -4,6 +4,9 @@
|
||||
<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" />
|
||||
</inspection_tool>
|
||||
<inspection_tool class="ThrowablePrintStackTrace" enabled="true" level="WARNING" enabled_by_default="true">
|
||||
<scope name="Tests" level="WARNING" enabled="false" />
|
||||
</inspection_tool>
|
||||
<inspection_tool class="WriteOnlyObject" enabled="false" level="WARNING" enabled_by_default="false" />
|
||||
</profile>
|
||||
</component>
|
||||
@@ -1,13 +1,6 @@
|
||||
package org.toop;
|
||||
|
||||
import org.toop.app.App;
|
||||
import org.toop.framework.audio.*;
|
||||
import org.toop.framework.networking.NetworkingClientEventListener;
|
||||
import org.toop.framework.networking.NetworkingClientManager;
|
||||
import org.toop.framework.resource.ResourceLoader;
|
||||
import org.toop.framework.resource.ResourceManager;
|
||||
import org.toop.framework.resource.resources.MusicAsset;
|
||||
import org.toop.framework.resource.resources.SoundEffectAsset;
|
||||
|
||||
public final class Main {
|
||||
static void main(String[] args) {
|
||||
|
||||
@@ -1,18 +1,21 @@
|
||||
package org.toop.app;
|
||||
|
||||
import javafx.application.Platform;
|
||||
import javafx.scene.paint.Color;
|
||||
import org.toop.Main;
|
||||
import javafx.scene.input.KeyCode;
|
||||
import javafx.scene.input.KeyCodeCombination;
|
||||
import javafx.scene.input.KeyEvent;
|
||||
|
||||
import org.toop.app.widget.Primitive;
|
||||
import org.toop.app.widget.Widget;
|
||||
import org.toop.app.widget.WidgetContainer;
|
||||
import org.toop.app.widget.complex.LoadingWidget;
|
||||
import org.toop.app.widget.display.SongDisplay;
|
||||
import org.toop.app.widget.popup.EscapePopup;
|
||||
import org.toop.app.widget.popup.QuitPopup;
|
||||
import org.toop.app.widget.view.MainView;
|
||||
import org.toop.framework.audio.*;
|
||||
import org.toop.framework.audio.events.AudioEvents;
|
||||
import org.toop.framework.eventbus.EventFlow;
|
||||
import org.toop.framework.eventbus.GlobalEventBus;
|
||||
import org.toop.framework.networking.NetworkingClientEventListener;
|
||||
import org.toop.framework.networking.NetworkingClientManager;
|
||||
import org.toop.framework.resource.ResourceLoader;
|
||||
@@ -30,6 +33,11 @@ import javafx.scene.Scene;
|
||||
import javafx.scene.layout.StackPane;
|
||||
import javafx.stage.Stage;
|
||||
|
||||
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 {
|
||||
private static Stage stage;
|
||||
private static Scene scene;
|
||||
@@ -37,14 +45,12 @@ public final class App extends Application {
|
||||
private static int height;
|
||||
private static int width;
|
||||
|
||||
private static boolean isQuitting;
|
||||
|
||||
public static void run(String[] args) {
|
||||
launch(args);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start(Stage stage) throws Exception {
|
||||
public void start(Stage stage) {
|
||||
// Start loading localization
|
||||
ResourceManager.loadAssets(new ResourceLoader("app/src/main/resources/localization"));
|
||||
ResourceManager.loadAssets(new ResourceLoader("app/src/main/resources/style"));
|
||||
@@ -62,8 +68,8 @@ public final class App extends Application {
|
||||
|
||||
scene.getRoot();
|
||||
|
||||
stage.setMinWidth(1080);
|
||||
stage.setMinHeight(720);
|
||||
stage.setMinWidth(1200);
|
||||
stage.setMinHeight(800);
|
||||
stage.setOnCloseRequest(event -> {
|
||||
event.consume();
|
||||
quit();
|
||||
@@ -78,10 +84,10 @@ public final class App extends Application {
|
||||
App.width = (int)stage.getWidth();
|
||||
App.height = (int)stage.getHeight();
|
||||
|
||||
App.isQuitting = false;
|
||||
|
||||
AppSettings.applySettings();
|
||||
|
||||
setKeybinds(root);
|
||||
|
||||
LoadingWidget loading = new LoadingWidget(Primitive.text(
|
||||
"Loading...", false), 0, 0, Integer.MAX_VALUE, false, false // Just set a high default
|
||||
);
|
||||
@@ -105,90 +111,143 @@ public final class App extends Application {
|
||||
Platform.runLater(() -> stage.setOpacity(1.0));
|
||||
}
|
||||
|
||||
Platform.runLater(() -> loading.setMaxAmount(e.isLoadingAmount()));
|
||||
|
||||
Platform.runLater(() -> {
|
||||
loading.setMaxAmount(e.isLoadingAmount());
|
||||
try {
|
||||
loading.setAmount(e.hasLoadedAmount());
|
||||
} catch (Exception ex) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
if (e.hasLoadedAmount() >= e.isLoadingAmount()-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");
|
||||
|
||||
// Start loading assets
|
||||
new Thread(() -> ResourceManager.loadAssets(new ResourceLoader("app/src/main/resources/assets")))
|
||||
.start();
|
||||
ExecutorService executor = Executors.newSingleThreadExecutor();
|
||||
try {
|
||||
executor.submit(
|
||||
() -> ResourceManager.loadAssets(new ResourceLoader("app/src/main/resources/assets")
|
||||
));
|
||||
} finally {
|
||||
executor.shutdown();
|
||||
}
|
||||
|
||||
stage.show();
|
||||
|
||||
}
|
||||
|
||||
private void setKeybinds(StackPane root) {
|
||||
root.addEventHandler(KeyEvent.KEY_PRESSED,event -> {
|
||||
if (event.getCode() == KeyCode.ESCAPE) {
|
||||
escapePopup();
|
||||
}
|
||||
});
|
||||
stage.setFullScreenExitKeyCombination(
|
||||
new KeyCodeCombination(
|
||||
KeyCode.F11
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
public void escapePopup() {
|
||||
|
||||
if ( WidgetContainer.getCurrentView() == null
|
||||
|| WidgetContainer.getCurrentView() instanceof MainView) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Objects.requireNonNull(
|
||||
WidgetContainer.find(widget -> widget instanceof QuitPopup || widget instanceof EscapePopup)
|
||||
).isEmpty()) {
|
||||
WidgetContainer.removeFirst(QuitPopup.class);
|
||||
WidgetContainer.removeFirst(EscapePopup.class);
|
||||
return;
|
||||
}
|
||||
|
||||
EscapePopup escPopup = new EscapePopup();
|
||||
escPopup.show(Pos.CENTER);
|
||||
}
|
||||
|
||||
private void setOnLoadingSuccess(LoadingWidget loading) {
|
||||
loading.setOnSuccess(() -> {
|
||||
initSystems();
|
||||
AppSettings.applyMusicVolumeSettings();
|
||||
|
||||
try {
|
||||
initSystems();
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
AppSettings.applyMusicVolumeSettings();
|
||||
new EventFlow().addPostEvent(new AudioEvents.StartBackgroundMusic()).postEvent();
|
||||
loading.hide();
|
||||
WidgetContainer.add(Pos.CENTER, new MainView());
|
||||
WidgetContainer.add(Pos.BOTTOM_RIGHT, new SongDisplay());
|
||||
stage.setOnCloseRequest(event -> {
|
||||
event.consume();
|
||||
startQuit();
|
||||
|
||||
if (WidgetContainer.getAllWidgets().stream().anyMatch(e -> e instanceof QuitPopup)) return;
|
||||
|
||||
QuitPopup a = new QuitPopup();
|
||||
a.show(Pos.CENTER);
|
||||
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private void initSystems() { // TODO Move to better place
|
||||
new Thread(() -> new NetworkingClientEventListener(new NetworkingClientManager())).start();
|
||||
private void initSystems() throws InterruptedException { // TODO Move to better place
|
||||
|
||||
new Thread(() -> {
|
||||
MusicManager<MusicAsset> musicManager =
|
||||
new MusicManager<>(ResourceManager.getAllOfTypeAndRemoveWrapper(MusicAsset.class), true);
|
||||
final int THREAD_COUNT = 2;
|
||||
CountDownLatch latch = new CountDownLatch(THREAD_COUNT);
|
||||
|
||||
SoundEffectManager<SoundEffectAsset> soundEffectManager =
|
||||
new SoundEffectManager<>(ResourceManager.getAllOfType(SoundEffectAsset.class));
|
||||
@SuppressWarnings("resource")
|
||||
ExecutorService threads = Executors.newFixedThreadPool(THREAD_COUNT);
|
||||
|
||||
AudioVolumeManager audioVolumeManager = new AudioVolumeManager()
|
||||
.registerManager(VolumeControl.MASTERVOLUME, musicManager)
|
||||
.registerManager(VolumeControl.MASTERVOLUME, soundEffectManager)
|
||||
.registerManager(VolumeControl.FX, soundEffectManager)
|
||||
.registerManager(VolumeControl.MUSIC, musicManager);
|
||||
try {
|
||||
|
||||
new AudioEventListener<>(
|
||||
musicManager,
|
||||
soundEffectManager,
|
||||
audioVolumeManager
|
||||
).initListeners("medium-button-click.wav");
|
||||
threads.submit(() -> {
|
||||
new NetworkingClientEventListener(
|
||||
GlobalEventBus.get(),
|
||||
new NetworkingClientManager(GlobalEventBus.get()));
|
||||
|
||||
}).start();
|
||||
latch.countDown();
|
||||
});
|
||||
|
||||
// Threads must be ready, before continue, TODO use latch instead
|
||||
try {
|
||||
Thread.sleep(200);
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
threads.submit(() -> {
|
||||
MusicManager<MusicAsset> musicManager =
|
||||
new MusicManager<>(
|
||||
GlobalEventBus.get(),
|
||||
ResourceManager.getAllOfTypeAndRemoveWrapper(MusicAsset.class),
|
||||
true
|
||||
);
|
||||
|
||||
public static void startQuit() {
|
||||
if (isQuitting) {
|
||||
return;
|
||||
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();
|
||||
}
|
||||
|
||||
WidgetContainer.add(Pos.CENTER, new QuitPopup());
|
||||
isQuitting = true;
|
||||
}
|
||||
|
||||
public static void stopQuit() {
|
||||
isQuitting = false;
|
||||
}
|
||||
}
|
||||
|
||||
public static void quit() {
|
||||
stage.close();
|
||||
|
||||
@@ -2,9 +2,7 @@ package org.toop.app;
|
||||
|
||||
import javafx.application.Platform;
|
||||
import javafx.geometry.Pos;
|
||||
import org.toop.app.gameControllers.AbstractGameController;
|
||||
import org.toop.app.gameControllers.ReversiController;
|
||||
import org.toop.app.gameControllers.TicTacToeController;
|
||||
import org.toop.app.gameControllers.*;
|
||||
import org.toop.app.widget.Primitive;
|
||||
import org.toop.app.widget.WidgetContainer;
|
||||
import org.toop.app.widget.complex.LoadingWidget;
|
||||
@@ -13,15 +11,17 @@ import org.toop.app.widget.popup.ErrorPopup;
|
||||
import org.toop.app.widget.popup.SendChallengePopup;
|
||||
import org.toop.app.widget.view.ServerView;
|
||||
import org.toop.framework.eventbus.EventFlow;
|
||||
import org.toop.framework.gameFramework.controller.GameController;
|
||||
import org.toop.framework.eventbus.GlobalEventBus;
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
import org.toop.framework.networking.clients.TournamentNetworkingClient;
|
||||
import org.toop.framework.networking.events.NetworkEvents;
|
||||
import org.toop.framework.networking.types.NetworkingConnector;
|
||||
import org.toop.game.games.reversi.BitboardReversi;
|
||||
import org.toop.game.games.tictactoe.BitboardTicTacToe;
|
||||
import org.toop.game.players.ArtificialPlayer;
|
||||
import org.toop.game.players.OnlinePlayer;
|
||||
import org.toop.game.games.reversi.ReversiAIR;
|
||||
import org.toop.game.games.reversi.ReversiR;
|
||||
import org.toop.game.games.tictactoe.TicTacToeAIR;
|
||||
import org.toop.game.players.ai.RandomAI;
|
||||
import org.toop.local.AppContext;
|
||||
|
||||
import java.util.List;
|
||||
@@ -42,13 +42,13 @@ public final class Server {
|
||||
private ServerView primary;
|
||||
private boolean isPolling = true;
|
||||
|
||||
private AbstractGameController<?> gameController;
|
||||
private GameController gameController;
|
||||
|
||||
private final AtomicBoolean isSingleGame = new AtomicBoolean(false);
|
||||
|
||||
private ScheduledExecutorService scheduler;
|
||||
|
||||
private EventFlow eventFlow = new EventFlow();
|
||||
private EventFlow connectFlow;
|
||||
|
||||
public static GameInformation.Type gameToType(String game) {
|
||||
if (game.equalsIgnoreCase("tic-tac-toe")) {
|
||||
@@ -89,78 +89,85 @@ public final class Server {
|
||||
Primitive.text("connecting"), 0, 0, reconnectAttempts, true, true
|
||||
);
|
||||
|
||||
WidgetContainer.getCurrentView().transitionNext(loading);
|
||||
WidgetContainer.getCurrentView().transitionNextCustom(loading, "disconnect", this::disconnect);
|
||||
|
||||
var a = new EventFlow()
|
||||
.addPostEvent(NetworkEvents.StartClient.class,
|
||||
new TournamentNetworkingClient(),
|
||||
new TournamentNetworkingClient(GlobalEventBus.get()),
|
||||
new NetworkingConnector(ip, parsedPort, reconnectAttempts, 1, TimeUnit.SECONDS)
|
||||
);
|
||||
|
||||
loading.setOnFailure(() -> {
|
||||
WidgetContainer.getCurrentView().transitionPrevious();
|
||||
a.unsubscribe("connecting");
|
||||
a.unsubscribe("startclient");
|
||||
if (WidgetContainer.getCurrentView() == loading) WidgetContainer.getCurrentView().transitionPrevious();
|
||||
a.unsubscribeAll();
|
||||
WidgetContainer.add(
|
||||
Pos.CENTER,
|
||||
new ErrorPopup(AppContext.getString("connecting-failed") + " " + ip + ":" + port)
|
||||
);
|
||||
});
|
||||
|
||||
a.onResponse(NetworkEvents.StartClientResponse.class, e -> {
|
||||
a.onResponse(NetworkEvents.CreatedIdForClient.class, e -> clientId = e.clientId(), true);
|
||||
|
||||
a.onResponse(NetworkEvents.StartClientResponse.class, e -> {
|
||||
if (!e.successful()) {
|
||||
return;
|
||||
}
|
||||
|
||||
WidgetContainer.getCurrentView().transitionPrevious();
|
||||
primary = new ServerView(user, this::sendChallenge);
|
||||
WidgetContainer.getCurrentView().transitionNextCustom(primary, "disconnect", this::disconnect);
|
||||
|
||||
a.unsubscribe("connecting");
|
||||
a.unsubscribe("startclient");
|
||||
|
||||
this.user = user;
|
||||
clientId = e.clientId();
|
||||
|
||||
new EventFlow().addPostEvent(new NetworkEvents.SendLogin(clientId, user)).postEvent();
|
||||
|
||||
primary = new ServerView(user, this::sendChallenge, this::disconnect);
|
||||
WidgetContainer.getCurrentView().transitionNext(primary);
|
||||
|
||||
startPopulateScheduler();
|
||||
populateGameList();
|
||||
|
||||
primary.removeViewFromPreviousChain(loading);
|
||||
|
||||
}, false, "startclient")
|
||||
.listen(
|
||||
NetworkEvents.ConnectTry.class,
|
||||
e -> Platform.runLater(
|
||||
() -> {
|
||||
try {
|
||||
loading.setAmount(e.amount());
|
||||
if (e.amount() >= loading.getMaxAmount()) {
|
||||
loading.triggerFailure();
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
),
|
||||
false, "connecting"
|
||||
)
|
||||
NetworkEvents.ConnectTry.class,
|
||||
e -> {
|
||||
if (clientId != e.clientId()) return;
|
||||
Platform.runLater(
|
||||
() -> {
|
||||
try {
|
||||
loading.setAmount(e.amount());
|
||||
if (e.amount() >= loading.getMaxAmount()) {
|
||||
loading.triggerFailure();
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
);
|
||||
},
|
||||
false, "connecting"
|
||||
)
|
||||
.postEvent();
|
||||
|
||||
eventFlow.listen(NetworkEvents.ChallengeResponse.class, this::handleReceivedChallenge, false)
|
||||
.listen(NetworkEvents.GameMatchResponse.class, this::handleMatchResponse, false)
|
||||
.listen(NetworkEvents.GameResultResponse.class, this::handleGameResult, false)
|
||||
.listen(NetworkEvents.GameMoveResponse.class, this::handleReceivedMove, false)
|
||||
.listen(NetworkEvents.YourTurnResponse.class, this::handleYourTurn, false);
|
||||
a.listen(NetworkEvents.ChallengeResponse.class, this::handleReceivedChallenge, false, "challenge")
|
||||
.listen(NetworkEvents.GameMatchResponse.class, this::handleMatchResponse, false, "match-response")
|
||||
.listen(NetworkEvents.GameResultResponse.class, this::handleGameResult, false, "game-result")
|
||||
.listen(NetworkEvents.GameMoveResponse.class, this::handleReceivedMove, false, "game-move")
|
||||
.listen(NetworkEvents.YourTurnResponse.class, this::handleYourTurn, false, "your-turn");
|
||||
|
||||
connectFlow = a;
|
||||
}
|
||||
|
||||
private void sendChallenge(String opponent) {
|
||||
if (!isPolling) return;
|
||||
|
||||
new SendChallengePopup(this, opponent, (playerInformation, gameType) -> {
|
||||
var a = new SendChallengePopup(this, opponent, (playerInformation, gameType) -> {
|
||||
new EventFlow().addPostEvent(new NetworkEvents.SendChallenge(clientId, opponent, gameType)).postEvent();
|
||||
isSingleGame.set(true);
|
||||
});
|
||||
|
||||
a.show(Pos.CENTER);
|
||||
}
|
||||
|
||||
private void handleMatchResponse(NetworkEvents.GameMatchResponse response) {
|
||||
@@ -194,26 +201,31 @@ public final class Server {
|
||||
information.players[0].computerThinkTime = 1;
|
||||
information.players[1].name = response.opponent();
|
||||
|
||||
Player[] players = new Player[2];
|
||||
|
||||
players[(myTurn + 1) % 2] = new OnlinePlayer<ReversiR>(response.opponent());
|
||||
|
||||
switch (type){
|
||||
/*switch (type){
|
||||
case TICTACTOE ->{
|
||||
players[myTurn] = new ArtificialPlayer<>(new TicTacToeAIR(), user);
|
||||
players[myTurn] = new ArtificialPlayer<>(new TicTacToeAIR(9), user);
|
||||
}
|
||||
case REVERSI ->{
|
||||
players[myTurn] = new ArtificialPlayer<>(new ReversiAIR(), user);
|
||||
}
|
||||
}
|
||||
}*/
|
||||
|
||||
|
||||
|
||||
switch (type) {
|
||||
case TICTACTOE ->{
|
||||
gameController = new TicTacToeController(players, false);
|
||||
Player<BitboardTicTacToe>[] players = new Player[2];
|
||||
players[(myTurn + 1) % 2] = new OnlinePlayer<>(response.opponent());
|
||||
players[myTurn] = new ArtificialPlayer<>(new RandomAI<BitboardTicTacToe>(), user);
|
||||
gameController = new TicTacToeBitController(players);
|
||||
}
|
||||
case REVERSI ->
|
||||
gameController = new ReversiController(players, false);
|
||||
case REVERSI -> {
|
||||
Player<BitboardReversi>[] players = new Player[2];
|
||||
players[(myTurn + 1) % 2] = new OnlinePlayer<>(response.opponent());
|
||||
players[myTurn] = new ArtificialPlayer<>(new RandomAI<BitboardReversi>(), user);
|
||||
gameController = new ReversiBitController(players, false);}
|
||||
default -> new ErrorPopup("Unsupported game type.");
|
||||
|
||||
}
|
||||
|
||||
if (gameController != null){
|
||||
@@ -250,11 +262,13 @@ public final class Server {
|
||||
String challengerName = extractQuotedValue(response.challengerName());
|
||||
String gameType = extractQuotedValue(response.gameType());
|
||||
final String finalGameType = gameType;
|
||||
new ChallengePopup(challengerName, gameType, (playerInformation) -> {
|
||||
var a = new ChallengePopup(challengerName, gameType, (playerInformation) -> {
|
||||
final int challengeId = Integer.parseInt(response.challengeId().replaceAll("\\D", ""));
|
||||
new EventFlow().addPostEvent(new NetworkEvents.SendAcceptChallenge(clientId, challengeId)).postEvent();
|
||||
isSingleGame.set(true);
|
||||
});
|
||||
|
||||
a.show(Pos.CENTER);
|
||||
}
|
||||
|
||||
private void sendMessage(String message) {
|
||||
@@ -265,7 +279,9 @@ public final class Server {
|
||||
new EventFlow().addPostEvent(new NetworkEvents.CloseClient(clientId)).postEvent();
|
||||
isPolling = false;
|
||||
stopScheduler();
|
||||
primary.transitionPrevious();
|
||||
connectFlow.unsubscribeAll();
|
||||
|
||||
WidgetContainer.getCurrentView().transitionPrevious();
|
||||
}
|
||||
|
||||
private void forfeitGame() {
|
||||
|
||||
248
app/src/main/java/org/toop/app/canvas/BitGameCanvas.java
Normal file
248
app/src/main/java/org/toop/app/canvas/BitGameCanvas.java
Normal file
@@ -0,0 +1,248 @@
|
||||
package org.toop.app.canvas;
|
||||
|
||||
import javafx.animation.KeyFrame;
|
||||
import javafx.animation.Timeline;
|
||||
import javafx.scene.canvas.Canvas;
|
||||
import javafx.scene.canvas.GraphicsContext;
|
||||
import javafx.scene.input.MouseButton;
|
||||
import javafx.scene.paint.Color;
|
||||
import javafx.scene.text.Font;
|
||||
import javafx.util.Duration;
|
||||
import org.toop.framework.eventbus.EventFlow;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
import org.toop.framework.gameFramework.view.GUIEvents;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public abstract class BitGameCanvas<T extends TurnBasedGame<T>> implements GameCanvas<T> {
|
||||
protected record Cell(float x, float y, float width, float height) {
|
||||
public boolean isInside(double x, double y) {
|
||||
return x >= this.x && x <= this.x + width &&
|
||||
y >= this.y && y <= this.y + height;
|
||||
}
|
||||
}
|
||||
|
||||
protected final Canvas canvas;
|
||||
protected final GraphicsContext graphics;
|
||||
|
||||
protected final Color color;
|
||||
protected final Color backgroundColor;
|
||||
|
||||
protected final int width;
|
||||
protected final int height;
|
||||
|
||||
protected final int rowSize;
|
||||
protected final int columnSize;
|
||||
|
||||
protected final int gapSize;
|
||||
protected final boolean edges;
|
||||
|
||||
protected final Cell[] cells;
|
||||
|
||||
private Consumer<Long> onCellCLicked;
|
||||
|
||||
public void setOnCellClicked(Consumer<Long> onClick) {
|
||||
this.onCellCLicked = onClick;
|
||||
}
|
||||
|
||||
protected BitGameCanvas(Color color, Color backgroundColor, int width, int height, int rowSize, int columnSize, int gapSize, boolean edges) {
|
||||
canvas = new Canvas(width, height);
|
||||
graphics = canvas.getGraphicsContext2D();
|
||||
|
||||
this.onCellCLicked = (c) -> new EventFlow().addPostEvent(GUIEvents.PlayerAttemptedMove.class, c).postEvent();
|
||||
|
||||
this.color = color;
|
||||
this.backgroundColor = backgroundColor;
|
||||
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
|
||||
this.rowSize = rowSize;
|
||||
this.columnSize = columnSize;
|
||||
|
||||
this.gapSize = gapSize;
|
||||
this.edges = edges;
|
||||
|
||||
cells = new Cell[rowSize * columnSize];
|
||||
|
||||
final float cellWidth = ((float) width - gapSize * rowSize - gapSize) / rowSize;
|
||||
final float cellHeight = ((float) height - gapSize * columnSize - gapSize) / columnSize;
|
||||
|
||||
for (int y = 0; y < columnSize; y++) {
|
||||
final float startY = y * cellHeight + y * gapSize + gapSize;
|
||||
|
||||
for (int x = 0; x < rowSize; x++) {
|
||||
final float startX = x * cellWidth + x * gapSize + gapSize;
|
||||
cells[x + y * rowSize] = new Cell(startX, startY, cellWidth, cellHeight);
|
||||
}
|
||||
}
|
||||
|
||||
canvas.setOnMouseClicked(event -> {
|
||||
if (event.getButton() != MouseButton.PRIMARY) {
|
||||
return;
|
||||
}
|
||||
|
||||
final int column = (int) ((event.getX() / this.width) * rowSize);
|
||||
final int row = (int) ((event.getY() / this.height) * columnSize);
|
||||
|
||||
final Cell cell = cells[column + row * rowSize];
|
||||
|
||||
if (cell.isInside(event.getX(), event.getY())) {
|
||||
event.consume();
|
||||
this.onCellCLicked.accept(1L << (column + row * rowSize));
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
render();
|
||||
}
|
||||
|
||||
public void loopOverBoard(long bb, Consumer<Integer> onCell){
|
||||
while (bb != 0) {
|
||||
int idx = Long.numberOfTrailingZeros(bb); // index of least-significant 1-bit
|
||||
onCell.accept(idx);
|
||||
|
||||
bb &= bb - 1; // clear LSB 1-bit
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void render() {
|
||||
graphics.setFill(backgroundColor);
|
||||
graphics.fillRect(0, 0, width, height);
|
||||
|
||||
graphics.setFill(color);
|
||||
|
||||
for (int x = 0; x < rowSize - 1; x++) {
|
||||
final float start = cells[x].x + cells[x].width;
|
||||
graphics.fillRect(start, gapSize, gapSize, height - gapSize * 2);
|
||||
}
|
||||
|
||||
for (int y = 0; y < columnSize - 1; y++) {
|
||||
final float start = cells[y * rowSize].y + cells[y * rowSize].height;
|
||||
graphics.fillRect(gapSize, start, width - gapSize * 2, gapSize);
|
||||
}
|
||||
|
||||
if (edges) {
|
||||
graphics.fillRect(0, 0, width, gapSize);
|
||||
graphics.fillRect(0, 0, gapSize, height);
|
||||
|
||||
graphics.fillRect(width - gapSize, 0, gapSize, height);
|
||||
graphics.fillRect(0, height - gapSize, width, gapSize);
|
||||
}
|
||||
}
|
||||
|
||||
public void fill(Color color, int cell) {
|
||||
final float x = cells[cell].x();
|
||||
final float y = cells[cell].y();
|
||||
|
||||
final float width = cells[cell].width();
|
||||
final float height = cells[cell].height();
|
||||
|
||||
graphics.setFill(color);
|
||||
graphics.fillRect(x, y, width, height);
|
||||
}
|
||||
|
||||
public void clear(int cell) {
|
||||
final float x = cells[cell].x();
|
||||
final float y = cells[cell].y();
|
||||
|
||||
final float width = cells[cell].width();
|
||||
final float height = cells[cell].height();
|
||||
|
||||
graphics.clearRect(x, y, width, height);
|
||||
|
||||
graphics.setFill(backgroundColor);
|
||||
graphics.fillRect(x, y, width, height);
|
||||
}
|
||||
|
||||
public void clearAll() {
|
||||
for (int i = 0; i < cells.length; i++) {
|
||||
clear(i);
|
||||
}
|
||||
}
|
||||
|
||||
public void drawPlayerMove(int player, int move) {
|
||||
final float x = cells[move].x() + gapSize;
|
||||
final float y = cells[move].y() + gapSize;
|
||||
|
||||
final float width = cells[move].width() - gapSize * 2;
|
||||
final float height = cells[move].height() - gapSize * 2;
|
||||
|
||||
graphics.setFill(color);
|
||||
graphics.setFont(Font.font("Arial", 40)); // TODO different font and size
|
||||
graphics.fillText(String.valueOf(player), x + width, y + height);
|
||||
}
|
||||
|
||||
public void drawDot(Color color, int cell) {
|
||||
final float x = cells[cell].x() + gapSize;
|
||||
final float y = cells[cell].y() + gapSize;
|
||||
|
||||
final float width = cells[cell].width() - gapSize * 2;
|
||||
final float height = cells[cell].height() - gapSize * 2;
|
||||
|
||||
graphics.setFill(color);
|
||||
graphics.fillOval(x, y, width, height);
|
||||
}
|
||||
|
||||
public void drawInnerDot(Color color, int cell, boolean slightlyBigger) {
|
||||
final float x = cells[cell].x() + gapSize;
|
||||
final float y = cells[cell].y() + gapSize;
|
||||
|
||||
float multiplier = slightlyBigger?1.4f:1.5f;
|
||||
|
||||
final float width = (cells[cell].width() - gapSize * 2)/multiplier;
|
||||
final float height = (cells[cell].height() - gapSize * 2)/multiplier;
|
||||
|
||||
float offset = slightlyBigger?5f:4f;
|
||||
|
||||
graphics.setFill(color);
|
||||
graphics.fillOval(x + width/offset, y + height/offset, width, height);
|
||||
}
|
||||
|
||||
private void drawDotScaled(Color color, int cell, double scale) {
|
||||
final float cx = cells[cell].x() + gapSize;
|
||||
final float cy = cells[cell].y() + gapSize;
|
||||
|
||||
final float fullWidth = cells[cell].width() - gapSize * 2;
|
||||
final float height = cells[cell].height() - gapSize * 2;
|
||||
|
||||
final float scaledWidth = (float)(fullWidth * scale);
|
||||
final float offsetX = (fullWidth - scaledWidth) / 2;
|
||||
|
||||
graphics.setFill(color);
|
||||
graphics.fillOval(cx + offsetX, cy, scaledWidth, height);
|
||||
}
|
||||
|
||||
public Timeline flipDot(Color fromColor, Color toColor, int cell) {
|
||||
final int steps = 60;
|
||||
final long duration = 250;
|
||||
final double interval = duration / (double) steps;
|
||||
|
||||
final Timeline timeline = new Timeline();
|
||||
|
||||
for (int i = 0; i <= steps; i++) {
|
||||
final double t = i / (double) steps;
|
||||
final KeyFrame keyFrame = new KeyFrame(Duration.millis(i * interval),
|
||||
_ -> {
|
||||
clear(cell);
|
||||
|
||||
final double scale = t <= 0.5 ? 1 - 2 * t : 2 * t - 1;
|
||||
final Color currentColor = t < 0.5 ? fromColor : toColor;
|
||||
|
||||
drawDotScaled(currentColor, cell, scale);
|
||||
}
|
||||
);
|
||||
|
||||
timeline.getKeyFrames().add(keyFrame);
|
||||
}
|
||||
|
||||
return timeline;
|
||||
}
|
||||
|
||||
public Canvas getCanvas() {
|
||||
return canvas;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package org.toop.app.canvas;
|
||||
|
||||
public interface BitLegalMoveDrawer {
|
||||
void showLegalMove(long move, int currentPlayerIndex);
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package org.toop.app.canvas;
|
||||
|
||||
import javafx.scene.paint.Color;
|
||||
import org.toop.framework.gameFramework.model.game.AbstractGame;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class Connect4Canvas extends GameCanvas {
|
||||
public Connect4Canvas(Color color, int width, int height, Consumer<Integer> onCellClicked) {
|
||||
super(color, Color.TRANSPARENT, width, height, 7, 6, 10, true, onCellClicked,null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void drawPlayerHover(int player, int move, AbstractGame game) {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
package org.toop.app.canvas;
|
||||
|
||||
import org.toop.framework.gameFramework.model.game.AbstractGame;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
|
||||
public interface DrawPlayerHover {
|
||||
void drawPlayerHover(int player, int move, AbstractGame game);
|
||||
void drawPlayerHover(int player, int move, TurnBasedGame game);
|
||||
}
|
||||
|
||||
@@ -1,237 +1,8 @@
|
||||
package org.toop.app.canvas;
|
||||
|
||||
import javafx.animation.KeyFrame;
|
||||
import javafx.animation.Timeline;
|
||||
import javafx.scene.canvas.Canvas;
|
||||
import javafx.scene.canvas.GraphicsContext;
|
||||
import javafx.scene.input.MouseButton;
|
||||
import javafx.scene.paint.Color;
|
||||
import javafx.scene.text.Font;
|
||||
import javafx.util.Duration;
|
||||
import org.toop.framework.gameFramework.model.game.AbstractGame;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public abstract class GameCanvas<T extends AbstractGame> implements DrawPlayerMove, DrawPlayerHover {
|
||||
protected record Cell(float x, float y, float width, float height) {
|
||||
public boolean isInside(double x, double y) {
|
||||
return x >= this.x && x <= this.x + width &&
|
||||
y >= this.y && y <= this.y + height;
|
||||
}
|
||||
}
|
||||
|
||||
protected final Canvas canvas;
|
||||
protected final GraphicsContext graphics;
|
||||
|
||||
protected final Color color;
|
||||
protected final Color backgroundColor;
|
||||
|
||||
protected final int width;
|
||||
protected final int height;
|
||||
|
||||
protected final int rowSize;
|
||||
protected final int columnSize;
|
||||
|
||||
protected final int gapSize;
|
||||
protected final boolean edges;
|
||||
|
||||
protected final Cell[] cells;
|
||||
|
||||
private Consumer<Integer> onCellCLicked;
|
||||
|
||||
public void setOnCellClicked(Consumer<Integer> onClick) {
|
||||
this.onCellCLicked = onClick;
|
||||
}
|
||||
|
||||
protected GameCanvas(Color color, Color backgroundColor, int width, int height, int rowSize, int columnSize, int gapSize, boolean edges, Consumer<Integer> onCellClicked, Consumer<Integer> newCellEntered) {
|
||||
canvas = new Canvas(width, height);
|
||||
graphics = canvas.getGraphicsContext2D();
|
||||
|
||||
this.onCellCLicked = onCellClicked;
|
||||
|
||||
this.color = color;
|
||||
this.backgroundColor = backgroundColor;
|
||||
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
|
||||
this.rowSize = rowSize;
|
||||
this.columnSize = columnSize;
|
||||
|
||||
this.gapSize = gapSize;
|
||||
this.edges = edges;
|
||||
|
||||
cells = new Cell[rowSize * columnSize];
|
||||
|
||||
final float cellWidth = ((float) width - gapSize * rowSize - gapSize) / rowSize;
|
||||
final float cellHeight = ((float) height - gapSize * columnSize - gapSize) / columnSize;
|
||||
|
||||
for (int y = 0; y < columnSize; y++) {
|
||||
final float startY = y * cellHeight + y * gapSize + gapSize;
|
||||
|
||||
for (int x = 0; x < rowSize; x++) {
|
||||
final float startX = x * cellWidth + x * gapSize + gapSize;
|
||||
cells[x + y * rowSize] = new Cell(startX, startY, cellWidth, cellHeight);
|
||||
}
|
||||
}
|
||||
|
||||
canvas.setOnMouseClicked(event -> {
|
||||
if (event.getButton() != MouseButton.PRIMARY) {
|
||||
return;
|
||||
}
|
||||
|
||||
final int column = (int) ((event.getX() / this.width) * rowSize);
|
||||
final int row = (int) ((event.getY() / this.height) * columnSize);
|
||||
|
||||
final Cell cell = cells[column + row * rowSize];
|
||||
|
||||
if (cell.isInside(event.getX(), event.getY())) {
|
||||
event.consume();
|
||||
this.onCellCLicked.accept(column + row * rowSize);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
render();
|
||||
}
|
||||
|
||||
private void render() {
|
||||
graphics.setFill(backgroundColor);
|
||||
graphics.fillRect(0, 0, width, height);
|
||||
|
||||
graphics.setFill(color);
|
||||
|
||||
for (int x = 0; x < rowSize - 1; x++) {
|
||||
final float start = cells[x].x + cells[x].width;
|
||||
graphics.fillRect(start, gapSize, gapSize, height - gapSize * 2);
|
||||
}
|
||||
|
||||
for (int y = 0; y < columnSize - 1; y++) {
|
||||
final float start = cells[y * rowSize].y + cells[y * rowSize].height;
|
||||
graphics.fillRect(gapSize, start, width - gapSize * 2, gapSize);
|
||||
}
|
||||
|
||||
if (edges) {
|
||||
graphics.fillRect(0, 0, width, gapSize);
|
||||
graphics.fillRect(0, 0, gapSize, height);
|
||||
|
||||
graphics.fillRect(width - gapSize, 0, gapSize, height);
|
||||
graphics.fillRect(0, height - gapSize, width, gapSize);
|
||||
}
|
||||
}
|
||||
|
||||
public void fill(Color color, int cell) {
|
||||
final float x = cells[cell].x();
|
||||
final float y = cells[cell].y();
|
||||
|
||||
final float width = cells[cell].width();
|
||||
final float height = cells[cell].height();
|
||||
|
||||
graphics.setFill(color);
|
||||
graphics.fillRect(x, y, width, height);
|
||||
}
|
||||
|
||||
public void clear(int cell) {
|
||||
final float x = cells[cell].x();
|
||||
final float y = cells[cell].y();
|
||||
|
||||
final float width = cells[cell].width();
|
||||
final float height = cells[cell].height();
|
||||
|
||||
graphics.clearRect(x, y, width, height);
|
||||
|
||||
graphics.setFill(backgroundColor);
|
||||
graphics.fillRect(x, y, width, height);
|
||||
}
|
||||
|
||||
public void clearAll() {
|
||||
for (int i = 0; i < cells.length; i++) {
|
||||
clear(i);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void drawPlayerMove(int player, int move) {
|
||||
final float x = cells[move].x() + gapSize;
|
||||
final float y = cells[move].y() + gapSize;
|
||||
|
||||
final float width = cells[move].width() - gapSize * 2;
|
||||
final float height = cells[move].height() - gapSize * 2;
|
||||
|
||||
graphics.setFill(color);
|
||||
graphics.setFont(Font.font("Arial", 40)); // TODO different font and size
|
||||
graphics.fillText(String.valueOf(player), x + width, y + height);
|
||||
}
|
||||
|
||||
public void drawDot(Color color, int cell) {
|
||||
final float x = cells[cell].x() + gapSize;
|
||||
final float y = cells[cell].y() + gapSize;
|
||||
|
||||
final float width = cells[cell].width() - gapSize * 2;
|
||||
final float height = cells[cell].height() - gapSize * 2;
|
||||
|
||||
graphics.setFill(color);
|
||||
graphics.fillOval(x, y, width, height);
|
||||
}
|
||||
|
||||
public void drawInnerDot(Color color, int cell, boolean slightlyBigger) {
|
||||
final float x = cells[cell].x() + gapSize;
|
||||
final float y = cells[cell].y() + gapSize;
|
||||
|
||||
float multiplier = slightlyBigger?1.4f:1.5f;
|
||||
|
||||
final float width = (cells[cell].width() - gapSize * 2)/multiplier;
|
||||
final float height = (cells[cell].height() - gapSize * 2)/multiplier;
|
||||
|
||||
float offset = slightlyBigger?5f:4f;
|
||||
|
||||
graphics.setFill(color);
|
||||
graphics.fillOval(x + width/offset, y + height/offset, width, height);
|
||||
}
|
||||
|
||||
private void drawDotScaled(Color color, int cell, double scale) {
|
||||
final float cx = cells[cell].x() + gapSize;
|
||||
final float cy = cells[cell].y() + gapSize;
|
||||
|
||||
final float fullWidth = cells[cell].width() - gapSize * 2;
|
||||
final float height = cells[cell].height() - gapSize * 2;
|
||||
|
||||
final float scaledWidth = (float)(fullWidth * scale);
|
||||
final float offsetX = (fullWidth - scaledWidth) / 2;
|
||||
|
||||
graphics.setFill(color);
|
||||
graphics.fillOval(cx + offsetX, cy, scaledWidth, height);
|
||||
}
|
||||
|
||||
public Timeline flipDot(Color fromColor, Color toColor, int cell) {
|
||||
final int steps = 60;
|
||||
final long duration = 250;
|
||||
final double interval = duration / (double) steps;
|
||||
|
||||
final Timeline timeline = new Timeline();
|
||||
|
||||
for (int i = 0; i <= steps; i++) {
|
||||
final double t = i / (double) steps;
|
||||
final KeyFrame keyFrame = new KeyFrame(Duration.millis(i * interval),
|
||||
_ -> {
|
||||
clear(cell);
|
||||
|
||||
final double scale = t <= 0.5 ? 1 - 2 * t : 2 * t - 1;
|
||||
final Color currentColor = t < 0.5 ? fromColor : toColor;
|
||||
|
||||
drawDotScaled(currentColor, cell, scale);
|
||||
}
|
||||
);
|
||||
|
||||
timeline.getKeyFrames().add(keyFrame);
|
||||
}
|
||||
|
||||
return timeline;
|
||||
}
|
||||
|
||||
public Canvas getCanvas() {
|
||||
return canvas;
|
||||
}
|
||||
}
|
||||
public interface GameCanvas<T extends TurnBasedGame<T>> extends GameDrawer<T>{
|
||||
Canvas getCanvas();
|
||||
}
|
||||
|
||||
7
app/src/main/java/org/toop/app/canvas/GameDrawer.java
Normal file
7
app/src/main/java/org/toop/app/canvas/GameDrawer.java
Normal file
@@ -0,0 +1,7 @@
|
||||
package org.toop.app.canvas;
|
||||
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
|
||||
public interface GameDrawer<T extends TurnBasedGame<T>> {
|
||||
void redraw(T gameCopy);
|
||||
}
|
||||
77
app/src/main/java/org/toop/app/canvas/ReversiBitCanvas.java
Normal file
77
app/src/main/java/org/toop/app/canvas/ReversiBitCanvas.java
Normal file
@@ -0,0 +1,77 @@
|
||||
package org.toop.app.canvas;
|
||||
|
||||
import javafx.scene.paint.Color;
|
||||
import org.toop.app.App;
|
||||
import org.toop.game.games.reversi.BitboardReversi;
|
||||
|
||||
public class ReversiBitCanvas extends BitGameCanvas<BitboardReversi> implements BitLegalMoveDrawer {
|
||||
|
||||
private final boolean switchColors;
|
||||
private final boolean local;
|
||||
|
||||
public ReversiBitCanvas(boolean switchColors, boolean local) {
|
||||
super(Color.GRAY, new Color(0f, 0.4f, 0.2f, 1f), (App.getHeight() / 4) * 3, (App.getHeight() / 4) * 3, 8, 8, 5, true);
|
||||
this.switchColors = switchColors;
|
||||
this.local = local;
|
||||
canvas.setOnMouseMoved(event -> {
|
||||
double mouseX = event.getX();
|
||||
double mouseY = event.getY();
|
||||
int cellId = -1;
|
||||
|
||||
BitGameCanvas.Cell hovered = null;
|
||||
for (BitGameCanvas.Cell cell : cells) {
|
||||
if (cell.isInside(mouseX, mouseY)) {
|
||||
hovered = cell;
|
||||
cellId = turnCoordsIntoCellId(mouseX, mouseY);
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private int turnCoordsIntoCellId(double x, double y) {
|
||||
final int column = (int) ((x / this.width) * rowSize);
|
||||
final int row = (int) ((y / this.height) * columnSize);
|
||||
return column + row * rowSize;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void redraw(BitboardReversi gameCopy) {
|
||||
clearAll();
|
||||
long[] board = gameCopy.getBoard();
|
||||
if (switchColors && local) {
|
||||
loopOverBoard(board[0], (i) -> drawDot(Color.BLACK, i));
|
||||
loopOverBoard(board[1], (i) -> drawDot(Color.WHITE, i));
|
||||
} else {
|
||||
loopOverBoard(board[0], (i) -> drawDot(Color.WHITE, i));
|
||||
loopOverBoard(board[1], (i) -> drawDot(Color.BLACK, i));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void showLegalMove(long move, int currentPlayerIndex) {
|
||||
int idx = Long.numberOfTrailingZeros(move);
|
||||
drawLegalMove(idx, currentPlayerIndex);
|
||||
}
|
||||
|
||||
public void drawLegalMove(int cell, int player) {
|
||||
Color innerColor;
|
||||
if (switchColors) {
|
||||
if (player == 0) {
|
||||
innerColor = new Color(0.0f, 0.0f, 0.0f, 0.6f);
|
||||
}
|
||||
else {
|
||||
innerColor = new Color(1.0f, 1.0f, 1.0f, 0.75f);
|
||||
}
|
||||
this.drawInnerDot(innerColor, cell, false);
|
||||
} else {
|
||||
if (player == 1) {
|
||||
innerColor = new Color(0.0f, 0.0f, 0.0f, 0.6f);
|
||||
}
|
||||
else {
|
||||
innerColor = new Color(1.0f, 1.0f, 1.0f, 0.75f);
|
||||
}
|
||||
this.drawInnerDot(innerColor, cell, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
package org.toop.app.canvas;
|
||||
|
||||
import javafx.scene.paint.Color;
|
||||
import org.toop.framework.gameFramework.model.game.AbstractGame;
|
||||
import org.toop.game.Move;
|
||||
import org.toop.game.games.reversi.ReversiR;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public final class ReversiCanvas extends GameCanvas<ReversiR> {
|
||||
private Move[] currentlyHighlightedMoves = null;
|
||||
public ReversiCanvas(Color color, int width, int height, Consumer<Integer> onCellClicked, Consumer<Integer> newCellEntered) {
|
||||
super(color, new Color(0f,0.4f,0.2f,1f), width, height, 8, 8, 5, true, onCellClicked, newCellEntered);
|
||||
drawStartingDots();
|
||||
|
||||
final AtomicReference<Cell> lastHoveredCell = new AtomicReference<>(null);
|
||||
|
||||
canvas.setOnMouseMoved(event -> {
|
||||
double mouseX = event.getX();
|
||||
double mouseY = event.getY();
|
||||
int cellId = -1;
|
||||
|
||||
Cell hovered = null;
|
||||
for (Cell cell : cells) {
|
||||
if (cell.isInside(mouseX, mouseY)) {
|
||||
hovered = cell;
|
||||
cellId = turnCoordsIntoCellId(mouseX, mouseY);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Cell previous = lastHoveredCell.get();
|
||||
|
||||
if (hovered != previous) {
|
||||
lastHoveredCell.set(hovered);
|
||||
newCellEntered.accept(cellId);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void setCurrentlyHighlightedMovesNull() {
|
||||
currentlyHighlightedMoves = null;
|
||||
}
|
||||
|
||||
public void drawHighlightDots(Move[] moves){
|
||||
if (currentlyHighlightedMoves != null){
|
||||
for (final Move move : currentlyHighlightedMoves){
|
||||
Color color = move.value() == 'W'? Color.BLACK: Color.WHITE;
|
||||
drawInnerDot(color, move.position(), true);
|
||||
}
|
||||
}
|
||||
currentlyHighlightedMoves = moves;
|
||||
if (moves != null) {
|
||||
for (Move move : moves) {
|
||||
Color color = move.value() == 'B' ? Color.BLACK : Color.WHITE;
|
||||
drawInnerDot(color, move.position(), false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private int turnCoordsIntoCellId(double x, double y) {
|
||||
final int column = (int) ((x / this.width) * rowSize);
|
||||
final int row = (int) ((y / this.height) * columnSize);
|
||||
return column + row * rowSize;
|
||||
}
|
||||
|
||||
public void drawStartingDots() {
|
||||
drawDot(Color.BLACK, 28);
|
||||
drawDot(Color.WHITE, 36);
|
||||
drawDot(Color.BLACK, 35);
|
||||
drawDot(Color.WHITE, 27);
|
||||
}
|
||||
|
||||
public void drawLegalPosition(int cell, char player) {
|
||||
|
||||
Color innerColor;
|
||||
if (player == 'B') {
|
||||
innerColor = new Color(0.0f, 0.0f, 0.0f, 0.6f);
|
||||
}
|
||||
else {
|
||||
innerColor = new Color(1.0f, 1.0f, 1.0f, 0.75f);
|
||||
}
|
||||
drawInnerDot(innerColor, cell,false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void drawPlayerMove(int player ,int move){
|
||||
super.drawPlayerMove(player, move);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void drawPlayerHover(int player, int move, AbstractGame game) {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package org.toop.app.canvas;
|
||||
|
||||
import javafx.scene.paint.Color;
|
||||
import org.toop.app.App;
|
||||
import org.toop.game.games.tictactoe.BitboardTicTacToe;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class TicTacToeBitCanvas extends BitGameCanvas<BitboardTicTacToe>{
|
||||
public TicTacToeBitCanvas() {
|
||||
super(
|
||||
Color.GRAY,
|
||||
Color.TRANSPARENT,
|
||||
(App.getHeight() / 4) * 3,
|
||||
(App.getHeight() / 4) * 3,
|
||||
3,
|
||||
3,
|
||||
30,
|
||||
false
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void redraw(BitboardTicTacToe gameCopy) {
|
||||
clearAll();
|
||||
drawMoves(gameCopy.getBoard());
|
||||
}
|
||||
|
||||
private void drawMoves(long[] gameBoard){
|
||||
loopOverBoard(gameBoard[0], (i) -> drawX(Color.RED, i));
|
||||
loopOverBoard(gameBoard[1], (i) -> drawO(Color.BLUE, i));
|
||||
}
|
||||
|
||||
|
||||
public void drawX(Color color, int cell) {
|
||||
graphics.setStroke(color);
|
||||
graphics.setLineWidth(gapSize);
|
||||
|
||||
final float x = cells[cell].x() + gapSize;
|
||||
final float y = cells[cell].y() + gapSize;
|
||||
|
||||
final float width = cells[cell].width() - gapSize * 2;
|
||||
final float height = cells[cell].height() - gapSize * 2;
|
||||
|
||||
graphics.strokeLine(x, y, x + width, y + height);
|
||||
graphics.strokeLine(x + width, y, x, y + height);
|
||||
}
|
||||
|
||||
public void drawO(Color color, int cell) {
|
||||
graphics.setStroke(color);
|
||||
graphics.setLineWidth(gapSize);
|
||||
|
||||
final float x = cells[cell].x() + gapSize;
|
||||
final float y = cells[cell].y() + gapSize;
|
||||
|
||||
final float width = cells[cell].width() - gapSize * 2;
|
||||
final float height = cells[cell].height() - gapSize * 2;
|
||||
|
||||
graphics.strokeOval(x, y, width, height);
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
package org.toop.app.canvas;
|
||||
|
||||
import javafx.scene.paint.Color;
|
||||
import org.toop.framework.gameFramework.model.game.AbstractGame;
|
||||
import org.toop.game.games.tictactoe.TicTacToeR;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public final class TicTacToeCanvas extends GameCanvas<TicTacToeR> {
|
||||
public TicTacToeCanvas(Color color, int width, int height, Consumer<Integer> onCellClicked) {
|
||||
super(color, Color.TRANSPARENT, width, height, 3, 3, 30, false, onCellClicked,null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void drawPlayerMove(int player, int move) {
|
||||
switch (player) {
|
||||
case 0 -> drawX(Color.RED, move);
|
||||
case 1 -> drawO(Color.BLUE, move);
|
||||
default -> super.drawPlayerMove(player, move);
|
||||
}
|
||||
}
|
||||
|
||||
public void drawX(Color color, int cell) {
|
||||
graphics.setStroke(color);
|
||||
graphics.setLineWidth(gapSize);
|
||||
|
||||
final float x = cells[cell].x() + gapSize;
|
||||
final float y = cells[cell].y() + gapSize;
|
||||
|
||||
final float width = cells[cell].width() - gapSize * 2;
|
||||
final float height = cells[cell].height() - gapSize * 2;
|
||||
|
||||
graphics.strokeLine(x, y, x + width, y + height);
|
||||
graphics.strokeLine(x + width, y, x, y + height);
|
||||
}
|
||||
|
||||
public void drawO(Color color, int cell) {
|
||||
graphics.setStroke(color);
|
||||
graphics.setLineWidth(gapSize);
|
||||
|
||||
final float x = cells[cell].x() + gapSize;
|
||||
final float y = cells[cell].y() + gapSize;
|
||||
|
||||
final float width = cells[cell].width() - gapSize * 2;
|
||||
final float height = cells[cell].height() - gapSize * 2;
|
||||
|
||||
graphics.strokeOval(x, y, width, height);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void drawPlayerHover(int player, int move, AbstractGame game) {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
package org.toop.app.gameControllers;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.toop.framework.gameFramework.controller.UpdatesGameUI;
|
||||
import org.toop.framework.gameFramework.view.GUIEvents;
|
||||
import org.toop.app.canvas.GameCanvas;
|
||||
import org.toop.framework.networking.events.NetworkEvents;
|
||||
import org.toop.framework.gameFramework.model.game.threadBehaviour.ThreadBehaviour;
|
||||
import org.toop.app.widget.view.GameView;
|
||||
import org.toop.framework.eventbus.EventFlow;
|
||||
import org.toop.game.gameThreads.OnlineThreadBehaviour;
|
||||
import org.toop.framework.gameFramework.model.game.AbstractGame;
|
||||
import org.toop.framework.gameFramework.model.game.SupportsOnlinePlay;
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public abstract class AbstractGameController<T extends AbstractGame<T>> implements UpdatesGameUI, ThreadBehaviour<T> {
|
||||
protected final EventFlow eventFlow = new EventFlow();
|
||||
|
||||
protected final List<Consumer<?>> listeners = new ArrayList<>();
|
||||
|
||||
// Logger for logging ofcourse
|
||||
protected final Logger logger = LogManager.getLogger(this.getClass());
|
||||
|
||||
// Reference to primary view
|
||||
protected final GameView primary;
|
||||
|
||||
// Reference to game canvas
|
||||
protected final GameCanvas<T> canvas;
|
||||
|
||||
private final Player<T>[] players; // List of players, can't be changed.
|
||||
protected final T game; // Reference to game instance
|
||||
private final ThreadBehaviour<T> gameThreadBehaviour;
|
||||
|
||||
// TODO: Change gameType to automatically happen with either dependency injection or something else.
|
||||
// TODO: Make visualisation of moves a behaviour.
|
||||
protected AbstractGameController(GameCanvas<T> canvas, Player<T>[] players, T game, ThreadBehaviour<T> gameThreadBehaviour, String gameType) {
|
||||
logger.info("Creating AbstractGameController");
|
||||
// Make sure player list matches expected size
|
||||
if (players.length != game.getPlayerCount()){
|
||||
logger.error("Player count mismatch");
|
||||
throw new IllegalArgumentException("players and game's players must have same length");
|
||||
}
|
||||
|
||||
this.canvas = canvas;
|
||||
this.players = players;
|
||||
this.game = game;
|
||||
this.gameThreadBehaviour = gameThreadBehaviour;
|
||||
|
||||
primary = new GameView(null, null, null, gameType);
|
||||
addListeners();
|
||||
}
|
||||
|
||||
public void start(){
|
||||
logger.info("Starting GameManager");
|
||||
gameThreadBehaviour.start();;
|
||||
}
|
||||
|
||||
public void stop(){
|
||||
logger.info("Stopping GameManager");
|
||||
removeListeners();
|
||||
gameThreadBehaviour.stop();
|
||||
}
|
||||
|
||||
public Player<T> getCurrentPlayer(){
|
||||
return game.getPlayer(getCurrentPlayerIndex());
|
||||
};
|
||||
|
||||
public int getCurrentPlayerIndex(){
|
||||
return game.getCurrentTurn();
|
||||
}
|
||||
|
||||
private void addListeners(){
|
||||
eventFlow
|
||||
.listen(GUIEvents.RefreshGameCanvas.class, this::onUpdateGameUI, false)
|
||||
.listen(GUIEvents.GameEnded.class, this::onGameFinish, false);
|
||||
}
|
||||
|
||||
private void removeListeners(){
|
||||
eventFlow.unsubscribeAll();
|
||||
}
|
||||
|
||||
private void onUpdateGameUI(GUIEvents.RefreshGameCanvas event){
|
||||
this.updateUI();
|
||||
}
|
||||
|
||||
private void onGameFinish(GUIEvents.GameEnded event){
|
||||
logger.info("Game Finished");
|
||||
String name = event.winner() == -1 ? null : getPlayer(event.winner()).getName();
|
||||
primary.gameOver(event.winOrTie(), name);
|
||||
stop();
|
||||
}
|
||||
|
||||
public Player<T> getPlayer(int player){
|
||||
if (player < 0 || player >= players.length){
|
||||
logger.error("Invalid player index");
|
||||
throw new IllegalArgumentException("player out of range");
|
||||
}
|
||||
return players[player];
|
||||
}
|
||||
|
||||
private boolean isOnline(){
|
||||
return this.gameThreadBehaviour instanceof SupportsOnlinePlay;
|
||||
}
|
||||
|
||||
public void onYourTurn(NetworkEvents.YourTurnResponse event){
|
||||
if (isOnline()){
|
||||
((OnlineThreadBehaviour<T>) this.gameThreadBehaviour).onYourTurn(event);
|
||||
}
|
||||
}
|
||||
|
||||
public void onMoveReceived(NetworkEvents.GameMoveResponse event){
|
||||
if (isOnline()){
|
||||
((OnlineThreadBehaviour<T>) this.gameThreadBehaviour).onMoveReceived(event);
|
||||
}
|
||||
}
|
||||
|
||||
public void gameFinished(NetworkEvents.GameResultResponse event){
|
||||
if (isOnline()){
|
||||
((OnlineThreadBehaviour<T>) this.gameThreadBehaviour).gameFinished(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package org.toop.app.gameControllers;
|
||||
|
||||
import javafx.application.Platform;
|
||||
import javafx.geometry.Pos;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.toop.app.canvas.GameCanvas;
|
||||
import org.toop.app.canvas.BitLegalMoveDrawer;
|
||||
import org.toop.app.widget.WidgetContainer;
|
||||
import org.toop.app.widget.view.GameView;
|
||||
import org.toop.framework.eventbus.EventFlow;
|
||||
import org.toop.framework.eventbus.GlobalEventBus;
|
||||
import org.toop.framework.gameFramework.controller.GameController;
|
||||
import org.toop.framework.gameFramework.model.game.SupportsOnlinePlay;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
import org.toop.framework.gameFramework.model.game.threadBehaviour.ThreadBehaviour;
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
import org.toop.framework.gameFramework.view.GUIEvents;
|
||||
import org.toop.framework.networking.events.NetworkEvents;
|
||||
import org.toop.game.players.LocalPlayer;
|
||||
|
||||
public class GenericGameController<T extends TurnBasedGame<T>, C extends GameCanvas<T>> implements GameController {
|
||||
protected final EventFlow eventFlow = new EventFlow();
|
||||
|
||||
// Logger for logging
|
||||
protected final Logger logger = LogManager.getLogger(this.getClass());
|
||||
|
||||
// Reference to gameView view
|
||||
protected final GameView gameView;
|
||||
|
||||
// Reference to String gametype
|
||||
protected final String gameType;
|
||||
|
||||
// Reference to game canvas
|
||||
protected final C canvas;
|
||||
|
||||
protected final TurnBasedGame<T> game; // Reference to game instance
|
||||
private final ThreadBehaviour gameThreadBehaviour;
|
||||
|
||||
// TODO: Change gameType to automatically happen with either dependency injection or something else.
|
||||
public GenericGameController(C canvas, T game, ThreadBehaviour gameThreadBehaviour, String gameType) {
|
||||
logger.info("Creating: " + this.getClass());
|
||||
|
||||
this.canvas = canvas;
|
||||
this.game = game;
|
||||
this.gameType = gameType;
|
||||
this.gameThreadBehaviour = gameThreadBehaviour;
|
||||
|
||||
// Tell thread how to send moves
|
||||
this.gameThreadBehaviour.setOnSendMove((id, m) -> GlobalEventBus.get().post(new NetworkEvents.SendMove(id, (short)translateMove(m))));
|
||||
|
||||
// Tell thread how to update UI
|
||||
this.gameThreadBehaviour.setOnUpdateUI(() -> Platform.runLater(this::updateUI));
|
||||
|
||||
// Change scene to game view
|
||||
gameView = new GameView(null, null, null, gameType);
|
||||
gameView.add(Pos.CENTER, canvas.getCanvas());
|
||||
WidgetContainer.getCurrentView().transitionNext(gameView, true);
|
||||
|
||||
// Listen to updates
|
||||
eventFlow
|
||||
.listen(GUIEvents.GameEnded.class, this::onGameFinish, false)
|
||||
.listen(GUIEvents.PlayerAttemptedMove.class, event -> {if (getCurrentPlayer() instanceof LocalPlayer<T> lp){lp.setLastMove(event.move());}}, false);
|
||||
}
|
||||
|
||||
public void start(){
|
||||
logger.info("Starting GameManager");
|
||||
updateUI();
|
||||
gameThreadBehaviour.start();
|
||||
}
|
||||
|
||||
public void stop(){
|
||||
logger.info("Stopping GameManager");
|
||||
removeListeners();
|
||||
gameThreadBehaviour.stop();
|
||||
}
|
||||
|
||||
public Player<T> getCurrentPlayer(){
|
||||
return game.getPlayer(getCurrentPlayerIndex());
|
||||
}
|
||||
|
||||
public int getCurrentPlayerIndex(){
|
||||
return game.getCurrentTurn();
|
||||
}
|
||||
|
||||
protected long translateMove(int move){
|
||||
return 1L << move;
|
||||
}
|
||||
|
||||
protected int translateMove(long move){
|
||||
return Long.numberOfTrailingZeros(move);
|
||||
}
|
||||
|
||||
private void removeListeners(){
|
||||
eventFlow.unsubscribeAll();
|
||||
}
|
||||
|
||||
private void onGameFinish(GUIEvents.GameEnded event){
|
||||
logger.info("Game Finished");
|
||||
String name = event.winner() == -1 ? null : getPlayer(event.winner()).getName();
|
||||
gameView.gameOver(event.winOrTie(), name);
|
||||
stop();
|
||||
}
|
||||
|
||||
public Player<T> getPlayer(int player){
|
||||
if (player < 0 || player >= 2){ // TODO: Make game turn player count
|
||||
logger.error("Invalid player index");
|
||||
throw new IllegalArgumentException("player out of range");
|
||||
}
|
||||
return game.getPlayer(player);
|
||||
}
|
||||
|
||||
private boolean isOnline(){
|
||||
return this.gameThreadBehaviour instanceof SupportsOnlinePlay;
|
||||
}
|
||||
|
||||
public void onYourTurn(NetworkEvents.YourTurnResponse event){
|
||||
if (isOnline()){
|
||||
((SupportsOnlinePlay) this.gameThreadBehaviour).onYourTurn(event.clientId());
|
||||
}
|
||||
}
|
||||
|
||||
public void onMoveReceived(NetworkEvents.GameMoveResponse event){
|
||||
if (isOnline()){
|
||||
((SupportsOnlinePlay) this.gameThreadBehaviour).onMoveReceived(
|
||||
translateMove(Integer.parseInt(event.move())));
|
||||
}
|
||||
}
|
||||
|
||||
public void gameFinished(NetworkEvents.GameResultResponse event){
|
||||
if (isOnline()){
|
||||
((SupportsOnlinePlay) this.gameThreadBehaviour).gameFinished(event.condition());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendMove(long clientId, long move) {
|
||||
new EventFlow().addPostEvent(NetworkEvents.SendMove.class, clientId, (short) Long.numberOfTrailingZeros(move)).asyncPostEvent();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateUI() {
|
||||
canvas.redraw(game.deepCopy());
|
||||
gameView.updatePlayerInfo(
|
||||
true,
|
||||
getCurrentPlayer().getName(),
|
||||
game.getCurrentTurn() == 0 ? "X" : "O",
|
||||
getPlayer((game.getCurrentTurn() + 1 ) % 2).getName(),
|
||||
this.gameType
|
||||
);
|
||||
// draw legal moves for bit canvasses
|
||||
if (canvas instanceof BitLegalMoveDrawer) {
|
||||
long movesLoop = game.getLegalMoves();
|
||||
while (movesLoop != 0) {
|
||||
long move = 1L << Long.numberOfTrailingZeros(movesLoop);
|
||||
((BitLegalMoveDrawer) canvas).showLegalMove(move, getCurrentPlayerIndex());
|
||||
movesLoop &= movesLoop - 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package org.toop.app.gameControllers;
|
||||
|
||||
import javafx.scene.paint.Color;
|
||||
import org.toop.app.canvas.ReversiBitCanvas;
|
||||
import org.toop.framework.gameFramework.model.game.threadBehaviour.ThreadBehaviour;
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
import org.toop.game.gameThreads.LocalThreadBehaviour;
|
||||
import org.toop.game.gameThreads.OnlineThreadBehaviour;
|
||||
import org.toop.game.games.reversi.BitboardReversi;
|
||||
import org.toop.game.players.LocalPlayer;
|
||||
import org.toop.game.players.OnlinePlayer;
|
||||
|
||||
public class ReversiBitController extends GenericGameController<BitboardReversi, ReversiBitCanvas> {
|
||||
public ReversiBitController(Player<BitboardReversi>[] players, boolean switchColors) {
|
||||
BitboardReversi game = new BitboardReversi(players);
|
||||
ThreadBehaviour thread = new LocalThreadBehaviour<>(game);
|
||||
for (Player<BitboardReversi> player : players) {
|
||||
if (player instanceof OnlinePlayer<BitboardReversi>) {
|
||||
thread = new OnlineThreadBehaviour<>(game);
|
||||
}
|
||||
}
|
||||
super(new ReversiBitCanvas(switchColors, players[0] instanceof LocalPlayer<BitboardReversi> || players[1] instanceof LocalPlayer<BitboardReversi>), game, thread, "Reversi");
|
||||
}
|
||||
}
|
||||
@@ -1,138 +0,0 @@
|
||||
package org.toop.app.gameControllers;
|
||||
|
||||
import javafx.animation.SequentialTransition;
|
||||
import javafx.geometry.Pos;
|
||||
import javafx.scene.paint.Color;
|
||||
import org.toop.app.App;
|
||||
import org.toop.app.canvas.ReversiCanvas;
|
||||
import org.toop.app.widget.WidgetContainer;
|
||||
import org.toop.framework.eventbus.EventFlow;
|
||||
import org.toop.framework.gameFramework.model.game.AbstractGame;
|
||||
import org.toop.framework.gameFramework.view.GUIEvents;
|
||||
import org.toop.game.gameThreads.LocalFixedRateThreadBehaviour;
|
||||
import org.toop.game.gameThreads.OnlineThreadBehaviour;
|
||||
import org.toop.game.players.LocalPlayer;
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
import org.toop.game.games.reversi.ReversiR;
|
||||
|
||||
public class ReversiController extends AbstractGameController<ReversiR> {
|
||||
// TODO: Refactor GUI update methods to follow designed system
|
||||
public ReversiController(Player<ReversiR>[] players, boolean local) {
|
||||
ReversiR ReversiR = new ReversiR(players);
|
||||
super(
|
||||
new ReversiCanvas(Color.GRAY, (App.getHeight() / 4) * 3, (App.getHeight() / 4) * 3,(c) -> {new EventFlow().addPostEvent(GUIEvents.PlayerAttemptedMove.class, c).postEvent();}, (c) -> {new EventFlow().addPostEvent(GUIEvents.PlayerMoveHovered.class, c).postEvent();}),
|
||||
players,
|
||||
ReversiR,
|
||||
local ? new LocalFixedRateThreadBehaviour<>(ReversiR, players) : new OnlineThreadBehaviour<>(ReversiR, players), // TODO: Player order matters here, this won't work atm
|
||||
"Reversi");
|
||||
eventFlow.listen(GUIEvents.PlayerAttemptedMove.class, event -> {if (getCurrentPlayer() instanceof LocalPlayer lp){lp.setMove(event.move());}}, false);
|
||||
eventFlow.listen(GUIEvents.PlayerMoveHovered.class, this::onHoverMove, false);
|
||||
initUI();
|
||||
}
|
||||
|
||||
|
||||
private void onHoverMove(GUIEvents.PlayerMoveHovered event){
|
||||
int cellEntered = event.move();
|
||||
canvas.drawPlayerHover(-1, cellEntered, game);
|
||||
/*// (information.players[game.getCurrentTurn()].isHuman) {
|
||||
int[] legalMoves = game.getLegalMoves();
|
||||
boolean isLegalMove = false;
|
||||
for (int move : legalMoves) {
|
||||
if (move == cellEntered){
|
||||
isLegalMove = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (cellEntered >= 0){
|
||||
int[] moves = null;
|
||||
if (isLegalMove) {
|
||||
moves = game.getFlipsForPotentialMove(
|
||||
new Point(cellEntered%game.getColumnSize(),cellEntered/game.getRowSize()),
|
||||
game.getCurrentPlayer());
|
||||
}
|
||||
canvas.drawHighlightDots(moves);
|
||||
}
|
||||
//}*/
|
||||
}
|
||||
|
||||
public ReversiController(Player<ReversiR>[] players) {
|
||||
this(players, true);
|
||||
}
|
||||
|
||||
private void updateCanvas(boolean animate) {
|
||||
// Todo: this is very inefficient. still very fast but if the grid is bigger it might cause issues. improve.
|
||||
canvas.clearAll();
|
||||
|
||||
for (int i = 0; i < game.getBoard().length; i++) {
|
||||
if (game.getBoard()[i] == 0) {
|
||||
canvas.drawDot(Color.WHITE, i);
|
||||
} else if (game.getBoard()[i] == 1) {
|
||||
canvas.drawDot(Color.BLACK, i);
|
||||
}
|
||||
}
|
||||
|
||||
final int[] flipped = game.getMostRecentlyFlippedPieces();
|
||||
|
||||
final SequentialTransition animation = new SequentialTransition();
|
||||
|
||||
final Color fromColor = getCurrentPlayerIndex() == 0? Color.WHITE : Color.BLACK;
|
||||
final Color toColor = getCurrentPlayerIndex() == 0? Color.BLACK : Color.WHITE;
|
||||
|
||||
if (animate && flipped != null) {
|
||||
for (final int flip : flipped) {
|
||||
canvas.clear(flip);
|
||||
canvas.drawDot(fromColor, flip);
|
||||
animation.getChildren().addFirst(canvas.flipDot(fromColor, toColor, flip));
|
||||
}
|
||||
}
|
||||
|
||||
animation.setOnFinished(_ -> {
|
||||
|
||||
if (getCurrentPlayer() instanceof LocalPlayer) {
|
||||
final int[] legalMoves = game.getLegalMoves();
|
||||
|
||||
for (final int legalMove : legalMoves) {
|
||||
drawLegalPosition(legalMove, getCurrentPlayerIndex());
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
animation.play();
|
||||
primary.nextPlayer(true, getCurrentPlayer().getName(), game.getCurrentTurn() == 0 ? "X" : "O", getPlayer((game.getCurrentTurn() + 1) % 2).getName());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateUI() {
|
||||
updateCanvas(false);
|
||||
}
|
||||
|
||||
public void drawLegalPosition(int cell, int player) {
|
||||
Color innerColor;
|
||||
if (player == 1) {
|
||||
innerColor = new Color(0.0f, 0.0f, 0.0f, 0.6f);
|
||||
}
|
||||
else {
|
||||
innerColor = new Color(1.0f, 1.0f, 1.0f, 0.75f);
|
||||
}
|
||||
canvas.drawInnerDot(innerColor, cell,false);
|
||||
}
|
||||
|
||||
private void initUI(){
|
||||
primary.add(Pos.CENTER, canvas.getCanvas());
|
||||
WidgetContainer.getCurrentView().transitionNext(primary, true);
|
||||
updateCanvas(false);
|
||||
}
|
||||
|
||||
private void drawMoves(){
|
||||
int[] board = game.getBoard();
|
||||
|
||||
// Draw each square
|
||||
for (int i = 0; i < board.length; i++){
|
||||
// If square isn't empty, draw player move
|
||||
if (board[i] != AbstractGame.EMPTY){
|
||||
canvas.drawPlayerMove(board[i], i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package org.toop.app.gameControllers;
|
||||
|
||||
import org.toop.app.canvas.TicTacToeBitCanvas;
|
||||
import org.toop.framework.gameFramework.model.game.threadBehaviour.ThreadBehaviour;
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
import org.toop.game.gameThreads.LocalFixedRateThreadBehaviour;
|
||||
import org.toop.game.gameThreads.LocalThreadBehaviour;
|
||||
import org.toop.game.gameThreads.OnlineThreadBehaviour;
|
||||
import org.toop.game.games.tictactoe.BitboardTicTacToe;
|
||||
import org.toop.game.players.OnlinePlayer;
|
||||
|
||||
public class TicTacToeBitController extends GenericGameController<BitboardTicTacToe, TicTacToeBitCanvas > {
|
||||
public TicTacToeBitController(Player<BitboardTicTacToe>[] players) {
|
||||
BitboardTicTacToe game = new BitboardTicTacToe(players);
|
||||
ThreadBehaviour thread = new LocalThreadBehaviour<>(game);
|
||||
for (Player<BitboardTicTacToe> player : players) {
|
||||
if (player instanceof OnlinePlayer<BitboardTicTacToe>){
|
||||
thread = new OnlineThreadBehaviour<>(game);
|
||||
}
|
||||
}
|
||||
super(new TicTacToeBitCanvas(), game, thread , "TicTacToe");
|
||||
}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
package org.toop.app.gameControllers;
|
||||
|
||||
import javafx.geometry.Pos;
|
||||
import javafx.scene.paint.Color;
|
||||
import org.toop.app.App;
|
||||
import org.toop.app.canvas.TicTacToeCanvas;
|
||||
import org.toop.framework.eventbus.EventFlow;
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
import org.toop.framework.gameFramework.view.GUIEvents;
|
||||
import org.toop.framework.gameFramework.model.game.AbstractGame;
|
||||
import org.toop.game.gameThreads.LocalThreadBehaviour;
|
||||
import org.toop.game.gameThreads.OnlineThreadBehaviour;
|
||||
import org.toop.game.players.LocalPlayer;
|
||||
import org.toop.app.widget.WidgetContainer;
|
||||
import org.toop.game.games.tictactoe.TicTacToeR;
|
||||
|
||||
public class TicTacToeController extends AbstractGameController<TicTacToeR> {
|
||||
|
||||
public TicTacToeController(Player<TicTacToeR>[] players, boolean local) {
|
||||
TicTacToeR ticTacToeR = new TicTacToeR(players);
|
||||
super(
|
||||
new TicTacToeCanvas(Color.GRAY, (App.getHeight() / 4) * 3, (App.getHeight() / 4) * 3,(c) -> {new EventFlow().addPostEvent(GUIEvents.PlayerAttemptedMove.class, c).postEvent();}),
|
||||
players,
|
||||
ticTacToeR,
|
||||
local ? new LocalThreadBehaviour(ticTacToeR, players) : new OnlineThreadBehaviour<>(ticTacToeR, players), // TODO: Player order matters here, this won't work atm
|
||||
"TicTacToe");
|
||||
|
||||
initUI();
|
||||
eventFlow.listen(GUIEvents.PlayerAttemptedMove.class, event -> {if (getCurrentPlayer() instanceof LocalPlayer lp){lp.setMove(event.move());}}, false);
|
||||
//addListener(GlobalEventBus.subscribe(GUIEvents.PlayerAttemptedMove.class, event -> {if (getCurrentPlayer() instanceof LocalPlayer lp){lp.setMove(event.move());}}));
|
||||
//new EventFlow().listen(GUIEvents.PlayerAttemptedMove.class, event -> {if (getCurrentPlayer() instanceof LocalPlayer lp){lp.setMove(event.move());}});
|
||||
}
|
||||
|
||||
public TicTacToeController(Player<TicTacToeR>[] players) {
|
||||
this(players, true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateUI() {
|
||||
canvas.clearAll();
|
||||
// TODO: wtf is even this pile of poop temp fix
|
||||
primary.nextPlayer(true, getCurrentPlayer().getName(), game.getCurrentTurn() == 0 ? "X" : "O", getPlayer((game.getCurrentTurn() + 1) % 2).getName());
|
||||
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.local.AppContext;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import javafx.collections.FXCollections;
|
||||
|
||||
@@ -2,19 +2,27 @@ package org.toop.app.widget;
|
||||
|
||||
import javafx.geometry.Pos;
|
||||
import javafx.scene.Node;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
public interface Widget {
|
||||
Logger logger = LogManager.getLogger(Widget.class);
|
||||
|
||||
Node getNode();
|
||||
|
||||
default void show(Pos position) {
|
||||
logger.debug("Showing Widget: {} at position: {}", this.getNode(), position.toString());
|
||||
WidgetContainer.add(position, this);
|
||||
}
|
||||
|
||||
default void hide() {
|
||||
logger.debug("Hiding Widget: {}", this.getNode());
|
||||
WidgetContainer.remove(this);
|
||||
}
|
||||
|
||||
default void replace(Pos position, Widget widget) {
|
||||
logger.debug("Replacing Widget: {}, with widget: {}, to position: {}",
|
||||
this.getNode(), widget.getNode(), position.toString());
|
||||
widget.show(position);
|
||||
hide();
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package org.toop.app.widget;
|
||||
|
||||
import javafx.scene.Node;
|
||||
import org.toop.app.widget.complex.PopupWidget;
|
||||
import org.toop.app.widget.complex.ViewWidget;
|
||||
|
||||
@@ -7,6 +8,10 @@ import javafx.application.Platform;
|
||||
import javafx.geometry.Pos;
|
||||
import javafx.scene.layout.StackPane;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
public final class WidgetContainer {
|
||||
private static StackPane root;
|
||||
private static ViewWidget currentView;
|
||||
@@ -38,7 +43,7 @@ public final class WidgetContainer {
|
||||
root.getChildren().addFirst(view.getNode());
|
||||
currentView = view;
|
||||
} else if (widget instanceof PopupWidget popup) {
|
||||
currentView.add(Pos.CENTER, popup);
|
||||
currentView.add(Pos.CENTER, (Widget) popup);
|
||||
} else {
|
||||
root.getChildren().add(widget.getNode());
|
||||
}
|
||||
@@ -52,13 +57,61 @@ public final class WidgetContainer {
|
||||
|
||||
Platform.runLater(() -> {
|
||||
if (widget instanceof PopupWidget popup) {
|
||||
currentView.remove(popup);
|
||||
currentView.remove((Widget) popup);
|
||||
} else {
|
||||
root.getChildren().remove(widget.getNode());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static void remove(Class<? extends Widget> widgetClass) {
|
||||
if (root == null || currentView == null) return;
|
||||
|
||||
Platform.runLater(() ->
|
||||
currentView.getChildren().removeIf(widget -> widget.getClass().isAssignableFrom(widgetClass))
|
||||
);
|
||||
}
|
||||
|
||||
public static void removeFirst(Class<? extends Widget> widgetClass) {
|
||||
if (root == null || currentView == null) return;
|
||||
|
||||
Platform.runLater(() -> {
|
||||
for (Node widget : currentView.getChildren()) {
|
||||
if (widgetClass.isAssignableFrom(widget.getClass())) {
|
||||
currentView.getChildren().remove(widget);
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static List<Widget> find(Class<? extends Widget> widgetClass) {
|
||||
if (root == null || currentView == null) return null;
|
||||
|
||||
return getAllWidgets()
|
||||
.stream()
|
||||
.filter(widget -> widget.getClass().isAssignableFrom(widgetClass))
|
||||
.toList();
|
||||
}
|
||||
|
||||
public static List<Widget> find(Predicate<Widget> predicate) {
|
||||
if (root == null || currentView == null) return null;
|
||||
|
||||
return getAllWidgets()
|
||||
.stream()
|
||||
.filter(predicate)
|
||||
.toList();
|
||||
}
|
||||
|
||||
public static Widget findFirst(Class<? extends Widget> widgetClass) {
|
||||
if (root == null || currentView == null) return null;
|
||||
|
||||
return getAllWidgets()
|
||||
.stream()
|
||||
.filter(widget -> widget.getClass().isAssignableFrom(widgetClass))
|
||||
.findFirst().orElse(null);
|
||||
}
|
||||
|
||||
public static ViewWidget getCurrentView() {
|
||||
return currentView;
|
||||
}
|
||||
@@ -74,4 +127,22 @@ public final class WidgetContainer {
|
||||
currentView = view;
|
||||
});
|
||||
}
|
||||
|
||||
public static List<Widget> getAllWidgets() {
|
||||
final List<Widget> children = new ArrayList<>();
|
||||
|
||||
for (var child : root.getChildren()) {
|
||||
if (child instanceof Widget widget) {
|
||||
children.add(widget);
|
||||
}
|
||||
}
|
||||
|
||||
for (var child : currentView.getNode().getChildren()) {
|
||||
if (child instanceof Widget widget) {
|
||||
children.add(widget);
|
||||
}
|
||||
}
|
||||
|
||||
return children;
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ package org.toop.app.widget.complex;
|
||||
|
||||
import javafx.application.Platform;
|
||||
import javafx.geometry.Pos;
|
||||
import javafx.scene.control.Control;
|
||||
import javafx.scene.Node;
|
||||
import javafx.scene.control.ProgressBar;
|
||||
import javafx.scene.control.ProgressIndicator;
|
||||
import javafx.scene.layout.VBox;
|
||||
@@ -144,11 +144,11 @@ public class LoadingWidget extends ViewWidget implements Update { // TODO make o
|
||||
|
||||
if (successTrigger.call()) {
|
||||
triggerSuccess();
|
||||
this.remove(this);
|
||||
this.remove((Node) this);
|
||||
return;
|
||||
} else if (failureTrigger.call()) {
|
||||
triggerFailure();
|
||||
this.remove(this);
|
||||
this.remove((Node) this);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -5,10 +5,13 @@ import org.toop.app.widget.Primitive;
|
||||
|
||||
import javafx.scene.Node;
|
||||
import javafx.scene.layout.VBox;
|
||||
import javafx.scene.text.Text;
|
||||
|
||||
public class PlayerInfoWidget {
|
||||
private final GameInformation.Player information;
|
||||
private final VBox container;
|
||||
private Text playerName;
|
||||
private boolean hasSet;
|
||||
|
||||
public PlayerInfoWidget(GameInformation.Player information) {
|
||||
this.information = information;
|
||||
@@ -16,10 +19,11 @@ public class PlayerInfoWidget {
|
||||
buildToggle().getNode(),
|
||||
buildContent()
|
||||
);
|
||||
this.playerName = null;
|
||||
}
|
||||
|
||||
private ToggleWidget buildToggle() {
|
||||
return new ToggleWidget(
|
||||
return new ToggleWidget(
|
||||
"computer", "player",
|
||||
information.isHuman,
|
||||
isHuman -> {
|
||||
@@ -33,51 +37,76 @@ public class PlayerInfoWidget {
|
||||
}
|
||||
|
||||
private Node buildContent() {
|
||||
if (information.isHuman) {
|
||||
var nameInput = new LabeledInputWidget(
|
||||
"name",
|
||||
"enter-your-name",
|
||||
information.name,
|
||||
newName -> information.name = newName
|
||||
);
|
||||
|
||||
return nameInput.getNode();
|
||||
} else {
|
||||
if (information.name == null || information.name.isEmpty()) {
|
||||
information.name = "Pism Bot";
|
||||
}
|
||||
if (information.isHuman) {
|
||||
var spacer = Primitive.vbox(
|
||||
makeAIButton(0, 0, "zwartepiet"),
|
||||
makeAIButton(0, 0, "sinterklaas"),
|
||||
makeAIButton(0, 0, "santa")
|
||||
); //todo make a better solution
|
||||
spacer.setVisible(false);
|
||||
var nameInput = new LabeledInputWidget(
|
||||
"name",
|
||||
"enter-your-name",
|
||||
information.name,
|
||||
newName -> information.name = newName
|
||||
);
|
||||
|
||||
var playerName = Primitive.text("");
|
||||
playerName.setText(information.name);
|
||||
return Primitive.vbox(spacer,nameInput.getNode());
|
||||
} else {
|
||||
var AIBox = Primitive.vbox(
|
||||
makeAIButton(0, 1, "zwartepiet"),
|
||||
makeAIButton(2, 1, "sinterklaas"),
|
||||
makeAIButton(9, 1, "santa")
|
||||
);
|
||||
|
||||
var nameDisplay = Primitive.vbox(
|
||||
Primitive.text("name"),
|
||||
playerName
|
||||
);
|
||||
this.playerName = Primitive.text("");
|
||||
playerName.setText(information.name);
|
||||
|
||||
var difficultySlider = new LabeledSliderWidget(
|
||||
"computer-difficulty",
|
||||
0, 5,
|
||||
information.computerDifficulty,
|
||||
newVal -> information.computerDifficulty = newVal
|
||||
);
|
||||
var nameDisplay = Primitive.vbox(
|
||||
Primitive.text("name"),
|
||||
playerName
|
||||
);
|
||||
|
||||
var thinkTimeSlider = new LabeledSliderWidget(
|
||||
"computer-think-time",
|
||||
0, 5,
|
||||
information.computerThinkTime,
|
||||
newVal -> information.computerThinkTime = newVal
|
||||
);
|
||||
if (!hasSet) {
|
||||
doDefault();
|
||||
hasSet = true;
|
||||
}
|
||||
|
||||
return Primitive.vbox(
|
||||
nameDisplay,
|
||||
difficultySlider.getNode(),
|
||||
thinkTimeSlider.getNode()
|
||||
);
|
||||
}
|
||||
}
|
||||
return Primitive.vbox(
|
||||
AIBox,
|
||||
nameDisplay
|
||||
);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public Node getNode() {
|
||||
return container;
|
||||
}
|
||||
|
||||
private Node makeAIButton(int depth, int thinktime, String name) {
|
||||
return Primitive.button(name, () -> {
|
||||
information.name = getName(name);
|
||||
information.computerDifficulty = depth;
|
||||
information.computerThinkTime = thinktime;
|
||||
this.playerName.setText(getName(name));
|
||||
});
|
||||
}
|
||||
|
||||
private String getName(String name) {
|
||||
return switch (name) {
|
||||
case "sinterklaas" -> "Sint. R. Klaas";
|
||||
case "zwartepiet" -> "Zwarte Piet";
|
||||
case "santa" -> "Santa";
|
||||
default -> "Default";
|
||||
};
|
||||
}
|
||||
|
||||
private void doDefault() {
|
||||
information.name = getName("zwartepiet");
|
||||
information.computerDifficulty = 0;
|
||||
information.computerThinkTime = 1;
|
||||
this.playerName.setText(getName("zwartepiet"));
|
||||
}
|
||||
}
|
||||
@@ -7,22 +7,19 @@ import javafx.geometry.Pos;
|
||||
import javafx.scene.Node;
|
||||
import javafx.scene.layout.StackPane;
|
||||
|
||||
public abstract class StackWidget implements Widget {
|
||||
private final StackPane container;
|
||||
|
||||
public abstract class StackWidget extends StackPane implements Widget {
|
||||
public StackWidget(String cssClass) {
|
||||
container = new StackPane();
|
||||
container.getStyleClass().add(cssClass);
|
||||
this.getStyleClass().add(cssClass);
|
||||
}
|
||||
|
||||
public void add(Pos position, Node node) {
|
||||
Platform.runLater(() -> {
|
||||
if (container.getChildren().contains(node)) {
|
||||
if (this.getChildren().contains(node)) {
|
||||
return;
|
||||
}
|
||||
|
||||
StackPane.setAlignment(node, position);
|
||||
container.getChildren().add(node);
|
||||
this.getChildren().add(node);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -32,7 +29,7 @@ public abstract class StackWidget implements Widget {
|
||||
|
||||
public void remove(Node node) {
|
||||
Platform.runLater(() -> {
|
||||
container.getChildren().remove(node);
|
||||
this.getChildren().remove(node);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -41,7 +38,7 @@ public abstract class StackWidget implements Widget {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Node getNode() {
|
||||
return container;
|
||||
public StackPane getNode() {
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,19 @@ public abstract class ViewWidget extends StackWidget {
|
||||
view.add(Pos.BOTTOM_LEFT, Primitive.vbox(backButton));
|
||||
}
|
||||
|
||||
public void transitionNextCustom(ViewWidget view, String key, Runnable runnable) {
|
||||
view.previous = this;
|
||||
|
||||
replace(Pos.CENTER, view);
|
||||
|
||||
var customButton = Primitive.button(key, () -> {
|
||||
runnable.run();
|
||||
view.transitionPrevious();
|
||||
});
|
||||
|
||||
view.add(Pos.BOTTOM_LEFT, Primitive.vbox(customButton));
|
||||
}
|
||||
|
||||
public void transitionPrevious() {
|
||||
if (previous == null) {
|
||||
return;
|
||||
@@ -46,6 +59,38 @@ public abstract class ViewWidget extends StackWidget {
|
||||
previous = null;
|
||||
}
|
||||
|
||||
public void removeIndexFromPreviousChain(int index) {
|
||||
ViewWidget view = this;
|
||||
|
||||
while (index > 0 && view != null) {
|
||||
index--;
|
||||
|
||||
if (index == 0) {
|
||||
if (view.previous != null && view.previous.previous != null) {
|
||||
view.previous = view.previous.previous;
|
||||
}
|
||||
}
|
||||
|
||||
view = view.previous;
|
||||
}
|
||||
}
|
||||
|
||||
public void removeViewFromPreviousChain(ViewWidget view) {
|
||||
ViewWidget prev = previous;
|
||||
int index = 0;
|
||||
|
||||
while (prev != null) {
|
||||
index++;
|
||||
|
||||
if (prev == view) {
|
||||
removeIndexFromPreviousChain(index);
|
||||
break;
|
||||
}
|
||||
|
||||
prev = prev.previous;
|
||||
}
|
||||
}
|
||||
|
||||
public void reload(ViewWidget view) {
|
||||
view.previous = previous;
|
||||
replace(Pos.CENTER, view);
|
||||
|
||||
@@ -49,11 +49,11 @@ public class SongDisplay extends VBox implements Widget {
|
||||
previousButton.getStyleClass().setAll("previous-button");
|
||||
|
||||
skipButton.setOnAction( event -> {
|
||||
GlobalEventBus.post(new AudioEvents.SkipMusic());
|
||||
GlobalEventBus.get().post(new AudioEvents.SkipMusic());
|
||||
});
|
||||
|
||||
pauseButton.setOnAction(event -> {
|
||||
GlobalEventBus.post(new AudioEvents.PauseMusic());
|
||||
GlobalEventBus.get().post(new AudioEvents.PauseMusic());
|
||||
if (pauseButton.getText().equals("⏸")) {
|
||||
pauseButton.setText("▶");
|
||||
}
|
||||
@@ -63,7 +63,7 @@ public class SongDisplay extends VBox implements Widget {
|
||||
});
|
||||
|
||||
previousButton.setOnAction( event -> {
|
||||
GlobalEventBus.post(new AudioEvents.PreviousMusic());
|
||||
GlobalEventBus.get().post(new AudioEvents.PreviousMusic());
|
||||
});
|
||||
|
||||
HBox control = new HBox(10, previousButton, pauseButton, skipButton);
|
||||
|
||||
@@ -8,6 +8,7 @@ import org.toop.app.widget.complex.PopupWidget;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import javafx.geometry.Pos;
|
||||
import org.toop.local.AppContext;
|
||||
|
||||
public final class ChallengePopup extends PopupWidget {
|
||||
private final GameInformation.Player playerInformation;
|
||||
@@ -28,19 +29,22 @@ public final class ChallengePopup extends PopupWidget {
|
||||
private void setupLayout() {
|
||||
var challengeText = Primitive.text("you-were-challenged-by");
|
||||
|
||||
var challengerHeader = Primitive.header("");
|
||||
challengerHeader.setText(challenger);
|
||||
var challengerHeader = Primitive.header(challenger, false);
|
||||
|
||||
var gameText = Primitive.text("to-a-game-of");
|
||||
gameText.setText(gameText.getText() + " " + game);
|
||||
var toAGameOfText = Primitive.text("to-a-game-of");
|
||||
var gameHeader = Primitive.header(game, false);
|
||||
|
||||
var acceptButton = Primitive.button("accept", () -> onAccept.accept(playerInformation));
|
||||
var acceptButton = Primitive.button("accept", () -> {
|
||||
onAccept.accept(playerInformation);
|
||||
this.hide();
|
||||
});
|
||||
var denyButton = Primitive.button("deny", () -> hide());
|
||||
|
||||
var leftSection = Primitive.vbox(
|
||||
challengeText,
|
||||
challengerHeader,
|
||||
gameText,
|
||||
toAGameOfText,
|
||||
gameHeader,
|
||||
Primitive.separator(),
|
||||
Primitive.hbox(
|
||||
acceptButton,
|
||||
|
||||
48
app/src/main/java/org/toop/app/widget/popup/EscapePopup.java
Normal file
48
app/src/main/java/org/toop/app/widget/popup/EscapePopup.java
Normal file
@@ -0,0 +1,48 @@
|
||||
package org.toop.app.widget.popup;
|
||||
|
||||
import javafx.geometry.Pos;
|
||||
import javafx.scene.Node;
|
||||
import org.toop.app.widget.Primitive;
|
||||
import org.toop.app.widget.Widget;
|
||||
import org.toop.app.widget.WidgetContainer;
|
||||
import org.toop.app.widget.complex.PopupWidget;
|
||||
import org.toop.app.widget.complex.ViewWidget;
|
||||
import org.toop.app.widget.view.GameView;
|
||||
import org.toop.app.widget.view.OptionsView;
|
||||
import org.toop.local.AppContext;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class EscapePopup extends PopupWidget {
|
||||
public EscapePopup() {
|
||||
ViewWidget currentView = WidgetContainer.getCurrentView();
|
||||
ArrayList<Node> nodes = new ArrayList<>();
|
||||
|
||||
nodes.add(Primitive.button("Continue", this::hide, false)); // TODO, localize
|
||||
|
||||
if (!(currentView.getClass().isAssignableFrom(OptionsView.class))) {
|
||||
var opt = Primitive.button("options", () -> {
|
||||
hide();
|
||||
WidgetContainer.getCurrentView().transitionNext(new OptionsView());
|
||||
});
|
||||
nodes.add(opt);
|
||||
}
|
||||
|
||||
if (currentView.getClass().isAssignableFrom(GameView.class)) {
|
||||
Widget tut = AppContext.currentTutorial();
|
||||
if (tut != null) {
|
||||
nodes.add(Primitive.button("tutorialstring", () -> {
|
||||
WidgetContainer.getCurrentView().add(Pos.CENTER, tut);
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
nodes.add(Primitive.button("quit", () -> {
|
||||
hide();
|
||||
WidgetContainer.add(Pos.CENTER, new QuitPopup());
|
||||
}));
|
||||
|
||||
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.PopupWidget;
|
||||
import org.toop.local.AppContext;
|
||||
|
||||
import javafx.geometry.Pos;
|
||||
|
||||
|
||||
@@ -15,14 +15,12 @@ public class QuitPopup extends PopupWidget {
|
||||
});
|
||||
|
||||
confirmWidget.addButton("no", () -> {
|
||||
App.stopQuit();
|
||||
hide();
|
||||
});
|
||||
|
||||
add(Pos.CENTER, confirmWidget);
|
||||
|
||||
setOnPop(() -> {
|
||||
App.stopQuit();
|
||||
hide();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ public final class SendChallengePopup extends PopupWidget {
|
||||
// --- Left side: challenge text and buttons ---
|
||||
var challengeText = Primitive.text("challenge");
|
||||
|
||||
var opponentHeader = Primitive.header(opponent);
|
||||
var opponentHeader = Primitive.header(opponent, false);
|
||||
|
||||
var gameText = Primitive.text("to-a-game-of");
|
||||
|
||||
@@ -61,7 +61,7 @@ public final class SendChallengePopup extends PopupWidget {
|
||||
|
||||
var sendButton = Primitive.button(
|
||||
"send",
|
||||
() -> onSend.accept(playerInformation, gameChoice.getValue())
|
||||
() -> { onSend.accept(playerInformation, gameChoice.getValue()); this.hide(); }
|
||||
);
|
||||
|
||||
var cancelButton = Primitive.button("cancel", () -> hide());
|
||||
|
||||
@@ -7,7 +7,6 @@ import javafx.scene.text.Text;
|
||||
import org.apache.maven.surefire.shared.lang3.tuple.ImmutablePair;
|
||||
import org.toop.app.widget.Primitive;
|
||||
import org.toop.app.widget.Updatable;
|
||||
import org.toop.app.widget.WidgetContainer;
|
||||
import org.toop.app.widget.complex.PopupWidget;
|
||||
|
||||
import org.toop.framework.resource.resources.ImageAsset;
|
||||
@@ -59,8 +58,6 @@ public class BaseTutorialWidget extends PopupWidget implements Updatable {
|
||||
var x = Primitive.vbox(imagery, tutorialText);
|
||||
|
||||
add(Pos.CENTER, Primitive.vbox(x, w));
|
||||
|
||||
WidgetContainer.add(Pos.CENTER, this);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -1,34 +1,44 @@
|
||||
package org.toop.app.widget.view;
|
||||
|
||||
import javafx.scene.paint.Color;
|
||||
import javafx.scene.shape.Circle;
|
||||
import javafx.scene.text.Font;
|
||||
import org.toop.app.widget.Primitive;
|
||||
import org.toop.app.widget.complex.ViewWidget;
|
||||
import org.toop.app.widget.popup.GameOverPopup;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import javafx.application.Platform;
|
||||
import javafx.geometry.Pos;
|
||||
import javafx.scene.control.Button;
|
||||
import javafx.scene.control.TextField;
|
||||
import javafx.scene.text.Text;
|
||||
import org.toop.app.widget.tutorial.BaseTutorialWidget;
|
||||
import org.toop.app.widget.tutorial.Connect4TutorialWidget;
|
||||
import org.toop.app.widget.tutorial.ReversiTutorialWidget;
|
||||
import org.toop.app.widget.tutorial.TicTacToeTutorialWidget;
|
||||
import org.toop.local.AppContext;
|
||||
import org.toop.local.AppSettings;
|
||||
|
||||
public final class GameView extends ViewWidget {
|
||||
private final Text currentPlayerHeader;
|
||||
private final Text currentMoveHeader;
|
||||
private final Text nextPlayerHeader;
|
||||
private final Text playerHeader;
|
||||
private final Text turnHeader;
|
||||
private final Text player1Header;
|
||||
private final Text player2Header;
|
||||
private final Circle player1Icon;
|
||||
private final Circle player2Icon;
|
||||
private final Button forfeitButton;
|
||||
private final Button exitButton;
|
||||
private final Button tutorialButton;
|
||||
private final TextField chatInput;
|
||||
private final Text keyThingy;
|
||||
private boolean hasSet = false;
|
||||
|
||||
public GameView(Runnable onForfeit, Runnable onExit, Consumer<String> onMessage, String gameType) {
|
||||
currentPlayerHeader = Primitive.header("");
|
||||
currentMoveHeader = Primitive.header("");
|
||||
nextPlayerHeader = Primitive.header("");
|
||||
playerHeader = Primitive.header("");
|
||||
turnHeader = Primitive.header("");
|
||||
keyThingy = Primitive.text("turnof");
|
||||
player1Header = Primitive.header("");
|
||||
player2Header = Primitive.header("");
|
||||
player1Icon = new Circle();
|
||||
player2Icon = new Circle();
|
||||
|
||||
if (onForfeit != null) {
|
||||
forfeitButton = Primitive.button("forfeit", () -> onForfeit.run());
|
||||
@@ -51,32 +61,27 @@ public final class GameView extends ViewWidget {
|
||||
chatInput = null;
|
||||
}
|
||||
|
||||
switch(gameType) {
|
||||
switch (gameType) {
|
||||
case "TicTacToe":
|
||||
this.tutorialButton = Primitive.button("tutorialstring", () -> new TicTacToeTutorialWidget(() -> {})); break;
|
||||
AppContext.setCurrentTutorial(new TicTacToeTutorialWidget(() -> {}));
|
||||
break;
|
||||
case "Reversi":
|
||||
this.tutorialButton = Primitive.button("tutorialstring", () -> new ReversiTutorialWidget(() -> {})); break;
|
||||
AppContext.setCurrentTutorial(new ReversiTutorialWidget(() -> {}));
|
||||
break;
|
||||
case "Connect4":
|
||||
this.tutorialButton = Primitive.button("tutorialstring", () -> new Connect4TutorialWidget(() -> {})); break;
|
||||
default:
|
||||
this.tutorialButton = null; break;
|
||||
AppContext.setCurrentTutorial(new Connect4TutorialWidget(() -> {}));
|
||||
break;
|
||||
}
|
||||
|
||||
setupLayout();
|
||||
}
|
||||
|
||||
private void setupLayout() {
|
||||
var playerInfo = Primitive.vbox(
|
||||
currentPlayerHeader,
|
||||
Primitive.hbox(
|
||||
Primitive.separator(),
|
||||
currentMoveHeader,
|
||||
Primitive.separator()
|
||||
),
|
||||
nextPlayerHeader
|
||||
);
|
||||
var turnInfo = Primitive.vbox(
|
||||
turnHeader
|
||||
);
|
||||
|
||||
add(Pos.TOP_RIGHT, playerInfo);
|
||||
add(Pos.TOP_CENTER, turnInfo);
|
||||
|
||||
var buttons = Primitive.vbox(
|
||||
forfeitButton,
|
||||
@@ -88,27 +93,89 @@ public final class GameView extends ViewWidget {
|
||||
if (chatInput != null) {
|
||||
add(Pos.BOTTOM_RIGHT, Primitive.vbox(chatInput));
|
||||
}
|
||||
|
||||
if (tutorialButton != null) {
|
||||
add(Pos.TOP_LEFT, tutorialButton);
|
||||
}
|
||||
}
|
||||
|
||||
public void nextPlayer(boolean isMe, String currentPlayer, String currentMove, String nextPlayer) {
|
||||
public void updatePlayerInfo(boolean isMe, String currentPlayer, String currentMove, String nextPlayer, String GameType) {
|
||||
Platform.runLater(() -> {
|
||||
currentPlayerHeader.setText(currentPlayer);
|
||||
currentMoveHeader.setText(currentMove);
|
||||
nextPlayerHeader.setText(nextPlayer);
|
||||
|
||||
if (isMe) {
|
||||
currentPlayerHeader.getStyleClass().add("my-turn");
|
||||
} else {
|
||||
currentPlayerHeader.getStyleClass().remove("my-turn");
|
||||
}
|
||||
if (!(hasSet)) {
|
||||
playerHeader.setText(currentPlayer + " vs. " + nextPlayer);
|
||||
hasSet = true;
|
||||
setPlayerHeaders(isMe, currentPlayer, nextPlayer, GameType);
|
||||
}
|
||||
//TODO idk if theres any way to check this? only EN uses 's and the rest doesnt. if theres a better way to do this pls let me know
|
||||
if (AppContext.getLocale().toLanguageTag().equals("en")) {
|
||||
turnHeader.setText(currentPlayer + keyThingy.getText());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void gameOver(boolean iWon, String winner) {
|
||||
new GameOverPopup(iWon, winner).show(Pos.CENTER);
|
||||
}
|
||||
|
||||
private void setPlayerHeaders(boolean isMe, String currentPlayer, String nextPlayer, String GameType) {
|
||||
if (GameType.equals("TicTacToe")) {
|
||||
if (isMe) {
|
||||
player1Header.setText("X: " + currentPlayer);
|
||||
player2Header.setText("O: " + nextPlayer);
|
||||
}
|
||||
else {
|
||||
player1Header.setText("X: " + nextPlayer);
|
||||
player2Header.setText("O: " + currentPlayer);
|
||||
}
|
||||
setPlayerInfoTTT();
|
||||
}
|
||||
else if (GameType.equals("Reversi")) {
|
||||
boolean swap = AppSettings.getSettings().getSwitchReversi();
|
||||
if (!swap) {
|
||||
player1Header.setText(nextPlayer);
|
||||
player2Header.setText(currentPlayer);
|
||||
}
|
||||
else {
|
||||
player1Header.setText(currentPlayer);
|
||||
player2Header.setText(nextPlayer);
|
||||
}
|
||||
setPlayerInfoReversi();
|
||||
}
|
||||
}
|
||||
|
||||
private void setPlayerInfoTTT() {
|
||||
var playerInfo = Primitive.vbox(
|
||||
playerHeader,
|
||||
Primitive.separator(),
|
||||
player1Header,
|
||||
player2Header
|
||||
);
|
||||
|
||||
add(Pos.TOP_RIGHT, playerInfo);
|
||||
}
|
||||
|
||||
private void setPlayerInfoReversi() {
|
||||
var player1box = Primitive.hbox(
|
||||
player1Icon,
|
||||
player1Header
|
||||
);
|
||||
|
||||
player1box.getStyleClass().add("hboxspacing");
|
||||
|
||||
var player2box = Primitive.hbox(
|
||||
player2Icon,
|
||||
player2Header
|
||||
);
|
||||
|
||||
player2box.getStyleClass().add("hboxspacing");
|
||||
|
||||
var playerInfo = Primitive.vbox(
|
||||
playerHeader,
|
||||
Primitive.separator(),
|
||||
player2box,
|
||||
player1box
|
||||
);
|
||||
|
||||
player1Icon.setRadius(player1Header.fontProperty().map(Font::getSize).getValue());
|
||||
player2Icon.setRadius(player2Header.fontProperty().map(Font::getSize).getValue());
|
||||
player1Icon.setFill(Color.BLACK);
|
||||
player2Icon.setFill(Color.WHITE);
|
||||
add(Pos.TOP_RIGHT, playerInfo);
|
||||
}
|
||||
}
|
||||
@@ -2,19 +2,21 @@ package org.toop.app.widget.view;
|
||||
|
||||
import javafx.application.Platform;
|
||||
import org.toop.app.GameInformation;
|
||||
import org.toop.app.gameControllers.AbstractGameController;
|
||||
import org.toop.app.gameControllers.ReversiController;
|
||||
import org.toop.app.gameControllers.TicTacToeController;
|
||||
import org.toop.app.gameControllers.ReversiBitController;
|
||||
import org.toop.app.gameControllers.TicTacToeBitController;
|
||||
import org.toop.framework.gameFramework.controller.GameController;
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
import org.toop.game.games.reversi.BitboardReversi;
|
||||
import org.toop.game.games.tictactoe.BitboardTicTacToe;
|
||||
import org.toop.game.players.ArtificialPlayer;
|
||||
import org.toop.game.players.LocalPlayer;
|
||||
import org.toop.app.widget.Primitive;
|
||||
import org.toop.app.widget.complex.PlayerInfoWidget;
|
||||
import org.toop.app.widget.complex.ViewWidget;
|
||||
import org.toop.app.widget.popup.ErrorPopup;
|
||||
import org.toop.game.games.reversi.ReversiAIR;
|
||||
import org.toop.game.games.tictactoe.TicTacToeAIR;
|
||||
import org.toop.app.widget.tutorial.*;
|
||||
import org.toop.game.players.ai.MiniMaxAI;
|
||||
import org.toop.game.players.ai.RandomAI;
|
||||
import org.toop.local.AppContext;
|
||||
|
||||
import javafx.geometry.Pos;
|
||||
@@ -25,7 +27,7 @@ import org.toop.local.AppSettings;
|
||||
public class LocalMultiplayerView extends ViewWidget {
|
||||
private final GameInformation information;
|
||||
|
||||
private AbstractGameController<?> gameController;
|
||||
private GameController gameController;
|
||||
|
||||
public LocalMultiplayerView(GameInformation.Type type) {
|
||||
this(new GameInformation(type));
|
||||
@@ -44,7 +46,7 @@ public class LocalMultiplayerView extends ViewWidget {
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Fix this temporary ass way of setting the players (Only works for TicTacToe)
|
||||
// TODO: Fix this temporary ass way of setting the players
|
||||
Player[] players = new Player[2];
|
||||
|
||||
switch (information.type) {
|
||||
@@ -52,55 +54,56 @@ public class LocalMultiplayerView extends ViewWidget {
|
||||
if (information.players[0].isHuman) {
|
||||
players[0] = new LocalPlayer<>(information.players[0].name);
|
||||
} else {
|
||||
players[0] = new ArtificialPlayer<>(new TicTacToeAIR(), information.players[0].name);
|
||||
players[0] = new ArtificialPlayer<>(new RandomAI<BitboardTicTacToe>(), "Random AI");
|
||||
}
|
||||
if (information.players[1].isHuman) {
|
||||
players[1] = new LocalPlayer<>(information.players[1].name);
|
||||
} else {
|
||||
players[1] = new ArtificialPlayer<>(new TicTacToeAIR(), information.players[1].name);
|
||||
players[1] = new ArtificialPlayer<>(new MiniMaxAI<BitboardTicTacToe>(9), "MiniMax AI");
|
||||
}
|
||||
if (AppSettings.getSettings().getTutorialFlag() && AppSettings.getSettings().getFirstTTT()) {
|
||||
new ShowEnableTutorialWidget(
|
||||
() -> new TicTacToeTutorialWidget(() -> {
|
||||
gameController = new TicTacToeController(players);
|
||||
gameController = new TicTacToeBitController(players);
|
||||
gameController.start();
|
||||
}),
|
||||
() -> Platform.runLater(() -> {
|
||||
gameController = new TicTacToeController(players);
|
||||
gameController = new TicTacToeBitController(players);
|
||||
gameController.start();
|
||||
}),
|
||||
() -> AppSettings.getSettings().setFirstTTT(false)
|
||||
);
|
||||
} else {
|
||||
gameController = new TicTacToeController(players);
|
||||
gameController = new TicTacToeBitController(players);
|
||||
gameController.start();
|
||||
}
|
||||
break;
|
||||
case REVERSI:
|
||||
boolean swap = AppSettings.getSettings().getSwitchReversi();
|
||||
if (information.players[0].isHuman) {
|
||||
players[0] = new LocalPlayer<>(information.players[0].name);
|
||||
} else {
|
||||
players[0] = new ArtificialPlayer<>(new ReversiAIR(), information.players[0].name);
|
||||
players[0] = new ArtificialPlayer<>(new RandomAI<BitboardReversi>(), "Random AI");
|
||||
}
|
||||
if (information.players[1].isHuman) {
|
||||
players[1] = new LocalPlayer<>(information.players[1].name);
|
||||
} else {
|
||||
players[1] = new ArtificialPlayer<>(new ReversiAIR(), information.players[1].name);
|
||||
players[1] = new ArtificialPlayer<>(new MiniMaxAI<BitboardReversi>(6), "MiniMax");
|
||||
}
|
||||
if (AppSettings.getSettings().getTutorialFlag() && AppSettings.getSettings().getFirstReversi()) {
|
||||
new ShowEnableTutorialWidget(
|
||||
() -> new ReversiTutorialWidget(() -> {
|
||||
gameController = new ReversiController(players);
|
||||
gameController = new ReversiBitController(players, swap);
|
||||
gameController.start();
|
||||
}),
|
||||
() -> Platform.runLater(() -> {
|
||||
gameController = new ReversiController(players);
|
||||
gameController = new ReversiBitController(players, swap);
|
||||
gameController.start();
|
||||
}),
|
||||
() -> AppSettings.getSettings().setFirstReversi(false)
|
||||
);
|
||||
} else {
|
||||
gameController = new ReversiController(players);
|
||||
gameController = new ReversiBitController(players, swap);
|
||||
gameController.start();
|
||||
}
|
||||
break;
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
package org.toop.app.widget.view;
|
||||
|
||||
import org.toop.app.App;
|
||||
import org.toop.app.widget.Primitive;
|
||||
import org.toop.app.widget.complex.ViewWidget;
|
||||
import javafx.geometry.Pos;
|
||||
import org.toop.app.widget.popup.QuitPopup;
|
||||
|
||||
public class MainView extends ViewWidget {
|
||||
public MainView() {
|
||||
@@ -24,7 +24,8 @@ public class MainView extends ViewWidget {
|
||||
});
|
||||
|
||||
var quitButton = Primitive.button("quit", () -> {
|
||||
App.startQuit();
|
||||
var a = new QuitPopup();
|
||||
a.show(Pos.CENTER);
|
||||
});
|
||||
|
||||
add(Pos.CENTER, Primitive.vbox(
|
||||
|
||||
@@ -3,7 +3,6 @@ package org.toop.app.widget.view;
|
||||
import org.toop.app.Server;
|
||||
import org.toop.app.widget.Primitive;
|
||||
import org.toop.app.widget.complex.LabeledInputWidget;
|
||||
import org.toop.app.widget.complex.LoadingWidget;
|
||||
import org.toop.app.widget.complex.ViewWidget;
|
||||
|
||||
import javafx.geometry.Pos;
|
||||
|
||||
@@ -74,7 +74,7 @@ public class OptionsView extends ViewWidget {
|
||||
AppSettings.getSettings().setVolume(val);
|
||||
new EventFlow()
|
||||
.addPostEvent(new AudioEvents.ChangeVolume(val, VolumeControl.MASTERVOLUME))
|
||||
.asyncPostEvent();
|
||||
.postEvent();
|
||||
}
|
||||
);
|
||||
|
||||
@@ -86,7 +86,7 @@ public class OptionsView extends ViewWidget {
|
||||
AppSettings.getSettings().setFxVolume(val);
|
||||
new EventFlow()
|
||||
.addPostEvent(new AudioEvents.ChangeVolume(val, VolumeControl.FX))
|
||||
.asyncPostEvent();
|
||||
.postEvent();
|
||||
}
|
||||
);
|
||||
|
||||
@@ -98,7 +98,7 @@ public class OptionsView extends ViewWidget {
|
||||
AppSettings.getSettings().setMusicVolume(val);
|
||||
new EventFlow()
|
||||
.addPostEvent(new AudioEvents.ChangeVolume(val, VolumeControl.MUSIC))
|
||||
.asyncPostEvent();
|
||||
.postEvent();
|
||||
}
|
||||
);
|
||||
|
||||
@@ -149,13 +149,22 @@ public class OptionsView extends ViewWidget {
|
||||
"small", "medium", "large"
|
||||
);
|
||||
|
||||
var swapReversiColors = new ToggleWidget(
|
||||
"reversinotswapped", "reversiswapped",
|
||||
AppSettings.getSettings().getSwitchReversi(),
|
||||
swap -> {
|
||||
AppSettings.getSettings().setSwitchReversi(swap);
|
||||
}
|
||||
);
|
||||
|
||||
return Primitive.vbox(
|
||||
Primitive.header("style"),
|
||||
Primitive.separator(),
|
||||
|
||||
themeWidget.getNode(),
|
||||
layoutWidget.getNode()
|
||||
layoutWidget.getNode(),
|
||||
Primitive.text("reversiswap"),
|
||||
swapReversiColors.getNode()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -14,14 +14,12 @@ import javafx.scene.control.ListView;
|
||||
public final class ServerView extends ViewWidget {
|
||||
private final String user;
|
||||
private final Consumer<String> onPlayerClicked;
|
||||
private final Runnable onDisconnect;
|
||||
|
||||
private final ListView<Button> listView;
|
||||
|
||||
public ServerView(String user, Consumer<String> onPlayerClicked, Runnable onDisconnect) {
|
||||
public ServerView(String user, Consumer<String> onPlayerClicked) {
|
||||
this.user = user;
|
||||
this.onPlayerClicked = onPlayerClicked;
|
||||
this.onDisconnect = onDisconnect;
|
||||
|
||||
this.listView = new ListView<>();
|
||||
|
||||
@@ -40,7 +38,6 @@ public final class ServerView extends ViewWidget {
|
||||
add(Pos.CENTER, playerListSection);
|
||||
|
||||
var disconnectButton = Primitive.button("disconnect", () -> {
|
||||
onDisconnect.run();
|
||||
transitionPrevious();
|
||||
});
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
package org.toop.local;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.MissingResourceException;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.toop.app.widget.tutorial.BaseTutorialWidget;
|
||||
import org.toop.framework.resource.ResourceManager;
|
||||
import org.toop.framework.resource.resources.LocalizationAsset;
|
||||
|
||||
@@ -16,11 +16,13 @@ import javafx.beans.property.ObjectProperty;
|
||||
import javafx.beans.property.SimpleObjectProperty;
|
||||
|
||||
public class AppContext {
|
||||
private static final Logger logger = LogManager.getLogger(AppContext.class);
|
||||
|
||||
private static final LocalizationAsset localization = ResourceManager.get("localization");
|
||||
private static Locale locale = Locale.forLanguageTag("en");
|
||||
|
||||
private static final ObjectProperty<Locale> localeProperty = new SimpleObjectProperty<>(locale);
|
||||
private static final Logger logger = LogManager.getLogger(AppContext.class);
|
||||
private static BaseTutorialWidget tutorialWidget;
|
||||
|
||||
public static LocalizationAsset getLocalization() {
|
||||
return localization;
|
||||
@@ -73,4 +75,12 @@ public class AppContext {
|
||||
public static StringBinding bindToKey(String key) {
|
||||
return bindToKey(key, true);
|
||||
}
|
||||
|
||||
public static void setCurrentTutorial(BaseTutorialWidget tutorial) {
|
||||
AppContext.tutorialWidget = tutorial;
|
||||
}
|
||||
|
||||
public static BaseTutorialWidget currentTutorial() {
|
||||
return AppContext.tutorialWidget;
|
||||
}
|
||||
}
|
||||
@@ -5,18 +5,16 @@ import org.toop.framework.audio.VolumeControl;
|
||||
import org.toop.framework.audio.events.AudioEvents;
|
||||
import org.toop.framework.eventbus.EventFlow;
|
||||
import org.toop.framework.resource.ResourceManager;
|
||||
import org.toop.framework.resource.ResourceMeta;
|
||||
import org.toop.framework.resource.resources.SettingsAsset;
|
||||
import org.toop.framework.settings.Settings;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Locale;
|
||||
|
||||
public class AppSettings {
|
||||
private static SettingsAsset settingsAsset;
|
||||
|
||||
public static void applySettings() {
|
||||
settingsAsset = getPath();
|
||||
settingsAsset = getSettingsAsset();
|
||||
if (!settingsAsset.isLoaded()) {
|
||||
settingsAsset.load();
|
||||
}
|
||||
@@ -36,35 +34,18 @@ public class AppSettings {
|
||||
|
||||
new EventFlow()
|
||||
.addPostEvent(new AudioEvents.ChangeVolume(settingsData.volume, VolumeControl.MASTERVOLUME))
|
||||
.asyncPostEvent();
|
||||
.postEvent();
|
||||
new EventFlow()
|
||||
.addPostEvent(new AudioEvents.ChangeVolume(settingsData.fxVolume, VolumeControl.FX))
|
||||
.asyncPostEvent();
|
||||
.postEvent();
|
||||
new EventFlow()
|
||||
.addPostEvent(new AudioEvents.ChangeVolume(settingsData.musicVolume, VolumeControl.MUSIC))
|
||||
.asyncPostEvent();
|
||||
.postEvent();
|
||||
}
|
||||
|
||||
public static SettingsAsset getPath() {
|
||||
public static SettingsAsset getSettingsAsset() {
|
||||
if (settingsAsset == null) {
|
||||
String os = System.getProperty("os.name").toLowerCase();
|
||||
String basePath;
|
||||
|
||||
if (os.contains("win")) {
|
||||
basePath = System.getenv("APPDATA");
|
||||
if (basePath == null) {
|
||||
basePath = System.getProperty("user.home");
|
||||
}
|
||||
} else if (os.contains("mac")) {
|
||||
basePath = System.getProperty("user.home") + "/Library/Application Support";
|
||||
} else {
|
||||
basePath = System.getProperty("user.home") + "/.config";
|
||||
}
|
||||
|
||||
File settingsFile =
|
||||
new File(basePath + File.separator + "ISY1" + File.separator + "settings.json");
|
||||
// this.settingsAsset = new SettingsAsset(settingsFile);
|
||||
ResourceManager.addAsset(new ResourceMeta<>("settings.json", new SettingsAsset(settingsFile)));
|
||||
settingsAsset = SettingsAsset.getPath();
|
||||
}
|
||||
return ResourceManager.get("settings.json");
|
||||
}
|
||||
@@ -110,5 +91,6 @@ public class AppSettings {
|
||||
settingsAsset.setMusicVolume(15);
|
||||
settingsAsset.setTutorialFlag(true);
|
||||
settingsAsset.setLayoutSize("medium");
|
||||
settingsAsset.setSwitchReversi(false);
|
||||
}
|
||||
}
|
||||
@@ -85,6 +85,14 @@ reversi4=\u0627\u0644\u0644\u0627\u0639\u0628 \u0627\u0644\u0630\u064a \u064a\u0
|
||||
tutorialstring=\u0627\u0644\u062f\u0631\u0633 \u0627\u0644\u062a\u0648\u0636\u064a\u062d\u064a
|
||||
startgame=\u0627\u0628\u062f\u0623 \u0627\u0644\u0644\u0639\u0628\u0629!
|
||||
goback=\u0627\u0631\u062c\u0639
|
||||
turnof=\u062F\u0648\u0631\u0647
|
||||
zwartepiet=\u0633\u0647\u0644: Zwarte Piet
|
||||
sinterklaas=\u0645\u062a\u0648\u0633\u0637: Sint R. Klaas
|
||||
santa=\u0635\u0639\u0628: Santa
|
||||
reversiswapped=\u0645\u0628\u062F\u0651\u064E\u0644
|
||||
reversinotswapped=\u063A\u064A\u0631\u0020\u0645\u0628\u062F\u0651\u064E\u0644
|
||||
reversiswap=\u0647\u0644\u0020\u062A\u0631\u064A\u062F\u0020\u062A\u0628\u062F\u064A\u0644\u0020\u0623\u0644\u0648\u0627\u0646\u0020\u0627\u0644\u0631\u064A\u0641\u064E\u0631\u0633\u064A\u061F\u0020\u0645\u062D\u0644\u064A\u0020\u0641\u0642\u0637\u002E
|
||||
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629
|
||||
chinese=\u4e2d\u6587 (\u0627\u0644\u0635\u064a\u0646\u064a\u0629)
|
||||
|
||||
@@ -87,6 +87,13 @@ reversi4=Der Spieler, der am Ende die meisten Steine auf dem Brett hat, gewinnt.
|
||||
tutorialstring=Tutorial
|
||||
startgame=Spiel starten!
|
||||
goback=Zur<EFBFBD>ck
|
||||
turnof=ist dran
|
||||
zwartepiet=Leicht: Zwarte Piet
|
||||
sinterklaas=Mittel: Sint R. Klaas
|
||||
santa=Schwer: Santa
|
||||
reversiswapped=Getauscht
|
||||
reversinotswapped=Nicht getauscht
|
||||
reversiswap=M\u00F6chten Sie die Reversi-Farben tauschen? Nur lokal.
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (Arabisch)
|
||||
chinese=\u4e2d\u6587 (Chinesisch)
|
||||
|
||||
@@ -24,6 +24,7 @@ error=Error
|
||||
exit=Exit
|
||||
forfeit=Forfeit
|
||||
fullscreen=Fullscreen
|
||||
game=REPLACE ME
|
||||
game-over=Game Over
|
||||
general=General
|
||||
high-contrast=High contrast
|
||||
@@ -88,7 +89,13 @@ reversi4=The player who wins at the end of the game is the one who has the most
|
||||
tutorialstring=Tutorial
|
||||
startgame=Start game!
|
||||
goback=Go back
|
||||
|
||||
turnof='s turn
|
||||
zwartepiet=Easy: Zwarte Piet
|
||||
sinterklaas=Medium: Sint R. Klaas
|
||||
santa=Hard:Santa
|
||||
reversiswapped=Swapped
|
||||
reversinotswapped=Not Swapped
|
||||
reversiswap=Do you want to swap the Reversi colors? Local only.
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (Arabic)
|
||||
chinese=\u4e2d\u6587 (Chinese)
|
||||
|
||||
@@ -86,7 +86,13 @@ reversi4=El jugador que gane al final del juego es quien tenga m
|
||||
tutorialstring=Tutorial
|
||||
startgame=\u00a1Iniciar juego!
|
||||
goback=Volver
|
||||
|
||||
turnof=le toca
|
||||
zwartepiet=F\u00e1cil: Zwarte Piet
|
||||
sinterklaas=Medio: Sint R. Klaas
|
||||
santa=Dif\u00edcil: Santa
|
||||
reversiswapped=Cambiado
|
||||
reversinotswapped=No cambiado
|
||||
reversiswap=\u00BFDeseas intercambiar los colores de Reversi? Solo local.
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (Ar\u00e1bigo)
|
||||
chinese=\u4e2d\u6587 (Chino)
|
||||
|
||||
@@ -86,6 +86,13 @@ reversi4=Le joueur qui a le plus de pions
|
||||
tutorialstring=Tutoriel
|
||||
startgame=D\u00e9marrer le jeu!
|
||||
goback=Retour
|
||||
turnof=\u00E0 son tour
|
||||
zwartepiet=Facile: Zwarte Piet
|
||||
sinterklaas=Moyen : Sint R. Klaas
|
||||
santa=Difficile: Santa
|
||||
reversiswapped=\u00C9chang\u00E9
|
||||
reversinotswapped=Non \u00E9chang\u00E9
|
||||
reversiswap=Voulez-vous \u00E9changer les couleurs de Reversi ? Local uniquement.
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (Arabe)
|
||||
chinese=\u4e2d\u6587 (Chinois)
|
||||
|
||||
@@ -86,6 +86,13 @@ reversi4=\u0916\u0941\u092f \u0915\u093f \u0915\u0940 \u0928\u093f\u092e\u0940 \
|
||||
tutorialstring=\u0924\u0942\u091f\u0949\u0930\u093f\u092f\u0932
|
||||
startgame=\u0916\u0947\u0932 \u0936\u0941\u0930\u0942 \u0915\u0930\u0947\u0902!
|
||||
goback=\u0935\u093e\u092a\u0938 \u091c\u093e\u090f\u0901
|
||||
turnof=\u0915\u0940 \u092C\u093E\u0930\u0940
|
||||
zwartepiet=\u0905\u0938\u093e\u0928: Zwarte Piet
|
||||
sinterklaas=\u092e\u0927\u094d\u092f\u092e: Sint R. Klaas
|
||||
santa=\u0915\u0924\u093f\u0928: Santa
|
||||
reversiswapped=\u092C\u0926\u0932\u093E\u0020\u0939\u0941\u0906
|
||||
reversinotswapped=\u0928\u0939\u0940\u0902\u0020\u092C\u0926\u0932\u093E\u0020\u0939\u0941\u0906
|
||||
reversiswap=\u0915\u094D\u092F\u093E\u0020\u0906\u092A\u0020\u0930\u093F\u0935\u0930\u094D\u0938\u0940\u0020\u0915\u0947\u0020\u0930\u0902\u0917\u0020\u092C\u0926\u0932\u0928\u093E\u0020\u091A\u093E\u0939\u0924\u0947\u0020\u0939\u0948\u0902?\u0020\u0915\u0947\u0935\u0932\u0020\u0938\u094D\u0925\u093E\u0928\u0940\u092F\u002E
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (\u0905\u0930\u092c\u0940)
|
||||
chinese=\u4e2d\u6587 (\u091a\u0940\u0928\u0940)
|
||||
|
||||
@@ -85,6 +85,13 @@ reversi4=Il giocatore che alla fine del gioco ha pi
|
||||
tutorialstring=Tutorial
|
||||
startgame=Avvia il gioco!
|
||||
goback=Indietro
|
||||
turnof=\u00E8 il suo turno
|
||||
zwartepiet=Facile: Zwarte Piet
|
||||
sinterklaas=Medio: Sint R. Klaas
|
||||
santa=Difficile: Santa
|
||||
reversiswapped=Scambiato
|
||||
reversinotswapped=Non scambiato
|
||||
reversiswap=Vuoi scambiare i colori di Reversi? Solo locale.
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (Arabo)
|
||||
chinese=\u4e2d\u6587 (Cinese)
|
||||
|
||||
@@ -85,6 +85,14 @@ reversi4=\u672c\u6b21\u306b\u30dc\u30fc\u30c9\u4e0a\u3067\u6700\u591a\u306e\u8ca
|
||||
tutorialstring=\u30c1\u30e5\u30fc\u30c8\u30ea\u30a2\u30eb
|
||||
startgame=\u30b2\u30fc\u30e0\u3092\u958b\u59cb\uff01
|
||||
goback=\u623b\u308b
|
||||
turnof=\u306E\u756A
|
||||
zwartepiet=\u7c21\u5358: Zwarte Piet
|
||||
sinterklaas=\u4e2d\u7d1a: Sint R. Klaas
|
||||
santa=\u96e3\u3057\u3044: Santa
|
||||
reversiswapped=\u5165\u308C\u66FF\u3048\u6E08\u307F
|
||||
reversinotswapped=\u672A\u5165\u308C\u66FF\u3048
|
||||
reversiswap=\u30EA\u30D0\u30FC\u30B7\u306E\u8272\u3092\u5165\u308C\u66FF\u3048\u307E\u3059\u304B?\u0020\u30ED\u30FC\u30AB\u30EB\u306E\u307F\u3067\u3059\u002E
|
||||
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (\u30a2\u30e9\u30d3\u30a2\u8a9e)
|
||||
chinese=\u4e2d\u6587 (\u4e2d\u6587)
|
||||
|
||||
@@ -85,6 +85,13 @@ reversi4=\uacbd\uc6b0 \uc5d0\uc11c \ucd5c\ub300 \ud648\uc744 \uac00\uc838\ub294
|
||||
tutorialstring=\ud14c\ud2b8\ub9ad
|
||||
startgame=\uac8c\uc784 \uc2dc\uc791!
|
||||
goback=\ub4a4\ub85c \uac00\uae30
|
||||
turnof=\uC758 \uCC28\uB840
|
||||
zwartepiet=\uc218\uc601: Zwarte Piet
|
||||
sinterklaas=\ubcf4\ud1b5: Sint R. Klaas
|
||||
santa=\uc5d0\uc18c: Santa
|
||||
reversiswapped=\uAD50\uCCB4\uB428
|
||||
reversinotswapped=\uAD50\uCCB4\uB418\uC9C0 \uC54A\uC74C
|
||||
reversiswap=\uB9AC\uBC84\uC2DC \uC0C9\uC0C1\uC744 \uBC14\uAFB8\uC2DC\uACA0\uC2B5\uB2C8\uAE4C?\u0020\uB85C\uCEEC \uC804\uC6A9\u0020\uC785\uB2C8\uB2E4\u002E
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (\u0639\u0631\u0628\u064a\u0629)
|
||||
chinese=\u4e2d\u6587 (\u4e2d\u6587)
|
||||
|
||||
@@ -85,6 +85,13 @@ reversi4=De speler die aan het einde van het spel de meeste stukken op het bord
|
||||
tutorialstring=Tutorial
|
||||
startgame=Spel starten!
|
||||
goback=Ga terug
|
||||
turnof=is aan de beurt
|
||||
zwartepiet=Makkelijk: Zwarte Piet
|
||||
sinterklaas=Gemiddeld: Sint R. Klaas
|
||||
santa=Moeilijk: Santa
|
||||
reversiswapped=Gewisseld
|
||||
reversinotswapped=Niet gewisseld
|
||||
reversiswap=Wil je de Reversi-kleuren wisselen? Alleen lokaal.
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (Arabisch)
|
||||
chinese=\u4e2d\u6587 (Chinees)
|
||||
|
||||
@@ -85,6 +85,13 @@ reversi4=\u0418043 \u0433043 \u0440043 \u043e043 \u043a043 \u043e043 \u0442043 \
|
||||
tutorialstring=\u0423\u0447\u0435\u0431\u043d\u0438\u043a
|
||||
startgame=\u041d\u0430\u0447\u0430\u0442\u044c \u0438\u0433\u0440\u0443!
|
||||
goback=\u041d\u0430\u0437\u0430\u0434
|
||||
turnof=\u0445\u043E\u0434\u0438\u0442
|
||||
zwartepiet=\u041b\u0435\u0433\u043a\u043e: Zwarte Piet
|
||||
sinterklaas=\u0421\u0440\u0435\u0434\u043d\u0438\u0439: Sint R. Klaas
|
||||
santa=\u0421\u043b\u043e\u0436\u043d\u043e: Santa
|
||||
reversiswapped=\u041F\u043E\u043C\u0435\u043D\u044F\u043D\u043E
|
||||
reversinotswapped=\u041D\u0435 \u043F\u043E\u043C\u0435\u043D\u044F\u043D\u043E
|
||||
reversiswap=\u0425\u043E\u0442\u0438\u0442\u0435 \u043F\u043E\u043C\u0435\u043D\u044F\u0442\u044C \u0446\u0432\u0435\u0442\u0430 \u0420\u0435\u0432\u0435\u0440\u0441\u0438?\u0020\u0422\u043E\u043B\u044C\u043A\u043E \u043B\u043E\u043A\u0430\u043B\u044C\u043D\u043E\u002E
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (\u0410\u0440\u0430\u0431\u0441\u043a\u0438\u0439)
|
||||
chinese=\u4e2d\u6587 (\u041a\u0438\u0442\u0430\u0439\u0441\u043a\u0438\u0439)
|
||||
|
||||
@@ -85,6 +85,13 @@ reversi4=\u672c\u6e38\u620f\u7ed3\u675f\u65f6\u8d62\u5f97\u6ee1\u8fc7\u76d8\u976
|
||||
tutorialstring=\u6559\u7a0b
|
||||
startgame=\u5f00\u59cb\u6e38\u620f\uff01
|
||||
goback=\u8fd4\u56de
|
||||
turnof=\u7684\u56DE\u5408
|
||||
zwartepiet=\u7b80\u5355: Zwarte Piet
|
||||
sinterklaas=\u4e2d\u7b49: Sint R. Klaas
|
||||
santa=\u56f0\u96be: Santa
|
||||
reversiswapped=\u5DF2\u4EA4\u6362
|
||||
reversinotswapped=\u672A\u4EA4\u6362
|
||||
reversiswap=\u662F\u5426\u8981\u4EA4\u6362\u9ED1\u767D\u68CB\u7684\u989C\u8272\uFF1F\u4EC5\u9650\u672C\u5730\u002E
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (\u963f\u62c9\u4f2f\u8bed)
|
||||
chinese=\u4e2d\u6587
|
||||
|
||||
@@ -166,7 +166,7 @@
|
||||
-fx-effect: dropshadow(gaussian, #88cc8899, 5, 0, 0, 1);
|
||||
}
|
||||
|
||||
.my-turn {
|
||||
.text.my-turn {
|
||||
-fx-fill: #e05656;
|
||||
-fx-font-weight: bold;
|
||||
}
|
||||
|
||||
@@ -164,7 +164,7 @@
|
||||
-fx-effect: dropshadow(gaussian, #70e070cc, 6, 0, 0, 2);
|
||||
}
|
||||
|
||||
.my-turn {
|
||||
.text.my-turn {
|
||||
-fx-fill: #ff4b4b;
|
||||
-fx-font-weight: bold;
|
||||
}
|
||||
|
||||
@@ -23,6 +23,11 @@
|
||||
-fx-spacing: 14;
|
||||
}
|
||||
|
||||
.hboxspacing {
|
||||
-fx-padding: 2;
|
||||
-fx-spacing: 10;
|
||||
}
|
||||
|
||||
.current-player {
|
||||
-fx-font-size: 32px;
|
||||
}
|
||||
|
||||
@@ -166,7 +166,7 @@
|
||||
-fx-effect: dropshadow(gaussian, #aad3aa99, 4, 0, 0, 1);
|
||||
}
|
||||
|
||||
.my-turn {
|
||||
.text.my-turn {
|
||||
-fx-fill: #d14b4b;
|
||||
-fx-font-weight: bold;
|
||||
}
|
||||
|
||||
@@ -23,6 +23,11 @@
|
||||
-fx-spacing: 10;
|
||||
}
|
||||
|
||||
.hboxspacing {
|
||||
-fx-padding: 2;
|
||||
-fx-spacing: 10;
|
||||
}
|
||||
|
||||
.current-player {
|
||||
-fx-font-size: 24px;
|
||||
}
|
||||
|
||||
@@ -23,6 +23,11 @@
|
||||
-fx-spacing: 6;
|
||||
}
|
||||
|
||||
.hboxspacing {
|
||||
-fx-padding: 2;
|
||||
-fx-spacing: 10;
|
||||
}
|
||||
|
||||
.current-player {
|
||||
-fx-font-size: 16px;
|
||||
}
|
||||
|
||||
@@ -5,26 +5,29 @@ import org.toop.framework.audio.interfaces.MusicManager;
|
||||
import org.toop.framework.audio.interfaces.SoundEffectManager;
|
||||
import org.toop.framework.audio.interfaces.VolumeManager;
|
||||
import org.toop.framework.eventbus.EventFlow;
|
||||
import org.toop.framework.eventbus.GlobalEventBus;
|
||||
import org.toop.framework.eventbus.bus.EventBus;
|
||||
import org.toop.framework.resource.types.AudioResource;
|
||||
|
||||
public class AudioEventListener<T extends AudioResource, K extends AudioResource> {
|
||||
private final EventBus eventBus;
|
||||
private final MusicManager<T> musicManager;
|
||||
private final SoundEffectManager<K> soundEffectManager;
|
||||
private final VolumeManager audioVolumeManager;
|
||||
|
||||
public AudioEventListener(
|
||||
EventBus eventBus,
|
||||
MusicManager<T> musicManager,
|
||||
SoundEffectManager<K> soundEffectManager,
|
||||
VolumeManager audioVolumeManager
|
||||
) {
|
||||
this.eventBus = eventBus;
|
||||
this.musicManager = musicManager;
|
||||
this.soundEffectManager = soundEffectManager;
|
||||
this.audioVolumeManager = audioVolumeManager;
|
||||
}
|
||||
|
||||
public AudioEventListener<?, ?> initListeners(String buttonSoundToPlay) {
|
||||
new EventFlow()
|
||||
new EventFlow(eventBus)
|
||||
.listen(AudioEvents.StopAudioManager.class, this::handleStopMusicManager, false)
|
||||
.listen(AudioEvents.PlayEffect.class, this::handlePlaySound, false)
|
||||
.listen(AudioEvents.SkipMusic.class, this::handleSkipSong, false)
|
||||
@@ -73,7 +76,7 @@ public class AudioEventListener<T extends AudioResource, K extends AudioResource
|
||||
}
|
||||
|
||||
private void handleGetVolume(AudioEvents.GetVolume event) {
|
||||
GlobalEventBus.postAsync(new AudioEvents.GetVolumeResponse(
|
||||
eventBus.post(new AudioEvents.GetVolumeResponse(
|
||||
audioVolumeManager.getVolume(event.controlType()),
|
||||
event.identifier()));
|
||||
}
|
||||
|
||||
@@ -6,8 +6,7 @@ import org.toop.framework.audio.events.AudioEvents;
|
||||
import org.toop.framework.dispatch.interfaces.Dispatcher;
|
||||
import org.toop.framework.dispatch.JavaFXDispatcher;
|
||||
import org.toop.annotations.TestsOnly;
|
||||
import org.toop.framework.eventbus.EventFlow;
|
||||
import org.toop.framework.eventbus.GlobalEventBus;
|
||||
import org.toop.framework.eventbus.bus.EventBus;
|
||||
import org.toop.framework.resource.types.AudioResource;
|
||||
|
||||
import java.util.*;
|
||||
@@ -18,6 +17,7 @@ import java.util.concurrent.TimeUnit;
|
||||
public class MusicManager<T extends AudioResource> implements org.toop.framework.audio.interfaces.MusicManager<T> {
|
||||
private static final Logger logger = LogManager.getLogger(MusicManager.class);
|
||||
|
||||
private final EventBus eventBus;
|
||||
private final List<T> backgroundMusic = new ArrayList<>();
|
||||
private final Dispatcher dispatcher;
|
||||
private final List<T> resources;
|
||||
@@ -27,7 +27,8 @@ public class MusicManager<T extends AudioResource> implements org.toop.framework
|
||||
private ScheduledExecutorService scheduler;
|
||||
|
||||
|
||||
public MusicManager(List<T> resources, boolean shuffleMusic) {
|
||||
public MusicManager(EventBus eventbus, List<T> resources, boolean shuffleMusic) {
|
||||
this.eventBus = eventbus;
|
||||
this.dispatcher = new JavaFXDispatcher();
|
||||
this.resources = resources;
|
||||
// Shuffle if wanting to shuffle
|
||||
@@ -40,7 +41,8 @@ public class MusicManager<T extends AudioResource> implements org.toop.framework
|
||||
* {@code @TestsOnly} DO NOT USE
|
||||
*/
|
||||
@TestsOnly
|
||||
public MusicManager(List<T> resources, Dispatcher dispatcher) {
|
||||
public MusicManager(EventBus eventBus, List<T> resources, Dispatcher dispatcher) {
|
||||
this.eventBus = eventBus;
|
||||
this.dispatcher = dispatcher;
|
||||
this.resources = new ArrayList<>(resources);
|
||||
backgroundMusic.addAll(resources);
|
||||
@@ -124,7 +126,7 @@ public class MusicManager<T extends AudioResource> implements org.toop.framework
|
||||
Runnable currentMusicTask = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
GlobalEventBus.post(new AudioEvents.PlayingMusic(track.getName(), track.currentPosition(), track.duration()));
|
||||
eventBus.post(new AudioEvents.PlayingMusic(track.getName(), track.currentPosition(), track.duration()));
|
||||
scheduler.schedule(this, 1, TimeUnit.SECONDS);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -2,18 +2,10 @@ package org.toop.framework.audio;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.toop.framework.resource.ResourceManager;
|
||||
import org.toop.framework.resource.ResourceMeta;
|
||||
import org.toop.framework.resource.resources.BaseResource;
|
||||
import org.toop.framework.resource.resources.MusicAsset;
|
||||
import org.toop.framework.resource.resources.SoundEffectAsset;
|
||||
import org.toop.framework.resource.types.AudioResource;
|
||||
|
||||
import javax.sound.sampled.Clip;
|
||||
import javax.sound.sampled.LineEvent;
|
||||
import javax.sound.sampled.LineUnavailableException;
|
||||
import javax.sound.sampled.UnsupportedAudioFileException;
|
||||
import java.io.IOException;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
|
||||
@@ -2,8 +2,6 @@ package org.toop.framework.audio.events;
|
||||
|
||||
import org.toop.framework.audio.VolumeControl;
|
||||
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 {
|
||||
/** Stops the audio manager. */
|
||||
|
||||
@@ -1,12 +1,7 @@
|
||||
package org.toop.framework.audio.interfaces;
|
||||
|
||||
import org.toop.framework.resource.resources.SoundEffectAsset;
|
||||
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> {
|
||||
void play(String name, boolean loop);
|
||||
void stop(String name);
|
||||
|
||||
@@ -13,10 +13,14 @@ import org.toop.framework.SnowflakeGenerator;
|
||||
import org.toop.framework.eventbus.events.EventType;
|
||||
import org.toop.framework.eventbus.events.ResponseToUniqueEvent;
|
||||
import org.toop.framework.eventbus.events.UniqueEvent;
|
||||
import org.toop.framework.eventbus.bus.EventBus;
|
||||
import org.toop.framework.eventbus.subscriber.DefaultNamedSubscriber;
|
||||
import org.toop.framework.eventbus.subscriber.NamedSubscriber;
|
||||
import org.toop.framework.eventbus.subscriber.Subscriber;
|
||||
|
||||
/**
|
||||
* EventFlow is a utility class for creating, posting, and optionally subscribing to events in a
|
||||
* type-safe and chainable manner. It is designed to work with the {@link GlobalEventBus}.
|
||||
* type-safe and chainable manner. It is designed to work with the {@link EventBus}.
|
||||
*
|
||||
* <p>This class supports automatic UUID assignment for {@link UniqueEvent} events, and
|
||||
* allows filtering subscribers so they only respond to events with a specific UUID. All
|
||||
@@ -31,6 +35,8 @@ public class EventFlow {
|
||||
/** Cache of constructor handles for event classes to avoid repeated reflection lookups. */
|
||||
private static final Map<Class<?>, MethodHandle> CONSTRUCTOR_CACHE = new ConcurrentHashMap<>();
|
||||
|
||||
private final EventBus eventBus;
|
||||
|
||||
/** Automatically assigned UUID for {@link UniqueEvent} events. */
|
||||
private long eventSnowflake = -1;
|
||||
|
||||
@@ -38,13 +44,19 @@ public class EventFlow {
|
||||
private EventType event = null;
|
||||
|
||||
/** The listener returned by GlobalEventBus subscription. Used for unsubscription. */
|
||||
private final List<ListenerHandler<?>> listeners = new ArrayList<>();
|
||||
private final List<NamedSubscriber<?>> listeners = new ArrayList<>();
|
||||
|
||||
/** Holds the results returned from the subscribed event, if any. */
|
||||
private Map<String, ?> result = null;
|
||||
|
||||
/** Empty constructor (event must be added via {@link #addPostEvent(Class, Object...)}). */
|
||||
public EventFlow() {}
|
||||
public EventFlow(EventBus eventBus) {
|
||||
this.eventBus = eventBus;
|
||||
}
|
||||
|
||||
public EventFlow() {
|
||||
this.eventBus = GlobalEventBus.get();
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
@@ -145,21 +157,19 @@ public class EventFlow {
|
||||
|
||||
action.accept(eventClass);
|
||||
|
||||
if (unsubscribeAfterSuccess) unsubscribe(id);
|
||||
if (unsubscribeAfterSuccess) unsubscribe(String.valueOf(id));
|
||||
|
||||
this.result = eventClass.result();
|
||||
};
|
||||
|
||||
// TODO Remove casts
|
||||
var listener = new ListenerHandler<>(
|
||||
id,
|
||||
var subscriber = new DefaultNamedSubscriber<>(
|
||||
name,
|
||||
(Class<ResponseToUniqueEvent>) event,
|
||||
(Consumer<ResponseToUniqueEvent>) newAction
|
||||
event,
|
||||
newAction
|
||||
);
|
||||
|
||||
GlobalEventBus.subscribe(listener);
|
||||
this.listeners.add(listener);
|
||||
eventBus.subscribe(subscriber);
|
||||
this.listeners.add(subscriber);
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -227,7 +237,7 @@ public class EventFlow {
|
||||
TT typedEvent = (TT) uuidEvent;
|
||||
action.accept(typedEvent);
|
||||
|
||||
if (unsubscribeAfterSuccess) unsubscribe(id);
|
||||
if (unsubscribeAfterSuccess) unsubscribe(String.valueOf(id));
|
||||
|
||||
this.result = typedEvent.result();
|
||||
} catch (ClassCastException _) {
|
||||
@@ -239,14 +249,13 @@ public class EventFlow {
|
||||
}
|
||||
};
|
||||
|
||||
var listener = new ListenerHandler<>(
|
||||
id,
|
||||
var listener = new DefaultNamedSubscriber<>(
|
||||
name,
|
||||
(Class<TT>) action.getClass().getDeclaredMethods()[0].getParameterTypes()[0],
|
||||
newAction
|
||||
);
|
||||
|
||||
GlobalEventBus.subscribe(listener);
|
||||
eventBus.subscribe(listener);
|
||||
this.listeners.add(listener);
|
||||
return this;
|
||||
}
|
||||
@@ -284,17 +293,16 @@ public class EventFlow {
|
||||
Consumer<TT> newAction = eventc -> {
|
||||
action.accept(eventc);
|
||||
|
||||
if (unsubscribeAfterSuccess) unsubscribe(id);
|
||||
if (unsubscribeAfterSuccess) unsubscribe(String.valueOf(id));
|
||||
};
|
||||
|
||||
var listener = new ListenerHandler<>(
|
||||
id,
|
||||
var listener = new DefaultNamedSubscriber<>(
|
||||
name,
|
||||
event,
|
||||
newAction
|
||||
);
|
||||
|
||||
GlobalEventBus.subscribe(listener);
|
||||
eventBus.subscribe(listener);
|
||||
this.listeners.add(listener);
|
||||
return this;
|
||||
}
|
||||
@@ -362,7 +370,7 @@ public class EventFlow {
|
||||
try {
|
||||
TT typedEvent = (TT) nonUuidEvent;
|
||||
action.accept(typedEvent);
|
||||
if (unsubscribeAfterSuccess) unsubscribe(id);
|
||||
if (unsubscribeAfterSuccess) unsubscribe(String.valueOf(id));
|
||||
} catch (ClassCastException _) {
|
||||
throw new ClassCastException(
|
||||
"Cannot cast "
|
||||
@@ -371,14 +379,13 @@ public class EventFlow {
|
||||
}
|
||||
};
|
||||
|
||||
var listener = new ListenerHandler<>(
|
||||
id,
|
||||
var listener = new DefaultNamedSubscriber<>(
|
||||
name,
|
||||
eventClass,
|
||||
newAction
|
||||
);
|
||||
|
||||
GlobalEventBus.subscribe(listener);
|
||||
eventBus.subscribe(listener);
|
||||
this.listeners.add(listener);
|
||||
return this;
|
||||
}
|
||||
@@ -401,15 +408,18 @@ public class EventFlow {
|
||||
* Posts the event added through {@link #addPostEvent}.
|
||||
*/
|
||||
public EventFlow postEvent() {
|
||||
GlobalEventBus.post(this.event);
|
||||
eventBus.post(this.event);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Posts the event added through {@link #addPostEvent} asynchronously.
|
||||
*
|
||||
* @deprecated use {@link #postEvent()} instead.
|
||||
*/
|
||||
@Deprecated
|
||||
public EventFlow asyncPostEvent() {
|
||||
GlobalEventBus.postAsync(this.event);
|
||||
eventBus.post(this.event);
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -417,28 +427,12 @@ public class EventFlow {
|
||||
*
|
||||
* Unsubscribe from an event.
|
||||
*
|
||||
* @param listenerObject The listener object to remove and unsubscribe.
|
||||
* @param action The listener object to remove and unsubscribe.
|
||||
*/
|
||||
public void unsubscribe(Object listenerObject) {
|
||||
public void unsubscribe(Consumer<?> action) {
|
||||
this.listeners.removeIf(handler -> {
|
||||
if (handler.getListener() == listenerObject) {
|
||||
GlobalEventBus.unsubscribe(handler);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Unsubscribe from an event.
|
||||
*
|
||||
* @param listenerId The id given to the {@link ListenerHandler}.
|
||||
*/
|
||||
public void unsubscribe(long listenerId) {
|
||||
this.listeners.removeIf(handler -> {
|
||||
if (handler.getId() == listenerId) {
|
||||
GlobalEventBus.unsubscribe(handler);
|
||||
if (handler.handler().equals(action)) {
|
||||
eventBus.unsubscribe(handler);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
@@ -452,8 +446,8 @@ public class EventFlow {
|
||||
*/
|
||||
public void unsubscribe(String name) {
|
||||
this.listeners.removeIf(handler -> {
|
||||
if (handler.getName().equals(name)) {
|
||||
GlobalEventBus.unsubscribe(handler);
|
||||
if (handler.id().equals(name)) {
|
||||
eventBus.unsubscribe(handler);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
@@ -465,7 +459,7 @@ public class EventFlow {
|
||||
*/
|
||||
public void unsubscribeAll() {
|
||||
listeners.removeIf(handler -> {
|
||||
GlobalEventBus.unsubscribe(handler);
|
||||
eventBus.unsubscribe(handler);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
@@ -503,8 +497,8 @@ public class EventFlow {
|
||||
*
|
||||
* @return Copy of the list of listeners.
|
||||
*/
|
||||
public ListenerHandler[] getListeners() {
|
||||
return listeners.toArray(new ListenerHandler[0]);
|
||||
public Subscriber<?>[] getListeners() {
|
||||
return listeners.toArray(new Subscriber[0]);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,193 +1,46 @@
|
||||
package org.toop.framework.eventbus;
|
||||
|
||||
import com.lmax.disruptor.*;
|
||||
import com.lmax.disruptor.dsl.Disruptor;
|
||||
import com.lmax.disruptor.dsl.ProducerType;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.toop.framework.eventbus.bus.DisruptorEventBus;
|
||||
import org.toop.framework.eventbus.bus.EventBus;
|
||||
import org.toop.framework.eventbus.events.EventType;
|
||||
import org.toop.framework.eventbus.events.UniqueEvent;
|
||||
import org.toop.framework.eventbus.store.DefaultSubscriberStore;
|
||||
import org.toop.framework.eventbus.subscriber.Subscriber;
|
||||
|
||||
/**
|
||||
* GlobalEventBus backed by the LMAX Disruptor for ultra-low latency, high-throughput event
|
||||
* publishing.
|
||||
*/
|
||||
public final class GlobalEventBus {
|
||||
private static final Logger logger = LogManager.getLogger(GlobalEventBus.class);
|
||||
public class GlobalEventBus implements EventBus {
|
||||
private static final EventBus INSTANCE = new DisruptorEventBus(
|
||||
LogManager.getLogger(DisruptorEventBus.class),
|
||||
new DefaultSubscriberStore()
|
||||
);
|
||||
|
||||
/** Map of event class to type-specific listeners. */
|
||||
private static final Map<Class<?>, CopyOnWriteArrayList<ListenerHandler<?>>>
|
||||
LISTENERS = new ConcurrentHashMap<>();
|
||||
|
||||
/** Map of event class to Snowflake-ID-specific listeners. */
|
||||
private static final Map<
|
||||
Class<?>, ConcurrentHashMap<Long, Consumer<? extends UniqueEvent>>>
|
||||
UUID_LISTENERS = new ConcurrentHashMap<>();
|
||||
|
||||
/** Disruptor ring buffer size (must be power of two). */
|
||||
private static final int RING_BUFFER_SIZE = 1024 * 64;
|
||||
|
||||
/** Disruptor instance. */
|
||||
private static final Disruptor<EventHolder> DISRUPTOR;
|
||||
|
||||
/** Ring buffer used for publishing events. */
|
||||
private static final RingBuffer<EventHolder> RING_BUFFER;
|
||||
|
||||
static {
|
||||
ThreadFactory threadFactory =
|
||||
r -> {
|
||||
Thread t = new Thread(r, "EventBus-Disruptor");
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
};
|
||||
|
||||
DISRUPTOR =
|
||||
new Disruptor<>(
|
||||
EventHolder::new,
|
||||
RING_BUFFER_SIZE,
|
||||
threadFactory,
|
||||
ProducerType.MULTI,
|
||||
new BusySpinWaitStrategy());
|
||||
|
||||
DISRUPTOR.handleEventsWith(
|
||||
(holder, seq, endOfBatch) -> {
|
||||
if (holder.event != null) {
|
||||
dispatchEvent(holder.event);
|
||||
holder.event = null;
|
||||
}
|
||||
});
|
||||
|
||||
DISRUPTOR.start();
|
||||
RING_BUFFER = DISRUPTOR.getRingBuffer();
|
||||
}
|
||||
|
||||
/** Prevent instantiation. */
|
||||
private GlobalEventBus() {}
|
||||
|
||||
/** Wrapper used inside the ring buffer. */
|
||||
private static class EventHolder {
|
||||
EventType event;
|
||||
public static EventBus get() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
// Subscription
|
||||
// ------------------------------------------------------------------------
|
||||
public static <T extends EventType> void subscribe(ListenerHandler<T> listener) {
|
||||
logger.debug("Subscribing to {}: {}", listener.getListenerClass().getSimpleName(), listener.getListener().getClass().getSimpleName());
|
||||
LISTENERS.computeIfAbsent(listener.getListenerClass(), _ -> new CopyOnWriteArrayList<>()).add(listener);
|
||||
@Override
|
||||
public void subscribe(Subscriber<? extends EventType> listener) {
|
||||
INSTANCE.subscribe(listener);
|
||||
}
|
||||
|
||||
// TODO
|
||||
public static <T extends UniqueEvent> void subscribeById(
|
||||
Class<T> eventClass, long eventId, Consumer<T> listener) {
|
||||
UUID_LISTENERS
|
||||
.computeIfAbsent(eventClass, _ -> new ConcurrentHashMap<>())
|
||||
.put(eventId, listener);
|
||||
@Override
|
||||
public void unsubscribe(Subscriber<? extends EventType> listener) {
|
||||
INSTANCE.unsubscribe(listener);
|
||||
}
|
||||
|
||||
public static void unsubscribe(ListenerHandler<?> listener) {
|
||||
logger.debug("Unsubscribing from {}: {}", listener.getListenerClass().getSimpleName(), listener.getListener().getClass().getSimpleName());
|
||||
LISTENERS.getOrDefault(listener.getListenerClass(), new CopyOnWriteArrayList<>())
|
||||
.remove(listener);
|
||||
LISTENERS.entrySet().removeIf(entry -> entry.getValue().isEmpty());
|
||||
@Override
|
||||
public <T extends EventType> void post(T event) {
|
||||
INSTANCE.post(event);
|
||||
}
|
||||
|
||||
// TODO
|
||||
public static <T extends UniqueEvent> void unsubscribeById(
|
||||
Class<T> eventClass, long eventId) {
|
||||
Map<Long, Consumer<? extends UniqueEvent>> map = UUID_LISTENERS.get(eventClass);
|
||||
if (map != null) map.remove(eventId);
|
||||
@Override
|
||||
public void shutdown() {
|
||||
INSTANCE.shutdown();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
// Posting
|
||||
// ------------------------------------------------------------------------
|
||||
public static <T extends EventType> void post(T event) {
|
||||
dispatchEvent(event); // synchronous
|
||||
}
|
||||
|
||||
public static <T extends EventType> void postAsync(T event) {
|
||||
long seq = RING_BUFFER.next();
|
||||
try {
|
||||
EventHolder holder = RING_BUFFER.get(seq);
|
||||
holder.event = event;
|
||||
} finally {
|
||||
RING_BUFFER.publish(seq);
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static <T extends EventType> void callListener(ListenerHandler<?> raw, EventType event) {
|
||||
ListenerHandler<T> handler = (ListenerHandler<T>) raw;
|
||||
Consumer<T> listener = handler.getListener();
|
||||
|
||||
T casted = (T) event;
|
||||
|
||||
listener.accept(casted);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static void dispatchEvent(EventType event) {
|
||||
Class<?> clazz = event.getClass();
|
||||
|
||||
logger.debug("Triggered event: {}", event.getClass().getSimpleName());
|
||||
|
||||
CopyOnWriteArrayList<ListenerHandler<?>> classListeners = LISTENERS.get(clazz);
|
||||
if (classListeners != null) {
|
||||
for (ListenerHandler<?> listener : classListeners) {
|
||||
try {
|
||||
callListener(listener, event);
|
||||
} catch (Throwable e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
CopyOnWriteArrayList<ListenerHandler<?>> genericListeners = LISTENERS.get(Object.class);
|
||||
if (genericListeners != null) {
|
||||
for (ListenerHandler<?> listener : genericListeners) {
|
||||
try {
|
||||
callListener(listener, event);
|
||||
} catch (Throwable e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (event instanceof UniqueEvent snowflakeEvent) {
|
||||
Map<Long, Consumer<? extends UniqueEvent>> map = UUID_LISTENERS.get(clazz);
|
||||
if (map != null) {
|
||||
Consumer<UniqueEvent> listener =
|
||||
(Consumer<UniqueEvent>) map.remove(snowflakeEvent.getIdentifier());
|
||||
if (listener != null) {
|
||||
try {
|
||||
listener.accept(snowflakeEvent);
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
// Lifecycle
|
||||
// ------------------------------------------------------------------------
|
||||
public static void shutdown() {
|
||||
DISRUPTOR.shutdown();
|
||||
LISTENERS.clear();
|
||||
UUID_LISTENERS.clear();
|
||||
}
|
||||
|
||||
public static void reset() {
|
||||
LISTENERS.clear();
|
||||
UUID_LISTENERS.clear();
|
||||
}
|
||||
|
||||
public static Map<Class<?>, CopyOnWriteArrayList<ListenerHandler<?>>> getAllListeners() {
|
||||
return LISTENERS;
|
||||
@Override
|
||||
public void reset() {
|
||||
INSTANCE.reset();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
package org.toop.framework.eventbus;
|
||||
|
||||
import org.toop.framework.SnowflakeGenerator;
|
||||
import org.toop.framework.eventbus.events.EventType;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class ListenerHandler<T extends EventType> {
|
||||
private final long id;
|
||||
private final String name;
|
||||
private final Class<T> clazz;
|
||||
private final Consumer<T> listener;
|
||||
|
||||
public ListenerHandler(long id, String name, Class<T> clazz, Consumer<T> listener) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.clazz = clazz;
|
||||
this.listener = listener;
|
||||
}
|
||||
|
||||
public ListenerHandler(String name, Class<T> clazz, Consumer<T> listener) {
|
||||
this(SnowflakeGenerator.nextId(), name, clazz, listener);
|
||||
}
|
||||
|
||||
public ListenerHandler(long id, Class<T> clazz, Consumer<T> listener) {
|
||||
this(id, String.valueOf(id), clazz, listener);
|
||||
}
|
||||
|
||||
public ListenerHandler(Class<T> clazz, Consumer<T> listener) {
|
||||
this(SnowflakeGenerator.nextId(), clazz, listener);
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public Consumer<T> getListener() {
|
||||
return listener;
|
||||
}
|
||||
|
||||
public Class<T> getListenerClass() {
|
||||
return clazz;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package org.toop.framework.eventbus.bus;
|
||||
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.toop.framework.eventbus.events.EventType;
|
||||
import org.toop.framework.eventbus.store.SubscriberStore;
|
||||
import org.toop.framework.eventbus.subscriber.Subscriber;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class DefaultEventBus implements EventBus {
|
||||
private final Logger logger;
|
||||
private final SubscriberStore eventsHolder;
|
||||
|
||||
public DefaultEventBus(Logger logger, SubscriberStore eventsHolder) {
|
||||
this.logger = logger;
|
||||
this.eventsHolder = eventsHolder;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void subscribe(Subscriber<? extends EventType> subscriber) {
|
||||
eventsHolder.add(subscriber);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unsubscribe(Subscriber<? extends EventType> subscriber) {
|
||||
eventsHolder.remove(subscriber);
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T extends EventType> void post(T event) {
|
||||
Class<T> eventType = (Class<T>) event.getClass();
|
||||
var subs = eventsHolder.get(eventType);
|
||||
if (subs != null) {
|
||||
for (Subscriber<?> subscriber : subs) {
|
||||
Class<T> eventClass = (Class<T>) subscriber.event();
|
||||
Consumer<EventType> action = (Consumer<EventType>) subscriber.handler();
|
||||
|
||||
action.accept((EventType) eventClass.cast(event));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown() {
|
||||
eventsHolder.reset();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reset() {
|
||||
eventsHolder.reset();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package org.toop.framework.eventbus.bus;
|
||||
|
||||
import com.lmax.disruptor.BusySpinWaitStrategy;
|
||||
import com.lmax.disruptor.RingBuffer;
|
||||
import com.lmax.disruptor.dsl.Disruptor;
|
||||
import com.lmax.disruptor.dsl.ProducerType;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.toop.framework.eventbus.subscriber.Subscriber;
|
||||
import org.toop.framework.eventbus.events.EventType;
|
||||
import org.toop.framework.eventbus.store.SubscriberStore;
|
||||
|
||||
import java.util.concurrent.ThreadFactory;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class DisruptorEventBus implements EventBus {
|
||||
/** Wrapper used inside the ring buffer. */
|
||||
private static class EventHolder<T> {
|
||||
T event;
|
||||
}
|
||||
|
||||
private final Logger logger;
|
||||
private final SubscriberStore eventsHolder;
|
||||
|
||||
private final Disruptor<EventHolder<? extends EventType>> disruptor;
|
||||
private final RingBuffer<EventHolder<? extends EventType>> ringBuffer;
|
||||
|
||||
public DisruptorEventBus(Logger logger, SubscriberStore eventsHolder) {
|
||||
this.logger = logger;
|
||||
this.eventsHolder = eventsHolder;
|
||||
|
||||
ThreadFactory threadFactory =
|
||||
r -> {
|
||||
Thread t = new Thread(r, "EventBus-Disruptor");
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
};
|
||||
|
||||
disruptor = getEventHolderDisruptor(threadFactory);
|
||||
|
||||
disruptor.start();
|
||||
this.ringBuffer = disruptor.getRingBuffer();
|
||||
}
|
||||
|
||||
private Disruptor<EventHolder<? extends EventType>> getEventHolderDisruptor(ThreadFactory threadFactory) {
|
||||
int RING_BUFFER_SIZE = 1024 * 64;
|
||||
Disruptor<EventHolder<? extends EventType>> disruptor = new Disruptor<>(
|
||||
EventHolder::new,
|
||||
RING_BUFFER_SIZE,
|
||||
threadFactory,
|
||||
ProducerType.MULTI,
|
||||
new BusySpinWaitStrategy());
|
||||
|
||||
disruptor.handleEventsWith(
|
||||
(holder, _, _) -> {
|
||||
if (holder.event != null) {
|
||||
dispatchEvent(holder.event);
|
||||
holder.event = null;
|
||||
}
|
||||
});
|
||||
return disruptor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void subscribe(Subscriber<? extends EventType> listener) {
|
||||
eventsHolder.add(listener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unsubscribe(Subscriber<? extends EventType> listener) {
|
||||
eventsHolder.remove(listener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T extends EventType> void post(T event) {
|
||||
long seq = ringBuffer.next();
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
EventHolder<T> holder = (EventHolder<T>) ringBuffer.get(seq);
|
||||
holder.event = event;
|
||||
} finally {
|
||||
ringBuffer.publish(seq);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown() {
|
||||
disruptor.shutdown();
|
||||
eventsHolder.reset();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reset() {
|
||||
eventsHolder.reset();
|
||||
}
|
||||
|
||||
private <T extends EventType> void dispatchEvent(T event) {
|
||||
var classListeners = eventsHolder.get(event.getClass());
|
||||
if (classListeners != null) {
|
||||
for (Subscriber<?> listener : classListeners) {
|
||||
try {
|
||||
callListener(listener, event);
|
||||
} catch (Throwable e) {
|
||||
logger.warn("Exception while handling event: {}", event, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private <T> void callListener(Subscriber<?> subscriber, T event) {
|
||||
Class<T> eventClass = (Class<T>) subscriber.event();
|
||||
Consumer<EventType> action = (Consumer<EventType>) subscriber.handler();
|
||||
|
||||
action.accept((EventType) eventClass.cast(event));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package org.toop.framework.eventbus.bus;
|
||||
|
||||
import org.toop.framework.eventbus.events.EventType;
|
||||
import org.toop.framework.eventbus.subscriber.Subscriber;
|
||||
|
||||
public interface EventBus {
|
||||
void subscribe(Subscriber<? extends EventType> subscriber);
|
||||
void unsubscribe(Subscriber<? extends EventType> subscriber);
|
||||
<T extends EventType> void post(T event);
|
||||
void shutdown();
|
||||
void reset();
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package org.toop.framework.eventbus.store;
|
||||
|
||||
import org.toop.framework.eventbus.events.EventType;
|
||||
import org.toop.framework.eventbus.subscriber.Subscriber;
|
||||
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
|
||||
public class AsyncSubscriberStore implements SubscriberStore {
|
||||
private final ConcurrentHashMap<Class<? extends EventType>, ConcurrentLinkedQueue<Subscriber<? extends EventType>>> queues = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<Class<? extends EventType>, Subscriber<? extends EventType>[]> snapshots = new ConcurrentHashMap<>();
|
||||
|
||||
@Override
|
||||
public void add(Subscriber<? extends EventType> sub) {
|
||||
queues.computeIfAbsent(sub.event(), _ -> new ConcurrentLinkedQueue<>()).add(sub);
|
||||
rebuildSnapshot(sub.event());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove(Subscriber<? extends EventType> sub) {
|
||||
ConcurrentLinkedQueue<Subscriber<?>> queue = queues.get(sub.event());
|
||||
if (queue != null) {
|
||||
queue.remove(sub);
|
||||
rebuildSnapshot(sub.event());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Subscriber<? extends EventType>[] get(Class<? extends EventType> event) {
|
||||
return snapshots.getOrDefault(event, new Subscriber<?>[0]);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reset() {
|
||||
queues.clear();
|
||||
snapshots.clear();
|
||||
}
|
||||
|
||||
private void rebuildSnapshot(Class<? extends EventType> event) {
|
||||
ConcurrentLinkedQueue<Subscriber<?>> queue = queues.get(event);
|
||||
if (queue != null) {
|
||||
snapshots.put(event, queue.toArray(new Subscriber<?>[0]));
|
||||
} else {
|
||||
snapshots.put(event, new Subscriber<?>[0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package org.toop.framework.eventbus.store;
|
||||
|
||||
import org.toop.framework.eventbus.events.EventType;
|
||||
import org.toop.framework.eventbus.subscriber.NamedSubscriber;
|
||||
import org.toop.framework.eventbus.subscriber.Subscriber;
|
||||
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public class DefaultSubscriberStore implements SubscriberStore {
|
||||
|
||||
private static final Subscriber<? extends EventType>[] EMPTY = new Subscriber<?>[0];
|
||||
|
||||
private final ConcurrentHashMap<Class<? extends EventType>, Subscriber<? extends EventType>[]>
|
||||
listeners = new ConcurrentHashMap<>();
|
||||
|
||||
@Override
|
||||
public void add(Subscriber<? extends EventType> sub) {
|
||||
listeners.compute(sub.event(), (_, arr) -> {
|
||||
if (arr == null || arr.length == 0) {
|
||||
return new Subscriber<?>[]{sub};
|
||||
}
|
||||
|
||||
int len = arr.length;
|
||||
Subscriber<?>[] newArr = new Subscriber[len + 1];
|
||||
System.arraycopy(arr, 0, newArr, 0, len);
|
||||
newArr[len] = sub;
|
||||
return newArr;
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove(Subscriber<? extends EventType> sub) {
|
||||
listeners.computeIfPresent(sub.event(), (_, arr) -> {
|
||||
int len = arr.length;
|
||||
|
||||
if (len == 1) {
|
||||
return arr[0].equals(sub) ? null : arr;
|
||||
}
|
||||
|
||||
int keep = 0;
|
||||
for (Subscriber<?> s : arr) {
|
||||
if (!s.equals(sub)) keep++;
|
||||
}
|
||||
|
||||
if (keep == len) {
|
||||
return arr;
|
||||
}
|
||||
if (keep == 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Subscriber<?>[] newArr = new Subscriber[keep];
|
||||
int i = 0;
|
||||
for (Subscriber<?> s : arr) {
|
||||
if (!s.equals(sub)) {
|
||||
newArr[i++] = s;
|
||||
}
|
||||
}
|
||||
|
||||
return newArr;
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public Subscriber<? extends EventType>[] get(Class<? extends EventType> event) {
|
||||
return listeners.getOrDefault(event, EMPTY);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reset() {
|
||||
listeners.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package org.toop.framework.eventbus.store;
|
||||
|
||||
import org.toop.framework.eventbus.events.EventType;
|
||||
import org.toop.framework.eventbus.subscriber.Subscriber;
|
||||
|
||||
public interface SubscriberStore {
|
||||
void add(Subscriber<? extends EventType> subscriber);
|
||||
void remove(Subscriber<? extends EventType> subscriber);
|
||||
Subscriber<? extends EventType>[] get(Class<? extends EventType> event);
|
||||
void reset();
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package org.toop.framework.eventbus.store;
|
||||
|
||||
import org.toop.framework.eventbus.events.EventType;
|
||||
import org.toop.framework.eventbus.subscriber.Subscriber;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public class SyncSubscriberStore implements SubscriberStore {
|
||||
private final Map<Class<? extends EventType>, List<Subscriber<? extends EventType>>> LISTENERS = new ConcurrentHashMap<>();
|
||||
private static final Subscriber<? extends EventType>[] EMPTY = new Subscriber<?>[0];
|
||||
|
||||
@Override
|
||||
public void add(Subscriber<? extends EventType> sub) {
|
||||
LISTENERS.computeIfAbsent(sub.event(), _ -> new ArrayList<>()).add(sub);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove(Subscriber<? extends EventType> sub) {
|
||||
LISTENERS.getOrDefault(sub.event(), new ArrayList<>()).remove(sub);
|
||||
LISTENERS.entrySet().removeIf(entry -> entry.getValue().isEmpty());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Subscriber<? extends EventType>[] get(Class<? extends EventType> event) {
|
||||
List<Subscriber<? extends EventType>> list = LISTENERS.get(event);
|
||||
if (list == null || list.isEmpty()) return EMPTY;
|
||||
return list.toArray(EMPTY);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reset() {
|
||||
LISTENERS.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package org.toop.framework.eventbus.subscriber;
|
||||
|
||||
import org.toop.framework.eventbus.events.EventType;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public record DefaultNamedSubscriber<K extends EventType>(String id, Class<K> event, Consumer<K> handler)
|
||||
implements NamedSubscriber<K> {}
|
||||
@@ -0,0 +1,8 @@
|
||||
package org.toop.framework.eventbus.subscriber;
|
||||
|
||||
import org.toop.framework.eventbus.events.EventType;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public record DefaultSubscriber<K extends EventType>(Class<K> event, Consumer<K> handler) implements Subscriber<K> {}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
package org.toop.framework.eventbus.subscriber;
|
||||
|
||||
public interface HasId<ID> {
|
||||
ID id();
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package org.toop.framework.eventbus.subscriber;
|
||||
|
||||
import org.toop.framework.eventbus.events.EventType;
|
||||
|
||||
public interface IdSubscriber<K extends EventType> extends Subscriber<K>, HasId<Long> {}
|
||||
@@ -0,0 +1,8 @@
|
||||
package org.toop.framework.eventbus.subscriber;
|
||||
|
||||
import org.toop.framework.eventbus.events.EventType;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public record LongIdSubscriber<K extends EventType>(Long id, Class<K> event, Consumer<K> handler)
|
||||
implements IdSubscriber<K> {}
|
||||
@@ -0,0 +1,5 @@
|
||||
package org.toop.framework.eventbus.subscriber;
|
||||
|
||||
import org.toop.framework.eventbus.events.EventType;
|
||||
|
||||
public interface NamedSubscriber<K extends EventType> extends Subscriber<K>, HasId<String> {}
|
||||
@@ -0,0 +1,10 @@
|
||||
package org.toop.framework.eventbus.subscriber;
|
||||
|
||||
import org.toop.framework.eventbus.events.EventType;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public interface Subscriber<K extends EventType> {
|
||||
Class<K> event();
|
||||
Consumer<K> handler();
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package org.toop.framework.gameFramework;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface LongPairConsumer {
|
||||
void accept(long a, long b);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package org.toop.framework.gameFramework.controller;
|
||||
|
||||
import org.toop.framework.gameFramework.model.game.SupportsOnlinePlay;
|
||||
import org.toop.framework.gameFramework.model.game.threadBehaviour.Controllable;
|
||||
import org.toop.framework.networking.events.NetworkEvents;
|
||||
|
||||
public interface GameController extends Controllable, UpdatesGameUI {
|
||||
/** Called when it is this player's turn to make a move. */
|
||||
void onYourTurn(NetworkEvents.YourTurnResponse event);
|
||||
|
||||
/** Called when a move from another player is received. */
|
||||
void onMoveReceived(NetworkEvents.GameMoveResponse event);
|
||||
|
||||
/** Called when the game has finished, with the final result. */
|
||||
void gameFinished(NetworkEvents.GameResultResponse event);
|
||||
|
||||
void sendMove(long clientId, long move);
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
package org.toop.framework.gameFramework.model.game;
|
||||
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public abstract class AbstractGame<T extends TurnBasedGame<T>> implements TurnBasedGame<T> {
|
||||
private final int playerCount; // How many players are playing
|
||||
private final Player<T>[] players;
|
||||
private int turn = 0; // What turn it is in the game
|
||||
|
||||
/** Constant representing an empty position on the board. */
|
||||
public static final int EMPTY = -1;
|
||||
|
||||
/** Number of rows in the game board. */
|
||||
private final int rowSize;
|
||||
|
||||
/** Number of columns in the game board. */
|
||||
private final int columnSize;
|
||||
|
||||
/** The game board stored as a one-dimensional array. */
|
||||
private final int[] board;
|
||||
|
||||
|
||||
|
||||
protected AbstractGame(int rowSize, int columnSize, int playerCount, Player<T>[] players) {
|
||||
assert rowSize > 0 && columnSize > 0;
|
||||
|
||||
this.rowSize = rowSize;
|
||||
this.columnSize = columnSize;
|
||||
|
||||
this.players = players;
|
||||
|
||||
board = new int[rowSize * columnSize];
|
||||
Arrays.fill(board, EMPTY);
|
||||
|
||||
this.playerCount = playerCount;
|
||||
}
|
||||
|
||||
protected AbstractGame(AbstractGame<T> other){
|
||||
this.rowSize = other.rowSize;
|
||||
this.columnSize = other.columnSize;
|
||||
this.board = other.board.clone();
|
||||
this.playerCount = other.playerCount;
|
||||
this.turn = other.turn;
|
||||
// TODO: Make this a deep copy, add deep copy interface to Player
|
||||
this.players = other.players;
|
||||
|
||||
}
|
||||
|
||||
public static boolean contains(int[] array, int value) {
|
||||
// O(n)
|
||||
for (int element : array){
|
||||
if (element == value) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public Player<T> getPlayer(int index) {
|
||||
return players[index];
|
||||
}
|
||||
|
||||
public int getPlayerCount(){return this.playerCount;}
|
||||
|
||||
protected void nextTurn() {
|
||||
turn += 1;
|
||||
}
|
||||
|
||||
public int getCurrentTurn() {
|
||||
return turn % playerCount;
|
||||
}
|
||||
|
||||
protected void setBoard(int position) {
|
||||
setBoard(position, getCurrentTurn());
|
||||
}
|
||||
|
||||
protected void setBoard(int position, int player) {
|
||||
this.board[position] = player;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of rows in the board.
|
||||
*
|
||||
* @return number of rows
|
||||
*/
|
||||
public int getRowSize() {
|
||||
return this.rowSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of columns in the board.
|
||||
*
|
||||
* @return number of columns
|
||||
*/
|
||||
public int getColumnSize() {
|
||||
return this.columnSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a copy of the current board state.
|
||||
*
|
||||
* @return a cloned array representing the board
|
||||
*/
|
||||
public int[] getBoard() {
|
||||
return this.board.clone();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package org.toop.framework.gameFramework.model.game;
|
||||
|
||||
public interface BoardProvider {
|
||||
long[] getBoard();
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
package org.toop.framework.gameFramework.model.game;
|
||||
|
||||
public interface DeepCopyable<T extends TurnBasedGame<T>> {
|
||||
public interface DeepCopyable<T> {
|
||||
T deepCopy();
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ public interface Playable {
|
||||
*
|
||||
* @return an array of integers representing legal moves
|
||||
*/
|
||||
int[] getLegalMoves();
|
||||
long getLegalMoves();
|
||||
|
||||
/**
|
||||
* Plays the given move and returns the resulting game state.
|
||||
@@ -20,5 +20,5 @@ public interface Playable {
|
||||
* @param move the move to apply
|
||||
* @return the {@link GameState} and additional info after the move
|
||||
*/
|
||||
PlayResult play(int move);
|
||||
PlayResult play(long move);
|
||||
}
|
||||
|
||||
@@ -10,11 +10,11 @@ import org.toop.framework.networking.events.NetworkEvents;
|
||||
public interface SupportsOnlinePlay {
|
||||
|
||||
/** Called when it is this player's turn to make a move. */
|
||||
void onYourTurn(NetworkEvents.YourTurnResponse event);
|
||||
void onYourTurn(long clientId);
|
||||
|
||||
/** Called when a move from another player is received. */
|
||||
void onMoveReceived(NetworkEvents.GameMoveResponse event);
|
||||
void onMoveReceived(long move);
|
||||
|
||||
/** Called when the game has finished, with the final result. */
|
||||
void gameFinished(NetworkEvents.GameResultResponse event);
|
||||
void gameFinished(String condition);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package org.toop.framework.gameFramework.model.game;
|
||||
|
||||
public interface TurnBasedGame<T extends TurnBasedGame<T>> extends Playable, DeepCopyable<T>, PlayerProvider<T> {
|
||||
public interface TurnBasedGame<T extends TurnBasedGame<T>> extends Playable, DeepCopyable<T>, PlayerProvider<T>, BoardProvider {
|
||||
int getCurrentTurn();
|
||||
int getPlayerCount();
|
||||
int getWinner();
|
||||
}
|
||||
|
||||
@@ -2,10 +2,12 @@ package org.toop.framework.gameFramework.model.game.threadBehaviour;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.toop.framework.gameFramework.LongPairConsumer;
|
||||
import org.toop.framework.gameFramework.controller.GameController;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* Base class for thread-based game behaviours.
|
||||
@@ -14,8 +16,9 @@ import java.util.concurrent.atomic.AtomicBoolean;
|
||||
* a running flag, a game reference, and a logger.
|
||||
* Subclasses implement the actual game-loop logic.
|
||||
*/
|
||||
public abstract class AbstractThreadBehaviour<T extends TurnBasedGame<T>> implements ThreadBehaviour<T> {
|
||||
|
||||
public abstract class AbstractThreadBehaviour<T extends TurnBasedGame<T>> implements ThreadBehaviour {
|
||||
private LongPairConsumer onSendMove;
|
||||
private Runnable onUpdateUI;
|
||||
/** Indicates whether the game loop or event processing is active. */
|
||||
protected final AtomicBoolean isRunning = new AtomicBoolean();
|
||||
|
||||
@@ -33,4 +36,26 @@ public abstract class AbstractThreadBehaviour<T extends TurnBasedGame<T>> implem
|
||||
public AbstractThreadBehaviour(T game) {
|
||||
this.game = game;
|
||||
}
|
||||
|
||||
protected void updateUI(){
|
||||
if (onUpdateUI != null) {
|
||||
onUpdateUI.run();
|
||||
}
|
||||
}
|
||||
|
||||
protected void sendMove(long clientId, long move){
|
||||
if (onSendMove != null) {
|
||||
onSendMove.accept(clientId, move);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setOnUpdateUI(Runnable onUpdateUI) {
|
||||
this.onUpdateUI = onUpdateUI;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setOnSendMove(LongPairConsumer onSendMove) {
|
||||
this.onSendMove = onSendMove;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
package org.toop.framework.gameFramework.model.game.threadBehaviour;
|
||||
|
||||
import org.toop.framework.gameFramework.LongPairConsumer;
|
||||
import org.toop.framework.gameFramework.controller.GameController;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
import org.toop.framework.gameFramework.model.player.AbstractPlayer;
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* Strategy interface for controlling game thread behavior.
|
||||
* <p>
|
||||
* Defines how a game's execution is started, stopped, and which player is active.
|
||||
*/
|
||||
public interface ThreadBehaviour<T extends TurnBasedGame<T>> extends Controllable {
|
||||
public interface ThreadBehaviour extends Controllable {
|
||||
void setOnUpdateUI(Runnable onUpdateUI);
|
||||
void setOnSendMove(LongPairConsumer onSendMove);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
package org.toop.framework.gameFramework.model.player;
|
||||
|
||||
import org.toop.framework.gameFramework.model.game.DeepCopyable;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
|
||||
public interface AI<T extends TurnBasedGame<T>> extends MoveProvider<T>, DeepCopyable<AI<T>> {
|
||||
}
|
||||
@@ -12,6 +12,6 @@ import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
*
|
||||
* @param <T> the specific type of game this AI can play, extending {@link GameR}
|
||||
*/
|
||||
public abstract class AbstractAI<T extends TurnBasedGame> implements MoveProvider<T> {
|
||||
public abstract class AbstractAI<T extends TurnBasedGame<T>> implements AI<T> {
|
||||
// Concrete AI implementations should override findBestMove(T game, int depth)
|
||||
}
|
||||
|
||||
@@ -5,44 +5,66 @@ import org.apache.logging.log4j.Logger;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
|
||||
/**
|
||||
* Abstract class representing a player in a game.
|
||||
* <p>
|
||||
* Players are entities that can make moves based on the current state of a game.
|
||||
* player types, such as human players or AI players.
|
||||
* </p>
|
||||
* <p>
|
||||
* Subclasses should override the {@link #getMove(GameR)} method to provide
|
||||
* specific move logic.
|
||||
* </p>
|
||||
* Base class for players in a turn-based game.
|
||||
*
|
||||
* @param <T> the game type
|
||||
*/
|
||||
public abstract class AbstractPlayer<T extends TurnBasedGame<T>> implements Player<T> {
|
||||
private int playerIndex = -1;
|
||||
|
||||
private Logger logger = LogManager.getLogger(this.getClass());
|
||||
|
||||
private final Logger logger = LogManager.getLogger(this.getClass());
|
||||
private final String name;
|
||||
|
||||
/**
|
||||
* Creates a new player with the given name.
|
||||
*
|
||||
* @param name the player name
|
||||
*/
|
||||
protected AbstractPlayer(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines the next move based on the provided game state.
|
||||
* <p>
|
||||
* The default implementation throws an {@link UnsupportedOperationException},
|
||||
* indicating that concrete subclasses must override this method to provide
|
||||
* actual move logic.
|
||||
* </p>
|
||||
* Creates a copy of another player.
|
||||
*
|
||||
* @param gameCopy a snapshot of the current game state
|
||||
* @return an integer representing the chosen move
|
||||
* @throws UnsupportedOperationException if the method is not overridden
|
||||
* @param other the player to copy
|
||||
*/
|
||||
public int getMove(T gameCopy) {
|
||||
logger.error("Method getMove not implemented.");
|
||||
throw new UnsupportedOperationException("Not supported yet.");
|
||||
protected AbstractPlayer(AbstractPlayer<T> other) {
|
||||
this.name = other.name;
|
||||
}
|
||||
|
||||
public String getName(){
|
||||
/**
|
||||
* Gets the player's move for the given game state.
|
||||
* A deep copy is provided so the player cannot modify the real state.
|
||||
* <p>
|
||||
* This method uses the Template Method Pattern: it defines the fixed
|
||||
* algorithm and delegates the variable part to {@link #determineMove(T)}.
|
||||
*
|
||||
* @param game the current game
|
||||
* @return the chosen move
|
||||
*/
|
||||
public final long getMove(T game) {
|
||||
return determineMove(game.deepCopy());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Determines the player's move using a safe copy of the game.
|
||||
* <p>
|
||||
* This method is called by {@link #getMove(T)} and should contain
|
||||
* the player's strategy for choosing a move.
|
||||
*
|
||||
* @param gameCopy a deep copy of the game
|
||||
* @return the chosen move
|
||||
*/
|
||||
protected abstract long determineMove(T gameCopy);
|
||||
|
||||
|
||||
/**
|
||||
* Returns the player's name.
|
||||
*
|
||||
* @return the name
|
||||
*/
|
||||
public String getName() {
|
||||
return this.name;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,6 @@ package org.toop.framework.gameFramework.model.player;
|
||||
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
|
||||
public interface MoveProvider<T extends TurnBasedGame> {
|
||||
int getMove(T game);
|
||||
public interface MoveProvider<T extends TurnBasedGame<T>> {
|
||||
long getMove(T game);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package org.toop.framework.gameFramework.model.player;
|
||||
|
||||
import org.toop.framework.gameFramework.model.game.DeepCopyable;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
|
||||
public interface Player<T extends TurnBasedGame<T>> extends NameProvider, MoveProvider<T> {
|
||||
public interface Player<T extends TurnBasedGame<T>> extends NameProvider, MoveProvider<T>, DeepCopyable<Player<T>> {
|
||||
}
|
||||
|
||||
@@ -10,10 +10,6 @@ import org.toop.framework.eventbus.events.GenericEvent;
|
||||
* player actions, and game completion.
|
||||
*/
|
||||
public class GUIEvents extends EventsBase {
|
||||
|
||||
/** Event to refresh or redraw the game canvas. */
|
||||
public record RefreshGameCanvas() implements GenericEvent {}
|
||||
|
||||
/**
|
||||
* Event indicating the game has ended.
|
||||
*
|
||||
@@ -23,8 +19,8 @@ public class GUIEvents extends EventsBase {
|
||||
public record GameEnded(boolean winOrTie, int winner) implements GenericEvent {}
|
||||
|
||||
/** Event indicating a player has attempted a move. */
|
||||
public record PlayerAttemptedMove(int move) implements GenericEvent {}
|
||||
public record PlayerAttemptedMove(long move) implements GenericEvent {}
|
||||
|
||||
/** Event indicating a player is hovering over a move (for UI feedback). */
|
||||
public record PlayerMoveHovered(int move) implements GenericEvent {}
|
||||
public record PlayerMoveHovered(long move) implements GenericEvent {}
|
||||
}
|
||||
|
||||
@@ -4,19 +4,20 @@ import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.toop.framework.SnowflakeGenerator;
|
||||
import org.toop.framework.eventbus.EventFlow;
|
||||
import org.toop.framework.eventbus.bus.EventBus;
|
||||
import org.toop.framework.networking.events.NetworkEvents;
|
||||
import org.toop.framework.networking.exceptions.ClientNotFoundException;
|
||||
import org.toop.framework.networking.interfaces.NetworkingClientManager;
|
||||
|
||||
public class NetworkingClientEventListener {
|
||||
|
||||
private static final Logger logger = LogManager.getLogger(NetworkingClientEventListener.class);
|
||||
|
||||
private final NetworkingClientManager clientManager;
|
||||
|
||||
/** Starts a connection manager, to manage, connections. */
|
||||
public NetworkingClientEventListener(NetworkingClientManager clientManager) {
|
||||
public NetworkingClientEventListener(EventBus eventBus, NetworkingClientManager clientManager) {
|
||||
this.clientManager = clientManager;
|
||||
new EventFlow()
|
||||
new EventFlow(eventBus)
|
||||
.listen(NetworkEvents.StartClient.class, this::handleStartClient, false)
|
||||
.listen(NetworkEvents.SendCommand.class, this::handleCommand, false)
|
||||
.listen(NetworkEvents.SendLogin.class, this::handleSendLogin, false)
|
||||
@@ -40,6 +41,7 @@ public class NetworkingClientEventListener {
|
||||
|
||||
void handleStartClient(NetworkEvents.StartClient event) {
|
||||
long clientId = SnowflakeGenerator.nextId();
|
||||
new EventFlow().addPostEvent(new NetworkEvents.CreatedIdForClient(clientId, event.identifier())).postEvent();
|
||||
clientManager.startClient(
|
||||
clientId,
|
||||
event.networkingClient(),
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user