mirror of
https://github.com/2OOP/pism.git
synced 2026-02-04 10:54:51 +00:00
Compare commits
97 Commits
UnitTests
...
Developmen
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ea32598d4c | ||
|
|
40e1c3b124 | ||
|
|
22a73fc50a | ||
|
|
af9a316639 | ||
|
|
8508377cb4 | ||
|
|
97276c7e80 | ||
|
|
11eda3c8b5 | ||
|
|
039c0393c8 | ||
|
|
319eaa33b1 | ||
|
|
940b26de41 | ||
|
|
2f161bcc0a | ||
|
|
ccdca4f0ea | ||
|
|
b5bd4adf91 | ||
|
|
f37c578a35 | ||
|
|
eb1784550f | ||
|
|
e8f66a62f0 | ||
|
|
4926bd161e | ||
|
|
b39659d02d | ||
|
|
c107e8c0d1 | ||
|
|
8a94aad622 | ||
|
|
992523b936 | ||
|
|
5d2fff7ae7 | ||
|
|
f168b974ab | ||
|
|
057487e4f9 | ||
|
|
fb32bc6f8e | ||
|
|
4c8bd89a35 | ||
|
|
f7b24edf1e | ||
|
|
e5ea838430 | ||
|
|
989e0a65c6 | ||
|
|
7565757b6b | ||
|
|
a6b2356a5e | ||
|
|
d078a70950 | ||
|
|
94e3fc71b8 | ||
|
|
9fcbe7d298 | ||
|
|
429e5bc90b | ||
|
|
35f7a4fd13 | ||
|
|
e2132b549d | ||
|
|
9aefcb9b7b | ||
| 58a9ce78fe | |||
| 230f7480e4 | |||
|
|
6aa0eb952a | ||
|
|
df93b44d19 | ||
|
|
67f39c3f3b | ||
| 6e6a383708 | |||
| b7dec7798b | |||
| 2caa4fc79f | |||
| e72d888d84 | |||
|
|
e149588b60 | ||
|
|
a7d1a964c2 | ||
|
|
380e219c08 | ||
|
|
dccf428bb8 | ||
|
|
4ad922423c | ||
|
|
6e2ea82a32 | ||
|
|
34c85ec472 | ||
| 2d9b34b7f6 | |||
|
|
8867d5a1ea | ||
|
|
b94d1b6c9d | ||
|
|
8cb0a86d4e | ||
|
|
c2f1df7143 | ||
|
|
0956286616 | ||
| 55de6b5b18 | |||
| 73d71f2a2d | |||
|
|
cbcce29780 | ||
|
|
afcd9be71e | ||
| a9145d44cf | |||
| c015100ebf | |||
|
|
cd5736afc8 | ||
|
|
89a9cb1e55 | ||
|
|
22270e58dc | ||
|
|
edd2c24b65 | ||
| c929abc4b8 | |||
|
|
8b85915c74 | ||
|
|
150fb2986f | ||
|
|
9c20fcbc39 | ||
|
|
4d31a8ed44 | ||
|
|
fc47d81b8e | ||
|
|
a60c702306 | ||
|
|
c30c118c04 | ||
| 4b8edf1585 | |||
| fa9c2ce32b | |||
|
|
2599f9fa40 | ||
|
|
84e411fa38 | ||
|
|
66cb000fad | ||
|
|
8146be16ed | ||
|
|
d702f82194 | ||
|
|
f4678edf2f | ||
|
|
9a0bfc4fce | ||
|
|
0b750d5c0d | ||
|
|
07f3319675 | ||
|
|
1dfa6a7c6e | ||
| 144de5100e | |||
| 40ddf08e2d | |||
| 2936cc0b72 | |||
|
|
d24feef73e | ||
|
|
59d46cb73c | ||
|
|
38681c5db0 | ||
|
|
cbe01fbca5 |
5
.idea/inspectionProfiles/Project_Default.xml
generated
5
.idea/inspectionProfiles/Project_Default.xml
generated
@@ -2,10 +2,7 @@
|
||||
<profile version="1.0">
|
||||
<option name="myName" value="Project Default" />
|
||||
<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" />
|
||||
<option name="METHOD_MATCHER_CONFIG" value="java.util.Formatter,format,java.io.Writer,append,com.google.common.base.Preconditions,checkNotNull,org.hibernate.Session,close,java.io.PrintWriter,printf,java.io.PrintStream,printf,java.lang.foreign.Arena,ofAuto,java.lang.foreign.Arena,global,org.toop.framework.audio.AudioPlayer,play,java.util.Map,remove,java.util.concurrent.Executors,newSingleThreadScheduledExecutor|newFixedThreadPool|newSingleThreadExecutor" />
|
||||
</inspection_tool>
|
||||
<inspection_tool class="WriteOnlyObject" enabled="false" level="WARNING" enabled_by_default="false" />
|
||||
</profile>
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
package org.toop.app;
|
||||
|
||||
import javafx.application.Application;
|
||||
import javafx.application.Platform;
|
||||
import javafx.geometry.Pos;
|
||||
import javafx.scene.Scene;
|
||||
import javafx.scene.input.KeyCode;
|
||||
import javafx.scene.input.KeyCodeCombination;
|
||||
import javafx.scene.input.KeyEvent;
|
||||
|
||||
import javafx.scene.layout.StackPane;
|
||||
import javafx.stage.Stage;
|
||||
import org.toop.app.widget.Primitive;
|
||||
import org.toop.app.widget.WidgetContainer;
|
||||
import org.toop.app.widget.complex.LoadingWidget;
|
||||
@@ -16,8 +20,8 @@ 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.networking.connection.NetworkingClientEventListener;
|
||||
import org.toop.framework.networking.connection.NetworkingClientManager;
|
||||
import org.toop.framework.resource.ResourceLoader;
|
||||
import org.toop.framework.resource.ResourceManager;
|
||||
import org.toop.framework.resource.events.AssetLoaderEvents;
|
||||
@@ -27,12 +31,6 @@ import org.toop.framework.resource.resources.SoundEffectAsset;
|
||||
import org.toop.local.AppContext;
|
||||
import org.toop.local.AppSettings;
|
||||
|
||||
import javafx.application.Application;
|
||||
import javafx.geometry.Pos;
|
||||
import javafx.scene.Scene;
|
||||
import javafx.scene.layout.StackPane;
|
||||
import javafx.stage.Stage;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
@@ -137,7 +135,6 @@ public final class App extends Application {
|
||||
}
|
||||
|
||||
stage.show();
|
||||
|
||||
}
|
||||
|
||||
private void setKeybinds(StackPane root) {
|
||||
|
||||
@@ -11,19 +11,19 @@ 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.game.players.ArtificialPlayer;
|
||||
import org.toop.framework.game.players.OnlinePlayer;
|
||||
import org.toop.framework.gameFramework.controller.GameController;
|
||||
import org.toop.framework.eventbus.GlobalEventBus;
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
import org.toop.framework.networking.clients.TournamentNetworkingClient;
|
||||
import org.toop.framework.networking.events.NetworkEvents;
|
||||
import org.toop.framework.networking.types.NetworkingConnector;
|
||||
import org.toop.game.games.reversi.BitboardReversi;
|
||||
import org.toop.game.games.tictactoe.BitboardTicTacToe;
|
||||
import org.toop.game.players.ArtificialPlayer;
|
||||
import org.toop.game.players.OnlinePlayer;
|
||||
import org.toop.game.players.ai.RandomAI;
|
||||
import org.toop.framework.networking.connection.clients.TournamentNetworkingClient;
|
||||
import org.toop.framework.networking.connection.events.NetworkEvents;
|
||||
import org.toop.framework.networking.connection.types.NetworkingConnector;
|
||||
import org.toop.framework.networking.server.gateway.NettyGatewayServer;
|
||||
import org.toop.game.players.ai.mcts.MCTSAI3;
|
||||
import org.toop.local.AppContext;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.Executors;
|
||||
@@ -32,7 +32,8 @@ import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
public final class Server {
|
||||
// TODO: Keep track of listeners. Remove them on Server connection close so reference is deleted.
|
||||
private NettyGatewayServer nettyGatewayServer;
|
||||
|
||||
private String user = "";
|
||||
private long clientId = -1;
|
||||
|
||||
@@ -60,10 +61,13 @@ public final class Server {
|
||||
return null;
|
||||
}
|
||||
|
||||
public Server(String ip, String port, String user) {
|
||||
this(ip, port, user, null);
|
||||
}
|
||||
|
||||
// Server has to deal with ALL network related listen events. This "server" can then interact with the manager to make stuff happen.
|
||||
// This prevents data races where events get sent to the game manager but the manager isn't ready yet.
|
||||
public Server(String ip, String port, String user) {
|
||||
public Server(String ip, String port, String user, NettyGatewayServer nettyGatewayServer) {
|
||||
if (ip.split("\\.").length < 4) {
|
||||
new ErrorPopup("\"" + ip + "\" " + AppContext.getString("is-not-a-valid-ip-address"));
|
||||
return;
|
||||
@@ -83,6 +87,8 @@ public final class Server {
|
||||
return;
|
||||
}
|
||||
|
||||
this.nettyGatewayServer = nettyGatewayServer;
|
||||
|
||||
final int reconnectAttempts = 10;
|
||||
|
||||
LoadingWidget loading = new LoadingWidget(
|
||||
@@ -113,7 +119,8 @@ public final class Server {
|
||||
return;
|
||||
}
|
||||
|
||||
primary = new ServerView(user, this::sendChallenge);
|
||||
primary = new ServerView(user, this::sendChallenge, user, clientId);
|
||||
|
||||
WidgetContainer.getCurrentView().transitionNextCustom(primary, "disconnect", this::disconnect);
|
||||
|
||||
a.unsubscribe("connecting");
|
||||
@@ -154,7 +161,9 @@ public final class Server {
|
||||
.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");
|
||||
.listen(NetworkEvents.YourTurnResponse.class, this::handleYourTurn, false, "your-turn")
|
||||
.listen(NetworkEvents.ClosedConnection.class, this::closedConnection, false, "closed-connection")
|
||||
.listen(NetworkEvents.TournamentResultResponse.class, this::handleTournamentResult, false, "tournament-result");
|
||||
|
||||
connectFlow = a;
|
||||
}
|
||||
@@ -191,45 +200,30 @@ public final class Server {
|
||||
return;
|
||||
}
|
||||
|
||||
final int myTurn = response.playerToMove().equalsIgnoreCase(response.opponent()) ? 1 : 0;
|
||||
final String startingPlayer = response.playerToMove();
|
||||
final int userStartingTurn = startingPlayer.equalsIgnoreCase(user) ? 0 : 1;
|
||||
final int opponentStartingTurn = 1 - userStartingTurn;
|
||||
|
||||
final GameInformation information = new GameInformation(type);
|
||||
//information.players[0] = playerInformation;
|
||||
information.players[0].name = user;
|
||||
information.players[0].isHuman = false;
|
||||
information.players[0].computerDifficulty = 5;
|
||||
information.players[0].computerThinkTime = 1;
|
||||
information.players[1].name = response.opponent();
|
||||
|
||||
/*switch (type){
|
||||
case TICTACTOE ->{
|
||||
players[myTurn] = new ArtificialPlayer<>(new TicTacToeAIR(9), user);
|
||||
}
|
||||
case REVERSI ->{
|
||||
players[myTurn] = new ArtificialPlayer<>(new ReversiAIR(), user);
|
||||
}
|
||||
}*/
|
||||
information.players[userStartingTurn].name = user;
|
||||
information.players[opponentStartingTurn].name = response.opponent();
|
||||
|
||||
Player[] players = new Player[2];
|
||||
|
||||
players[userStartingTurn] = new ArtificialPlayer(new MCTSAI3(1000, 8), user);
|
||||
players[opponentStartingTurn] = new OnlinePlayer(response.opponent());
|
||||
|
||||
switch (type) {
|
||||
case TICTACTOE ->{
|
||||
Player<BitboardTicTacToe>[] players = new Player[2];
|
||||
players[(myTurn + 1) % 2] = new OnlinePlayer<>(response.opponent());
|
||||
players[myTurn] = new ArtificialPlayer<>(new RandomAI<BitboardTicTacToe>(), user);
|
||||
gameController = new TicTacToeBitController(players);
|
||||
}
|
||||
case REVERSI -> {
|
||||
Player<BitboardReversi>[] players = new Player[2];
|
||||
players[(myTurn + 1) % 2] = new OnlinePlayer<>(response.opponent());
|
||||
players[myTurn] = new ArtificialPlayer<>(new RandomAI<BitboardReversi>(), user);
|
||||
gameController = new ReversiBitController(players, false);}
|
||||
case TICTACTOE -> gameController = new TicTacToeBitController(players);
|
||||
case REVERSI -> gameController = new ReversiBitController(players);
|
||||
default -> new ErrorPopup("Unsupported game type.");
|
||||
|
||||
}
|
||||
|
||||
if (gameController != null) {
|
||||
primary.reEnableButton(); // Re enable subscribe button
|
||||
gameController.start();
|
||||
isPolling = true; // Fixes server getting stuck
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -249,6 +243,13 @@ public final class Server {
|
||||
gameController.gameFinished(response);
|
||||
}
|
||||
|
||||
private void handleTournamentResult(NetworkEvents.TournamentResultResponse response) {
|
||||
IO.println(response.gameType());
|
||||
IO.println(Arrays.toString(response.names()));
|
||||
IO.println(Arrays.toString(response.scoreTypes()));
|
||||
IO.println(Arrays.toString(response.scores().toArray()));
|
||||
}
|
||||
|
||||
private void handleReceivedMove(NetworkEvents.GameMoveResponse response) {
|
||||
if (gameController == null) {
|
||||
return;
|
||||
@@ -263,7 +264,7 @@ public final class Server {
|
||||
String gameType = extractQuotedValue(response.gameType());
|
||||
final String finalGameType = gameType;
|
||||
var a = new ChallengePopup(challengerName, gameType, (playerInformation) -> {
|
||||
final int challengeId = Integer.parseInt(response.challengeId().replaceAll("\\D", ""));
|
||||
final long challengeId = Long.parseLong(response.challengeId().replaceAll("\\D", ""));
|
||||
new EventFlow().addPostEvent(new NetworkEvents.SendAcceptChallenge(clientId, challengeId)).postEvent();
|
||||
isSingleGame.set(true);
|
||||
});
|
||||
@@ -281,9 +282,27 @@ public final class Server {
|
||||
stopScheduler();
|
||||
connectFlow.unsubscribeAll();
|
||||
|
||||
if (nettyGatewayServer != null) {
|
||||
nettyGatewayServer.stop();
|
||||
}
|
||||
|
||||
WidgetContainer.getCurrentView().transitionPrevious();
|
||||
}
|
||||
|
||||
private void closedConnection(NetworkEvents.ClosedConnection e) {
|
||||
new EventFlow().addPostEvent(new NetworkEvents.CloseClient(clientId)).postEvent();
|
||||
isPolling = false;
|
||||
stopScheduler();
|
||||
connectFlow.unsubscribeAll();
|
||||
|
||||
if (nettyGatewayServer != null) {
|
||||
nettyGatewayServer.stop();
|
||||
}
|
||||
|
||||
WidgetContainer.getCurrentView().transitionPrevious();
|
||||
WidgetContainer.add(Pos.CENTER, new ErrorPopup("Server closed connection."));
|
||||
}
|
||||
|
||||
private void forfeitGame() {
|
||||
new EventFlow().addPostEvent(new NetworkEvents.SendForfeit(clientId)).postEvent();
|
||||
}
|
||||
@@ -330,7 +349,10 @@ public final class Server {
|
||||
|
||||
private void gamesListFromServerHandler(NetworkEvents.GamelistResponse event) {
|
||||
gameList.clear();
|
||||
gameList.addAll(List.of(event.gamelist()));
|
||||
var gl = new java.util.ArrayList<>(List.of(event.gamelist()));
|
||||
gl.sort(String::compareTo);
|
||||
gameList.addAll(gl);
|
||||
primary.updateGameList(gl);
|
||||
}
|
||||
|
||||
public void populateGameList() {
|
||||
|
||||
@@ -14,7 +14,7 @@ import org.toop.framework.gameFramework.view.GUIEvents;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public abstract class BitGameCanvas<T extends TurnBasedGame<T>> implements GameCanvas<T> {
|
||||
public abstract class BitGameCanvas implements GameCanvas {
|
||||
protected record Cell(float x, float y, float width, float height) {
|
||||
public boolean isInside(double x, double y) {
|
||||
return x >= this.x && x <= this.x + width &&
|
||||
@@ -78,6 +78,7 @@ public abstract class BitGameCanvas<T extends TurnBasedGame<T>> implements GameC
|
||||
}
|
||||
|
||||
canvas.setOnMouseClicked(event -> {
|
||||
|
||||
if (event.getButton() != MouseButton.PRIMARY) {
|
||||
return;
|
||||
}
|
||||
@@ -93,9 +94,6 @@ public abstract class BitGameCanvas<T extends TurnBasedGame<T>> implements GameC
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
render();
|
||||
}
|
||||
|
||||
@@ -108,7 +106,6 @@ public abstract class BitGameCanvas<T extends TurnBasedGame<T>> implements GameC
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void render() {
|
||||
graphics.setFill(backgroundColor);
|
||||
graphics.fillRect(0, 0, width, height);
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
package org.toop.app.canvas;
|
||||
|
||||
public interface BitLegalMoveDrawer {
|
||||
void showLegalMove(long move, int currentPlayerIndex);
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package org.toop.app.canvas;
|
||||
import javafx.scene.canvas.Canvas;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
|
||||
public interface GameCanvas<T extends TurnBasedGame<T>> extends GameDrawer<T>{
|
||||
public interface GameCanvas {
|
||||
Canvas getCanvas();
|
||||
void redraw(TurnBasedGame gameCopy);
|
||||
}
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
package org.toop.app.canvas;
|
||||
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
|
||||
public interface GameDrawer<T extends TurnBasedGame<T>> {
|
||||
void redraw(T gameCopy);
|
||||
}
|
||||
@@ -2,17 +2,15 @@ package org.toop.app.canvas;
|
||||
|
||||
import javafx.scene.paint.Color;
|
||||
import org.toop.app.App;
|
||||
import org.toop.game.games.reversi.BitboardReversi;
|
||||
import org.toop.framework.game.games.reversi.BitboardReversi;
|
||||
import org.toop.framework.game.players.LocalPlayer;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
|
||||
public class ReversiBitCanvas extends BitGameCanvas<BitboardReversi> implements BitLegalMoveDrawer {
|
||||
|
||||
private final boolean switchColors;
|
||||
private final boolean local;
|
||||
|
||||
public ReversiBitCanvas(boolean switchColors, boolean local) {
|
||||
public class ReversiBitCanvas extends BitGameCanvas {
|
||||
private TurnBasedGame gameCopy;
|
||||
private int previousCell;
|
||||
public ReversiBitCanvas() {
|
||||
super(Color.GRAY, new Color(0f, 0.4f, 0.2f, 1f), (App.getHeight() / 4) * 3, (App.getHeight() / 4) * 3, 8, 8, 5, true);
|
||||
this.switchColors = switchColors;
|
||||
this.local = local;
|
||||
canvas.setOnMouseMoved(event -> {
|
||||
double mouseX = event.getX();
|
||||
double mouseY = event.getY();
|
||||
@@ -26,6 +24,9 @@ public class ReversiBitCanvas extends BitGameCanvas<BitboardReversi> implements
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (hovered != null) {
|
||||
checkHoverDots(hovered, cellId);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -36,42 +37,32 @@ public class ReversiBitCanvas extends BitGameCanvas<BitboardReversi> implements
|
||||
}
|
||||
|
||||
@Override
|
||||
public void redraw(BitboardReversi gameCopy) {
|
||||
public void redraw(TurnBasedGame gameCopy) {
|
||||
this.gameCopy = 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));
|
||||
}
|
||||
|
||||
public void drawLegalDots(TurnBasedGame gameCopy){
|
||||
long legal = gameCopy.getLegalMoves();
|
||||
loopOverBoard(legal, (i) -> drawInnerDot(gameCopy.getCurrentTurn()==0?new Color(1f,1f,1f,0.65f) :new Color(0f,0f,0f,0.65f), i,false));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void showLegalMove(long move, int currentPlayerIndex) {
|
||||
int idx = Long.numberOfTrailingZeros(move);
|
||||
drawLegalMove(idx, currentPlayerIndex);
|
||||
private void checkHoverDots(BitGameCanvas.Cell hovered, int cellId){
|
||||
if (previousCell == cellId){
|
||||
return;
|
||||
}
|
||||
long backflips = ((BitboardReversi)gameCopy).getFlips(1L << previousCell);
|
||||
loopOverBoard(backflips, (i) -> drawInnerDot(gameCopy.getCurrentTurn()==1?Color.WHITE:Color.BLACK, i,true));
|
||||
previousCell = cellId;
|
||||
if (gameCopy.getPlayer(gameCopy.getCurrentTurn()) instanceof LocalPlayer) {
|
||||
long legal = gameCopy.getLegalMoves();
|
||||
if ((legal & (1L << cellId)) != 0) {
|
||||
long flips = ((BitboardReversi) gameCopy).getFlips(1L << cellId);
|
||||
loopOverBoard(flips, (i) -> drawInnerDot(gameCopy.getCurrentTurn() == 0 ? Color.WHITE : Color.BLACK, i, false));
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,12 +2,9 @@ package org.toop.app.canvas;
|
||||
|
||||
import javafx.scene.paint.Color;
|
||||
import org.toop.app.App;
|
||||
import org.toop.game.games.tictactoe.BitboardTicTacToe;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class TicTacToeBitCanvas extends BitGameCanvas<BitboardTicTacToe>{
|
||||
public class TicTacToeBitCanvas extends BitGameCanvas{
|
||||
public TicTacToeBitCanvas() {
|
||||
super(
|
||||
Color.GRAY,
|
||||
@@ -22,7 +19,7 @@ public class TicTacToeBitCanvas extends BitGameCanvas<BitboardTicTacToe>{
|
||||
}
|
||||
|
||||
@Override
|
||||
public void redraw(BitboardTicTacToe gameCopy) {
|
||||
public void redraw(TurnBasedGame gameCopy) {
|
||||
clearAll();
|
||||
drawMoves(gameCopy.getBoard());
|
||||
}
|
||||
@@ -30,6 +27,7 @@ public class TicTacToeBitCanvas extends BitGameCanvas<BitboardTicTacToe>{
|
||||
private void drawMoves(long[] gameBoard){
|
||||
loopOverBoard(gameBoard[0], (i) -> drawX(Color.RED, i));
|
||||
loopOverBoard(gameBoard[1], (i) -> drawO(Color.BLUE, i));
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -5,21 +5,22 @@ 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.canvas.ReversiBitCanvas;
|
||||
import org.toop.app.widget.WidgetContainer;
|
||||
import org.toop.app.widget.view.GameView;
|
||||
import org.toop.framework.eventbus.EventFlow;
|
||||
import org.toop.framework.eventbus.GlobalEventBus;
|
||||
import org.toop.framework.game.games.reversi.BitboardReversi;
|
||||
import org.toop.framework.gameFramework.controller.GameController;
|
||||
import org.toop.framework.gameFramework.model.game.SupportsOnlinePlay;
|
||||
import org.toop.framework.gameFramework.model.game.threadBehaviour.SupportsOnlinePlay;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
import org.toop.framework.gameFramework.model.game.threadBehaviour.ThreadBehaviour;
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
import org.toop.framework.gameFramework.view.GUIEvents;
|
||||
import org.toop.framework.networking.events.NetworkEvents;
|
||||
import org.toop.game.players.LocalPlayer;
|
||||
import org.toop.framework.networking.connection.events.NetworkEvents;
|
||||
import org.toop.framework.game.players.LocalPlayer;
|
||||
|
||||
public class GenericGameController<T extends TurnBasedGame<T>, C extends GameCanvas<T>> implements GameController {
|
||||
public class GenericGameController implements GameController {
|
||||
protected final EventFlow eventFlow = new EventFlow();
|
||||
|
||||
// Logger for logging
|
||||
@@ -28,26 +29,24 @@ public class GenericGameController<T extends TurnBasedGame<T>, C extends GameCan
|
||||
// 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 GameCanvas canvas;
|
||||
|
||||
protected final TurnBasedGame<T> game; // Reference to game instance
|
||||
protected final TurnBasedGame game; // Reference to game instance
|
||||
private final ThreadBehaviour gameThreadBehaviour;
|
||||
|
||||
// TODO: Change gameType to automatically happen with either dependency injection or something else.
|
||||
public GenericGameController(C canvas, T game, ThreadBehaviour gameThreadBehaviour, String gameType) {
|
||||
logger.info("Creating: " + this.getClass());
|
||||
public GenericGameController(GameCanvas canvas, TurnBasedGame 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))));
|
||||
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));
|
||||
@@ -58,24 +57,40 @@ public class GenericGameController<T extends TurnBasedGame<T>, C extends GameCan
|
||||
WidgetContainer.getCurrentView().transitionNext(gameView, true);
|
||||
|
||||
// Listen to updates
|
||||
logger.info("Game controller started listening");
|
||||
eventFlow
|
||||
.listen(GUIEvents.GameEnded.class, this::onGameFinish, false)
|
||||
.listen(GUIEvents.PlayerAttemptedMove.class, event -> {if (getCurrentPlayer() instanceof LocalPlayer<T> lp){lp.setLastMove(event.move());}}, false);
|
||||
.listen(GUIEvents.PlayerAttemptedMove.class, event -> {
|
||||
logger.info("User attempting move {}", event.move());
|
||||
logger.info("Current player's turn {}", getCurrentPlayer().getName());
|
||||
logger.info("First player {}", game.getPlayer(0).getName());
|
||||
logger.info("Username {}", getCurrentPlayer().getName());
|
||||
logger.info("User is class {}, {}", getCurrentPlayer().getClass(), getCurrentPlayer() instanceof LocalPlayer);
|
||||
if (getCurrentPlayer() instanceof LocalPlayer lp) {
|
||||
try {
|
||||
lp.setLastMove(event.move());
|
||||
} catch (Exception e) {
|
||||
IO.println(e);
|
||||
}
|
||||
}
|
||||
}, false);
|
||||
}
|
||||
|
||||
public void start(){
|
||||
logger.info("Starting GameManager");
|
||||
updateUI();
|
||||
gameThreadBehaviour.start();
|
||||
logger.info("GameManager started");
|
||||
}
|
||||
|
||||
public void stop(){
|
||||
logger.info("Stopping GameManager");
|
||||
removeListeners();
|
||||
gameThreadBehaviour.stop();
|
||||
logger.info("GameManager stopped");
|
||||
}
|
||||
|
||||
public Player<T> getCurrentPlayer(){
|
||||
public Player getCurrentPlayer(){
|
||||
return game.getPlayer(getCurrentPlayerIndex());
|
||||
}
|
||||
|
||||
@@ -96,14 +111,14 @@ public class GenericGameController<T extends TurnBasedGame<T>, C extends GameCan
|
||||
}
|
||||
|
||||
private void onGameFinish(GUIEvents.GameEnded event){
|
||||
logger.info("Game Finished");
|
||||
logger.info("OnlineTurnBasedGame 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
|
||||
public Player getPlayer(int player){
|
||||
if (player < 0 || player > game.getPlayerCount()-1){ // TODO: Make game turn player count
|
||||
logger.error("Invalid player index");
|
||||
throw new IllegalArgumentException("player out of range");
|
||||
}
|
||||
@@ -140,21 +155,17 @@ public class GenericGameController<T extends TurnBasedGame<T>, C extends GameCan
|
||||
|
||||
@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;
|
||||
TurnBasedGame gameCopy = game.deepCopy();
|
||||
canvas.redraw(gameCopy);
|
||||
String gameType = game.getClass().getSimpleName().replace("Bitboard","");
|
||||
gameView.nextPlayer(true, getCurrentPlayer().getName(), game.getPlayer(1-getCurrentPlayerIndex()).getName(),gameType);
|
||||
if (gameType.equals("Reversi")) {
|
||||
BitboardReversi reversiGame = (BitboardReversi) game;
|
||||
BitboardReversi.Score reversiScore = reversiGame.getScore();
|
||||
gameView.setPlayer1Score(reversiScore.black());
|
||||
gameView.setPlayer2Score(reversiScore.white());
|
||||
if (getCurrentPlayer() instanceof LocalPlayer) {
|
||||
((ReversiBitCanvas)canvas).drawLegalDots(gameCopy);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,24 +1,29 @@
|
||||
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;
|
||||
import org.toop.framework.game.gameThreads.LocalThreadBehaviour;
|
||||
import org.toop.framework.game.gameThreads.OnlineThreadBehaviour;
|
||||
import org.toop.framework.game.games.reversi.BitboardReversi;
|
||||
import org.toop.framework.game.players.OnlinePlayer;
|
||||
|
||||
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");
|
||||
import java.util.Arrays;
|
||||
|
||||
public class ReversiBitController extends GenericGameController {
|
||||
|
||||
private BitboardReversi game;
|
||||
|
||||
public ReversiBitController(Player[] players) {
|
||||
BitboardReversi game = new BitboardReversi();
|
||||
game.init(players);
|
||||
ThreadBehaviour thread = Arrays.stream(players).anyMatch(e -> e instanceof OnlinePlayer) ?
|
||||
new OnlineThreadBehaviour(game) : new LocalThreadBehaviour(game);
|
||||
|
||||
super(new ReversiBitCanvas(), game, thread, "Reversi");
|
||||
}
|
||||
|
||||
public BitboardReversi.Score getScore() {
|
||||
return game.getScore();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,21 +3,21 @@ package org.toop.app.gameControllers;
|
||||
import org.toop.app.canvas.TicTacToeBitCanvas;
|
||||
import org.toop.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;
|
||||
import org.toop.framework.game.gameThreads.LocalThreadBehaviour;
|
||||
import org.toop.framework.game.gameThreads.OnlineThreadBehaviour;
|
||||
import org.toop.framework.game.games.tictactoe.BitboardTicTacToe;
|
||||
import org.toop.framework.game.players.OnlinePlayer;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class TicTacToeBitController extends GenericGameController {
|
||||
public TicTacToeBitController(Player[] players) {
|
||||
BitboardTicTacToe game = new BitboardTicTacToe();
|
||||
game.init(players);
|
||||
|
||||
ThreadBehaviour thread = Arrays.stream(players).anyMatch(e -> e instanceof OnlinePlayer) ?
|
||||
new OnlineThreadBehaviour(game) : new LocalThreadBehaviour(game);
|
||||
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,7 +64,7 @@ public final class Primitive {
|
||||
return imageView;
|
||||
}
|
||||
|
||||
public static Button button(String key, Runnable onAction, boolean localize) {
|
||||
public static Button button(String key, Runnable onAction, boolean localize, boolean disableOnClick) {
|
||||
var button = new Button();
|
||||
button.getStyleClass().add("button");
|
||||
|
||||
@@ -75,6 +75,7 @@ public final class Primitive {
|
||||
|
||||
if (onAction != null) {
|
||||
button.setOnAction(_ -> {
|
||||
if (disableOnClick) button.setDisable(true);
|
||||
onAction.run();
|
||||
playButtonSound();
|
||||
});
|
||||
@@ -83,8 +84,8 @@ public final class Primitive {
|
||||
return button;
|
||||
}
|
||||
|
||||
public static Button button(String key, Runnable onAction) {
|
||||
return button(key, onAction, true);
|
||||
public static Button button(String key, Runnable onAction, boolean disableOnClick) {
|
||||
return button(key, onAction, true, disableOnClick);
|
||||
}
|
||||
|
||||
public static TextField input(String promptKey, String text, Consumer<String> onValueChanged, boolean localize) {
|
||||
|
||||
@@ -26,7 +26,7 @@ public class ConfirmWidget implements Widget {
|
||||
|
||||
public void addButton(String key, Runnable onClick) {
|
||||
Platform.runLater(() -> {
|
||||
var button = Primitive.button(key, onClick);
|
||||
var button = Primitive.button(key, onClick, false);
|
||||
buttonsContainer.getChildren().add(button);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -91,7 +91,7 @@ public class PlayerInfoWidget {
|
||||
information.computerDifficulty = depth;
|
||||
information.computerThinkTime = thinktime;
|
||||
this.playerName.setText(getName(name));
|
||||
});
|
||||
}, false);
|
||||
}
|
||||
|
||||
private String getName(String name) {
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
package org.toop.app.widget.complex;
|
||||
|
||||
import javafx.collections.FXCollections;
|
||||
import javafx.collections.ObservableList;
|
||||
import javafx.geometry.Pos;
|
||||
import javafx.scene.control.TableColumn;
|
||||
import javafx.scene.control.TableView;
|
||||
import javafx.scene.control.cell.PropertyValueFactory;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class TableWidget<DATATYPE> extends PopupWidget {
|
||||
private ObservableList<DATATYPE> serverList = FXCollections.observableArrayList();
|
||||
private TableView<DATATYPE> table = new TableView<>();
|
||||
|
||||
|
||||
public TableWidget(String... columns) {
|
||||
var cols = new ArrayList<TableColumn<DATATYPE, String>>();
|
||||
|
||||
for (String column : columns) {
|
||||
TableColumn<DATATYPE, String> col = new TableColumn<>(column.toUpperCase());
|
||||
col.setCellValueFactory(new PropertyValueFactory<>(column));
|
||||
cols.add(col);
|
||||
}
|
||||
|
||||
table.getColumns().addAll(cols);
|
||||
update();
|
||||
onColumnClicked();
|
||||
|
||||
add(Pos.CENTER, table);
|
||||
}
|
||||
|
||||
public void add(DATATYPE serverFound) {
|
||||
serverList.add(serverFound);
|
||||
update();
|
||||
}
|
||||
|
||||
public void add(List<DATATYPE> serverFound) {
|
||||
serverList.addAll(serverFound);
|
||||
}
|
||||
|
||||
public void remove(DATATYPE serverFound) {
|
||||
serverList.remove(serverFound);
|
||||
update();
|
||||
}
|
||||
|
||||
public void onColumnClicked() {
|
||||
table.setOnMouseClicked(event -> {
|
||||
DATATYPE selected = table.getSelectionModel().getSelectedItem();
|
||||
if (selected == null) return;
|
||||
IO.println(selected.toString());
|
||||
});
|
||||
}
|
||||
|
||||
private void update() {
|
||||
table.setItems(serverList);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -32,7 +32,7 @@ public abstract class ViewWidget extends StackWidget {
|
||||
|
||||
var backButton = Primitive.button("back", () -> {
|
||||
view.transitionPrevious();
|
||||
});
|
||||
}, false);
|
||||
|
||||
view.add(Pos.BOTTOM_LEFT, Primitive.vbox(backButton));
|
||||
}
|
||||
@@ -45,7 +45,7 @@ public abstract class ViewWidget extends StackWidget {
|
||||
var customButton = Primitive.button(key, () -> {
|
||||
runnable.run();
|
||||
view.transitionPrevious();
|
||||
});
|
||||
}, false);
|
||||
|
||||
view.add(Pos.BOTTOM_LEFT, Primitive.vbox(customButton));
|
||||
}
|
||||
@@ -97,7 +97,7 @@ public abstract class ViewWidget extends StackWidget {
|
||||
|
||||
var backButton = Primitive.button("back", () -> {
|
||||
view.transitionPrevious();
|
||||
});
|
||||
}, false);
|
||||
|
||||
view.add(Pos.BOTTOM_LEFT, Primitive.vbox(backButton));
|
||||
}
|
||||
|
||||
@@ -37,8 +37,8 @@ public final class ChallengePopup extends PopupWidget {
|
||||
var acceptButton = Primitive.button("accept", () -> {
|
||||
onAccept.accept(playerInformation);
|
||||
this.hide();
|
||||
});
|
||||
var denyButton = Primitive.button("deny", () -> hide());
|
||||
}, false);
|
||||
var denyButton = Primitive.button("deny", () -> hide(), false);
|
||||
|
||||
var leftSection = Primitive.vbox(
|
||||
challengeText,
|
||||
|
||||
@@ -18,13 +18,13 @@ public class EscapePopup extends PopupWidget {
|
||||
ViewWidget currentView = WidgetContainer.getCurrentView();
|
||||
ArrayList<Node> nodes = new ArrayList<>();
|
||||
|
||||
nodes.add(Primitive.button("Continue", this::hide, false)); // TODO, localize
|
||||
nodes.add(Primitive.button("Continue", this::hide, false, false)); // TODO, localize
|
||||
|
||||
if (!(currentView.getClass().isAssignableFrom(OptionsView.class))) {
|
||||
var opt = Primitive.button("options", () -> {
|
||||
hide();
|
||||
WidgetContainer.getCurrentView().transitionNext(new OptionsView());
|
||||
});
|
||||
}, false);
|
||||
nodes.add(opt);
|
||||
}
|
||||
|
||||
@@ -33,14 +33,14 @@ public class EscapePopup extends PopupWidget {
|
||||
if (tut != null) {
|
||||
nodes.add(Primitive.button("tutorialstring", () -> {
|
||||
WidgetContainer.getCurrentView().add(Pos.CENTER, tut);
|
||||
}));
|
||||
}, false));
|
||||
}
|
||||
}
|
||||
|
||||
nodes.add(Primitive.button("quit", () -> {
|
||||
hide();
|
||||
WidgetContainer.add(Pos.CENTER, new QuitPopup());
|
||||
}));
|
||||
}, false));
|
||||
|
||||
add(Pos.CENTER, Primitive.vbox(nodes.toArray(new Node[0])));
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import org.toop.app.widget.complex.ConfirmWidget;
|
||||
import org.toop.app.widget.complex.PopupWidget;
|
||||
|
||||
import javafx.geometry.Pos;
|
||||
import org.toop.framework.game.games.reversi.BitboardReversi;
|
||||
|
||||
public final class GameOverPopup extends PopupWidget {
|
||||
public GameOverPopup(boolean winOrTie, String winner) {
|
||||
@@ -15,7 +16,6 @@ public final class GameOverPopup extends PopupWidget {
|
||||
else{
|
||||
confirmWidget.setMessage("It was a tie!");
|
||||
}
|
||||
|
||||
confirmWidget.addButton("ok", this::hide);
|
||||
|
||||
add(Pos.CENTER, confirmWidget);
|
||||
|
||||
@@ -62,9 +62,9 @@ public final class SendChallengePopup extends PopupWidget {
|
||||
var sendButton = Primitive.button(
|
||||
"send",
|
||||
() -> { onSend.accept(playerInformation, gameChoice.getValue()); this.hide(); }
|
||||
);
|
||||
, false);
|
||||
|
||||
var cancelButton = Primitive.button("cancel", () -> hide());
|
||||
var cancelButton = Primitive.button("cancel", () -> hide(), false);
|
||||
|
||||
var leftSection = Primitive.vbox(
|
||||
challengeText,
|
||||
|
||||
@@ -47,8 +47,8 @@ public class BaseTutorialWidget extends PopupWidget implements Updatable {
|
||||
this.pages = pages;
|
||||
this.nextScreen = nextScreen;
|
||||
|
||||
previousButton = Primitive.button("goback", () -> { update(false); this.hide(); });
|
||||
nextButton = Primitive.button(">", () -> update(true));
|
||||
previousButton = Primitive.button("goback", () -> { update(false); this.hide(); }, false);
|
||||
nextButton = Primitive.button(">", () -> update(true), false);
|
||||
|
||||
var w = Primitive.hbox(
|
||||
previousButton,
|
||||
|
||||
@@ -10,9 +10,9 @@ public class ShowEnableTutorialWidget extends PopupWidget {
|
||||
|
||||
public ShowEnableTutorialWidget(Runnable tutorial, Runnable nextScreen, Runnable appSettingsSetter) {
|
||||
var a = Primitive.hbox(
|
||||
Primitive.button("ok", () -> { appSettingsSetter.run(); tutorial.run(); this.hide(); }),
|
||||
Primitive.button("no", () -> { appSettingsSetter.run(); nextScreen.run(); this.hide(); }),
|
||||
Primitive.button("never", () -> { AppSettings.getSettings().setTutorialFlag(false); nextScreen.run(); this.hide(); })
|
||||
Primitive.button("ok", () -> { appSettingsSetter.run(); tutorial.run(); this.hide(); }, false),
|
||||
Primitive.button("no", () -> { appSettingsSetter.run(); nextScreen.run(); this.hide(); }, false),
|
||||
Primitive.button("never", () -> { AppSettings.getSettings().setTutorialFlag(false); nextScreen.run(); this.hide(); }, false)
|
||||
);
|
||||
|
||||
var txt = Primitive.text("tutorial");
|
||||
|
||||
@@ -6,6 +6,8 @@ import javafx.scene.text.Font;
|
||||
import org.toop.app.widget.Primitive;
|
||||
import org.toop.app.widget.complex.ViewWidget;
|
||||
import org.toop.app.widget.popup.GameOverPopup;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.function.Consumer;
|
||||
import javafx.application.Platform;
|
||||
import javafx.geometry.Pos;
|
||||
@@ -16,15 +18,16 @@ import org.toop.app.widget.tutorial.Connect4TutorialWidget;
|
||||
import org.toop.app.widget.tutorial.ReversiTutorialWidget;
|
||||
import org.toop.app.widget.tutorial.TicTacToeTutorialWidget;
|
||||
import org.toop.local.AppContext;
|
||||
import org.toop.local.AppSettings;
|
||||
|
||||
public final class GameView extends ViewWidget {
|
||||
private final Text playerHeader;
|
||||
private final Text turnHeader;
|
||||
private final Text player1Header;
|
||||
private final Text player2Header;
|
||||
private final Circle player1Icon;
|
||||
private final Circle player2Icon;
|
||||
private Circle player1Icon;
|
||||
private Circle player2Icon;
|
||||
private final Text player1Score;
|
||||
private final Text player2Score;
|
||||
private final Button forfeitButton;
|
||||
private final Button exitButton;
|
||||
private final TextField chatInput;
|
||||
@@ -39,9 +42,11 @@ public final class GameView extends ViewWidget {
|
||||
player2Header = Primitive.header("");
|
||||
player1Icon = new Circle();
|
||||
player2Icon = new Circle();
|
||||
player1Score = Primitive.header("");
|
||||
player2Score = Primitive.header("");
|
||||
|
||||
if (onForfeit != null) {
|
||||
forfeitButton = Primitive.button("forfeit", () -> onForfeit.run());
|
||||
forfeitButton = Primitive.button("forfeit", () -> onForfeit.run(), false);
|
||||
} else {
|
||||
forfeitButton = null;
|
||||
}
|
||||
@@ -49,7 +54,7 @@ public final class GameView extends ViewWidget {
|
||||
exitButton = Primitive.button("exit", () -> {
|
||||
onExit.run();
|
||||
transitionPrevious();
|
||||
});
|
||||
}, false);
|
||||
|
||||
if (onMessage != null) {
|
||||
chatInput = Primitive.input("enter-your-message", "", null);
|
||||
@@ -95,7 +100,7 @@ public final class GameView extends ViewWidget {
|
||||
}
|
||||
}
|
||||
|
||||
public void updatePlayerInfo(boolean isMe, String currentPlayer, String currentMove, String nextPlayer, String GameType) {
|
||||
public void nextPlayer(boolean isMe, String currentPlayer, String nextPlayer, String GameType) {
|
||||
Platform.runLater(() -> {
|
||||
if (!(hasSet)) {
|
||||
playerHeader.setText(currentPlayer + " vs. " + nextPlayer);
|
||||
@@ -114,7 +119,7 @@ public final class GameView extends ViewWidget {
|
||||
}
|
||||
|
||||
private void setPlayerHeaders(boolean isMe, String currentPlayer, String nextPlayer, String GameType) {
|
||||
if (GameType.equals("TicTacToe")) {
|
||||
if (Objects.equals(GameType, "TicTacToe")) {
|
||||
if (isMe) {
|
||||
player1Header.setText("X: " + currentPlayer);
|
||||
player2Header.setText("O: " + nextPlayer);
|
||||
@@ -125,16 +130,15 @@ public final class GameView extends ViewWidget {
|
||||
}
|
||||
setPlayerInfoTTT();
|
||||
}
|
||||
else if (GameType.equals("Reversi")) {
|
||||
boolean swap = AppSettings.getSettings().getSwitchReversi();
|
||||
if (!swap) {
|
||||
player1Header.setText(nextPlayer);
|
||||
player2Header.setText(currentPlayer);
|
||||
}
|
||||
else {
|
||||
else if (Objects.equals(GameType, "Reversi")) {
|
||||
if (isMe) {
|
||||
player1Header.setText(currentPlayer);
|
||||
player2Header.setText(nextPlayer);
|
||||
}
|
||||
else {
|
||||
player1Header.setText(nextPlayer);
|
||||
player2Header.setText(currentPlayer);
|
||||
}
|
||||
setPlayerInfoReversi();
|
||||
}
|
||||
}
|
||||
@@ -153,14 +157,16 @@ public final class GameView extends ViewWidget {
|
||||
private void setPlayerInfoReversi() {
|
||||
var player1box = Primitive.hbox(
|
||||
player1Icon,
|
||||
player1Header
|
||||
player1Header,
|
||||
player1Score
|
||||
);
|
||||
|
||||
player1box.getStyleClass().add("hboxspacing");
|
||||
|
||||
var player2box = Primitive.hbox(
|
||||
player2Icon,
|
||||
player2Header
|
||||
player2Header,
|
||||
player2Score
|
||||
);
|
||||
|
||||
player2box.getStyleClass().add("hboxspacing");
|
||||
@@ -168,14 +174,22 @@ public final class GameView extends ViewWidget {
|
||||
var playerInfo = Primitive.vbox(
|
||||
playerHeader,
|
||||
Primitive.separator(),
|
||||
player2box,
|
||||
player1box
|
||||
player1box,
|
||||
player2box
|
||||
);
|
||||
|
||||
player1Icon.setRadius(player1Header.fontProperty().map(Font::getSize).getValue());
|
||||
player2Icon.setRadius(player2Header.fontProperty().map(Font::getSize).getValue());
|
||||
player1Icon.setFill(Color.BLACK);
|
||||
player2Icon.setFill(Color.WHITE);
|
||||
player1Icon.setFill(Color.WHITE);
|
||||
player2Icon.setFill(Color.BLACK);
|
||||
add(Pos.TOP_RIGHT, playerInfo);
|
||||
}
|
||||
|
||||
public void setPlayer1Score(int score) {
|
||||
player1Score.setText("(" + Integer.toString(score) + ")");
|
||||
}
|
||||
|
||||
public void setPlayer2Score(int score) {
|
||||
player2Score.setText("(" + Integer.toString(score) + ")");
|
||||
}
|
||||
}
|
||||
@@ -4,19 +4,19 @@ import javafx.application.Platform;
|
||||
import org.toop.app.GameInformation;
|
||||
import org.toop.app.gameControllers.ReversiBitController;
|
||||
import org.toop.app.gameControllers.TicTacToeBitController;
|
||||
import org.toop.framework.game.players.LocalPlayer;
|
||||
import org.toop.framework.gameFramework.controller.GameController;
|
||||
import org.toop.framework.gameFramework.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.framework.game.players.ArtificialPlayer;
|
||||
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.app.widget.tutorial.*;
|
||||
import org.toop.game.players.ai.MiniMaxAI;
|
||||
import org.toop.game.players.ai.RandomAI;
|
||||
import org.toop.game.players.ai.mcts.MCTSAI1;
|
||||
import org.toop.game.players.ai.mcts.MCTSAI3;
|
||||
import org.toop.game.players.ai.mcts.MCTSAI4;
|
||||
import org.toop.local.AppContext;
|
||||
|
||||
import javafx.geometry.Pos;
|
||||
@@ -52,14 +52,14 @@ public class LocalMultiplayerView extends ViewWidget {
|
||||
switch (information.type) {
|
||||
case TICTACTOE:
|
||||
if (information.players[0].isHuman) {
|
||||
players[0] = new LocalPlayer<>(information.players[0].name);
|
||||
players[0] = new LocalPlayer(information.players[0].name);
|
||||
} else {
|
||||
players[0] = new ArtificialPlayer<>(new RandomAI<BitboardTicTacToe>(), "Random AI");
|
||||
players[0] = new ArtificialPlayer(new MCTSAI1(100), "MCTS AI");
|
||||
}
|
||||
if (information.players[1].isHuman) {
|
||||
players[1] = new LocalPlayer<>(information.players[1].name);
|
||||
players[1] = new LocalPlayer(information.players[1].name);
|
||||
} else {
|
||||
players[1] = new ArtificialPlayer<>(new MiniMaxAI<BitboardTicTacToe>(9), "MiniMax AI");
|
||||
players[1] = new ArtificialPlayer(new MiniMaxAI(9), "MiniMax AI");
|
||||
}
|
||||
if (AppSettings.getSettings().getTutorialFlag() && AppSettings.getSettings().getFirstTTT()) {
|
||||
new ShowEnableTutorialWidget(
|
||||
@@ -79,36 +79,36 @@ public class LocalMultiplayerView extends ViewWidget {
|
||||
}
|
||||
break;
|
||||
case REVERSI:
|
||||
boolean swap = AppSettings.getSettings().getSwitchReversi();
|
||||
if (information.players[0].isHuman) {
|
||||
players[0] = new LocalPlayer<>(information.players[0].name);
|
||||
players[0] = new LocalPlayer(information.players[0].name);
|
||||
} else {
|
||||
players[0] = new ArtificialPlayer<>(new RandomAI<BitboardReversi>(), "Random AI");
|
||||
// players[0] = new ArtificialPlayer(new RandomAI(), "Random AI");
|
||||
players[0] = new ArtificialPlayer(new MCTSAI1(100), "MCTS V1 AI");
|
||||
}
|
||||
if (information.players[1].isHuman) {
|
||||
players[1] = new LocalPlayer<>(information.players[1].name);
|
||||
players[1] = new LocalPlayer(information.players[1].name);
|
||||
} else {
|
||||
players[1] = new ArtificialPlayer<>(new MiniMaxAI<BitboardReversi>(6), "MiniMax");
|
||||
players[1] = new ArtificialPlayer(new MCTSAI4(100, 8), "MCTS V4 AI");
|
||||
}
|
||||
if (AppSettings.getSettings().getTutorialFlag() && AppSettings.getSettings().getFirstReversi()) {
|
||||
new ShowEnableTutorialWidget(
|
||||
() -> new ReversiTutorialWidget(() -> {
|
||||
gameController = new ReversiBitController(players, swap);
|
||||
gameController = new ReversiBitController(players);
|
||||
gameController.start();
|
||||
}),
|
||||
() -> Platform.runLater(() -> {
|
||||
gameController = new ReversiBitController(players, swap);
|
||||
gameController = new ReversiBitController(players);
|
||||
gameController.start();
|
||||
}),
|
||||
() -> AppSettings.getSettings().setFirstReversi(false)
|
||||
);
|
||||
} else {
|
||||
gameController = new ReversiBitController(players, swap);
|
||||
gameController = new ReversiBitController(players);
|
||||
gameController.start();
|
||||
}
|
||||
break;
|
||||
}
|
||||
});
|
||||
}, false);
|
||||
|
||||
var playerSection = setupPlayerSections();
|
||||
|
||||
|
||||
@@ -10,11 +10,11 @@ public class LocalView extends ViewWidget {
|
||||
public LocalView() {
|
||||
var ticTacToeButton = Primitive.button("tic-tac-toe", () -> {
|
||||
transitionNext(new LocalMultiplayerView(GameInformation.Type.TICTACTOE));
|
||||
});
|
||||
}, false);
|
||||
|
||||
var reversiButton = Primitive.button("reversi", () -> {
|
||||
transitionNext(new LocalMultiplayerView(GameInformation.Type.REVERSI));
|
||||
});
|
||||
}, false);
|
||||
|
||||
add(Pos.CENTER, Primitive.vbox(
|
||||
ticTacToeButton,
|
||||
|
||||
@@ -9,24 +9,24 @@ public class MainView extends ViewWidget {
|
||||
public MainView() {
|
||||
var localButton = Primitive.button("local", () -> {
|
||||
transitionNext(new LocalView());
|
||||
});
|
||||
}, false);
|
||||
|
||||
var onlineButton = Primitive.button("online", () -> {
|
||||
transitionNext(new OnlineView());
|
||||
});
|
||||
}, false);
|
||||
|
||||
var creditsButton = Primitive.button("credits", () -> {
|
||||
transitionNext(new CreditsView());
|
||||
});
|
||||
}, false);
|
||||
|
||||
var optionsButton = Primitive.button("options", () -> {
|
||||
transitionNext(new OptionsView());
|
||||
});
|
||||
}, false);
|
||||
|
||||
var quitButton = Primitive.button("quit", () -> {
|
||||
var a = new QuitPopup();
|
||||
a.show(Pos.CENTER);
|
||||
});
|
||||
}, false);
|
||||
|
||||
add(Pos.CENTER, Primitive.vbox(
|
||||
localButton,
|
||||
|
||||
@@ -6,6 +6,14 @@ import org.toop.app.widget.complex.LabeledInputWidget;
|
||||
import org.toop.app.widget.complex.ViewWidget;
|
||||
|
||||
import javafx.geometry.Pos;
|
||||
import org.toop.framework.game.games.reversi.BitboardReversi;
|
||||
import org.toop.framework.game.games.tictactoe.BitboardTicTacToe;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
import org.toop.framework.networking.server.gateway.NettyGatewayServer;
|
||||
import org.toop.framework.networking.server.stores.TurnBasedGameTypeStore;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public class OnlineView extends ViewWidget {
|
||||
public OnlineView() {
|
||||
@@ -21,7 +29,31 @@ public class OnlineView extends ViewWidget {
|
||||
serverPortInput.getValue(),
|
||||
playerNameInput.getValue()
|
||||
);
|
||||
});
|
||||
}, false);
|
||||
|
||||
var localHostButton = Primitive.button("host!", () -> {
|
||||
|
||||
var tps = new TurnBasedGameTypeStore();
|
||||
tps.register("tic-tac-toe", BitboardTicTacToe::new);
|
||||
tps.register("reversi", BitboardReversi::new);
|
||||
|
||||
var a = new NettyGatewayServer(6666, tps, Duration.ofSeconds(10));
|
||||
|
||||
new Thread(() -> {
|
||||
try {
|
||||
a.start();
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}).start();
|
||||
|
||||
new Server(
|
||||
"127.0.0.1",
|
||||
"6666",
|
||||
"host",
|
||||
a
|
||||
);
|
||||
}, false, false);
|
||||
|
||||
add(Pos.CENTER, Primitive.vbox(
|
||||
serverInformationHeader,
|
||||
@@ -32,7 +64,9 @@ public class OnlineView extends ViewWidget {
|
||||
playerNameInput.getNode(),
|
||||
Primitive.separator(),
|
||||
|
||||
connectButton
|
||||
connectButton,
|
||||
Primitive.separator(),
|
||||
localHostButton
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -149,22 +149,13 @@ 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(),
|
||||
Primitive.text("reversiswap"),
|
||||
swapReversiColors.getNode()
|
||||
layoutWidget.getNode()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,57 +1,115 @@
|
||||
package org.toop.app.widget.view;
|
||||
|
||||
import javafx.collections.FXCollections;
|
||||
import javafx.css.converter.StringConverter;
|
||||
import javafx.scene.control.ComboBox;
|
||||
import org.toop.app.widget.Primitive;
|
||||
import org.toop.app.widget.complex.ViewWidget;
|
||||
|
||||
import java.io.Reader;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import javafx.application.Platform;
|
||||
import javafx.geometry.Pos;
|
||||
import javafx.scene.control.Button;
|
||||
import javafx.scene.control.ListView;
|
||||
import org.toop.framework.eventbus.EventFlow;
|
||||
import org.toop.framework.eventbus.GlobalEventBus;
|
||||
import org.toop.framework.networking.connection.events.NetworkEvents;
|
||||
|
||||
public final class ServerView extends ViewWidget {
|
||||
private final String user;
|
||||
private final Consumer<String> onPlayerClicked;
|
||||
private final long clientId;
|
||||
|
||||
private final ComboBox<String> gameListSub;
|
||||
private final ComboBox<String> gameListTour;
|
||||
private final ListView<Button> listView;
|
||||
private Button subscribeButton;
|
||||
|
||||
public ServerView(String user, Consumer<String> onPlayerClicked) {
|
||||
public ServerView(String user, Consumer<String> onPlayerClicked, String userName, long clientId) {
|
||||
this.user = user;
|
||||
this.onPlayerClicked = onPlayerClicked;
|
||||
this.clientId = clientId;
|
||||
|
||||
this.gameListSub = new ComboBox<>();
|
||||
this.gameListTour = new ComboBox<>();
|
||||
this.listView = new ListView<>();
|
||||
|
||||
setupLayout();
|
||||
setupLayout(userName);
|
||||
}
|
||||
|
||||
private void setupLayout() {
|
||||
private void setupLayout(String userName) {
|
||||
var playerHeader = Primitive.header(user, false);
|
||||
|
||||
if (userName.equals("host")) { // TODO is fragile
|
||||
var tournamentButton = Primitive.hbox(
|
||||
gameListTour,
|
||||
Primitive.button(
|
||||
"tournament",
|
||||
() -> GlobalEventBus.get().post(new NetworkEvents.SendCommand(clientId, "tournament", "start", gameListTour.getValue())),
|
||||
false,
|
||||
false
|
||||
)
|
||||
);
|
||||
|
||||
add(Pos.BOTTOM_CENTER, tournamentButton);
|
||||
} else {
|
||||
subscribeButton = Primitive.button(
|
||||
"subscribe",
|
||||
() -> new EventFlow().addPostEvent(new NetworkEvents.SendSubscribe(clientId, gameListSub.getValue())).postEvent(),
|
||||
false,
|
||||
true
|
||||
); // TODO localize
|
||||
|
||||
var subscribe = Primitive.hbox(gameListSub, subscribeButton);
|
||||
|
||||
var playerListSection = Primitive.vbox(
|
||||
playerHeader,
|
||||
Primitive.separator(),
|
||||
subscribe,
|
||||
listView
|
||||
);
|
||||
|
||||
add(Pos.CENTER, playerListSection);
|
||||
|
||||
var disconnectButton = Primitive.button("disconnect", () -> {
|
||||
transitionPrevious();
|
||||
});
|
||||
var disconnectButton = Primitive.button(
|
||||
"disconnect",
|
||||
this::transitionPrevious,
|
||||
false
|
||||
);
|
||||
|
||||
add(Pos.BOTTOM_LEFT, Primitive.vbox(disconnectButton));
|
||||
}
|
||||
}
|
||||
|
||||
public void update(List<String> players) {
|
||||
Platform.runLater(() -> {
|
||||
listView.getItems().clear();
|
||||
|
||||
for (String player : players) {
|
||||
var playerButton = Primitive.button(player, () -> onPlayerClicked.accept(player), false);
|
||||
var playerButton = Primitive.button(player, () -> onPlayerClicked.accept(player), false, false);
|
||||
listView.getItems().add(playerButton);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void updateGameList(List<String> games) {
|
||||
Platform.runLater(() -> {
|
||||
gameListSub.getItems().clear();
|
||||
gameListSub.setItems(FXCollections.observableArrayList(games));
|
||||
gameListSub.getSelectionModel().select(0);
|
||||
|
||||
gameListTour.getItems().clear();
|
||||
gameListTour.setItems(FXCollections.observableArrayList(games));
|
||||
gameListTour.getSelectionModel().select(0);
|
||||
});
|
||||
}
|
||||
|
||||
public void reEnableButton() {
|
||||
subscribeButton.setDisable(false);
|
||||
}
|
||||
}
|
||||
@@ -5,16 +5,18 @@ 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 = getSettingsAsset();
|
||||
settingsAsset = getPath();
|
||||
if (!settingsAsset.isLoaded()) {
|
||||
settingsAsset.load();
|
||||
}
|
||||
@@ -43,9 +45,26 @@ public class AppSettings {
|
||||
.postEvent();
|
||||
}
|
||||
|
||||
public static SettingsAsset getSettingsAsset() {
|
||||
public static SettingsAsset getPath() {
|
||||
if (settingsAsset == null) {
|
||||
settingsAsset = SettingsAsset.getPath();
|
||||
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)));
|
||||
}
|
||||
return ResourceManager.get("settings.json");
|
||||
}
|
||||
@@ -91,6 +110,5 @@ public class AppSettings {
|
||||
settingsAsset.setMusicVolume(15);
|
||||
settingsAsset.setTutorialFlag(true);
|
||||
settingsAsset.setLayoutSize("medium");
|
||||
settingsAsset.setSwitchReversi(false);
|
||||
}
|
||||
}
|
||||
@@ -89,9 +89,6 @@ turnof=\u062F\u0648\u0631\u0647
|
||||
zwartepiet=\u0633\u0647\u0644: Zwarte Piet
|
||||
sinterklaas=\u0645\u062a\u0648\u0633\u0637: Sint R. Klaas
|
||||
santa=\u0635\u0639\u0628: Santa
|
||||
reversiswapped=\u0645\u0628\u062F\u0651\u064E\u0644
|
||||
reversinotswapped=\u063A\u064A\u0631\u0020\u0645\u0628\u062F\u0651\u064E\u0644
|
||||
reversiswap=\u0647\u0644\u0020\u062A\u0631\u064A\u062F\u0020\u062A\u0628\u062F\u064A\u0644\u0020\u0623\u0644\u0648\u0627\u0646\u0020\u0627\u0644\u0631\u064A\u0641\u064E\u0631\u0633\u064A\u061F\u0020\u0645\u062D\u0644\u064A\u0020\u0641\u0642\u0637\u002E
|
||||
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629
|
||||
|
||||
@@ -91,9 +91,6 @@ turnof=ist dran
|
||||
zwartepiet=Leicht: Zwarte Piet
|
||||
sinterklaas=Mittel: Sint R. Klaas
|
||||
santa=Schwer: Santa
|
||||
reversiswapped=Getauscht
|
||||
reversinotswapped=Nicht getauscht
|
||||
reversiswap=M\u00F6chten Sie die Reversi-Farben tauschen? Nur lokal.
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (Arabisch)
|
||||
chinese=\u4e2d\u6587 (Chinesisch)
|
||||
|
||||
@@ -93,9 +93,6 @@ turnof='s turn
|
||||
zwartepiet=Easy: Zwarte Piet
|
||||
sinterklaas=Medium: Sint R. Klaas
|
||||
santa=Hard:Santa
|
||||
reversiswapped=Swapped
|
||||
reversinotswapped=Not Swapped
|
||||
reversiswap=Do you want to swap the Reversi colors? Local only.
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (Arabic)
|
||||
chinese=\u4e2d\u6587 (Chinese)
|
||||
|
||||
@@ -90,9 +90,6 @@ turnof=le toca
|
||||
zwartepiet=F\u00e1cil: Zwarte Piet
|
||||
sinterklaas=Medio: Sint R. Klaas
|
||||
santa=Dif\u00edcil: Santa
|
||||
reversiswapped=Cambiado
|
||||
reversinotswapped=No cambiado
|
||||
reversiswap=\u00BFDeseas intercambiar los colores de Reversi? Solo local.
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (Ar\u00e1bigo)
|
||||
chinese=\u4e2d\u6587 (Chino)
|
||||
|
||||
@@ -90,9 +90,6 @@ turnof=\u00E0 son tour
|
||||
zwartepiet=Facile: Zwarte Piet
|
||||
sinterklaas=Moyen : Sint R. Klaas
|
||||
santa=Difficile: Santa
|
||||
reversiswapped=\u00C9chang\u00E9
|
||||
reversinotswapped=Non \u00E9chang\u00E9
|
||||
reversiswap=Voulez-vous \u00E9changer les couleurs de Reversi ? Local uniquement.
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (Arabe)
|
||||
chinese=\u4e2d\u6587 (Chinois)
|
||||
|
||||
@@ -90,9 +90,6 @@ turnof=\u0915\u0940 \u092C\u093E\u0930\u0940
|
||||
zwartepiet=\u0905\u0938\u093e\u0928: Zwarte Piet
|
||||
sinterklaas=\u092e\u0927\u094d\u092f\u092e: Sint R. Klaas
|
||||
santa=\u0915\u0924\u093f\u0928: Santa
|
||||
reversiswapped=\u092C\u0926\u0932\u093E\u0020\u0939\u0941\u0906
|
||||
reversinotswapped=\u0928\u0939\u0940\u0902\u0020\u092C\u0926\u0932\u093E\u0020\u0939\u0941\u0906
|
||||
reversiswap=\u0915\u094D\u092F\u093E\u0020\u0906\u092A\u0020\u0930\u093F\u0935\u0930\u094D\u0938\u0940\u0020\u0915\u0947\u0020\u0930\u0902\u0917\u0020\u092C\u0926\u0932\u0928\u093E\u0020\u091A\u093E\u0939\u0924\u0947\u0020\u0939\u0948\u0902?\u0020\u0915\u0947\u0935\u0932\u0020\u0938\u094D\u0925\u093E\u0928\u0940\u092F\u002E
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (\u0905\u0930\u092c\u0940)
|
||||
chinese=\u4e2d\u6587 (\u091a\u0940\u0928\u0940)
|
||||
|
||||
@@ -89,9 +89,6 @@ turnof=\u00E8 il suo turno
|
||||
zwartepiet=Facile: Zwarte Piet
|
||||
sinterklaas=Medio: Sint R. Klaas
|
||||
santa=Difficile: Santa
|
||||
reversiswapped=Scambiato
|
||||
reversinotswapped=Non scambiato
|
||||
reversiswap=Vuoi scambiare i colori di Reversi? Solo locale.
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (Arabo)
|
||||
chinese=\u4e2d\u6587 (Cinese)
|
||||
|
||||
@@ -89,10 +89,6 @@ turnof=\u306E\u756A
|
||||
zwartepiet=\u7c21\u5358: Zwarte Piet
|
||||
sinterklaas=\u4e2d\u7d1a: Sint R. Klaas
|
||||
santa=\u96e3\u3057\u3044: Santa
|
||||
reversiswapped=\u5165\u308C\u66FF\u3048\u6E08\u307F
|
||||
reversinotswapped=\u672A\u5165\u308C\u66FF\u3048
|
||||
reversiswap=\u30EA\u30D0\u30FC\u30B7\u306E\u8272\u3092\u5165\u308C\u66FF\u3048\u307E\u3059\u304B?\u0020\u30ED\u30FC\u30AB\u30EB\u306E\u307F\u3067\u3059\u002E
|
||||
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (\u30a2\u30e9\u30d3\u30a2\u8a9e)
|
||||
chinese=\u4e2d\u6587 (\u4e2d\u6587)
|
||||
|
||||
@@ -89,9 +89,6 @@ turnof=\uC758 \uCC28\uB840
|
||||
zwartepiet=\uc218\uc601: Zwarte Piet
|
||||
sinterklaas=\ubcf4\ud1b5: Sint R. Klaas
|
||||
santa=\uc5d0\uc18c: Santa
|
||||
reversiswapped=\uAD50\uCCB4\uB428
|
||||
reversinotswapped=\uAD50\uCCB4\uB418\uC9C0 \uC54A\uC74C
|
||||
reversiswap=\uB9AC\uBC84\uC2DC \uC0C9\uC0C1\uC744 \uBC14\uAFB8\uC2DC\uACA0\uC2B5\uB2C8\uAE4C?\u0020\uB85C\uCEEC \uC804\uC6A9\u0020\uC785\uB2C8\uB2E4\u002E
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (\u0639\u0631\u0628\u064a\u0629)
|
||||
chinese=\u4e2d\u6587 (\u4e2d\u6587)
|
||||
|
||||
@@ -89,9 +89,6 @@ turnof=is aan de beurt
|
||||
zwartepiet=Makkelijk: Zwarte Piet
|
||||
sinterklaas=Gemiddeld: Sint R. Klaas
|
||||
santa=Moeilijk: Santa
|
||||
reversiswapped=Gewisseld
|
||||
reversinotswapped=Niet gewisseld
|
||||
reversiswap=Wil je de Reversi-kleuren wisselen? Alleen lokaal.
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (Arabisch)
|
||||
chinese=\u4e2d\u6587 (Chinees)
|
||||
|
||||
@@ -89,9 +89,6 @@ turnof=\u0445\u043E\u0434\u0438\u0442
|
||||
zwartepiet=\u041b\u0435\u0433\u043a\u043e: Zwarte Piet
|
||||
sinterklaas=\u0421\u0440\u0435\u0434\u043d\u0438\u0439: Sint R. Klaas
|
||||
santa=\u0421\u043b\u043e\u0436\u043d\u043e: Santa
|
||||
reversiswapped=\u041F\u043E\u043C\u0435\u043D\u044F\u043D\u043E
|
||||
reversinotswapped=\u041D\u0435 \u043F\u043E\u043C\u0435\u043D\u044F\u043D\u043E
|
||||
reversiswap=\u0425\u043E\u0442\u0438\u0442\u0435 \u043F\u043E\u043C\u0435\u043D\u044F\u0442\u044C \u0446\u0432\u0435\u0442\u0430 \u0420\u0435\u0432\u0435\u0440\u0441\u0438?\u0020\u0422\u043E\u043B\u044C\u043A\u043E \u043B\u043E\u043A\u0430\u043B\u044C\u043D\u043E\u002E
|
||||
|
||||
arabic=\u0627\u0644\u0639\u0631\u0628\u064a\u0629 (\u0410\u0440\u0430\u0431\u0441\u043a\u0438\u0439)
|
||||
chinese=\u4e2d\u6587 (\u041a\u0438\u0442\u0430\u0439\u0441\u043a\u0438\u0439)
|
||||
|
||||
@@ -89,9 +89,6 @@ 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
|
||||
|
||||
@@ -147,7 +147,6 @@
|
||||
<version>2.42.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
|
||||
@@ -415,11 +415,9 @@ public class EventFlow {
|
||||
/**
|
||||
* Posts the event added through {@link #addPostEvent} asynchronously.
|
||||
*
|
||||
* @deprecated use {@link #postEvent()} instead.
|
||||
*/
|
||||
@Deprecated
|
||||
public EventFlow asyncPostEvent() {
|
||||
eventBus.post(this.event);
|
||||
GlobalEventBus.get().post(this.event);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,20 @@
|
||||
package org.toop.framework.eventbus;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.toop.framework.eventbus.bus.AsyncEventBus;
|
||||
import org.toop.framework.eventbus.bus.DefaultEventBus;
|
||||
import org.toop.framework.eventbus.bus.DisruptorEventBus;
|
||||
import org.toop.framework.eventbus.bus.EventBus;
|
||||
import org.toop.framework.eventbus.events.EventType;
|
||||
import org.toop.framework.eventbus.store.DefaultSubscriberStore;
|
||||
import org.toop.framework.eventbus.subscriber.Subscriber;
|
||||
|
||||
public class GlobalEventBus implements EventBus {
|
||||
private static final EventBus INSTANCE = new DisruptorEventBus(
|
||||
LogManager.getLogger(DisruptorEventBus.class),
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
public class GlobalEventBus implements AsyncEventBus {
|
||||
private static final AsyncEventBus INSTANCE = new DefaultEventBus(
|
||||
LogManager.getLogger(DefaultEventBus.class),
|
||||
new DefaultSubscriberStore()
|
||||
);
|
||||
|
||||
@@ -34,6 +39,11 @@ public class GlobalEventBus implements EventBus {
|
||||
INSTANCE.post(event);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T extends EventType> void asyncPost(T event) {
|
||||
INSTANCE.asyncPost(event);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown() {
|
||||
INSTANCE.shutdown();
|
||||
@@ -43,4 +53,5 @@ public class GlobalEventBus implements EventBus {
|
||||
public void reset() {
|
||||
INSTANCE.reset();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
package org.toop.framework.eventbus.bus;
|
||||
|
||||
import org.toop.framework.eventbus.events.EventType;
|
||||
|
||||
public interface AsyncEventBus extends EventBus {
|
||||
<T extends EventType> void asyncPost(T event);
|
||||
}
|
||||
@@ -5,12 +5,16 @@ import org.toop.framework.eventbus.events.EventType;
|
||||
import org.toop.framework.eventbus.store.SubscriberStore;
|
||||
import org.toop.framework.eventbus.subscriber.Subscriber;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class DefaultEventBus implements EventBus {
|
||||
public class DefaultEventBus implements AsyncEventBus {
|
||||
private final Logger logger;
|
||||
private final SubscriberStore eventsHolder;
|
||||
|
||||
private final ExecutorService asyncExecutor = Executors.newCachedThreadPool();
|
||||
|
||||
public DefaultEventBus(Logger logger, SubscriberStore eventsHolder) {
|
||||
this.logger = logger;
|
||||
this.eventsHolder = eventsHolder;
|
||||
@@ -36,11 +40,16 @@ public class DefaultEventBus implements EventBus {
|
||||
Class<T> eventClass = (Class<T>) subscriber.event();
|
||||
Consumer<EventType> action = (Consumer<EventType>) subscriber.handler();
|
||||
|
||||
action.accept((EventType) eventClass.cast(event));
|
||||
action.accept(eventClass.cast(event));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T extends EventType> void asyncPost(T event) {
|
||||
asyncExecutor.submit(() -> post(event));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown() {
|
||||
eventsHolder.reset();
|
||||
@@ -50,4 +59,5 @@ public class DefaultEventBus implements EventBus {
|
||||
public void reset() {
|
||||
eventsHolder.reset();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,40 +1,57 @@
|
||||
package org.toop.game;
|
||||
package org.toop.framework.game;
|
||||
|
||||
import org.toop.framework.gameFramework.GameState;
|
||||
import org.toop.framework.gameFramework.model.game.PlayResult;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
// There is AI performance to be gained by getting rid of non-primitives and thus speeding up deepCopy
|
||||
public abstract class BitboardGame<T extends BitboardGame<T>> implements TurnBasedGame<T> {
|
||||
public abstract class BitboardGame implements TurnBasedGame {
|
||||
private final int columnSize;
|
||||
private final int rowSize;
|
||||
|
||||
private Player<T>[] players;
|
||||
protected PlayResult state;
|
||||
|
||||
private Player[] players;
|
||||
|
||||
// long is 64 bits. Every game has a limit of 64 cells maximum.
|
||||
private final long[] playerBitboard;
|
||||
private int currentTurn = 0;
|
||||
protected final long[] playerBitboard;
|
||||
protected int currentTurn = 0;
|
||||
private final int playerCount;
|
||||
|
||||
public BitboardGame(int columnSize, int rowSize, int playerCount, Player<T>[] players) {
|
||||
public BitboardGame(int columnSize, int rowSize, int playerCount) {
|
||||
this.columnSize = columnSize;
|
||||
this.rowSize = rowSize;
|
||||
this.players = players;
|
||||
this.playerCount = playerCount;
|
||||
this.state = new PlayResult(GameState.NORMAL, -1);
|
||||
|
||||
this.playerBitboard = new long[playerCount];
|
||||
|
||||
Arrays.fill(playerBitboard, 0L);
|
||||
}
|
||||
|
||||
public BitboardGame(BitboardGame<T> other) {
|
||||
@Override
|
||||
public void init(Player[] players) {
|
||||
this.players = players;
|
||||
|
||||
Arrays.fill(playerBitboard, 0L);
|
||||
}
|
||||
|
||||
public BitboardGame(BitboardGame other) {
|
||||
this.columnSize = other.columnSize;
|
||||
this.rowSize = other.rowSize;
|
||||
this.playerCount = other.playerCount;
|
||||
this.state = other.state;
|
||||
|
||||
this.playerBitboard = other.playerBitboard.clone();
|
||||
this.currentTurn = other.currentTurn;
|
||||
this.players = Arrays.stream(other.players)
|
||||
.map(Player<T>::deepCopy)
|
||||
.toArray(Player[]::new);
|
||||
this.players = other.players;
|
||||
// TODO: Players are not deep copied, which is bad. I don't know why but deepcopying breaks it. Fix it
|
||||
//this.players = Arrays.stream(other.players)
|
||||
// .map(Player::deepCopy)
|
||||
// .toArray(Player[]::new);
|
||||
}
|
||||
|
||||
public int getColumnSize() {
|
||||
@@ -57,11 +74,13 @@ public abstract class BitboardGame<T extends BitboardGame<T>> implements TurnBas
|
||||
return playerBitboard.length;
|
||||
}
|
||||
|
||||
public int getAmountOfTurns() { return currentTurn; }
|
||||
|
||||
public int getCurrentTurn() {
|
||||
return getCurrentPlayerIndex();
|
||||
}
|
||||
|
||||
public Player<T> getPlayer(int index) {return players[index];}
|
||||
public Player getPlayer(int index) {return players[index];}
|
||||
|
||||
public int getCurrentPlayerIndex() {
|
||||
return currentTurn % playerBitboard.length;
|
||||
@@ -71,11 +90,19 @@ public abstract class BitboardGame<T extends BitboardGame<T>> implements TurnBas
|
||||
return (currentTurn + 1) % playerBitboard.length;
|
||||
}
|
||||
|
||||
public Player<T> getCurrentPlayer(){
|
||||
public Player getCurrentPlayer(){
|
||||
return players[getCurrentPlayerIndex()];
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlayResult getState() {
|
||||
return state;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isTerminal() {
|
||||
return state.state() == GameState.WIN || state.state() == GameState.DRAW;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long[] getBoard() {return this.playerBitboard;}
|
||||
@@ -1,3 +1,3 @@
|
||||
package org.toop.game;
|
||||
package org.toop.framework.game;
|
||||
// TODO: Remove this, only used in ReversiCanvas. Needs to not
|
||||
public record Move(int position, char value) {}
|
||||
@@ -1,4 +1,4 @@
|
||||
package org.toop.game.gameThreads;
|
||||
package org.toop.framework.game.gameThreads;
|
||||
|
||||
import org.toop.framework.eventbus.EventFlow;
|
||||
import org.toop.framework.gameFramework.GameState;
|
||||
@@ -16,7 +16,7 @@ import java.util.function.Consumer;
|
||||
* Runs a separate thread that executes game turns at a fixed frequency (default 60 updates/sec),
|
||||
* applying player moves, updating the game state, and dispatching UI events.
|
||||
*/
|
||||
public class LocalFixedRateThreadBehaviour<T extends TurnBasedGame<T>> extends AbstractThreadBehaviour<T> implements Runnable {
|
||||
public class LocalFixedRateThreadBehaviour extends AbstractThreadBehaviour implements Runnable {
|
||||
|
||||
|
||||
/**
|
||||
@@ -24,7 +24,7 @@ public class LocalFixedRateThreadBehaviour<T extends TurnBasedGame<T>> extends A
|
||||
*
|
||||
* @param game the game instance
|
||||
*/
|
||||
public LocalFixedRateThreadBehaviour(T game) {
|
||||
public LocalFixedRateThreadBehaviour(TurnBasedGame game) {
|
||||
super(game);
|
||||
}
|
||||
|
||||
@@ -59,7 +59,7 @@ public class LocalFixedRateThreadBehaviour<T extends TurnBasedGame<T>> extends A
|
||||
if (now >= nextUpdate) {
|
||||
nextUpdate += UPDATE_INTERVAL;
|
||||
|
||||
Player<T> currentPlayer = game.getPlayer(game.getCurrentTurn());
|
||||
Player currentPlayer = game.getPlayer(game.getCurrentTurn());
|
||||
long move = currentPlayer.getMove(game.deepCopy());
|
||||
PlayResult result = game.play(move);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package org.toop.game.gameThreads;
|
||||
package org.toop.framework.game.gameThreads;
|
||||
|
||||
import org.toop.framework.eventbus.EventFlow;
|
||||
import org.toop.framework.gameFramework.model.game.threadBehaviour.AbstractThreadBehaviour;
|
||||
@@ -16,14 +16,14 @@ import java.util.function.Consumer;
|
||||
* Repeatedly gets the current player's move, applies it to the game,
|
||||
* updates the UI, and stops when the game ends or {@link #stop()} is called.
|
||||
*/
|
||||
public class LocalThreadBehaviour<T extends TurnBasedGame<T>> extends AbstractThreadBehaviour<T> implements Runnable {
|
||||
public class LocalThreadBehaviour extends AbstractThreadBehaviour implements Runnable {
|
||||
|
||||
/**
|
||||
* Creates a new behaviour for a local turn-based game.
|
||||
*
|
||||
* @param game the game instance
|
||||
*/
|
||||
public LocalThreadBehaviour(T game) {
|
||||
public LocalThreadBehaviour(TurnBasedGame game) {
|
||||
super(game);
|
||||
}
|
||||
|
||||
@@ -48,7 +48,7 @@ public class LocalThreadBehaviour<T extends TurnBasedGame<T>> extends AbstractTh
|
||||
@Override
|
||||
public void run() {
|
||||
while (isRunning.get()) {
|
||||
Player<T> currentPlayer = game.getPlayer(game.getCurrentTurn());
|
||||
Player currentPlayer = game.getPlayer(game.getCurrentTurn());
|
||||
long move = currentPlayer.getMove(game.deepCopy());
|
||||
PlayResult result = game.play(move);
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
package org.toop.game.gameThreads;
|
||||
package org.toop.framework.game.gameThreads;
|
||||
|
||||
import org.toop.framework.eventbus.EventFlow;
|
||||
import org.toop.framework.gameFramework.model.game.threadBehaviour.AbstractThreadBehaviour;
|
||||
import org.toop.framework.gameFramework.view.GUIEvents;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
import org.toop.framework.gameFramework.model.game.SupportsOnlinePlay;
|
||||
import org.toop.framework.gameFramework.model.game.threadBehaviour.SupportsOnlinePlay;
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
import org.toop.game.players.OnlinePlayer;
|
||||
import org.toop.framework.game.players.OnlinePlayer;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
/**
|
||||
* Handles online multiplayer game logic.
|
||||
@@ -14,17 +17,20 @@ import org.toop.game.players.OnlinePlayer;
|
||||
* Reacts to server events, sending moves and updating the game state
|
||||
* for the local player while receiving moves from other players.
|
||||
*/
|
||||
public class OnlineThreadBehaviour<T extends TurnBasedGame<T>> extends AbstractThreadBehaviour<T> implements SupportsOnlinePlay {
|
||||
public class OnlineThreadBehaviour extends AbstractThreadBehaviour implements SupportsOnlinePlay {
|
||||
|
||||
private ExecutorService moveExecutor = Executors.newSingleThreadExecutor();
|
||||
|
||||
/**
|
||||
* Creates behaviour and sets the first local player
|
||||
* (non-online player) from the given array.
|
||||
*/
|
||||
public OnlineThreadBehaviour(T game) {
|
||||
public OnlineThreadBehaviour(TurnBasedGame game) {
|
||||
super(game);
|
||||
}
|
||||
|
||||
/** Finds the first non-online player in the array. */
|
||||
private int getFirstNotOnlinePlayer(Player<T>[] players) {
|
||||
private int getFirstNotOnlinePlayer(Player[] players) {
|
||||
for (int i = 0; i < players.length; i++) {
|
||||
if (!(players[i] instanceof OnlinePlayer)) {
|
||||
return i;
|
||||
@@ -51,8 +57,30 @@ public class OnlineThreadBehaviour<T extends TurnBasedGame<T>> extends AbstractT
|
||||
*/
|
||||
@Override
|
||||
public void onYourTurn(long clientId) {
|
||||
if (!isRunning.get()) return;
|
||||
long move = game.getPlayer(game.getCurrentTurn()).getMove(game.deepCopy());
|
||||
logger.info("Yourturn");
|
||||
if (!isRunning.get()) {
|
||||
logger.warn("Game is not running!");
|
||||
return;
|
||||
}
|
||||
|
||||
TurnBasedGame gameCopy = game.deepCopy();
|
||||
if (gameCopy == null) {
|
||||
logger.error("Could not deep copy game");
|
||||
return;
|
||||
}
|
||||
logger.info("Successfully collected game copy");
|
||||
|
||||
Player player = gameCopy.getPlayer(game.getCurrentTurn());
|
||||
if (player == null) {
|
||||
logger.error("Could not find current turn's player");
|
||||
return;
|
||||
}
|
||||
logger.info("Successfully collected current turn's player");
|
||||
|
||||
long move = player.getMove(gameCopy);
|
||||
logger.info("Move set: {}", move);
|
||||
logger.info("Completed onYourTurn");
|
||||
|
||||
sendMove(clientId, move);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package org.toop.game.gameThreads;
|
||||
package org.toop.framework.game.gameThreads;
|
||||
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
import org.toop.framework.networking.events.NetworkEvents;
|
||||
|
||||
/**
|
||||
* Online thread behaviour that adds a fixed delay before processing
|
||||
@@ -10,14 +9,14 @@ import org.toop.framework.networking.events.NetworkEvents;
|
||||
* This is identical to {@link OnlineThreadBehaviour}, but inserts a
|
||||
* short sleep before delegating to the base implementation.
|
||||
*/
|
||||
public class OnlineWithSleepThreadBehaviour<T extends TurnBasedGame<T>> extends OnlineThreadBehaviour<T> {
|
||||
public class OnlineWithSleepThreadBehaviour extends OnlineThreadBehaviour {
|
||||
|
||||
/**
|
||||
* Creates the behaviour and forwards the players to the base class.
|
||||
*
|
||||
* @param game the online-capable turn-based game
|
||||
*/
|
||||
public OnlineWithSleepThreadBehaviour(T game) {
|
||||
public OnlineWithSleepThreadBehaviour(TurnBasedGame game) {
|
||||
super(game);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
package org.toop.framework.game.gameThreads;
|
||||
|
||||
import org.toop.framework.gameFramework.GameState;
|
||||
import org.toop.framework.gameFramework.model.game.PlayResult;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
import org.toop.framework.gameFramework.model.game.threadBehaviour.AbstractThreadBehaviour;
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
import org.toop.framework.utils.ImmutablePair;
|
||||
import org.toop.framework.utils.Pair;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class ServerThreadBehaviour extends AbstractThreadBehaviour implements Runnable {
|
||||
private final Consumer<ImmutablePair<String, Integer>> onPlayerMove;
|
||||
private final Consumer<Pair<GameState, Integer>> onGameEnd;
|
||||
|
||||
private final ExecutorService moveExecutor = Executors.newSingleThreadExecutor();
|
||||
|
||||
private final Duration timeOut;
|
||||
/**
|
||||
* Creates a new base behaviour for the specified game.
|
||||
*
|
||||
* @param game the turn-based game to control
|
||||
*/
|
||||
public ServerThreadBehaviour(
|
||||
TurnBasedGame game,
|
||||
Consumer<ImmutablePair<String,
|
||||
Integer>> onPlayerMove,
|
||||
Consumer<Pair<GameState, Integer>> onGameEnd,
|
||||
Duration timeOut
|
||||
) {
|
||||
this.onPlayerMove = onPlayerMove;
|
||||
this.onGameEnd = onGameEnd;
|
||||
this.timeOut = timeOut;
|
||||
super(game);
|
||||
}
|
||||
|
||||
private void notifyPlayerMove(ImmutablePair<String, Integer> pair) {
|
||||
if (onPlayerMove != null) {
|
||||
onPlayerMove.accept(pair);
|
||||
}
|
||||
}
|
||||
|
||||
private void notifyGameEnd(ImmutablePair<GameState, Integer> pair) {
|
||||
if (onGameEnd != null) {
|
||||
onGameEnd.accept(pair);
|
||||
}
|
||||
}
|
||||
|
||||
/** Starts the game loop in a new thread. */
|
||||
@Override
|
||||
public void start() {
|
||||
if (isRunning.compareAndSet(false, true)) {
|
||||
new Thread(this).start();
|
||||
}
|
||||
}
|
||||
|
||||
/** Stops the game loop after the current iteration. */
|
||||
@Override
|
||||
public void stop() {
|
||||
isRunning.set(false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
while (isRunning.get()) {
|
||||
Player currentPlayer = game.getPlayer(game.getCurrentTurn());
|
||||
|
||||
Future<Long> move = moveExecutor.submit(() -> currentPlayer.getMove(game.deepCopy()));
|
||||
|
||||
PlayResult result;
|
||||
try {
|
||||
long moveResult = move.get(timeOut.toMillis(), TimeUnit.MILLISECONDS);
|
||||
result = game.play(moveResult);
|
||||
|
||||
GameState state = result.state();
|
||||
notifyPlayerMove(new ImmutablePair<>(currentPlayer.getName(), Long.numberOfTrailingZeros(moveResult)));
|
||||
|
||||
switch (state) {
|
||||
case WIN, DRAW -> {
|
||||
isRunning.set(false);
|
||||
moveExecutor.shutdown();
|
||||
notifyGameEnd(new ImmutablePair<>(state, game.getWinner()));
|
||||
}
|
||||
case NORMAL, TURN_SKIPPED -> { /* continue normally */ }
|
||||
default -> {
|
||||
logger.error("Unexpected state {}", state);
|
||||
isRunning.set(false);
|
||||
moveExecutor.shutdown();
|
||||
throw new RuntimeException("Unknown state: " + state);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (InterruptedException | ExecutionException e) {
|
||||
isRunning.set(false);
|
||||
notifyGameEnd(new ImmutablePair<>(GameState.DRAW, 0));
|
||||
moveExecutor.shutdown();
|
||||
return;
|
||||
} catch (TimeoutException e) {
|
||||
isRunning.set(false);
|
||||
notifyGameEnd(new ImmutablePair<>(GameState.WIN, 1+game.getWinner()%2));
|
||||
moveExecutor.shutdown();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
package org.toop.framework.game.games.reversi;
|
||||
|
||||
import org.toop.framework.game.BitboardGame;
|
||||
import org.toop.framework.gameFramework.GameState;
|
||||
import org.toop.framework.gameFramework.model.game.PlayResult;
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
|
||||
public class BitboardReversi extends BitboardGame {
|
||||
|
||||
public record Score(int black, int white) {}
|
||||
|
||||
private final long notAFile = 0xfefefefefefefefeL;
|
||||
private final long notHFile = 0x7f7f7f7f7f7f7f7fL;
|
||||
|
||||
public BitboardReversi() {
|
||||
super(8, 8, 2);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(Player[] players) {
|
||||
super.init(players);
|
||||
// Black (player 0)
|
||||
setPlayerBitboard(0, (1L << (3 + 4 * 8)) | (1L << (4 + 3 * 8)));
|
||||
|
||||
// White (player 1)
|
||||
setPlayerBitboard(1, (1L << (3 + 3 * 8)) | (1L << (4 + 4 * 8)));
|
||||
}
|
||||
|
||||
public BitboardReversi(BitboardReversi other) {
|
||||
super(other);
|
||||
}
|
||||
|
||||
public long getLegalMoves() {
|
||||
long legalMoves = 0L;
|
||||
|
||||
final long player = getPlayerBitboard(getCurrentPlayerIndex());
|
||||
final long opponent = getPlayerBitboard(getNextPlayer());
|
||||
|
||||
final long empty = ~(player | opponent);
|
||||
|
||||
long mask;
|
||||
long direction;
|
||||
|
||||
// north
|
||||
mask = opponent;
|
||||
direction = (player << 8) & mask;
|
||||
|
||||
direction |= (direction << 8) & mask;
|
||||
direction |= (direction << 8) & mask;
|
||||
direction |= (direction << 8) & mask;
|
||||
direction |= (direction << 8) & mask;
|
||||
direction |= (direction << 8) & mask;
|
||||
legalMoves |= (direction << 8) & empty;
|
||||
|
||||
// south
|
||||
mask = opponent;
|
||||
direction = (player >>> 8) & mask;
|
||||
|
||||
direction |= (direction >>> 8) & mask;
|
||||
direction |= (direction >>> 8) & mask;
|
||||
direction |= (direction >>> 8) & mask;
|
||||
direction |= (direction >>> 8) & mask;
|
||||
direction |= (direction >>> 8) & mask;
|
||||
legalMoves |= (direction >>> 8) & empty;
|
||||
|
||||
// east
|
||||
mask = opponent & notAFile;
|
||||
direction = (player << 1) & mask;
|
||||
|
||||
direction |= (direction << 1) & mask;
|
||||
direction |= (direction << 1) & mask;
|
||||
direction |= (direction << 1) & mask;
|
||||
direction |= (direction << 1) & mask;
|
||||
direction |= (direction << 1) & mask;
|
||||
legalMoves |= (direction << 1) & empty & notAFile;
|
||||
|
||||
// west
|
||||
mask = opponent & notHFile;
|
||||
direction = (player >>> 1) & mask;
|
||||
|
||||
direction |= (direction >>> 1) & mask;
|
||||
direction |= (direction >>> 1) & mask;
|
||||
direction |= (direction >>> 1) & mask;
|
||||
direction |= (direction >>> 1) & mask;
|
||||
direction |= (direction >>> 1) & mask;
|
||||
legalMoves |= (direction >>> 1) & empty & notHFile;
|
||||
|
||||
// north-east
|
||||
mask = opponent & notAFile;
|
||||
direction = (player << 9) & mask;
|
||||
|
||||
direction |= (direction << 9) & mask;
|
||||
direction |= (direction << 9) & mask;
|
||||
direction |= (direction << 9) & mask;
|
||||
direction |= (direction << 9) & mask;
|
||||
direction |= (direction << 9) & mask;
|
||||
legalMoves |= (direction << 9) & empty & notAFile;
|
||||
|
||||
// north-west
|
||||
mask = opponent & notHFile;
|
||||
direction = (player << 7) & mask;
|
||||
|
||||
direction |= (direction << 7) & mask;
|
||||
direction |= (direction << 7) & mask;
|
||||
direction |= (direction << 7) & mask;
|
||||
direction |= (direction << 7) & mask;
|
||||
direction |= (direction << 7) & mask;
|
||||
legalMoves |= (direction << 7) & empty & notHFile;
|
||||
|
||||
// south-east
|
||||
mask = opponent & notAFile;
|
||||
direction = (player >>> 7) & mask;
|
||||
|
||||
direction |= (direction >>> 7) & mask;
|
||||
direction |= (direction >>> 7) & mask;
|
||||
direction |= (direction >>> 7) & mask;
|
||||
direction |= (direction >>> 7) & mask;
|
||||
direction |= (direction >>> 7) & mask;
|
||||
legalMoves |= (direction >>> 7) & empty & notAFile;
|
||||
|
||||
// south-west
|
||||
mask = opponent & notHFile;
|
||||
direction = (player >>> 9) & mask;
|
||||
|
||||
direction |= (direction >>> 9) & mask;
|
||||
direction |= (direction >>> 9) & mask;
|
||||
direction |= (direction >>> 9) & mask;
|
||||
direction |= (direction >>> 9) & mask;
|
||||
direction |= (direction >>> 9) & mask;
|
||||
legalMoves |= (direction >>> 9) & empty & notHFile;
|
||||
|
||||
return legalMoves;
|
||||
}
|
||||
|
||||
public long getFlips(long move) {
|
||||
long flips = 0L;
|
||||
|
||||
final long player = getPlayerBitboard(getCurrentPlayerIndex());
|
||||
final long opponent = getPlayerBitboard(getNextPlayer());
|
||||
|
||||
long mask;
|
||||
long direction;
|
||||
|
||||
// north
|
||||
mask = opponent;
|
||||
direction = (move << 8) & mask;
|
||||
|
||||
direction |= (direction << 8) & mask;
|
||||
direction |= (direction << 8) & mask;
|
||||
direction |= (direction << 8) & mask;
|
||||
direction |= (direction << 8) & mask;
|
||||
direction |= (direction << 8) & mask;
|
||||
|
||||
if (((direction << 8) & player) != 0) {
|
||||
flips |= direction;
|
||||
}
|
||||
|
||||
// south
|
||||
mask = opponent;
|
||||
direction = (move >>> 8) & mask;
|
||||
|
||||
direction |= (direction >>> 8) & mask;
|
||||
direction |= (direction >>> 8) & mask;
|
||||
direction |= (direction >>> 8) & mask;
|
||||
direction |= (direction >>> 8) & mask;
|
||||
direction |= (direction >>> 8) & mask;
|
||||
|
||||
if (((direction >>> 8) & player) != 0) {
|
||||
flips |= direction;
|
||||
}
|
||||
|
||||
// east
|
||||
mask = opponent & notAFile;
|
||||
direction = (move << 1) & mask;
|
||||
|
||||
direction |= (direction << 1) & mask;
|
||||
direction |= (direction << 1) & mask;
|
||||
direction |= (direction << 1) & mask;
|
||||
direction |= (direction << 1) & mask;
|
||||
direction |= (direction << 1) & mask;
|
||||
|
||||
if (((direction << 1) & player & notAFile) != 0) {
|
||||
flips |= direction;
|
||||
}
|
||||
|
||||
// west
|
||||
mask = opponent & notHFile;
|
||||
direction = (move >>> 1) & mask;
|
||||
|
||||
direction |= (direction >>> 1) & mask;
|
||||
direction |= (direction >>> 1) & mask;
|
||||
direction |= (direction >>> 1) & mask;
|
||||
direction |= (direction >>> 1) & mask;
|
||||
direction |= (direction >>> 1) & mask;
|
||||
|
||||
if (((direction >>> 1) & player & notHFile) != 0) {
|
||||
flips |= direction;
|
||||
}
|
||||
|
||||
// north-east
|
||||
mask = opponent & notAFile;
|
||||
direction = (move << 9) & mask;
|
||||
|
||||
direction |= (direction << 9) & mask;
|
||||
direction |= (direction << 9) & mask;
|
||||
direction |= (direction << 9) & mask;
|
||||
direction |= (direction << 9) & mask;
|
||||
direction |= (direction << 9) & mask;
|
||||
|
||||
if (((direction << 9) & player & notAFile) != 0) {
|
||||
flips |= direction;
|
||||
}
|
||||
|
||||
// north-west
|
||||
mask = opponent & notHFile;
|
||||
direction = (move << 7) & mask;
|
||||
|
||||
direction |= (direction << 7) & mask;
|
||||
direction |= (direction << 7) & mask;
|
||||
direction |= (direction << 7) & mask;
|
||||
direction |= (direction << 7) & mask;
|
||||
direction |= (direction << 7) & mask;
|
||||
|
||||
if (((direction << 7) & player & notHFile) != 0) {
|
||||
flips |= direction;
|
||||
}
|
||||
|
||||
// south-east
|
||||
mask = opponent & notAFile;
|
||||
direction = (move >>> 7) & mask;
|
||||
|
||||
direction |= (direction >>> 7) & mask;
|
||||
direction |= (direction >>> 7) & mask;
|
||||
direction |= (direction >>> 7) & mask;
|
||||
direction |= (direction >>> 7) & mask;
|
||||
direction |= (direction >>> 7) & mask;
|
||||
|
||||
if (((direction >>> 7) & player & notAFile) != 0) {
|
||||
flips |= direction;
|
||||
}
|
||||
|
||||
// south-west
|
||||
mask = opponent & notHFile;
|
||||
direction = (move >>> 9) & mask;
|
||||
|
||||
direction |= (direction >>> 9) & mask;
|
||||
direction |= (direction >>> 9) & mask;
|
||||
direction |= (direction >>> 9) & mask;
|
||||
direction |= (direction >>> 9) & mask;
|
||||
direction |= (direction >>> 9) & mask;
|
||||
|
||||
if (((direction >>> 9) & player & notHFile) != 0) {
|
||||
flips |= direction;
|
||||
}
|
||||
|
||||
return flips;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BitboardReversi deepCopy() {return new BitboardReversi(this);}
|
||||
|
||||
public PlayResult play(long move) {
|
||||
final long flips = getFlips(move);
|
||||
|
||||
long player = getPlayerBitboard(getCurrentPlayerIndex());
|
||||
long opponent = getPlayerBitboard(getNextPlayer());
|
||||
|
||||
player |= move | flips;
|
||||
opponent &= ~flips;
|
||||
|
||||
setPlayerBitboard(getCurrentPlayerIndex(), player);
|
||||
setPlayerBitboard(getNextPlayer(), opponent);
|
||||
|
||||
nextTurn();
|
||||
|
||||
final long nextLegalMoves = getLegalMoves();
|
||||
|
||||
if (nextLegalMoves == 0) {
|
||||
nextTurn();
|
||||
|
||||
final long skippedLegalMoves = getLegalMoves();
|
||||
|
||||
if (skippedLegalMoves == 0) {
|
||||
int winner = getWinner();
|
||||
|
||||
if (winner == -1) {
|
||||
state = new PlayResult(GameState.DRAW, -1);
|
||||
return state;
|
||||
}
|
||||
|
||||
state = new PlayResult(GameState.WIN, winner);
|
||||
return state;
|
||||
}
|
||||
|
||||
state = new PlayResult(GameState.TURN_SKIPPED, getCurrentPlayerIndex());
|
||||
return state;
|
||||
}
|
||||
|
||||
state = new PlayResult(GameState.NORMAL, getCurrentPlayerIndex());
|
||||
return state;
|
||||
}
|
||||
|
||||
public Score getScore() {
|
||||
return new Score(
|
||||
Long.bitCount(getPlayerBitboard(0)),
|
||||
Long.bitCount(getPlayerBitboard(1))
|
||||
);
|
||||
}
|
||||
|
||||
public int getWinner(){
|
||||
final long black = getPlayerBitboard(0);
|
||||
final long white = getPlayerBitboard(1);
|
||||
|
||||
final int blackCount = Long.bitCount(black);
|
||||
final int whiteCount = Long.bitCount(white);
|
||||
|
||||
if (blackCount == whiteCount){
|
||||
return -1;
|
||||
}
|
||||
else if (blackCount > whiteCount){
|
||||
return 0;
|
||||
}
|
||||
else {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public float rateMove(long move) {
|
||||
final long corners = 0x8100000000000081L;
|
||||
|
||||
if ((move & corners) != 0L) {
|
||||
return 0.4f;
|
||||
}
|
||||
|
||||
final long xSquares = 0x0042000000004200L;
|
||||
|
||||
if ((move & xSquares) != 0) {
|
||||
return -0.4f;
|
||||
}
|
||||
|
||||
final long cSquares = 0x4281000000008142L;
|
||||
|
||||
if ((move & cSquares) != 0) {
|
||||
return -0.1f;
|
||||
}
|
||||
|
||||
return 0.0f;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long heuristicMove(long legalMoves) {
|
||||
long bestMove = 0L;
|
||||
float bestMoveRate = Float.NEGATIVE_INFINITY;
|
||||
|
||||
while (legalMoves != 0L) {
|
||||
final long move = legalMoves & -legalMoves;
|
||||
final float moveRate = rateMove(move);
|
||||
|
||||
if (moveRate > bestMoveRate) {
|
||||
bestMove = move;
|
||||
bestMoveRate = moveRate;
|
||||
}
|
||||
|
||||
legalMoves &= ~move;
|
||||
}
|
||||
|
||||
return bestMove;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setFrom(long player1, long player2, int turn) {
|
||||
this.playerBitboard[0] = player1;
|
||||
this.playerBitboard[1] = player2;
|
||||
this.currentTurn = turn;
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,12 @@
|
||||
package org.toop.game.games.tictactoe;
|
||||
package org.toop.framework.game.games.tictactoe;
|
||||
|
||||
import org.toop.framework.gameFramework.GameState;
|
||||
import org.toop.framework.gameFramework.model.game.PlayResult;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
import org.toop.game.BitboardGame;
|
||||
import org.toop.framework.game.BitboardGame;
|
||||
|
||||
public class BitboardTicTacToe extends BitboardGame<BitboardTicTacToe> {
|
||||
public class BitboardTicTacToe extends BitboardGame {
|
||||
private final long[] winningLines = {
|
||||
0b111000000L, // top row
|
||||
0b000111000L, // middle row
|
||||
@@ -17,9 +18,15 @@ public class BitboardTicTacToe extends BitboardGame<BitboardTicTacToe> {
|
||||
0b001010100L // anti-diagonal
|
||||
};
|
||||
|
||||
public BitboardTicTacToe(Player<BitboardTicTacToe>[] players) {
|
||||
super(3, 3, 2, players);
|
||||
public BitboardTicTacToe() {
|
||||
super(3, 3, 2);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(Player[] players) {
|
||||
super.init(players);
|
||||
}
|
||||
|
||||
public BitboardTicTacToe(BitboardTicTacToe other) {
|
||||
super(other);
|
||||
}
|
||||
@@ -39,7 +46,8 @@ public class BitboardTicTacToe extends BitboardGame<BitboardTicTacToe> {
|
||||
public PlayResult play(long move) {
|
||||
// Player loses if move is invalid
|
||||
if ((move & getLegalMoves()) == 0 || Long.bitCount(move) != 1){
|
||||
return new PlayResult(GameState.WIN, getNextPlayer());
|
||||
state = new PlayResult(GameState.WIN, getNextPlayer());
|
||||
return state;
|
||||
}
|
||||
|
||||
// Move is legal, make move
|
||||
@@ -50,7 +58,8 @@ public class BitboardTicTacToe extends BitboardGame<BitboardTicTacToe> {
|
||||
|
||||
// Check if current player won
|
||||
if (checkWin(playerBitboard)) {
|
||||
return new PlayResult(GameState.WIN, getCurrentPlayerIndex());
|
||||
state = new PlayResult(GameState.WIN, getCurrentPlayerIndex());
|
||||
return state;
|
||||
}
|
||||
|
||||
// Proceed to next turn
|
||||
@@ -59,11 +68,13 @@ public class BitboardTicTacToe extends BitboardGame<BitboardTicTacToe> {
|
||||
|
||||
// Check for early draw
|
||||
if (getLegalMoves() == 0L || checkEarlyDraw()) {
|
||||
return new PlayResult(GameState.DRAW, -1);
|
||||
state = new PlayResult(GameState.DRAW, -1);
|
||||
return state;
|
||||
}
|
||||
|
||||
// Nothing weird happened, continue on as normal
|
||||
return new PlayResult(GameState.NORMAL, -1);
|
||||
state = new PlayResult(GameState.NORMAL, -1);
|
||||
return state;
|
||||
}
|
||||
|
||||
private boolean checkWin(long board) {
|
||||
@@ -100,4 +111,18 @@ public class BitboardTicTacToe extends BitboardGame<BitboardTicTacToe> {
|
||||
public BitboardTicTacToe deepCopy() {
|
||||
return new BitboardTicTacToe(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public float rateMove(long move) {
|
||||
return 0.0f;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long heuristicMove(long legalMoves) {
|
||||
return legalMoves;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setFrom(long player1, long player2, int turn) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package org.toop.framework.game.players;
|
||||
|
||||
import org.toop.framework.gameFramework.model.player.*;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
|
||||
/**
|
||||
* Represents a player controlled by an AI in a game.
|
||||
* <p>
|
||||
* This player uses an {@link AbstractAI} instance to determine its moves. The generic
|
||||
* parameter {@code T} specifies the type of {@link GameR} the AI can handle.
|
||||
* </p>
|
||||
*
|
||||
* @param <T> the specific type of game this AI player can play
|
||||
*/
|
||||
public class ArtificialPlayer extends AbstractPlayer {
|
||||
|
||||
/**
|
||||
* The AI instance used to calculate moves.
|
||||
*/
|
||||
private final AI ai;
|
||||
|
||||
/**
|
||||
* Constructs a new ArtificialPlayer using the specified AI.
|
||||
*
|
||||
* @param ai the AI instance that determines moves for this player
|
||||
*/
|
||||
public ArtificialPlayer(AI ai, String name) {
|
||||
super(name);
|
||||
this.ai = ai;
|
||||
}
|
||||
|
||||
public ArtificialPlayer(ArtificialPlayer other) {
|
||||
super(other);
|
||||
this.ai = other.ai.deepCopy();
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines the next move for this player using its AI.
|
||||
* <p>
|
||||
* This method overrides {@link AbstractPlayer#getMove(GameR)}. Because the AI is
|
||||
* typed to {@code T}, a runtime cast is required. It is the caller's
|
||||
* responsibility to ensure that {@code gameCopy} is of type {@code T}.
|
||||
* </p>
|
||||
*
|
||||
* @param gameCopy a copy of the current game state
|
||||
* @return the integer representing the chosen move
|
||||
* @throws ClassCastException if {@code gameCopy} is not of type {@code T}
|
||||
*/
|
||||
protected long determineMove(TurnBasedGame gameCopy) {
|
||||
return ai.getMove(gameCopy);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a deep copy of this AI player.
|
||||
*
|
||||
* @return a copy of this player
|
||||
*/
|
||||
@Override
|
||||
public ArtificialPlayer deepCopy() {
|
||||
return new ArtificialPlayer(this);
|
||||
}
|
||||
|
||||
public AI getAi() {
|
||||
return ai;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package org.toop.game.players;
|
||||
package org.toop.framework.game.players;
|
||||
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
import org.toop.framework.gameFramework.model.player.AbstractPlayer;
|
||||
@@ -11,7 +11,7 @@ import java.util.concurrent.ExecutionException;
|
||||
*
|
||||
* @param <T> the type of turn-based game
|
||||
*/
|
||||
public class LocalPlayer<T extends TurnBasedGame<T>> extends AbstractPlayer<T> {
|
||||
public class LocalPlayer extends AbstractPlayer {
|
||||
|
||||
private CompletableFuture<Long> LastMove = new CompletableFuture<>();
|
||||
|
||||
@@ -29,7 +29,7 @@ public class LocalPlayer<T extends TurnBasedGame<T>> extends AbstractPlayer<T> {
|
||||
*
|
||||
* @param other the player to copy
|
||||
*/
|
||||
public LocalPlayer(LocalPlayer<T> other) {
|
||||
public LocalPlayer(LocalPlayer other) {
|
||||
super(other);
|
||||
this.LastMove = other.LastMove;
|
||||
}
|
||||
@@ -41,15 +41,20 @@ public class LocalPlayer<T extends TurnBasedGame<T>> extends AbstractPlayer<T> {
|
||||
* @return the chosen move
|
||||
*/
|
||||
@Override
|
||||
protected long determineMove(T gameCopy) {
|
||||
protected long determineMove(TurnBasedGame gameCopy) {
|
||||
long legalMoves = gameCopy.getLegalMoves();
|
||||
long move;
|
||||
|
||||
try {
|
||||
do {
|
||||
move = getLastMove();
|
||||
IO.println("GETTING MOVE");
|
||||
} while ((legalMoves & move) == 0);
|
||||
|
||||
return move;
|
||||
} catch (Exception e) {
|
||||
IO.println(e);
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -81,7 +86,23 @@ public class LocalPlayer<T extends TurnBasedGame<T>> extends AbstractPlayer<T> {
|
||||
* @return a copy of this player
|
||||
*/
|
||||
@Override
|
||||
public LocalPlayer<T> deepCopy() {
|
||||
return new LocalPlayer<>(this);
|
||||
public LocalPlayer deepCopy() {
|
||||
return new LocalPlayer(this);
|
||||
}
|
||||
|
||||
/*public void register() {
|
||||
// Listening to PlayerAttemptedMove
|
||||
new EventFlow().listen(GUIEvents.PlayerAttemptedMove.class, event -> {
|
||||
if (!LastMove.isDone()) {
|
||||
LastMove.complete(event.move()); // complete the future
|
||||
}
|
||||
}, true); // auto-unsubscribe
|
||||
}
|
||||
|
||||
// This blocks until the next move arrives
|
||||
public int take() throws ExecutionException, InterruptedException {
|
||||
int move = LastMove.get(); // blocking
|
||||
LastMove = new CompletableFuture<>(); // reset for next move
|
||||
return move;
|
||||
}*/
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package org.toop.game.players;
|
||||
package org.toop.framework.game.players;
|
||||
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
import org.toop.framework.gameFramework.model.player.AbstractPlayer;
|
||||
@@ -9,7 +9,7 @@ import org.toop.framework.gameFramework.model.player.Player;
|
||||
*
|
||||
* @param <T> the type of turn-based game
|
||||
*/
|
||||
public class OnlinePlayer<T extends TurnBasedGame<T>> extends AbstractPlayer<T> {
|
||||
public class OnlinePlayer extends AbstractPlayer {
|
||||
|
||||
/**
|
||||
* Creates a new online player with the given name.
|
||||
@@ -25,7 +25,7 @@ public class OnlinePlayer<T extends TurnBasedGame<T>> extends AbstractPlayer<T>
|
||||
*
|
||||
* @param other the player to copy
|
||||
*/
|
||||
public OnlinePlayer(OnlinePlayer<T> other) {
|
||||
public OnlinePlayer(OnlinePlayer other) {
|
||||
super(other);
|
||||
}
|
||||
|
||||
@@ -37,7 +37,7 @@ public class OnlinePlayer<T extends TurnBasedGame<T>> extends AbstractPlayer<T>
|
||||
* @throws UnsupportedOperationException always
|
||||
*/
|
||||
@Override
|
||||
protected long determineMove(T gameCopy) {
|
||||
protected long determineMove(TurnBasedGame gameCopy) {
|
||||
throw new UnsupportedOperationException("An online player does not support determining move");
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ public class OnlinePlayer<T extends TurnBasedGame<T>> extends AbstractPlayer<T>
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public Player<T> deepCopy() {
|
||||
return new OnlinePlayer<>(this);
|
||||
public Player deepCopy() {
|
||||
return new OnlinePlayer(this);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package org.toop.framework.game.players;
|
||||
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
import org.toop.framework.gameFramework.model.player.AbstractPlayer;
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
import org.toop.framework.networking.server.client.NettyClient;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
|
||||
public class ServerPlayer extends AbstractPlayer {
|
||||
private NettyClient client;
|
||||
private CompletableFuture<Long> lastMove;
|
||||
|
||||
public ServerPlayer(NettyClient client) {
|
||||
super(client.name());
|
||||
this.client = client;
|
||||
}
|
||||
|
||||
public void setMove(long move) {
|
||||
lastMove.complete(move);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Player deepCopy() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long determineMove(TurnBasedGame game) {
|
||||
lastMove = new CompletableFuture<>();
|
||||
|
||||
client.send("SVR GAME YOURTURN {TURNMESSAGE: \"<bericht voor deze beurt>\"}");
|
||||
return lastMove.join();
|
||||
}
|
||||
}
|
||||
@@ -4,13 +4,13 @@ package org.toop.framework.gameFramework;
|
||||
* Represents the current state of a turn-based game.
|
||||
*/
|
||||
public enum GameState {
|
||||
/** Game is ongoing and no special condition applies. */
|
||||
/** OnlineTurnBasedGame is ongoing and no special condition applies. */
|
||||
NORMAL,
|
||||
|
||||
/** Game ended in a draw. */
|
||||
/** OnlineTurnBasedGame ended in a draw. */
|
||||
DRAW,
|
||||
|
||||
/** Game ended with a win for a player. */
|
||||
/** OnlineTurnBasedGame ended with a win for a player. */
|
||||
WIN,
|
||||
|
||||
/** Next player's turn was skipped. */
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
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;
|
||||
import org.toop.framework.networking.connection.events.NetworkEvents;
|
||||
|
||||
public interface GameController extends Controllable, UpdatesGameUI {
|
||||
public interface GameController {
|
||||
/** Called when it is this player's turn to make a move. */
|
||||
void onYourTurn(NetworkEvents.YourTurnResponse event);
|
||||
|
||||
@@ -14,5 +12,12 @@ public interface GameController extends Controllable, UpdatesGameUI {
|
||||
/** Called when the game has finished, with the final result. */
|
||||
void gameFinished(NetworkEvents.GameResultResponse event);
|
||||
|
||||
void start();
|
||||
|
||||
void stop();
|
||||
|
||||
/** Called to refresh or update the game UI. */
|
||||
void updateUI();
|
||||
|
||||
void sendMove(long clientId, long move);
|
||||
}
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
package org.toop.framework.gameFramework.controller;
|
||||
|
||||
/**
|
||||
* Interface for classes that can trigger a UI update.
|
||||
*/
|
||||
public interface UpdatesGameUI {
|
||||
|
||||
/** Called to refresh or update the game UI. */
|
||||
void updateUI();
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package org.toop.framework.gameFramework.model.game;
|
||||
|
||||
public interface BoardProvider {
|
||||
long[] getBoard();
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package org.toop.framework.gameFramework.model.game;
|
||||
|
||||
import org.toop.framework.gameFramework.GameState;
|
||||
|
||||
/**
|
||||
* Interface for turn-based games that can be played and queried for legal moves.
|
||||
*/
|
||||
public interface Playable {
|
||||
|
||||
/**
|
||||
* Returns the moves that are currently valid in the game.
|
||||
*
|
||||
* @return an array of integers representing legal moves
|
||||
*/
|
||||
long getLegalMoves();
|
||||
|
||||
/**
|
||||
* Plays the given move and returns the resulting game state.
|
||||
*
|
||||
* @param move the move to apply
|
||||
* @return the {@link GameState} and additional info after the move
|
||||
*/
|
||||
PlayResult play(long move);
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
package org.toop.framework.gameFramework.model.game;
|
||||
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
|
||||
public interface PlayerProvider<T extends TurnBasedGame<T>> {
|
||||
Player<T> getPlayer(int index);
|
||||
}
|
||||
@@ -1,7 +1,21 @@
|
||||
package org.toop.framework.gameFramework.model.game;
|
||||
|
||||
public interface TurnBasedGame<T extends TurnBasedGame<T>> extends Playable, DeepCopyable<T>, PlayerProvider<T>, BoardProvider {
|
||||
import org.toop.framework.gameFramework.model.player.Player;
|
||||
|
||||
public interface TurnBasedGame extends DeepCopyable<TurnBasedGame> {
|
||||
void init(Player[] players);
|
||||
long[] getBoard();
|
||||
int getCurrentTurn();
|
||||
int getPlayerCount();
|
||||
Player getPlayer(int index);
|
||||
int getWinner();
|
||||
long getLegalMoves();
|
||||
PlayResult play(long move);
|
||||
PlayResult getState();
|
||||
boolean isTerminal();
|
||||
|
||||
float rateMove(long move);
|
||||
long heuristicMove(long legalMoves);
|
||||
|
||||
void setFrom(long player1, long player2, int turn);
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ package org.toop.framework.gameFramework.model.game.threadBehaviour;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.toop.framework.gameFramework.LongPairConsumer;
|
||||
import org.toop.framework.gameFramework.controller.GameController;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
@@ -16,14 +15,14 @@ import java.util.function.Consumer;
|
||||
* 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 {
|
||||
public abstract class AbstractThreadBehaviour implements ThreadBehaviour {
|
||||
private LongPairConsumer onSendMove;
|
||||
private Runnable onUpdateUI;
|
||||
/** Indicates whether the game loop or event processing is active. */
|
||||
protected final AtomicBoolean isRunning = new AtomicBoolean();
|
||||
|
||||
/** The game instance controlled by this behaviour. */
|
||||
protected final T game;
|
||||
protected final TurnBasedGame game;
|
||||
|
||||
/** Logger for the subclass to report errors or debug info. */
|
||||
protected final Logger logger = LogManager.getLogger(this.getClass());
|
||||
@@ -33,7 +32,7 @@ public abstract class AbstractThreadBehaviour<T extends TurnBasedGame<T>> implem
|
||||
*
|
||||
* @param game the turn-based game to control
|
||||
*/
|
||||
public AbstractThreadBehaviour(T game) {
|
||||
public AbstractThreadBehaviour(TurnBasedGame game) {
|
||||
this.game = game;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
package org.toop.framework.gameFramework.model.game.threadBehaviour;
|
||||
|
||||
public interface Controllable {
|
||||
void start();
|
||||
|
||||
void stop();
|
||||
}
|
||||
@@ -1,6 +1,4 @@
|
||||
package org.toop.framework.gameFramework.model.game;
|
||||
|
||||
import org.toop.framework.networking.events.NetworkEvents;
|
||||
package org.toop.framework.gameFramework.model.game.threadBehaviour;
|
||||
|
||||
/**
|
||||
* Interface for games that support online multiplayer play.
|
||||
@@ -11,8 +11,11 @@ import java.util.function.Consumer;
|
||||
* <p>
|
||||
* Defines how a game's execution is started, stopped, and which player is active.
|
||||
*/
|
||||
public interface ThreadBehaviour extends Controllable {
|
||||
public interface ThreadBehaviour {
|
||||
void setOnUpdateUI(Runnable onUpdateUI);
|
||||
void setOnSendMove(LongPairConsumer onSendMove);
|
||||
void start();
|
||||
void stop();
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -3,5 +3,6 @@ package org.toop.framework.gameFramework.model.player;
|
||||
import org.toop.framework.gameFramework.model.game.DeepCopyable;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
|
||||
public interface AI<T extends TurnBasedGame<T>> extends MoveProvider<T>, DeepCopyable<AI<T>> {
|
||||
public interface AI extends DeepCopyable<AI> {
|
||||
long getMove(TurnBasedGame game);
|
||||
}
|
||||
|
||||
@@ -12,6 +12,6 @@ import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
*
|
||||
* @param <T> the specific type of game this AI can play, extending {@link GameR}
|
||||
*/
|
||||
public abstract class AbstractAI<T extends TurnBasedGame<T>> implements AI<T> {
|
||||
public abstract class AbstractAI implements AI {
|
||||
// Concrete AI implementations should override findBestMove(T game, int depth)
|
||||
}
|
||||
|
||||
@@ -5,44 +5,42 @@ import org.apache.logging.log4j.Logger;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
|
||||
/**
|
||||
* Base class for players in a turn-based game.
|
||||
*
|
||||
* @param <T> the game type
|
||||
* Abstract class representing a player in a game.
|
||||
* <p>
|
||||
* Players are entities that can make moves based on the current state of a game.
|
||||
* player types, such as human players or AI players.
|
||||
* </p>
|
||||
* <p>
|
||||
* Subclasses should override the {@link #getMove(GameR)} method to provide
|
||||
* specific move logic.
|
||||
* </p>
|
||||
*/
|
||||
public abstract class AbstractPlayer<T extends TurnBasedGame<T>> implements Player<T> {
|
||||
|
||||
public abstract class AbstractPlayer implements Player {
|
||||
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) {
|
||||
System.out.println("Player " + name + " has been created");
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a copy of another player.
|
||||
*
|
||||
* @param other the player to copy
|
||||
*/
|
||||
protected AbstractPlayer(AbstractPlayer<T> other) {
|
||||
protected AbstractPlayer(AbstractPlayer other) {
|
||||
this.name = other.name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the player's move for the given game state.
|
||||
* A deep copy is provided so the player cannot modify the real state.
|
||||
* Determines the next move based on the provided game state.
|
||||
* <p>
|
||||
* This method uses the Template Method Pattern: it defines the fixed
|
||||
* algorithm and delegates the variable part to {@link #determineMove(T)}.
|
||||
* The default implementation throws an {@link UnsupportedOperationException},
|
||||
* indicating that concrete subclasses must override this method to provide
|
||||
* actual move logic.
|
||||
* </p>
|
||||
*
|
||||
* @param game the current game
|
||||
* @return the chosen move
|
||||
* @param gameCopy a snapshot of the current game state
|
||||
* @return an integer representing the chosen move
|
||||
* @throws UnsupportedOperationException if the method is not overridden
|
||||
*/
|
||||
public final long getMove(T game) {
|
||||
public final long getMove(TurnBasedGame game) {
|
||||
return determineMove(game.deepCopy());
|
||||
}
|
||||
|
||||
@@ -56,7 +54,7 @@ public abstract class AbstractPlayer<T extends TurnBasedGame<T>> implements Play
|
||||
* @param gameCopy a deep copy of the game
|
||||
* @return the chosen move
|
||||
*/
|
||||
protected abstract long determineMove(T gameCopy);
|
||||
protected abstract long determineMove(TurnBasedGame gameCopy);
|
||||
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
package org.toop.framework.gameFramework.model.player;
|
||||
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
|
||||
public interface MoveProvider<T extends TurnBasedGame<T>> {
|
||||
long getMove(T game);
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package org.toop.framework.gameFramework.model.player;
|
||||
|
||||
public interface NameProvider {
|
||||
String getName();
|
||||
}
|
||||
@@ -3,5 +3,7 @@ package org.toop.framework.gameFramework.model.player;
|
||||
import org.toop.framework.gameFramework.model.game.DeepCopyable;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
|
||||
public interface Player<T extends TurnBasedGame<T>> extends NameProvider, MoveProvider<T>, DeepCopyable<Player<T>> {
|
||||
public interface Player extends DeepCopyable<Player> {
|
||||
String getName();
|
||||
long getMove(TurnBasedGame game);
|
||||
}
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
package org.toop.framework.networking;
|
||||
package org.toop.framework.networking.connection;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.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;
|
||||
import org.toop.framework.networking.connection.events.NetworkEvents;
|
||||
import org.toop.framework.networking.connection.exceptions.ClientNotFoundException;
|
||||
import org.toop.framework.networking.connection.interfaces.NetworkingClientManager;
|
||||
|
||||
public class NetworkingClientEventListener {
|
||||
private static final Logger logger = LogManager.getLogger(NetworkingClientEventListener.class);
|
||||
@@ -1,4 +1,4 @@
|
||||
package org.toop.framework.networking;
|
||||
package org.toop.framework.networking.connection;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
@@ -10,13 +10,13 @@ import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.toop.framework.eventbus.EventFlow;
|
||||
import org.toop.framework.eventbus.bus.EventBus;
|
||||
import org.toop.framework.networking.events.NetworkEvents;
|
||||
import org.toop.framework.networking.exceptions.ClientNotFoundException;
|
||||
import org.toop.framework.networking.exceptions.CouldNotConnectException;
|
||||
import org.toop.framework.networking.interfaces.NetworkingClient;
|
||||
import org.toop.framework.networking.types.NetworkingConnector;
|
||||
import org.toop.framework.networking.connection.events.NetworkEvents;
|
||||
import org.toop.framework.networking.connection.exceptions.ClientNotFoundException;
|
||||
import org.toop.framework.networking.connection.exceptions.CouldNotConnectException;
|
||||
import org.toop.framework.networking.connection.interfaces.NetworkingClient;
|
||||
import org.toop.framework.networking.connection.types.NetworkingConnector;
|
||||
|
||||
public class NetworkingClientManager implements org.toop.framework.networking.interfaces.NetworkingClientManager {
|
||||
public class NetworkingClientManager implements org.toop.framework.networking.connection.interfaces.NetworkingClientManager {
|
||||
private static final Logger logger = LogManager.getLogger(NetworkingClientManager.class);
|
||||
|
||||
private final EventBus eventBus;
|
||||
@@ -1,4 +1,4 @@
|
||||
package org.toop.framework.networking.clients;
|
||||
package org.toop.framework.networking.connection.clients;
|
||||
|
||||
import io.netty.bootstrap.Bootstrap;
|
||||
import io.netty.channel.*;
|
||||
@@ -12,9 +12,10 @@ import io.netty.util.CharsetUtil;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.toop.framework.eventbus.bus.EventBus;
|
||||
import org.toop.framework.networking.exceptions.CouldNotConnectException;
|
||||
import org.toop.framework.networking.handlers.NetworkingGameClientHandler;
|
||||
import org.toop.framework.networking.interfaces.NetworkingClient;
|
||||
import org.toop.framework.networking.connection.events.NetworkEvents;
|
||||
import org.toop.framework.networking.connection.exceptions.CouldNotConnectException;
|
||||
import org.toop.framework.networking.connection.handlers.NetworkingGameClientHandler;
|
||||
import org.toop.framework.networking.connection.interfaces.NetworkingClient;
|
||||
|
||||
import java.net.InetSocketAddress;
|
||||
|
||||
@@ -23,6 +24,7 @@ public class TournamentNetworkingClient implements NetworkingClient {
|
||||
|
||||
private final EventBus eventBus;
|
||||
private Channel channel;
|
||||
private long clientId;
|
||||
|
||||
public TournamentNetworkingClient(EventBus eventBus) {
|
||||
this.eventBus = eventBus;
|
||||
@@ -35,6 +37,7 @@ public class TournamentNetworkingClient implements NetworkingClient {
|
||||
|
||||
@Override
|
||||
public void connect(long clientId, String host, int port) throws CouldNotConnectException {
|
||||
this.clientId = clientId;
|
||||
try {
|
||||
Bootstrap bootstrap = new Bootstrap();
|
||||
EventLoopGroup workerGroup = new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory());
|
||||
@@ -75,6 +78,7 @@ public class TournamentNetworkingClient implements NetworkingClient {
|
||||
logger.info("Connection {} sent message: '{}' ", this.channel.remoteAddress(), literalMsg);
|
||||
} else {
|
||||
logger.warn("Cannot send message: '{}', connection inactive. ", literalMsg);
|
||||
eventBus.post(new NetworkEvents.ClosedConnection(clientId));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package org.toop.framework.networking.events;
|
||||
package org.toop.framework.networking.connection.events;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
@@ -6,8 +6,8 @@ import java.util.concurrent.CompletableFuture;
|
||||
import org.toop.annotations.AutoResponseResult;
|
||||
import org.toop.framework.eventbus.GlobalEventBus;
|
||||
import org.toop.framework.eventbus.events.*;
|
||||
import org.toop.framework.networking.interfaces.NetworkingClient;
|
||||
import org.toop.framework.networking.types.NetworkingConnector;
|
||||
import org.toop.framework.networking.connection.interfaces.NetworkingClient;
|
||||
import org.toop.framework.networking.connection.types.NetworkingConnector;
|
||||
|
||||
/**
|
||||
* Defines all event types related to the networking subsystem.
|
||||
@@ -65,6 +65,9 @@ public class NetworkEvents extends EventsBase {
|
||||
public record GameResultResponse(long clientId, String condition)
|
||||
implements GenericEvent {}
|
||||
|
||||
public record TournamentResultResponse(long clientId, String gameType, String[] names, String[] scoreTypes, List<Integer[]> scores)
|
||||
implements GenericEvent {}
|
||||
|
||||
/** Indicates that a game move has been processed or received. */
|
||||
public record GameMoveResponse(long clientId, String player, String move, String details)
|
||||
implements GenericEvent {}
|
||||
@@ -102,7 +105,7 @@ public class NetworkEvents extends EventsBase {
|
||||
implements GenericEvent {}
|
||||
|
||||
/** Requests to accept an existing challenge. */
|
||||
public record SendAcceptChallenge(long clientId, int challengeId)
|
||||
public record SendAcceptChallenge(long clientId, long challengeId)
|
||||
implements GenericEvent {}
|
||||
|
||||
/** Requests to forfeit the current game. */
|
||||
@@ -219,4 +222,5 @@ public class NetworkEvents extends EventsBase {
|
||||
/** Response to a {@link ChangeAddress} event, carrying the success result. */
|
||||
public record ChangeAddressResponse(boolean successful, long identifier)
|
||||
implements ResponseToUniqueEvent {}
|
||||
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package org.toop.framework.networking.exceptions;
|
||||
package org.toop.framework.networking.connection.exceptions;
|
||||
|
||||
/**
|
||||
* Thrown when an operation is attempted on a networking client
|
||||
@@ -1,4 +1,4 @@
|
||||
package org.toop.framework.networking.exceptions;
|
||||
package org.toop.framework.networking.connection.exceptions;
|
||||
|
||||
public class CouldNotConnectException extends RuntimeException {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package org.toop.framework.networking.exceptions;
|
||||
package org.toop.framework.networking.connection.exceptions;
|
||||
|
||||
public class NetworkingInitializationException extends RuntimeException {
|
||||
public NetworkingInitializationException(String message, Throwable cause) {
|
||||
@@ -1,15 +1,18 @@
|
||||
package org.toop.framework.networking.handlers;
|
||||
package org.toop.framework.networking.connection.handlers;
|
||||
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.regex.MatchResult;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.toop.framework.eventbus.bus.EventBus;
|
||||
import org.toop.framework.networking.events.NetworkEvents;
|
||||
import org.toop.framework.networking.connection.events.NetworkEvents;
|
||||
|
||||
public class NetworkingGameClientHandler extends ChannelInboundHandlerAdapter {
|
||||
private static final Logger logger = LogManager.getLogger(NetworkingGameClientHandler.class);
|
||||
@@ -94,6 +97,9 @@ public class NetworkingGameClientHandler extends ChannelInboundHandlerAdapter {
|
||||
case "HELP":
|
||||
helpHandler(recSrvRemoved);
|
||||
return;
|
||||
case "RESULTS":
|
||||
resultsHandler(recSrvRemoved);
|
||||
return;
|
||||
default:
|
||||
// return
|
||||
}
|
||||
@@ -103,6 +109,66 @@ public class NetworkingGameClientHandler extends ChannelInboundHandlerAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
private static String extract(String input, String key) {
|
||||
Pattern p = Pattern.compile(
|
||||
key + "\\s*:\\s*(\\[[^]]*]|\"[^\"]*\")",
|
||||
Pattern.CASE_INSENSITIVE
|
||||
);
|
||||
Matcher m = p.matcher(input);
|
||||
return m.find() ? m.group(1) : null;
|
||||
}
|
||||
|
||||
private void resultsHandler(String rec) {
|
||||
// TODO all of this
|
||||
|
||||
IO.println(rec);
|
||||
|
||||
String gameTypeRaw = extract(rec, "GAMETYPE");
|
||||
String usersRaw = extract(rec, "USERS");
|
||||
String scoreTypesRaw = extract(rec, "SCORETYPES");
|
||||
String scoresRaw = extract(rec, "SCORES");
|
||||
|
||||
if (usersRaw == null) return;
|
||||
|
||||
String[] users;
|
||||
if (usersRaw.length() > 2) {
|
||||
users = Arrays.stream(usersRaw.substring(1, usersRaw.length() - 1).split(","))
|
||||
.map(s -> s.trim().replace("\"", ""))
|
||||
.toArray(String[]::new);
|
||||
} else {
|
||||
users = new String[]{};
|
||||
}
|
||||
|
||||
String[] scoreTypes;
|
||||
if (scoreTypesRaw.length() > 2) {
|
||||
scoreTypes = Arrays.stream(scoreTypesRaw.substring(1, usersRaw.length() - 1).split(","))
|
||||
.map(s -> s.trim().replace("\"", ""))
|
||||
.toArray(String[]::new);
|
||||
} else {
|
||||
scoreTypes = new String[]{};
|
||||
}
|
||||
|
||||
if (scoresRaw == null) return;
|
||||
if (scoresRaw.length() > 2) {
|
||||
List<Integer[]> scores = Arrays.stream(
|
||||
scoresRaw.substring(1, scoresRaw.length() - 1) // remove outer []
|
||||
.split("\\],\\[")
|
||||
)
|
||||
.map(part -> part.replace("[", "").replace("]", ""))
|
||||
.map(part -> Arrays.stream(part.split(","))
|
||||
.map(String::trim)
|
||||
.map(Integer::parseInt)
|
||||
.toArray(Integer[]::new)
|
||||
)
|
||||
.toList();
|
||||
|
||||
eventBus.post(new NetworkEvents.TournamentResultResponse(this.connectionId, gameTypeRaw, users, scoreTypes, scores));
|
||||
} else {
|
||||
eventBus.post(new NetworkEvents.TournamentResultResponse(this.connectionId, gameTypeRaw, users, scoreTypes, new ArrayList<>()));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void gameMoveHandler(String rec) {
|
||||
String[] msg =
|
||||
Pattern.compile(
|
||||
@@ -1,6 +1,6 @@
|
||||
package org.toop.framework.networking.interfaces;
|
||||
package org.toop.framework.networking.connection.interfaces;
|
||||
|
||||
import org.toop.framework.networking.exceptions.CouldNotConnectException;
|
||||
import org.toop.framework.networking.connection.exceptions.CouldNotConnectException;
|
||||
|
||||
import java.net.InetSocketAddress;
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
package org.toop.framework.networking.interfaces;
|
||||
package org.toop.framework.networking.connection.interfaces;
|
||||
|
||||
import org.toop.framework.networking.exceptions.ClientNotFoundException;
|
||||
import org.toop.framework.networking.exceptions.CouldNotConnectException;
|
||||
import org.toop.framework.networking.types.NetworkingConnector;
|
||||
import org.toop.framework.networking.connection.exceptions.ClientNotFoundException;
|
||||
import org.toop.framework.networking.connection.exceptions.CouldNotConnectException;
|
||||
import org.toop.framework.networking.connection.types.NetworkingConnector;
|
||||
|
||||
public interface NetworkingClientManager {
|
||||
void startClient(
|
||||
@@ -1,4 +1,4 @@
|
||||
package org.toop.framework.networking.types;
|
||||
package org.toop.framework.networking.connection.types;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
package org.toop.framework.networking.types;
|
||||
package org.toop.framework.networking.connection.types;
|
||||
|
||||
public record ServerCommand(long clientId, String command) {}
|
||||
@@ -0,0 +1,3 @@
|
||||
package org.toop.framework.networking.connection.types;
|
||||
|
||||
public record ServerMessage(String message) {}
|
||||
@@ -0,0 +1,7 @@
|
||||
package org.toop.framework.networking.server;
|
||||
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
public record GameResultFuture(OnlineGame<TurnBasedGame> game, CompletableFuture<Integer> result) {}
|
||||
@@ -0,0 +1,26 @@
|
||||
package org.toop.framework.networking.server;
|
||||
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
public interface GameServer<GAMETYPE, CLIENT, CHALLENGEIDTYPE> {
|
||||
GameResultFuture startGame(String gameType, Duration turnTime, CLIENT... clients);
|
||||
|
||||
void addClient(CLIENT client);
|
||||
void removeClient(CLIENT client);
|
||||
|
||||
void challengeClient(String fromClientName, String toClientName, String gameTypeKey);
|
||||
void acceptChallenge(CHALLENGEIDTYPE challengeId);
|
||||
|
||||
void subscribeClient(String clientName, String gameTypeKey);
|
||||
void unsubscribeClient(String clientName);
|
||||
|
||||
List<String> gameTypes();
|
||||
List<OnlineGame<GAMETYPE>> ongoingGames();
|
||||
|
||||
List<CLIENT> onlineUsers();
|
||||
void shutdown();
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package org.toop.framework.networking.server;
|
||||
|
||||
import org.toop.framework.networking.server.client.NettyClient;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface MatchExecutor {
|
||||
GameResultFuture submit(String gameType, Duration turnTime, NettyClient... clients);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package org.toop.framework.networking.server;
|
||||
|
||||
import org.toop.framework.networking.server.client.NettyClient;
|
||||
|
||||
public interface OnlineGame<T> {
|
||||
long id();
|
||||
T game();
|
||||
NettyClient[] users();
|
||||
void start();
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package org.toop.framework.networking.server;
|
||||
|
||||
import org.toop.framework.game.gameThreads.ServerThreadBehaviour;
|
||||
import org.toop.framework.gameFramework.GameState;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
import org.toop.framework.networking.server.client.NettyClient;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Arrays;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
public class OnlineTurnBasedGame implements OnlineGame<TurnBasedGame> {
|
||||
|
||||
private long id;
|
||||
private NettyClient[] clients;
|
||||
private NettyClient[] admins;
|
||||
private TurnBasedGame game;
|
||||
private ServerThreadBehaviour gameThread;
|
||||
|
||||
private final CompletableFuture<Integer> resultFuture;
|
||||
|
||||
public OnlineTurnBasedGame(NettyClient[] admins, TurnBasedGame game, CompletableFuture<Integer> resultFuture, Duration timeOut, NettyClient... clients) {
|
||||
this.game = game;
|
||||
this.gameThread = new ServerThreadBehaviour(
|
||||
game,
|
||||
(pair) -> notifyMoveMade(pair.getLeft(), pair.getRight()),
|
||||
(pair) -> notifyGameEnd(pair.getLeft(), pair.getRight()),
|
||||
timeOut
|
||||
);
|
||||
this.resultFuture = resultFuture;
|
||||
this.clients = clients;
|
||||
this.admins = admins;
|
||||
}
|
||||
|
||||
private void notifyMoveMade(String speler, int move){
|
||||
for (NettyClient admin : admins) {
|
||||
admin.send(String.format("SVR GAME MOVE {PLAYER: \"%s\", MOVE: \"%s\", DETAILS: \"<reactie spel op zet>\"}", speler, move));
|
||||
}
|
||||
for (NettyClient client : clients) {
|
||||
client.send(String.format("SVR GAME MOVE {PLAYER: \"%s\", MOVE: \"%s\", DETAILS: \"<reactie spel op zet>\"}", speler, move));
|
||||
}
|
||||
}
|
||||
|
||||
private void notifyGameEnd(GameState state, int winner) {
|
||||
if (state == GameState.DRAW) {
|
||||
Arrays.stream(admins).forEach(a -> a.send("SVR GAME END"));
|
||||
|
||||
for (NettyClient client : clients) {
|
||||
client.send("SVR GAME DRAW {PLAYERONESCORE: \"<score speler1>\", PLAYERTWOSCORE: \"<score speler2>\", COMMENT: \"<comment>\"}");
|
||||
}
|
||||
} else {
|
||||
Arrays.stream(admins).forEach(a -> a.send("SVR GAME END"));
|
||||
clients[winner].send("SVR GAME WIN {PLAYERONESCORE: \"<score speler1>\", PLAYERTWOSCORE: \"<score speler2>\", COMMENT: \"<comment>\"}");
|
||||
clients[(winner+1)%2].send("SVR GAME LOSS {PLAYERONESCORE: \"<score speler1>\", PLAYERTWOSCORE: \"<score speler2>\", COMMENT: \"<comment>\"}");
|
||||
}
|
||||
|
||||
// Remove game from clients
|
||||
for (NettyClient client : clients) {
|
||||
admins = null;
|
||||
client.clearGame();
|
||||
}
|
||||
|
||||
if (resultFuture != null) {
|
||||
if (state.equals(GameState.DRAW)) resultFuture.complete(-1); // Return -1 if draw
|
||||
else resultFuture.complete(winner); // Return number for winner's index
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public long id() {
|
||||
return id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public org.toop.framework.gameFramework.model.game.TurnBasedGame game() {
|
||||
return game;
|
||||
}
|
||||
|
||||
@Override
|
||||
public NettyClient[] users() {
|
||||
return clients;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
this.gameThread.start();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
package org.toop.framework.networking.server;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import org.toop.framework.game.players.ServerPlayer;
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
import org.toop.framework.networking.server.challenges.gamechallenge.GameChallenge;
|
||||
import org.toop.framework.networking.server.challenges.gamechallenge.GameChallengeTimer;
|
||||
import org.toop.framework.networking.server.client.NettyClient;
|
||||
import org.toop.framework.networking.server.stores.ClientStore;
|
||||
import org.toop.framework.networking.server.stores.SubscriptionStore;
|
||||
import org.toop.framework.networking.server.stores.TurnBasedGameStore;
|
||||
import org.toop.framework.networking.server.stores.TurnBasedGameTypeStore;
|
||||
import org.toop.framework.networking.server.tournaments.*;
|
||||
import org.toop.framework.networking.server.tournaments.matchmakers.DoubleRoundRobinMatchMaker;
|
||||
import org.toop.framework.networking.server.tournaments.scoresystems.*;
|
||||
import org.toop.framework.utils.ImmutablePair;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.time.Duration;
|
||||
|
||||
public class Server implements GameServer<TurnBasedGame, NettyClient, Long> {
|
||||
|
||||
final private TurnBasedGameTypeStore gameTypesStore;
|
||||
final private ClientStore<Long, NettyClient> clientStore;
|
||||
final private List<GameChallenge> gameChallenges = new CopyOnWriteArrayList<>();
|
||||
final private TurnBasedGameStore gameStore;
|
||||
|
||||
final private SubscriptionStore subscriptionStore;
|
||||
|
||||
final private Duration challengeDuration;
|
||||
final private ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
|
||||
|
||||
private final List<NettyClient> admins = new ArrayList<>();
|
||||
|
||||
public Server(
|
||||
Duration challengeDuration,
|
||||
TurnBasedGameTypeStore turnBasedGameTypeStore,
|
||||
ClientStore<Long, NettyClient> clientStore,
|
||||
TurnBasedGameStore gameStore,
|
||||
SubscriptionStore subStore
|
||||
) {
|
||||
this.gameTypesStore = turnBasedGameTypeStore;
|
||||
this.challengeDuration = challengeDuration;
|
||||
this.clientStore = clientStore;
|
||||
this.gameStore = gameStore;
|
||||
this.subscriptionStore = subStore;
|
||||
|
||||
scheduler.schedule(this::serverTask, 0, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addClient(NettyClient client) {
|
||||
if (admins.isEmpty()) admins.addLast(client);
|
||||
clientStore.add(client);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeClient(NettyClient client) {
|
||||
admins.remove(client);
|
||||
clientStore.remove(client.id());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> gameTypes() {
|
||||
return new ArrayList<>(gameTypesStore.all().keySet());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<OnlineGame<TurnBasedGame>> ongoingGames() {
|
||||
return gameStore.all().stream().toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void challengeClient(String fromUser, String toUser, String gameType) {
|
||||
|
||||
NettyClient from = getUser(fromUser);
|
||||
if (from == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!gameTypesStore.all().containsKey(gameType)) {
|
||||
from.send("ERR gametype not found \n");
|
||||
return;
|
||||
}
|
||||
|
||||
NettyClient to = getUser(toUser);
|
||||
if (to == null) {
|
||||
from.send("ERR user not found \n");
|
||||
return;
|
||||
}
|
||||
|
||||
var ch = new GameChallenge(from, to, gameType, new GameChallengeTimer(challengeDuration));
|
||||
|
||||
to.send(
|
||||
"SVR GAME CHALLENGE {CHALLENGER: \"%s\", CHALLENGENUMBER: \"%s\", GAMETYPE: \"%s\"} \n"
|
||||
.formatted(from.name(), ch.id(), gameType)
|
||||
);
|
||||
|
||||
if (!isValidChallenge(ch)) {
|
||||
warnUserExpiredChallenge(from, ch.id());
|
||||
ch.forceExpire();
|
||||
return;
|
||||
}
|
||||
|
||||
gameChallenges.addLast(ch);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void acceptChallenge(Long challengeId) {
|
||||
for (var challenge : gameChallenges) {
|
||||
if (challenge.id() == challengeId) {
|
||||
startGame(challenge.acceptChallenge(), Duration.ofSeconds(10), challenge.getUsers());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void subscribeClient(String clientName, String gameTypeKey) {
|
||||
|
||||
if (!gameTypesStore.all().containsKey(gameTypeKey)) {
|
||||
return;
|
||||
}
|
||||
|
||||
subscriptionStore.add(new ImmutablePair<>(gameTypeKey, clientName));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unsubscribeClient(String clientName) {
|
||||
subscriptionStore.remove(clientName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public GameResultFuture startGame(String gameType, Duration turnTime, NettyClient... clients) {
|
||||
if (!gameTypesStore.all().containsKey(gameType)) return null;
|
||||
|
||||
try {
|
||||
|
||||
ServerPlayer[] players = new ServerPlayer[clients.length];
|
||||
|
||||
var gameResult = new CompletableFuture<Integer>();
|
||||
|
||||
var game = new OnlineTurnBasedGame(
|
||||
getAdmins().toArray(NettyClient[]::new),
|
||||
gameTypesStore.create(gameType),
|
||||
gameResult,
|
||||
turnTime,
|
||||
clients
|
||||
);
|
||||
|
||||
var grfReturn = new GameResultFuture(game, gameResult);
|
||||
|
||||
for (int i = 0; i < clients.length; i++) {
|
||||
players[i] = new ServerPlayer(clients[i]);
|
||||
clients[i].setGame(new ImmutablePair<>(game, players[i]));
|
||||
}
|
||||
|
||||
game.game().init(players);
|
||||
gameStore.add(game);
|
||||
|
||||
clients[0].send(String.format("SVR GAME MATCH {PLAYERTOMOVE: \"%s\", GAMETYPE: \"%s\", OPPONENT: \"%s\"}\n",
|
||||
clients[0].name(),
|
||||
gameType,
|
||||
clients[1].name()));
|
||||
clients[1].send(String.format("SVR GAME MATCH {PLAYERTOMOVE: \"%s\", GAMETYPE: \"%s\", OPPONENT: \"%s\"}\n",
|
||||
clients[0].name(),
|
||||
gameType,
|
||||
clients[0].name()));
|
||||
|
||||
game.start();
|
||||
return grfReturn;
|
||||
} catch (Exception e) {
|
||||
IO.println("ERROR: Failed to start OnlineTurnBasedGame");
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<NettyClient> onlineUsers() {
|
||||
return clientStore.all().stream().toList();
|
||||
}
|
||||
|
||||
public List<NettyClient> getAdmins() {
|
||||
return new ArrayList<>(admins); // Clone so the list can't be edited.
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown() {
|
||||
scheduler.shutdown();
|
||||
gameChallenges.clear();
|
||||
}
|
||||
|
||||
private void serverTask() {
|
||||
checkChallenges();
|
||||
checkSubscriptions();
|
||||
scheduler.schedule(this::serverTask, 500, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
private void checkChallenges() {
|
||||
for (int i = gameChallenges.size() - 1; i >= 0; i--) {
|
||||
var challenge = gameChallenges.get(i);
|
||||
|
||||
if (isValidChallenge(challenge)) continue;
|
||||
|
||||
if (challenge.isExpired()) {
|
||||
if (!challenge.isChallengeAccepted()) Arrays.stream(challenge.getUsers())
|
||||
.forEach(user -> warnUserExpiredChallenge(user, challenge.id()));
|
||||
|
||||
gameChallenges.remove(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void checkSubscriptions() {
|
||||
if (subscriptionStore.allKeys().isEmpty()) return;
|
||||
|
||||
Random ran = new Random();
|
||||
|
||||
for (String key : subscriptionStore.allKeys()) {
|
||||
List<String> userNames = (List<String>) subscriptionStore.allValues(key);
|
||||
if (userNames.size() < 2) continue;
|
||||
|
||||
while (userNames.size() > 1) {
|
||||
int left = ran.nextInt(userNames.size());
|
||||
int right;
|
||||
do {
|
||||
right = ran.nextInt(userNames.size());
|
||||
} while (left == right);
|
||||
|
||||
String userLeft = userNames.get(left);
|
||||
String userRight = userNames.get(right);
|
||||
|
||||
// Remove user if he is in a game
|
||||
boolean userInGame = false;
|
||||
|
||||
if (getUser(userLeft).game() != null) {
|
||||
userNames.remove(userLeft);
|
||||
userInGame = true;
|
||||
} else if (getUser(userRight).game() != null) {
|
||||
userNames.remove(userRight);
|
||||
userInGame = true;
|
||||
}
|
||||
|
||||
if (userInGame) { continue; }
|
||||
|
||||
int first = Math.max(left, right);
|
||||
int second = Math.min(left, right);
|
||||
|
||||
userNames.remove(first);
|
||||
userNames.remove(second);
|
||||
|
||||
startGame(key, Duration.ofSeconds(10), getUser(userLeft), getUser(userRight));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private NettyClient getUser(String username) {
|
||||
return clientStore.all().stream().filter(e -> e.name().equalsIgnoreCase(username)).findFirst().orElse(null);
|
||||
}
|
||||
|
||||
private NettyClient getUser(long id) {
|
||||
return clientStore.get(id);
|
||||
}
|
||||
|
||||
private void warnUserExpiredChallenge(NettyClient client, long challengeId) {
|
||||
client.send("SVR GAME CHALLENGE CANCELLED {CHALLENGENUMBER: \"" + challengeId + "\"}" + "\n");
|
||||
}
|
||||
|
||||
private boolean isValidChallenge(GameChallenge gameChallenge) { // TODO move to challenge class
|
||||
for (var user : gameChallenge.getUsers()) {
|
||||
if (clientStore.get(user.id()) == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (user.game() != null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (gameChallenge.isExpired()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public void startTournament(String gameType, NettyClient requestor, boolean shuffle) {
|
||||
if (!admins.contains(requestor)) {
|
||||
requestor.send("ERR you do not have the privileges to start a tournament");
|
||||
return;
|
||||
}
|
||||
|
||||
var tournamentUsers = new ArrayList<>(onlineUsers());
|
||||
tournamentUsers.removeIf(admins::contains);
|
||||
|
||||
Tournament tournament = new Tournament.Builder()
|
||||
.matchExecutor(this::startGame)
|
||||
.tournamentRunner(new AsyncTournamentRunner())
|
||||
.matchMaker(new DoubleRoundRobinMatchMaker())
|
||||
.addScoreSystem(new MatchCountScoreSystem())
|
||||
.addScoreSystem(new WinCountScoreSystem())
|
||||
.addScoreSystem(new DrawCountScoreSystem())
|
||||
.addScoreSystem(new LoseCountScoreSystem())
|
||||
.resultBroadcaster(this::endTournament)
|
||||
.turnTimeout(Duration.ofSeconds(10))
|
||||
.addPlayers(tournamentUsers.toArray(NettyClient[]::new))
|
||||
.addAdmins(admins.toArray(NettyClient[]::new))
|
||||
.build();
|
||||
|
||||
new Thread(() -> tournament.run(gameType)).start();
|
||||
}
|
||||
|
||||
public void endTournament(List<IntegerScoreSystem> systems) {
|
||||
if (systems.isEmpty()) return;
|
||||
|
||||
Map<String, List<ImmutablePair<String, Integer>>> combined = new HashMap<>();
|
||||
|
||||
for (var system : systems) {
|
||||
for (var player : system.getScore().keySet()) {
|
||||
combined.putIfAbsent(player.name(), new ArrayList<>());
|
||||
combined.get(player.name()).addLast(new ImmutablePair<>(system.scoreName(), system.getScore().get(player)));
|
||||
}
|
||||
}
|
||||
|
||||
List<String> names = new ArrayList<>();
|
||||
List<String> systemNames = new ArrayList<>();
|
||||
List<List<Integer>> scores = new ArrayList<>();
|
||||
|
||||
for (var player : combined.entrySet()) {
|
||||
names.addLast(player.getKey());
|
||||
scores.addLast(new ArrayList<>());
|
||||
for (var system : player.getValue()) {
|
||||
if (!systemNames.contains(system.getLeft())) systemNames.addLast(system.getLeft());
|
||||
scores.getLast().addLast(system.getRight());
|
||||
}
|
||||
}
|
||||
|
||||
Gson gson = new Gson();
|
||||
|
||||
String namesJson = gson.toJson(names);
|
||||
String systemNamesJson = gson.toJson(systemNames);
|
||||
String scoresJson = gson.toJson(scores);
|
||||
|
||||
String msg = String.format(
|
||||
"SVR RESULTS {GAMETYPE: \"%s\", USERS: %s, SCORETYPES: %s, SCORES: %s, TOURNAMENT: 1}",
|
||||
"none", // TODO gametype
|
||||
namesJson,
|
||||
systemNamesJson,
|
||||
scoresJson
|
||||
);
|
||||
|
||||
for (var user : onlineUsers()) {
|
||||
user.send(msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package org.toop.framework.networking.server.challenges.gamechallenge;
|
||||
|
||||
import org.toop.framework.SnowflakeGenerator;
|
||||
import org.toop.framework.networking.server.client.NettyClient;
|
||||
import org.toop.framework.utils.SimpleTimer;
|
||||
|
||||
public class GameChallenge {
|
||||
private final long id = SnowflakeGenerator.nextId(); // I don't need this, but the tournament server uses it...
|
||||
|
||||
private final NettyClient from;
|
||||
private final NettyClient to;
|
||||
private final String gameType;
|
||||
private final SimpleTimer timer;
|
||||
|
||||
private boolean isChallengeAccepted = false;
|
||||
|
||||
public GameChallenge(NettyClient from, NettyClient to, String gameType, SimpleTimer timer) {
|
||||
this.from = from;
|
||||
this.to = to;
|
||||
this.gameType = gameType;
|
||||
this.timer = timer;
|
||||
}
|
||||
|
||||
public long id() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public NettyClient[] getUsers() {
|
||||
return new NettyClient[]{from, to};
|
||||
}
|
||||
|
||||
public void forceExpire() {
|
||||
timer.forceExpire();
|
||||
}
|
||||
|
||||
public String acceptChallenge() {
|
||||
isChallengeAccepted = true;
|
||||
timer.forceExpire();
|
||||
return gameType;
|
||||
}
|
||||
|
||||
public boolean isChallengeAccepted() {
|
||||
return isChallengeAccepted;
|
||||
}
|
||||
|
||||
public boolean isExpired() {
|
||||
return timer.isExpired();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package org.toop.framework.networking.server.challenges.gamechallenge;
|
||||
|
||||
import org.toop.framework.utils.SimpleTimer;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.Duration;
|
||||
|
||||
public class GameChallengeTimer implements SimpleTimer {
|
||||
|
||||
private final Instant createdAt;
|
||||
private final Duration timeout;
|
||||
|
||||
private boolean isExpired = false;
|
||||
|
||||
public GameChallengeTimer(Duration duration) {
|
||||
this.createdAt = Instant.now();
|
||||
this.timeout = duration;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void forceExpire() {
|
||||
this.isExpired = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isExpired() {
|
||||
if (this.isExpired) return true;
|
||||
return Instant.now().isAfter(createdAt.plus(timeout));
|
||||
}
|
||||
|
||||
@Override
|
||||
public long secondsRemaining() {
|
||||
return Duration.between(Instant.now(), createdAt.plus(timeout)).toSeconds();
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user