mirror of
https://github.com/2OOP/pism.git
synced 2026-02-04 19:04:49 +00:00
Compare commits
12 Commits
223-create
...
96afc9543a
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
96afc9543a | ||
|
|
0c1b106da5 | ||
|
|
aca0b2dcc0 | ||
|
|
75963a891b | ||
|
|
6b644ed8fa | ||
|
|
6a395cc40b | ||
|
|
5e5948d1fe | ||
|
|
9c01aabbe1 | ||
|
|
0cb52b042f | ||
|
|
56a8d12e46 | ||
| 65220d9649 | |||
|
|
c64a2e2c65 |
@@ -19,9 +19,10 @@ import org.toop.framework.networking.connection.clients.TournamentNetworkingClie
|
|||||||
import org.toop.framework.networking.connection.events.NetworkEvents;
|
import org.toop.framework.networking.connection.events.NetworkEvents;
|
||||||
import org.toop.framework.networking.connection.types.NetworkingConnector;
|
import org.toop.framework.networking.connection.types.NetworkingConnector;
|
||||||
import org.toop.framework.networking.server.gateway.NettyGatewayServer;
|
import org.toop.framework.networking.server.gateway.NettyGatewayServer;
|
||||||
import org.toop.game.players.LocalPlayer;
|
import org.toop.framework.game.players.LocalPlayer;
|
||||||
import org.toop.local.AppContext;
|
import org.toop.local.AppContext;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.concurrent.CopyOnWriteArrayList;
|
import java.util.concurrent.CopyOnWriteArrayList;
|
||||||
import java.util.concurrent.Executors;
|
import java.util.concurrent.Executors;
|
||||||
@@ -117,7 +118,8 @@ public final class Server {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
primary = new ServerView(user, this::sendChallenge, clientId);
|
primary = new ServerView(user, this::sendChallenge, user, clientId);
|
||||||
|
|
||||||
WidgetContainer.getCurrentView().transitionNextCustom(primary, "disconnect", this::disconnect);
|
WidgetContainer.getCurrentView().transitionNextCustom(primary, "disconnect", this::disconnect);
|
||||||
|
|
||||||
a.unsubscribe("connecting");
|
a.unsubscribe("connecting");
|
||||||
@@ -159,7 +161,8 @@ public final class Server {
|
|||||||
.listen(NetworkEvents.GameResultResponse.class, this::handleGameResult, false, "game-result")
|
.listen(NetworkEvents.GameResultResponse.class, this::handleGameResult, false, "game-result")
|
||||||
.listen(NetworkEvents.GameMoveResponse.class, this::handleReceivedMove, false, "game-move")
|
.listen(NetworkEvents.GameMoveResponse.class, this::handleReceivedMove, false, "game-move")
|
||||||
.listen(NetworkEvents.YourTurnResponse.class, this::handleYourTurn, false, "your-turn")
|
.listen(NetworkEvents.YourTurnResponse.class, this::handleYourTurn, false, "your-turn")
|
||||||
.listen(NetworkEvents.ClosedConnection.class, this::closedConnection, false, "closed-connection");
|
.listen(NetworkEvents.ClosedConnection.class, this::closedConnection, false, "closed-connection")
|
||||||
|
.listen(NetworkEvents.TournamentResultResponse.class, this::handleTournamentResult, false, "tournament-result");
|
||||||
|
|
||||||
connectFlow = a;
|
connectFlow = a;
|
||||||
}
|
}
|
||||||
@@ -196,30 +199,21 @@ public final class Server {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
final int myTurn = response.playerToMove().equalsIgnoreCase(response.opponent()) ? 1 : 0;
|
final String startingPlayer = response.playerToMove();
|
||||||
|
final int userStartingTurn = startingPlayer.equalsIgnoreCase(user) ? 0 : 1;
|
||||||
|
final int opponentStartingTurn = 1 - userStartingTurn;
|
||||||
|
|
||||||
final GameInformation information = new GameInformation(type);
|
final GameInformation information = new GameInformation(type);
|
||||||
//information.players[0] = playerInformation;
|
information.players[userStartingTurn].name = user;
|
||||||
information.players[0].name = user;
|
information.players[opponentStartingTurn].name = response.opponent();
|
||||||
information.players[0].isHuman = true; // Make false and uncomment/comment code at lines HERE To make use of AI.
|
|
||||||
// information.players[0].computerDifficulty = 5; // HERE
|
Player[] players = new Player[2];
|
||||||
// information.players[0].computerThinkTime = 1; // HERE
|
players[userStartingTurn] = new LocalPlayer(user);
|
||||||
information.players[1].name = response.opponent();
|
players[opponentStartingTurn] = new OnlinePlayer(response.opponent());
|
||||||
|
|
||||||
switch (type) {
|
switch (type) {
|
||||||
case TICTACTOE -> {
|
case TICTACTOE -> gameController = new TicTacToeBitController(players);
|
||||||
Player[] players = new Player[2];
|
case REVERSI -> gameController = new ReversiBitController(players);
|
||||||
players[Math.abs(myTurn-1)] = new OnlinePlayer(response.opponent());
|
|
||||||
players[myTurn] = new LocalPlayer(user); // HERE
|
|
||||||
// players[myTurn] = new ArtificialPlayer(new RandomAI(), user); // HERE
|
|
||||||
gameController = new TicTacToeBitController(players);
|
|
||||||
}
|
|
||||||
case REVERSI -> {
|
|
||||||
Player[] players = new Player[2];
|
|
||||||
players[Math.abs(myTurn-1)] = new OnlinePlayer(response.opponent());
|
|
||||||
players[myTurn] = new LocalPlayer(user); // HERE
|
|
||||||
// players[myTurn] = new ArtificialPlayer(new RandomAI(), user); // HERE
|
|
||||||
gameController = new ReversiBitController(players);}
|
|
||||||
default -> new ErrorPopup("Unsupported game type.");
|
default -> new ErrorPopup("Unsupported game type.");
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -247,6 +241,12 @@ public final class Server {
|
|||||||
gameController.gameFinished(response);
|
gameController.gameFinished(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void handleTournamentResult(NetworkEvents.TournamentResultResponse response) {
|
||||||
|
IO.println(response.gameType());
|
||||||
|
IO.println(Arrays.toString(response.names()));
|
||||||
|
IO.println(Arrays.toString(response.scores()));
|
||||||
|
}
|
||||||
|
|
||||||
private void handleReceivedMove(NetworkEvents.GameMoveResponse response) {
|
private void handleReceivedMove(NetworkEvents.GameMoveResponse response) {
|
||||||
if (gameController == null) {
|
if (gameController == null) {
|
||||||
return;
|
return;
|
||||||
@@ -346,7 +346,8 @@ public final class Server {
|
|||||||
|
|
||||||
private void gamesListFromServerHandler(NetworkEvents.GamelistResponse event) {
|
private void gamesListFromServerHandler(NetworkEvents.GamelistResponse event) {
|
||||||
gameList.clear();
|
gameList.clear();
|
||||||
var gl = List.of(event.gamelist());
|
var gl = new java.util.ArrayList<>(List.of(event.gamelist()));
|
||||||
|
gl.sort(String::compareTo);
|
||||||
gameList.addAll(gl);
|
gameList.addAll(gl);
|
||||||
primary.updateGameList(gl);
|
primary.updateGameList(gl);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -78,6 +78,7 @@ public abstract class BitGameCanvas implements GameCanvas {
|
|||||||
}
|
}
|
||||||
|
|
||||||
canvas.setOnMouseClicked(event -> {
|
canvas.setOnMouseClicked(event -> {
|
||||||
|
|
||||||
if (event.getButton() != MouseButton.PRIMARY) {
|
if (event.getButton() != MouseButton.PRIMARY) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -93,9 +94,6 @@ public abstract class BitGameCanvas implements GameCanvas {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
render();
|
render();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ import org.toop.framework.gameFramework.model.game.threadBehaviour.ThreadBehavio
|
|||||||
import org.toop.framework.gameFramework.model.player.Player;
|
import org.toop.framework.gameFramework.model.player.Player;
|
||||||
import org.toop.framework.gameFramework.view.GUIEvents;
|
import org.toop.framework.gameFramework.view.GUIEvents;
|
||||||
import org.toop.framework.networking.connection.events.NetworkEvents;
|
import org.toop.framework.networking.connection.events.NetworkEvents;
|
||||||
import org.toop.game.players.LocalPlayer;
|
import org.toop.framework.game.players.LocalPlayer;
|
||||||
|
|
||||||
public class GenericGameController implements GameController {
|
public class GenericGameController implements GameController {
|
||||||
protected final EventFlow eventFlow = new EventFlow();
|
protected final EventFlow eventFlow = new EventFlow();
|
||||||
@@ -35,14 +35,16 @@ public class GenericGameController implements GameController {
|
|||||||
|
|
||||||
// TODO: Change gameType to automatically happen with either dependency injection or something else.
|
// TODO: Change gameType to automatically happen with either dependency injection or something else.
|
||||||
public GenericGameController(GameCanvas canvas, TurnBasedGame game, ThreadBehaviour gameThreadBehaviour, String gameType) {
|
public GenericGameController(GameCanvas canvas, TurnBasedGame game, ThreadBehaviour gameThreadBehaviour, String gameType) {
|
||||||
logger.info("Creating: " + this.getClass());
|
logger.info("Creating: {}", this.getClass());
|
||||||
|
|
||||||
this.canvas = canvas;
|
this.canvas = canvas;
|
||||||
this.game = game;
|
this.game = game;
|
||||||
this.gameThreadBehaviour = gameThreadBehaviour;
|
this.gameThreadBehaviour = gameThreadBehaviour;
|
||||||
|
|
||||||
// Tell thread how to send moves
|
// Tell thread how to send moves
|
||||||
this.gameThreadBehaviour.setOnSendMove((id, m) -> GlobalEventBus.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
|
// Tell thread how to update UI
|
||||||
this.gameThreadBehaviour.setOnUpdateUI(() -> Platform.runLater(this::updateUI));
|
this.gameThreadBehaviour.setOnUpdateUI(() -> Platform.runLater(this::updateUI));
|
||||||
@@ -53,21 +55,37 @@ public class GenericGameController implements GameController {
|
|||||||
WidgetContainer.getCurrentView().transitionNext(gameView, true);
|
WidgetContainer.getCurrentView().transitionNext(gameView, true);
|
||||||
|
|
||||||
// Listen to updates
|
// Listen to updates
|
||||||
|
logger.info("Game controller started listening");
|
||||||
eventFlow
|
eventFlow
|
||||||
.listen(GUIEvents.GameEnded.class, this::onGameFinish, false)
|
.listen(GUIEvents.GameEnded.class, this::onGameFinish, false)
|
||||||
.listen(GUIEvents.PlayerAttemptedMove.class, event -> {if (getCurrentPlayer() instanceof LocalPlayer 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(){
|
public void start(){
|
||||||
logger.info("Starting GameManager");
|
logger.info("Starting GameManager");
|
||||||
updateUI();
|
updateUI();
|
||||||
gameThreadBehaviour.start();
|
gameThreadBehaviour.start();
|
||||||
|
logger.info("GameManager started");
|
||||||
}
|
}
|
||||||
|
|
||||||
public void stop(){
|
public void stop(){
|
||||||
logger.info("Stopping GameManager");
|
logger.info("Stopping GameManager");
|
||||||
removeListeners();
|
removeListeners();
|
||||||
gameThreadBehaviour.stop();
|
gameThreadBehaviour.stop();
|
||||||
|
logger.info("GameManager stopped");
|
||||||
}
|
}
|
||||||
|
|
||||||
public Player getCurrentPlayer(){
|
public Player getCurrentPlayer(){
|
||||||
@@ -98,7 +116,7 @@ public class GenericGameController implements GameController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public Player getPlayer(int player){
|
public Player getPlayer(int player){
|
||||||
if (player < 0 || player >= 2){ // TODO: Make game turn player count
|
if (player < 0 || player > game.getPlayerCount()-1){ // TODO: Make game turn player count
|
||||||
logger.error("Invalid player index");
|
logger.error("Invalid player index");
|
||||||
throw new IllegalArgumentException("player out of range");
|
throw new IllegalArgumentException("player out of range");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import org.toop.framework.game.gameThreads.LocalThreadBehaviour;
|
|||||||
import org.toop.framework.game.gameThreads.OnlineThreadBehaviour;
|
import org.toop.framework.game.gameThreads.OnlineThreadBehaviour;
|
||||||
import org.toop.framework.game.games.tictactoe.BitboardTicTacToe;
|
import org.toop.framework.game.games.tictactoe.BitboardTicTacToe;
|
||||||
import org.toop.framework.game.players.OnlinePlayer;
|
import org.toop.framework.game.players.OnlinePlayer;
|
||||||
import org.toop.framework.networking.server.OnlineGame;
|
|
||||||
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
|
|
||||||
@@ -19,6 +18,6 @@ public class TicTacToeBitController extends GenericGameController {
|
|||||||
ThreadBehaviour thread = Arrays.stream(players).anyMatch(e -> e instanceof OnlinePlayer) ?
|
ThreadBehaviour thread = Arrays.stream(players).anyMatch(e -> e instanceof OnlinePlayer) ?
|
||||||
new OnlineThreadBehaviour(game) : new LocalThreadBehaviour(game);
|
new OnlineThreadBehaviour(game) : new LocalThreadBehaviour(game);
|
||||||
|
|
||||||
super(new TicTacToeBitCanvas(), game, thread , "TicTacToe");
|
super(new TicTacToeBitCanvas(), game, thread, "TicTacToe");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ import org.toop.app.widget.complex.PlayerInfoWidget;
|
|||||||
import org.toop.app.widget.complex.ViewWidget;
|
import org.toop.app.widget.complex.ViewWidget;
|
||||||
import org.toop.app.widget.popup.ErrorPopup;
|
import org.toop.app.widget.popup.ErrorPopup;
|
||||||
import org.toop.app.widget.tutorial.*;
|
import org.toop.app.widget.tutorial.*;
|
||||||
import org.toop.game.players.LocalPlayer;
|
import org.toop.framework.game.players.LocalPlayer;
|
||||||
import org.toop.game.players.ai.MCTSAI;
|
import org.toop.game.players.ai.MCTSAI;
|
||||||
import org.toop.game.players.ai.MCTSAI2;
|
import org.toop.game.players.ai.MCTSAI2;
|
||||||
import org.toop.game.players.ai.MCTSAI3;
|
import org.toop.game.players.ai.MCTSAI3;
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ import javafx.scene.control.ComboBox;
|
|||||||
import org.toop.app.widget.Primitive;
|
import org.toop.app.widget.Primitive;
|
||||||
import org.toop.app.widget.complex.ViewWidget;
|
import org.toop.app.widget.complex.ViewWidget;
|
||||||
|
|
||||||
|
import java.io.Reader;
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
import java.util.function.Consumer;
|
import java.util.function.Consumer;
|
||||||
@@ -15,6 +17,7 @@ import javafx.geometry.Pos;
|
|||||||
import javafx.scene.control.Button;
|
import javafx.scene.control.Button;
|
||||||
import javafx.scene.control.ListView;
|
import javafx.scene.control.ListView;
|
||||||
import org.toop.framework.eventbus.EventFlow;
|
import org.toop.framework.eventbus.EventFlow;
|
||||||
|
import org.toop.framework.eventbus.GlobalEventBus;
|
||||||
import org.toop.framework.networking.connection.events.NetworkEvents;
|
import org.toop.framework.networking.connection.events.NetworkEvents;
|
||||||
|
|
||||||
public final class ServerView extends ViewWidget {
|
public final class ServerView extends ViewWidget {
|
||||||
@@ -22,32 +25,34 @@ public final class ServerView extends ViewWidget {
|
|||||||
private final Consumer<String> onPlayerClicked;
|
private final Consumer<String> onPlayerClicked;
|
||||||
private final long clientId;
|
private final long clientId;
|
||||||
|
|
||||||
private final ComboBox<String> gameList;
|
private final ComboBox<String> gameListSub;
|
||||||
|
private final ComboBox<String> gameListTour;
|
||||||
private final ListView<Button> listView;
|
private final ListView<Button> listView;
|
||||||
private Button subscribeButton;
|
private Button subscribeButton;
|
||||||
|
|
||||||
public ServerView(String user, Consumer<String> onPlayerClicked, long clientId) {
|
public ServerView(String user, Consumer<String> onPlayerClicked, String userName, long clientId) {
|
||||||
this.user = user;
|
this.user = user;
|
||||||
this.onPlayerClicked = onPlayerClicked;
|
this.onPlayerClicked = onPlayerClicked;
|
||||||
this.clientId = clientId;
|
this.clientId = clientId;
|
||||||
|
|
||||||
this.gameList = new ComboBox<>();
|
this.gameListSub = new ComboBox<>();
|
||||||
|
this.gameListTour = new ComboBox<>();
|
||||||
this.listView = new ListView<>();
|
this.listView = new ListView<>();
|
||||||
|
|
||||||
setupLayout();
|
setupLayout(userName);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void setupLayout() {
|
private void setupLayout(String userName) {
|
||||||
var playerHeader = Primitive.header(user, false);
|
var playerHeader = Primitive.header(user, false);
|
||||||
|
|
||||||
subscribeButton = Primitive.button(
|
subscribeButton = Primitive.button(
|
||||||
"subscribe",
|
"subscribe",
|
||||||
() -> new EventFlow().addPostEvent(new NetworkEvents.SendSubscribe(clientId, gameList.getValue())).postEvent(),
|
() -> new EventFlow().addPostEvent(new NetworkEvents.SendSubscribe(clientId, gameListSub.getValue())).postEvent(),
|
||||||
false,
|
false,
|
||||||
true
|
true
|
||||||
); // TODO localize
|
); // TODO localize
|
||||||
|
|
||||||
var subscribe = Primitive.hbox(gameList, subscribeButton);
|
var subscribe = Primitive.hbox(gameListSub, subscribeButton);
|
||||||
|
|
||||||
var playerListSection = Primitive.vbox(
|
var playerListSection = Primitive.vbox(
|
||||||
playerHeader,
|
playerHeader,
|
||||||
@@ -58,6 +63,20 @@ public final class ServerView extends ViewWidget {
|
|||||||
|
|
||||||
add(Pos.CENTER, playerListSection);
|
add(Pos.CENTER, playerListSection);
|
||||||
|
|
||||||
|
if (userName.equals("host")) {
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
var disconnectButton = Primitive.button(
|
var disconnectButton = Primitive.button(
|
||||||
"disconnect", () -> transitionPrevious(), false);
|
"disconnect", () -> transitionPrevious(), false);
|
||||||
|
|
||||||
@@ -77,9 +96,13 @@ public final class ServerView extends ViewWidget {
|
|||||||
|
|
||||||
public void updateGameList(List<String> games) {
|
public void updateGameList(List<String> games) {
|
||||||
Platform.runLater(() -> {
|
Platform.runLater(() -> {
|
||||||
gameList.getItems().clear();
|
gameListSub.getItems().clear();
|
||||||
gameList.setItems(FXCollections.observableArrayList(games));
|
gameListSub.setItems(FXCollections.observableArrayList(games));
|
||||||
gameList.getSelectionModel().select(0);
|
gameListSub.getSelectionModel().select(0);
|
||||||
|
|
||||||
|
gameListTour.getItems().clear();
|
||||||
|
gameListTour.setItems(FXCollections.observableArrayList(games));
|
||||||
|
gameListTour.getSelectionModel().select(0);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -415,11 +415,9 @@ public class EventFlow {
|
|||||||
/**
|
/**
|
||||||
* Posts the event added through {@link #addPostEvent} asynchronously.
|
* Posts the event added through {@link #addPostEvent} asynchronously.
|
||||||
*
|
*
|
||||||
* @deprecated use {@link #postEvent()} instead.
|
|
||||||
*/
|
*/
|
||||||
@Deprecated
|
|
||||||
public EventFlow asyncPostEvent() {
|
public EventFlow asyncPostEvent() {
|
||||||
eventBus.post(this.event);
|
GlobalEventBus.get().post(this.event);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,15 +1,20 @@
|
|||||||
package org.toop.framework.eventbus;
|
package org.toop.framework.eventbus;
|
||||||
|
|
||||||
import org.apache.logging.log4j.LogManager;
|
import org.apache.logging.log4j.LogManager;
|
||||||
|
import org.toop.framework.eventbus.bus.AsyncEventBus;
|
||||||
|
import org.toop.framework.eventbus.bus.DefaultEventBus;
|
||||||
import org.toop.framework.eventbus.bus.DisruptorEventBus;
|
import org.toop.framework.eventbus.bus.DisruptorEventBus;
|
||||||
import org.toop.framework.eventbus.bus.EventBus;
|
import org.toop.framework.eventbus.bus.EventBus;
|
||||||
import org.toop.framework.eventbus.events.EventType;
|
import org.toop.framework.eventbus.events.EventType;
|
||||||
import org.toop.framework.eventbus.store.DefaultSubscriberStore;
|
import org.toop.framework.eventbus.store.DefaultSubscriberStore;
|
||||||
import org.toop.framework.eventbus.subscriber.Subscriber;
|
import org.toop.framework.eventbus.subscriber.Subscriber;
|
||||||
|
|
||||||
public class GlobalEventBus implements EventBus {
|
import java.util.concurrent.ExecutorService;
|
||||||
private static final EventBus INSTANCE = new DisruptorEventBus(
|
import java.util.concurrent.Executors;
|
||||||
LogManager.getLogger(DisruptorEventBus.class),
|
|
||||||
|
public class GlobalEventBus implements AsyncEventBus {
|
||||||
|
private static final AsyncEventBus INSTANCE = new DefaultEventBus(
|
||||||
|
LogManager.getLogger(DefaultEventBus.class),
|
||||||
new DefaultSubscriberStore()
|
new DefaultSubscriberStore()
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -34,6 +39,11 @@ public class GlobalEventBus implements EventBus {
|
|||||||
INSTANCE.post(event);
|
INSTANCE.post(event);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public <T extends EventType> void asyncPost(T event) {
|
||||||
|
INSTANCE.asyncPost(event);
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void shutdown() {
|
public void shutdown() {
|
||||||
INSTANCE.shutdown();
|
INSTANCE.shutdown();
|
||||||
@@ -43,4 +53,5 @@ public class GlobalEventBus implements EventBus {
|
|||||||
public void reset() {
|
public void reset() {
|
||||||
INSTANCE.reset();
|
INSTANCE.reset();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package org.toop.framework.eventbus.bus;
|
||||||
|
|
||||||
|
import org.toop.framework.eventbus.events.EventType;
|
||||||
|
|
||||||
|
public interface AsyncEventBus extends EventBus {
|
||||||
|
<T extends EventType> void asyncPost(T event);
|
||||||
|
}
|
||||||
@@ -5,12 +5,16 @@ import org.toop.framework.eventbus.events.EventType;
|
|||||||
import org.toop.framework.eventbus.store.SubscriberStore;
|
import org.toop.framework.eventbus.store.SubscriberStore;
|
||||||
import org.toop.framework.eventbus.subscriber.Subscriber;
|
import org.toop.framework.eventbus.subscriber.Subscriber;
|
||||||
|
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
import java.util.function.Consumer;
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
public class DefaultEventBus implements EventBus {
|
public class DefaultEventBus implements AsyncEventBus {
|
||||||
private final Logger logger;
|
private final Logger logger;
|
||||||
private final SubscriberStore eventsHolder;
|
private final SubscriberStore eventsHolder;
|
||||||
|
|
||||||
|
private final ExecutorService asyncExecutor = Executors.newCachedThreadPool();
|
||||||
|
|
||||||
public DefaultEventBus(Logger logger, SubscriberStore eventsHolder) {
|
public DefaultEventBus(Logger logger, SubscriberStore eventsHolder) {
|
||||||
this.logger = logger;
|
this.logger = logger;
|
||||||
this.eventsHolder = eventsHolder;
|
this.eventsHolder = eventsHolder;
|
||||||
@@ -36,11 +40,16 @@ public class DefaultEventBus implements EventBus {
|
|||||||
Class<T> eventClass = (Class<T>) subscriber.event();
|
Class<T> eventClass = (Class<T>) subscriber.event();
|
||||||
Consumer<EventType> action = (Consumer<EventType>) subscriber.handler();
|
Consumer<EventType> action = (Consumer<EventType>) subscriber.handler();
|
||||||
|
|
||||||
action.accept((EventType) eventClass.cast(event));
|
action.accept(eventClass.cast(event));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public <T extends EventType> void asyncPost(T event) {
|
||||||
|
asyncExecutor.submit(() -> post(event));
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void shutdown() {
|
public void shutdown() {
|
||||||
eventsHolder.reset();
|
eventsHolder.reset();
|
||||||
@@ -50,4 +59,5 @@ public class DefaultEventBus implements EventBus {
|
|||||||
public void reset() {
|
public void reset() {
|
||||||
eventsHolder.reset();
|
eventsHolder.reset();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -47,9 +47,11 @@ public abstract class BitboardGame implements TurnBasedGame {
|
|||||||
|
|
||||||
this.playerBitboard = other.playerBitboard.clone();
|
this.playerBitboard = other.playerBitboard.clone();
|
||||||
this.currentTurn = other.currentTurn;
|
this.currentTurn = other.currentTurn;
|
||||||
this.players = Arrays.stream(other.players)
|
this.players = other.players;
|
||||||
.map(Player::deepCopy)
|
// TODO: Players are not deep copied, which is bad. I don't know why but deepcopying breaks it. Fix it
|
||||||
.toArray(Player[]::new);
|
//this.players = Arrays.stream(other.players)
|
||||||
|
// .map(Player::deepCopy)
|
||||||
|
// .toArray(Player[]::new);
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getColumnSize() {
|
public int getColumnSize() {
|
||||||
|
|||||||
@@ -8,6 +8,9 @@ import org.toop.framework.gameFramework.model.game.threadBehaviour.SupportsOnlin
|
|||||||
import org.toop.framework.gameFramework.model.player.Player;
|
import org.toop.framework.gameFramework.model.player.Player;
|
||||||
import org.toop.framework.game.players.OnlinePlayer;
|
import org.toop.framework.game.players.OnlinePlayer;
|
||||||
|
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handles online multiplayer game logic.
|
* Handles online multiplayer game logic.
|
||||||
* <p>
|
* <p>
|
||||||
@@ -15,6 +18,9 @@ import org.toop.framework.game.players.OnlinePlayer;
|
|||||||
* for the local player while receiving moves from other players.
|
* for the local player while receiving moves from other players.
|
||||||
*/
|
*/
|
||||||
public class OnlineThreadBehaviour extends AbstractThreadBehaviour implements SupportsOnlinePlay {
|
public class OnlineThreadBehaviour extends AbstractThreadBehaviour implements SupportsOnlinePlay {
|
||||||
|
|
||||||
|
private ExecutorService moveExecutor = Executors.newSingleThreadExecutor();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates behaviour and sets the first local player
|
* Creates behaviour and sets the first local player
|
||||||
* (non-online player) from the given array.
|
* (non-online player) from the given array.
|
||||||
@@ -51,8 +57,30 @@ public class OnlineThreadBehaviour extends AbstractThreadBehaviour implements Su
|
|||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public void onYourTurn(long clientId) {
|
public void onYourTurn(long clientId) {
|
||||||
if (!isRunning.get()) return;
|
logger.info("Yourturn");
|
||||||
long move = game.getPlayer(game.getCurrentTurn()).getMove(game.deepCopy());
|
if (!isRunning.get()) {
|
||||||
|
logger.warn("Game is not running!");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
TurnBasedGame gameCopy = game.deepCopy();
|
||||||
|
if (gameCopy == null) {
|
||||||
|
logger.error("Could not deep copy game");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
logger.info("Successfully collected game copy");
|
||||||
|
|
||||||
|
Player player = gameCopy.getPlayer(game.getCurrentTurn());
|
||||||
|
if (player == null) {
|
||||||
|
logger.error("Could not find current turn's player");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
logger.info("Successfully collected current turn's player");
|
||||||
|
|
||||||
|
long move = player.getMove(gameCopy);
|
||||||
|
logger.info("Move set: {}", move);
|
||||||
|
logger.info("Completed onYourTurn");
|
||||||
|
|
||||||
sendMove(clientId, move);
|
sendMove(clientId, move);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,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.game.TurnBasedGame;
|
||||||
import org.toop.framework.gameFramework.model.player.AbstractPlayer;
|
import org.toop.framework.gameFramework.model.player.AbstractPlayer;
|
||||||
@@ -45,11 +45,16 @@ public class LocalPlayer extends AbstractPlayer {
|
|||||||
long legalMoves = gameCopy.getLegalMoves();
|
long legalMoves = gameCopy.getLegalMoves();
|
||||||
long move;
|
long move;
|
||||||
|
|
||||||
do {
|
try {
|
||||||
move = getLastMove();
|
do {
|
||||||
} while ((legalMoves & move) == 0);
|
move = getLastMove();
|
||||||
|
IO.println("GETTING MOVE");
|
||||||
return move;
|
} while ((legalMoves & move) == 0);
|
||||||
|
return move;
|
||||||
|
} catch (Exception e) {
|
||||||
|
IO.println(e);
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -65,6 +65,9 @@ public class NetworkEvents extends EventsBase {
|
|||||||
public record GameResultResponse(long clientId, String condition)
|
public record GameResultResponse(long clientId, String condition)
|
||||||
implements GenericEvent {}
|
implements GenericEvent {}
|
||||||
|
|
||||||
|
public record TournamentResultResponse(long clientId, String gameType, String[] names, Integer[] scores)
|
||||||
|
implements GenericEvent {}
|
||||||
|
|
||||||
/** Indicates that a game move has been processed or received. */
|
/** Indicates that a game move has been processed or received. */
|
||||||
public record GameMoveResponse(long clientId, String player, String move, String details)
|
public record GameMoveResponse(long clientId, String player, String move, String details)
|
||||||
implements GenericEvent {}
|
implements GenericEvent {}
|
||||||
@@ -219,4 +222,5 @@ public class NetworkEvents extends EventsBase {
|
|||||||
/** Response to a {@link ChangeAddress} event, carrying the success result. */
|
/** Response to a {@link ChangeAddress} event, carrying the success result. */
|
||||||
public record ChangeAddressResponse(boolean successful, long identifier)
|
public record ChangeAddressResponse(boolean successful, long identifier)
|
||||||
implements ResponseToUniqueEvent {}
|
implements ResponseToUniqueEvent {}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package org.toop.framework.networking.connection.handlers;
|
|||||||
import io.netty.channel.ChannelHandlerContext;
|
import io.netty.channel.ChannelHandlerContext;
|
||||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
import java.util.regex.MatchResult;
|
import java.util.regex.MatchResult;
|
||||||
import java.util.regex.Matcher;
|
import java.util.regex.Matcher;
|
||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
@@ -94,6 +95,9 @@ public class NetworkingGameClientHandler extends ChannelInboundHandlerAdapter {
|
|||||||
case "HELP":
|
case "HELP":
|
||||||
helpHandler(recSrvRemoved);
|
helpHandler(recSrvRemoved);
|
||||||
return;
|
return;
|
||||||
|
case "RESULTS":
|
||||||
|
resultsHandler(recSrvRemoved);
|
||||||
|
return;
|
||||||
default:
|
default:
|
||||||
// return
|
// return
|
||||||
}
|
}
|
||||||
@@ -103,6 +107,34 @@ 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) {
|
||||||
|
IO.println(rec);
|
||||||
|
|
||||||
|
String gameTypeRaw = extract(rec, "GAMETYPE");
|
||||||
|
String usersRaw = extract(rec, "USERS");
|
||||||
|
String scoresRaw = extract(rec, "SCORES");
|
||||||
|
|
||||||
|
String[] users = Arrays.stream(usersRaw.substring(1, usersRaw.length() - 1).split(","))
|
||||||
|
.map(s -> s.trim().replace("\"", ""))
|
||||||
|
.toArray(String[]::new);
|
||||||
|
|
||||||
|
Integer[] scores = Arrays.stream(scoresRaw.substring(1, scoresRaw.length() - 1).split(","))
|
||||||
|
.map(String::trim)
|
||||||
|
.map(Integer::parseInt)
|
||||||
|
.toArray(Integer[]::new);
|
||||||
|
|
||||||
|
eventBus.post(new NetworkEvents.TournamentResultResponse(this.connectionId, gameTypeRaw, users, scores));
|
||||||
|
}
|
||||||
|
|
||||||
private void gameMoveHandler(String rec) {
|
private void gameMoveHandler(String rec) {
|
||||||
String[] msg =
|
String[] msg =
|
||||||
Pattern.compile(
|
Pattern.compile(
|
||||||
|
|||||||
@@ -1,9 +1,12 @@
|
|||||||
package org.toop.framework.networking.server;
|
package org.toop.framework.networking.server;
|
||||||
|
|
||||||
|
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
|
||||||
public interface GameServer<GAMETYPE, CLIENT, CHALLENGEIDTYPE> {
|
public interface GameServer<GAMETYPE, CLIENT, CHALLENGEIDTYPE> {
|
||||||
void startGame(String gameType, CLIENT... clients);
|
OnlineGame<TurnBasedGame> startGame(String gameType, CompletableFuture<Void> futureOrNull, CLIENT... clients);
|
||||||
|
|
||||||
void addClient(CLIENT client);
|
void addClient(CLIENT client);
|
||||||
void removeClient(CLIENT client);
|
void removeClient(CLIENT client);
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ import org.toop.framework.gameFramework.GameState;
|
|||||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||||
import org.toop.framework.networking.server.client.NettyClient;
|
import org.toop.framework.networking.server.client.NettyClient;
|
||||||
|
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
|
||||||
public class OnlineTurnBasedGame implements OnlineGame<TurnBasedGame> {
|
public class OnlineTurnBasedGame implements OnlineGame<TurnBasedGame> {
|
||||||
|
|
||||||
private long id;
|
private long id;
|
||||||
@@ -12,6 +14,19 @@ public class OnlineTurnBasedGame implements OnlineGame<TurnBasedGame> {
|
|||||||
private TurnBasedGame game;
|
private TurnBasedGame game;
|
||||||
private ServerThreadBehaviour gameThread;
|
private ServerThreadBehaviour gameThread;
|
||||||
|
|
||||||
|
private CompletableFuture<Void> futureOrNull = null;
|
||||||
|
|
||||||
|
public OnlineTurnBasedGame(TurnBasedGame game, CompletableFuture<Void> futureOrNull, NettyClient... clients) {
|
||||||
|
this.game = game;
|
||||||
|
this.gameThread = new ServerThreadBehaviour(
|
||||||
|
game,
|
||||||
|
(pair) -> notifyMoveMade(pair.getLeft(), pair.getRight()),
|
||||||
|
(pair) -> notifyGameEnd(pair.getLeft(), pair.getRight())
|
||||||
|
);
|
||||||
|
this.futureOrNull = futureOrNull;
|
||||||
|
this.clients = clients;
|
||||||
|
}
|
||||||
|
|
||||||
public OnlineTurnBasedGame(TurnBasedGame game, NettyClient... clients) {
|
public OnlineTurnBasedGame(TurnBasedGame game, NettyClient... clients) {
|
||||||
this.game = game;
|
this.game = game;
|
||||||
this.gameThread = new ServerThreadBehaviour(
|
this.gameThread = new ServerThreadBehaviour(
|
||||||
@@ -43,6 +58,10 @@ public class OnlineTurnBasedGame implements OnlineGame<TurnBasedGame> {
|
|||||||
for(NettyClient client : clients) {
|
for(NettyClient client : clients) {
|
||||||
client.clearGame();
|
client.clearGame();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (futureOrNull != null) {
|
||||||
|
futureOrNull.complete(null);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package org.toop.framework.networking.server;
|
package org.toop.framework.networking.server;
|
||||||
|
|
||||||
|
import com.google.gson.Gson;
|
||||||
import org.toop.framework.game.players.ServerPlayer;
|
import org.toop.framework.game.players.ServerPlayer;
|
||||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
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.GameChallenge;
|
||||||
@@ -9,6 +10,7 @@ import org.toop.framework.networking.server.stores.ClientStore;
|
|||||||
import org.toop.framework.networking.server.stores.SubscriptionStore;
|
import org.toop.framework.networking.server.stores.SubscriptionStore;
|
||||||
import org.toop.framework.networking.server.stores.TurnBasedGameStore;
|
import org.toop.framework.networking.server.stores.TurnBasedGameStore;
|
||||||
import org.toop.framework.networking.server.stores.TurnBasedGameTypeStore;
|
import org.toop.framework.networking.server.stores.TurnBasedGameTypeStore;
|
||||||
|
import org.toop.framework.networking.server.tournaments.*;
|
||||||
import org.toop.framework.utils.ImmutablePair;
|
import org.toop.framework.utils.ImmutablePair;
|
||||||
|
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
@@ -33,7 +35,6 @@ public class Server implements GameServer<TurnBasedGame, NettyClient, Long> {
|
|||||||
ClientStore<Long, NettyClient> clientStore,
|
ClientStore<Long, NettyClient> clientStore,
|
||||||
TurnBasedGameStore gameStore,
|
TurnBasedGameStore gameStore,
|
||||||
SubscriptionStore subStore
|
SubscriptionStore subStore
|
||||||
|
|
||||||
) {
|
) {
|
||||||
this.gameTypesStore = turnBasedGameTypeStore;
|
this.gameTypesStore = turnBasedGameTypeStore;
|
||||||
this.challengeDuration = challengeDuration;
|
this.challengeDuration = challengeDuration;
|
||||||
@@ -103,7 +104,7 @@ public class Server implements GameServer<TurnBasedGame, NettyClient, Long> {
|
|||||||
public void acceptChallenge(Long challengeId) {
|
public void acceptChallenge(Long challengeId) {
|
||||||
for (var challenge : gameChallenges) {
|
for (var challenge : gameChallenges) {
|
||||||
if (challenge.id() == challengeId) {
|
if (challenge.id() == challengeId) {
|
||||||
startGame(challenge.acceptChallenge(), challenge.getUsers());
|
startGame(challenge.acceptChallenge(), null, challenge.getUsers());
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -125,12 +126,12 @@ public class Server implements GameServer<TurnBasedGame, NettyClient, Long> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void startGame(String gameType, NettyClient... clients) {
|
public OnlineGame<TurnBasedGame> startGame(String gameType, CompletableFuture<Void> futureOrNull, NettyClient... clients) {
|
||||||
if (!gameTypesStore.all().containsKey(gameType)) return;
|
if (!gameTypesStore.all().containsKey(gameType)) return null;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
ServerPlayer[] players = new ServerPlayer[clients.length];
|
ServerPlayer[] players = new ServerPlayer[clients.length];
|
||||||
var game = new OnlineTurnBasedGame(gameTypesStore.create(gameType), clients);
|
var game = new OnlineTurnBasedGame(gameTypesStore.create(gameType), futureOrNull, clients);
|
||||||
|
|
||||||
for (int i = 0; i < clients.length; i++) {
|
for (int i = 0; i < clients.length; i++) {
|
||||||
players[i] = new ServerPlayer(clients[i]);
|
players[i] = new ServerPlayer(clients[i]);
|
||||||
@@ -149,10 +150,12 @@ public class Server implements GameServer<TurnBasedGame, NettyClient, Long> {
|
|||||||
gameType,
|
gameType,
|
||||||
clients[0].name()));
|
clients[0].name()));
|
||||||
game.start();
|
game.start();
|
||||||
|
return game;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
IO.println("ERROR: Failed to start OnlineTurnBasedGame");
|
IO.println("ERROR: Failed to start OnlineTurnBasedGame");
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -218,7 +221,6 @@ public class Server implements GameServer<TurnBasedGame, NettyClient, Long> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (userInGame) { continue; }
|
if (userInGame) { continue; }
|
||||||
//
|
|
||||||
|
|
||||||
int first = Math.max(left, right);
|
int first = Math.max(left, right);
|
||||||
int second = Math.min(left, right);
|
int second = Math.min(left, right);
|
||||||
@@ -226,7 +228,7 @@ public class Server implements GameServer<TurnBasedGame, NettyClient, Long> {
|
|||||||
userNames.remove(first);
|
userNames.remove(first);
|
||||||
userNames.remove(second);
|
userNames.remove(second);
|
||||||
|
|
||||||
startGame(key, getUser(userLeft), getUser(userRight));
|
startGame(key, null, getUser(userLeft), getUser(userRight));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -260,4 +262,50 @@ public class Server implements GameServer<TurnBasedGame, NettyClient, Long> {
|
|||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void startTournament(Tournament tournament, String gameType) {
|
||||||
|
try {
|
||||||
|
var tb = new TournamentBuilder();
|
||||||
|
var cTournament = tb.create(
|
||||||
|
tournament,
|
||||||
|
onlineUsers(),
|
||||||
|
this,
|
||||||
|
new BasicScoreManager(new HashMap<>()),
|
||||||
|
new BasicMatchManager(),
|
||||||
|
new RandomShuffle()
|
||||||
|
);
|
||||||
|
new Thread(() -> cTournament.run(gameType)).start();
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
getUser("host").send("ERR not enough clients to start a tournament");
|
||||||
|
} catch (RuntimeException e) {
|
||||||
|
getUser("host").send("ERR no matches could be created to start a tournament with");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void endTournament(Map<NettyClient, Integer> score, String gameType) {
|
||||||
|
|
||||||
|
List<String> u = new ArrayList<>();
|
||||||
|
List<Integer> s = new ArrayList<>();
|
||||||
|
|
||||||
|
for (var entry : score.entrySet()) {
|
||||||
|
u.add(entry.getKey().name());
|
||||||
|
s.add(entry.getValue());
|
||||||
|
}
|
||||||
|
|
||||||
|
Gson gson = new Gson();
|
||||||
|
|
||||||
|
String users = gson.toJson(u);
|
||||||
|
String scores = gson.toJson(s);
|
||||||
|
|
||||||
|
String msg = String.format(
|
||||||
|
"SVR RESULTS {GAMETYPE: \"%s\", USERS: %s, SCORES: %s, TOURNAMENT: 1}",
|
||||||
|
gameType,
|
||||||
|
users,
|
||||||
|
scores
|
||||||
|
);
|
||||||
|
|
||||||
|
for (var user : onlineUsers()) {
|
||||||
|
user.send(msg);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,8 +11,6 @@ import org.toop.framework.networking.server.Server;
|
|||||||
import org.toop.framework.networking.server.client.Client;
|
import org.toop.framework.networking.server.client.Client;
|
||||||
import org.toop.framework.networking.server.parsing.Parser;
|
import org.toop.framework.networking.server.parsing.Parser;
|
||||||
|
|
||||||
import java.util.Arrays;
|
|
||||||
|
|
||||||
public class NettyClientSession extends SimpleChannelInboundHandler<String> implements ClientSession<OnlineTurnBasedGame, ServerPlayer> {
|
public class NettyClientSession extends SimpleChannelInboundHandler<String> implements ClientSession<OnlineTurnBasedGame, ServerPlayer> {
|
||||||
|
|
||||||
private final NettyClient client;
|
private final NettyClient client;
|
||||||
@@ -41,13 +39,9 @@ public class NettyClientSession extends SimpleChannelInboundHandler<String> impl
|
|||||||
@Override
|
@Override
|
||||||
protected void channelRead0(ChannelHandlerContext ctx, String msg) {
|
protected void channelRead0(ChannelHandlerContext ctx, String msg) {
|
||||||
|
|
||||||
IO.println(msg);
|
|
||||||
|
|
||||||
ParsedMessage p = Parser.parse(msg);
|
ParsedMessage p = Parser.parse(msg);
|
||||||
if (p == null) return;
|
if (p == null) return;
|
||||||
|
|
||||||
IO.println(p.command() + " " + Arrays.toString(p.args()));
|
|
||||||
|
|
||||||
handler.handle(p);
|
handler.handle(p);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import org.toop.framework.networking.server.OnlineTurnBasedGame;
|
|||||||
import org.toop.framework.networking.server.Server;
|
import org.toop.framework.networking.server.Server;
|
||||||
import org.toop.framework.networking.server.client.Client;
|
import org.toop.framework.networking.server.client.Client;
|
||||||
import org.toop.framework.networking.server.parsing.ParsedMessage;
|
import org.toop.framework.networking.server.parsing.ParsedMessage;
|
||||||
|
import org.toop.framework.networking.server.tournaments.BasicTournament;
|
||||||
import org.toop.framework.utils.Utils;
|
import org.toop.framework.utils.Utils;
|
||||||
|
|
||||||
public class MessageHandler implements Handler<ParsedMessage> {
|
public class MessageHandler implements Handler<ParsedMessage> {
|
||||||
@@ -28,6 +29,7 @@ public class MessageHandler implements Handler<ParsedMessage> {
|
|||||||
case "challenge" -> handleChallenge(message, client);
|
case "challenge" -> handleChallenge(message, client);
|
||||||
case "message" -> handleMessage(message, client);
|
case "message" -> handleMessage(message, client);
|
||||||
case "help" -> handleHelp(message, client);
|
case "help" -> handleHelp(message, client);
|
||||||
|
case "tournament" -> handleTournament(message, client);
|
||||||
default -> client.send("ERROR Unknown command");
|
default -> client.send("ERROR Unknown command");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -107,4 +109,14 @@ public class MessageHandler implements Handler<ParsedMessage> {
|
|||||||
// TODO check if not number
|
// TODO check if not number
|
||||||
client.player().setMove(1L << Integer.parseInt(p.args()[0]));
|
client.player().setMove(1L << Integer.parseInt(p.args()[0]));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void handleTournament(ParsedMessage p, Client<OnlineTurnBasedGame, ServerPlayer> client) {
|
||||||
|
if(!hasArgs(p.args())) return;
|
||||||
|
|
||||||
|
if (!client.name().equalsIgnoreCase("host")) return;
|
||||||
|
|
||||||
|
if (p.args()[0].equalsIgnoreCase("start") && p.args().length > 1) {
|
||||||
|
server.startTournament(new BasicTournament(), p.args()[1]);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,85 @@
|
|||||||
|
package org.toop.framework.networking.server.tournaments;
|
||||||
|
|
||||||
|
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||||
|
import org.toop.framework.networking.server.OnlineGame;
|
||||||
|
import org.toop.framework.networking.server.Server;
|
||||||
|
import org.toop.framework.networking.server.client.NettyClient;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
|
|
||||||
|
public class BasicMatchManager implements MatchManager {
|
||||||
|
|
||||||
|
private final HashMap<NettyClient, List<NettyClient>> matches = new HashMap<>(); // TODO store
|
||||||
|
private final ArrayList<TournamentMatch> matchOrder = new ArrayList<>(); // TODO store
|
||||||
|
private int matchIndex = 0;
|
||||||
|
|
||||||
|
public BasicMatchManager() {}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void addClient(NettyClient client) {
|
||||||
|
matches.putIfAbsent(client, new ArrayList<>());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<NettyClient> getClients() {
|
||||||
|
return matches.keySet().stream().toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void createMatches() {
|
||||||
|
for (var match : matches.entrySet()) {
|
||||||
|
for (var matchNoSelf : matches.keySet()) {
|
||||||
|
if (match.getKey() == matchNoSelf) continue;
|
||||||
|
|
||||||
|
match.getValue().addLast(matchNoSelf);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var client : matches.entrySet()) {
|
||||||
|
for (var opponent : client.getValue()) {
|
||||||
|
matchOrder.addLast(new TournamentMatch(client.getKey(), opponent));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public TournamentMatch next() {
|
||||||
|
matchIndex++;
|
||||||
|
if (matchIndex >= matchOrder.size()) return null;
|
||||||
|
|
||||||
|
return matchOrder.get(matchIndex);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run(Server server, ScoreManager scoreManager, String gameType) {
|
||||||
|
new Thread(() -> {
|
||||||
|
for (var match : matchOrder) {
|
||||||
|
final CompletableFuture<Void> finished = new CompletableFuture<>();
|
||||||
|
|
||||||
|
AtomicReference<OnlineGame<TurnBasedGame>> game = new AtomicReference<>();
|
||||||
|
new Thread(() -> game.set(server.startGame(gameType, finished, match.getLeft(), match.getRight()))).start(); // TODO can possibly create a race condition
|
||||||
|
|
||||||
|
finished.join();
|
||||||
|
switch (game.get().game().getWinner()) {
|
||||||
|
case 0 -> scoreManager.addScore(match.getLeft());
|
||||||
|
case 1 -> scoreManager.addScore(match.getRight());
|
||||||
|
default -> {}
|
||||||
|
}
|
||||||
|
|
||||||
|
match.getLeft().clearGame();
|
||||||
|
match.getRight().clearGame();
|
||||||
|
}
|
||||||
|
|
||||||
|
server.endTournament(scoreManager.getScore(), gameType);
|
||||||
|
}).start();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void shuffle(Shuffler shuffler) {
|
||||||
|
shuffler.shuffle(matchOrder);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package org.toop.framework.networking.server.tournaments;
|
||||||
|
|
||||||
|
import org.toop.framework.networking.server.client.NettyClient;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class BasicScoreManager implements ScoreManager {
|
||||||
|
|
||||||
|
private final Map<NettyClient, Integer> scores;
|
||||||
|
|
||||||
|
public BasicScoreManager(Map<NettyClient, Integer> store) {
|
||||||
|
scores = store;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void addClient(NettyClient client) {
|
||||||
|
scores.putIfAbsent(client, getInitScore());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void addScore(NettyClient client) {
|
||||||
|
int clientScore = scores.get(client);
|
||||||
|
scores.put(client, clientScore + getWinPointAmount());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Map<NettyClient, Integer> getScore() {
|
||||||
|
return scores;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
package org.toop.framework.networking.server.tournaments;
|
||||||
|
|
||||||
|
import org.toop.framework.networking.server.Server;
|
||||||
|
|
||||||
|
public class BasicTournament implements Tournament {
|
||||||
|
private Server server;
|
||||||
|
|
||||||
|
private ScoreManager scoreManager;
|
||||||
|
private MatchManager matchManager;
|
||||||
|
|
||||||
|
public BasicTournament() {}
|
||||||
|
|
||||||
|
public void init(TournamentBuilder builder) {
|
||||||
|
server = builder.server;
|
||||||
|
scoreManager = builder.scoreManager;
|
||||||
|
matchManager = builder.matchManager;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean run(String gameType) throws RuntimeException {
|
||||||
|
if (server.gameTypes().stream().noneMatch(e -> e.equalsIgnoreCase(gameType))) return false;
|
||||||
|
|
||||||
|
matchManager.run(server, scoreManager, gameType);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// @Override
|
||||||
|
// public HashMap<NettyClient, Integer> end() {
|
||||||
|
//
|
||||||
|
// for (var match : matchList) {
|
||||||
|
// match.getLeft().clearGame(); // TODO send msg to client
|
||||||
|
// match.getRight().clearGame(); // TODO send msg to client
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// gameType = null;
|
||||||
|
// matchList = null;
|
||||||
|
// matches.clear();
|
||||||
|
//
|
||||||
|
// HashMap<NettyClient, Integer> retScore = new HashMap<>(score);
|
||||||
|
//
|
||||||
|
// score.clear();
|
||||||
|
//
|
||||||
|
// clients = null;
|
||||||
|
//
|
||||||
|
// return retScore;
|
||||||
|
// }
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
package org.toop.framework.networking.server.tournaments;
|
||||||
|
|
||||||
|
import org.toop.framework.networking.server.Server;
|
||||||
|
import org.toop.framework.networking.server.client.NettyClient;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public interface MatchManager {
|
||||||
|
void addClient(NettyClient client);
|
||||||
|
List<NettyClient> getClients();
|
||||||
|
void createMatches();
|
||||||
|
TournamentMatch next();
|
||||||
|
void run(Server server, ScoreManager scoreManager, String gameType);
|
||||||
|
void shuffle(Shuffler shuffler);
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package org.toop.framework.networking.server.tournaments;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Random;
|
||||||
|
|
||||||
|
public class RandomShuffle implements Shuffler {
|
||||||
|
@Override
|
||||||
|
public <T> void shuffle(List<T> listToShuffle) {
|
||||||
|
final int SHUFFLE_AMOUNT = listToShuffle.size() * 2;
|
||||||
|
|
||||||
|
Random rand = new Random();
|
||||||
|
|
||||||
|
for (int i = 0; i <= SHUFFLE_AMOUNT; i++) {
|
||||||
|
int index = rand.nextInt(listToShuffle.size());
|
||||||
|
T match = listToShuffle.get(index);
|
||||||
|
listToShuffle.remove(index);
|
||||||
|
listToShuffle.addLast(match);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package org.toop.framework.networking.server.tournaments;
|
||||||
|
|
||||||
|
import org.toop.framework.networking.server.client.NettyClient;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public interface ScoreManager {
|
||||||
|
void addClient(NettyClient client);
|
||||||
|
void addScore(NettyClient client);
|
||||||
|
Map<NettyClient, Integer> getScore();
|
||||||
|
|
||||||
|
default int getWinPointAmount() {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
default int getInitScore() {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package org.toop.framework.networking.server.tournaments;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public interface Shuffler {
|
||||||
|
<T> void shuffle(List<T> listToShuffle);
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package org.toop.framework.networking.server.tournaments;
|
||||||
|
|
||||||
|
import org.toop.framework.networking.server.client.NettyClient;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
|
||||||
|
public interface Tournament {
|
||||||
|
void init(TournamentBuilder builder);
|
||||||
|
boolean run(String gameType);
|
||||||
|
// HashMap<NettyClient, Integer> end();
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package org.toop.framework.networking.server.tournaments;
|
||||||
|
|
||||||
|
import org.toop.framework.networking.server.Server;
|
||||||
|
import org.toop.framework.networking.server.client.NettyClient;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class TournamentBuilder {
|
||||||
|
public Server server;
|
||||||
|
public ScoreManager scoreManager;
|
||||||
|
public MatchManager matchManager;
|
||||||
|
|
||||||
|
public TournamentBuilder() {}
|
||||||
|
|
||||||
|
public Tournament create(
|
||||||
|
Tournament tournament,
|
||||||
|
List<NettyClient> clients,
|
||||||
|
Server server,
|
||||||
|
ScoreManager scoreManager,
|
||||||
|
MatchManager matchManager,
|
||||||
|
Shuffler shuffler
|
||||||
|
) {
|
||||||
|
|
||||||
|
this.server = server;
|
||||||
|
this.scoreManager = scoreManager;
|
||||||
|
this.matchManager = matchManager;
|
||||||
|
|
||||||
|
for (var client : clients) {
|
||||||
|
matchManager.addClient(client);
|
||||||
|
scoreManager.addClient(client);
|
||||||
|
}
|
||||||
|
|
||||||
|
matchManager.createMatches();
|
||||||
|
matchManager.shuffle(shuffler);
|
||||||
|
|
||||||
|
tournament.init(this);
|
||||||
|
return tournament;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package org.toop.framework.networking.server.tournaments;
|
||||||
|
|
||||||
|
import org.toop.framework.networking.server.client.NettyClient;
|
||||||
|
import org.toop.framework.utils.ImmutablePair;
|
||||||
|
|
||||||
|
public class TournamentMatch extends ImmutablePair<NettyClient, NettyClient> {
|
||||||
|
public TournamentMatch(NettyClient a, NettyClient b) {
|
||||||
|
super(a, b);
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user