mirror of
https://github.com/2OOP/pism.git
synced 2026-02-04 19:04:49 +00:00
Compare commits
7 Commits
223-create
...
6a395cc40b
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6a395cc40b | ||
|
|
5e5948d1fe | ||
|
|
9c01aabbe1 | ||
|
|
0cb52b042f | ||
|
|
56a8d12e46 | ||
| 65220d9649 | |||
|
|
c64a2e2c65 |
@@ -19,7 +19,7 @@ import org.toop.framework.networking.connection.clients.TournamentNetworkingClie
|
||||
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.LocalPlayer;
|
||||
import org.toop.framework.game.players.LocalPlayer;
|
||||
import org.toop.local.AppContext;
|
||||
|
||||
import java.util.List;
|
||||
@@ -117,7 +117,9 @@ public final class Server {
|
||||
return;
|
||||
}
|
||||
|
||||
primary = new ServerView(user, this::sendChallenge, clientId);
|
||||
primary = new ServerView(user, this::sendChallenge, () -> {
|
||||
GlobalEventBus.get().post(new NetworkEvents.SendCommand(clientId, "tournament", "start", "tic-tac-toe"));
|
||||
}, clientId);
|
||||
WidgetContainer.getCurrentView().transitionNextCustom(primary, "disconnect", this::disconnect);
|
||||
|
||||
a.unsubscribe("connecting");
|
||||
@@ -196,30 +198,21 @@ 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 = true; // Make false and uncomment/comment code at lines HERE To make use of AI.
|
||||
// information.players[0].computerDifficulty = 5; // HERE
|
||||
// information.players[0].computerThinkTime = 1; // HERE
|
||||
information.players[1].name = response.opponent();
|
||||
information.players[userStartingTurn].name = user;
|
||||
information.players[opponentStartingTurn].name = response.opponent();
|
||||
|
||||
Player[] players = new Player[2];
|
||||
players[userStartingTurn] = new LocalPlayer(user);
|
||||
players[opponentStartingTurn] = new OnlinePlayer(response.opponent());
|
||||
|
||||
switch (type) {
|
||||
case TICTACTOE -> {
|
||||
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 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);}
|
||||
case TICTACTOE -> gameController = new TicTacToeBitController(players);
|
||||
case REVERSI -> gameController = new ReversiBitController(players);
|
||||
default -> new ErrorPopup("Unsupported game type.");
|
||||
|
||||
}
|
||||
|
||||
@@ -78,6 +78,7 @@ public abstract class BitGameCanvas implements GameCanvas {
|
||||
}
|
||||
|
||||
canvas.setOnMouseClicked(event -> {
|
||||
|
||||
if (event.getButton() != MouseButton.PRIMARY) {
|
||||
return;
|
||||
}
|
||||
@@ -93,9 +94,6 @@ public abstract class BitGameCanvas implements GameCanvas {
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
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.view.GUIEvents;
|
||||
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 {
|
||||
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.
|
||||
public GenericGameController(GameCanvas canvas, TurnBasedGame game, ThreadBehaviour gameThreadBehaviour, String gameType) {
|
||||
logger.info("Creating: " + this.getClass());
|
||||
logger.info("Creating: {}", this.getClass());
|
||||
|
||||
this.canvas = canvas;
|
||||
this.game = game;
|
||||
this.gameThreadBehaviour = gameThreadBehaviour;
|
||||
|
||||
// Tell thread how to send moves
|
||||
this.gameThreadBehaviour.setOnSendMove((id, m) -> GlobalEventBus.get().post(new NetworkEvents.SendMove(id, (short)translateMove(m))));
|
||||
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));
|
||||
@@ -53,21 +55,37 @@ public class GenericGameController implements GameController {
|
||||
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 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 getCurrentPlayer(){
|
||||
@@ -98,7 +116,7 @@ public class GenericGameController implements GameController {
|
||||
}
|
||||
|
||||
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");
|
||||
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.games.tictactoe.BitboardTicTacToe;
|
||||
import org.toop.framework.game.players.OnlinePlayer;
|
||||
import org.toop.framework.networking.server.OnlineGame;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
@@ -19,6 +18,6 @@ public class TicTacToeBitController extends GenericGameController {
|
||||
ThreadBehaviour thread = Arrays.stream(players).anyMatch(e -> e instanceof OnlinePlayer) ?
|
||||
new OnlineThreadBehaviour(game) : new LocalThreadBehaviour(game);
|
||||
|
||||
super(new TicTacToeBitCanvas(), game, thread , "TicTacToe");
|
||||
super(new TicTacToeBitCanvas(), game, thread, "TicTacToe");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ 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.LocalPlayer;
|
||||
import org.toop.framework.game.players.LocalPlayer;
|
||||
import org.toop.game.players.ai.MCTSAI;
|
||||
import org.toop.game.players.ai.MCTSAI2;
|
||||
import org.toop.game.players.ai.MCTSAI3;
|
||||
|
||||
@@ -6,6 +6,7 @@ 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.List;
|
||||
import java.util.Locale;
|
||||
import java.util.function.Consumer;
|
||||
@@ -20,15 +21,17 @@ 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 Runnable tournamentRequest;
|
||||
private final long clientId;
|
||||
|
||||
private final ComboBox<String> gameList;
|
||||
private final ListView<Button> listView;
|
||||
private Button subscribeButton;
|
||||
|
||||
public ServerView(String user, Consumer<String> onPlayerClicked, long clientId) {
|
||||
public ServerView(String user, Consumer<String> onPlayerClicked, Runnable tournamentRequest, long clientId) {
|
||||
this.user = user;
|
||||
this.onPlayerClicked = onPlayerClicked;
|
||||
this.tournamentRequest = tournamentRequest;
|
||||
this.clientId = clientId;
|
||||
|
||||
this.gameList = new ComboBox<>();
|
||||
@@ -58,6 +61,17 @@ public final class ServerView extends ViewWidget {
|
||||
|
||||
add(Pos.CENTER, playerListSection);
|
||||
|
||||
var tournamentButton = Primitive.vbox(
|
||||
Primitive.button(
|
||||
"tournament",
|
||||
tournamentRequest,
|
||||
false,
|
||||
false
|
||||
)
|
||||
);
|
||||
|
||||
add(Pos.BOTTOM_CENTER, tournamentButton);
|
||||
|
||||
var disconnectButton = Primitive.button(
|
||||
"disconnect", () -> transitionPrevious(), false);
|
||||
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -47,9 +47,11 @@ public abstract class BitboardGame implements TurnBasedGame {
|
||||
|
||||
this.playerBitboard = other.playerBitboard.clone();
|
||||
this.currentTurn = other.currentTurn;
|
||||
this.players = Arrays.stream(other.players)
|
||||
.map(Player::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() {
|
||||
|
||||
@@ -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.game.players.OnlinePlayer;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
/**
|
||||
* Handles online multiplayer game logic.
|
||||
* <p>
|
||||
@@ -15,6 +18,9 @@ import org.toop.framework.game.players.OnlinePlayer;
|
||||
* for the local player while receiving moves from other players.
|
||||
*/
|
||||
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.
|
||||
@@ -51,8 +57,30 @@ public class OnlineThreadBehaviour extends AbstractThreadBehaviour implements Su
|
||||
*/
|
||||
@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,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;
|
||||
@@ -45,11 +45,16 @@ public class LocalPlayer extends AbstractPlayer {
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
package org.toop.framework.networking.server;
|
||||
|
||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
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 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.networking.server.client.NettyClient;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
public class OnlineTurnBasedGame implements OnlineGame<TurnBasedGame> {
|
||||
|
||||
private long id;
|
||||
@@ -12,6 +14,19 @@ public class OnlineTurnBasedGame implements OnlineGame<TurnBasedGame> {
|
||||
private TurnBasedGame game;
|
||||
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) {
|
||||
this.game = game;
|
||||
this.gameThread = new ServerThreadBehaviour(
|
||||
@@ -43,6 +58,10 @@ public class OnlineTurnBasedGame implements OnlineGame<TurnBasedGame> {
|
||||
for(NettyClient client : clients) {
|
||||
client.clearGame();
|
||||
}
|
||||
|
||||
if (futureOrNull != null) {
|
||||
futureOrNull.complete(null);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -9,6 +9,8 @@ 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.BasicTournament;
|
||||
import org.toop.framework.networking.server.tournaments.Tournament;
|
||||
import org.toop.framework.utils.ImmutablePair;
|
||||
|
||||
import java.util.*;
|
||||
@@ -33,7 +35,6 @@ public class Server implements GameServer<TurnBasedGame, NettyClient, Long> {
|
||||
ClientStore<Long, NettyClient> clientStore,
|
||||
TurnBasedGameStore gameStore,
|
||||
SubscriptionStore subStore
|
||||
|
||||
) {
|
||||
this.gameTypesStore = turnBasedGameTypeStore;
|
||||
this.challengeDuration = challengeDuration;
|
||||
@@ -103,7 +104,7 @@ public class Server implements GameServer<TurnBasedGame, NettyClient, Long> {
|
||||
public void acceptChallenge(Long challengeId) {
|
||||
for (var challenge : gameChallenges) {
|
||||
if (challenge.id() == challengeId) {
|
||||
startGame(challenge.acceptChallenge(), challenge.getUsers());
|
||||
startGame(challenge.acceptChallenge(), null, challenge.getUsers());
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -125,12 +126,12 @@ public class Server implements GameServer<TurnBasedGame, NettyClient, Long> {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void startGame(String gameType, NettyClient... clients) {
|
||||
if (!gameTypesStore.all().containsKey(gameType)) return;
|
||||
public OnlineGame<TurnBasedGame> startGame(String gameType, CompletableFuture<Void> futureOrNull, NettyClient... clients) {
|
||||
if (!gameTypesStore.all().containsKey(gameType)) return null;
|
||||
|
||||
try {
|
||||
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++) {
|
||||
players[i] = new ServerPlayer(clients[i]);
|
||||
@@ -149,10 +150,12 @@ public class Server implements GameServer<TurnBasedGame, NettyClient, Long> {
|
||||
gameType,
|
||||
clients[0].name()));
|
||||
game.start();
|
||||
return game;
|
||||
} catch (Exception e) {
|
||||
IO.println("ERROR: Failed to start OnlineTurnBasedGame");
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -226,7 +229,7 @@ public class Server implements GameServer<TurnBasedGame, NettyClient, Long> {
|
||||
userNames.remove(first);
|
||||
userNames.remove(second);
|
||||
|
||||
startGame(key, getUser(userLeft), getUser(userRight));
|
||||
startGame(key, null, getUser(userLeft), getUser(userRight));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -260,4 +263,19 @@ public class Server implements GameServer<TurnBasedGame, NettyClient, Long> {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public void startTournament(Tournament tournament, String gameType) {
|
||||
tournament.init(clientStore.all().toArray(new NettyClient[0]));
|
||||
new Thread(() -> tournament.start(gameType)).start();
|
||||
}
|
||||
|
||||
public void endTournament(Map<NettyClient, Integer> score) {
|
||||
IO.println("TOUNAMENT WINNER IS: "); // TODO
|
||||
IO.println("SCORES");
|
||||
IO.println("-----------------------------------");
|
||||
for (var a : score.entrySet()) {
|
||||
String b = "" + a.getKey().name() + ": " + a.getValue();
|
||||
IO.println(b);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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.parsing.Parser;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class NettyClientSession extends SimpleChannelInboundHandler<String> implements ClientSession<OnlineTurnBasedGame, ServerPlayer> {
|
||||
|
||||
private final NettyClient client;
|
||||
@@ -41,13 +39,9 @@ public class NettyClientSession extends SimpleChannelInboundHandler<String> impl
|
||||
@Override
|
||||
protected void channelRead0(ChannelHandlerContext ctx, String msg) {
|
||||
|
||||
IO.println(msg);
|
||||
|
||||
ParsedMessage p = Parser.parse(msg);
|
||||
if (p == null) return;
|
||||
|
||||
IO.println(p.command() + " " + Arrays.toString(p.args()));
|
||||
|
||||
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.client.Client;
|
||||
import org.toop.framework.networking.server.parsing.ParsedMessage;
|
||||
import org.toop.framework.networking.server.tournaments.BasicTournament;
|
||||
import org.toop.framework.utils.Utils;
|
||||
|
||||
public class MessageHandler implements Handler<ParsedMessage> {
|
||||
@@ -28,6 +29,7 @@ public class MessageHandler implements Handler<ParsedMessage> {
|
||||
case "challenge" -> handleChallenge(message, client);
|
||||
case "message" -> handleMessage(message, client);
|
||||
case "help" -> handleHelp(message, client);
|
||||
case "tournament" -> handleTournament(message, client);
|
||||
default -> client.send("ERROR Unknown command");
|
||||
}
|
||||
}
|
||||
@@ -107,4 +109,14 @@ public class MessageHandler implements Handler<ParsedMessage> {
|
||||
// TODO check if not number
|
||||
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(server), p.args()[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
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.Random;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
public class BasicTournament implements Tournament {
|
||||
private final int POINTS_FOR_WIN = 1;
|
||||
|
||||
private Server server;
|
||||
private String gameType;
|
||||
private ArrayList<TournamentMatch> matchList = new ArrayList<>();
|
||||
|
||||
private final HashMap<NettyClient, List<NettyClient>> matches = new HashMap<>();
|
||||
private final HashMap<NettyClient, Integer> score = new HashMap<>();
|
||||
private NettyClient[] clients;
|
||||
|
||||
public BasicTournament(Server server) {
|
||||
this.server = server;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(NettyClient[] clients) {
|
||||
// if (this.clients == null || clients.length < 1) return;
|
||||
|
||||
for (NettyClient client : clients) {
|
||||
int INIT_SCORE = 0;
|
||||
|
||||
matches.putIfAbsent(client, new ArrayList<>());
|
||||
score.putIfAbsent(client, INIT_SCORE);
|
||||
}
|
||||
|
||||
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()) {
|
||||
matchList.addLast(new TournamentMatch(client.getKey(), opponent));
|
||||
}
|
||||
}
|
||||
|
||||
shuffle();
|
||||
}
|
||||
|
||||
public void shuffle() { // TODO make shuffle own class so user can use different shuffles
|
||||
|
||||
final int SHUFFLE_AMOUNT = matchList.size() * 2;
|
||||
|
||||
Random rand = new Random();
|
||||
|
||||
for (int i = 0; i <= SHUFFLE_AMOUNT; i++) {
|
||||
int index = rand.nextInt(matchList.size());
|
||||
TournamentMatch match = matchList.get(index);
|
||||
matchList.remove(index);
|
||||
matchList.addLast(match);
|
||||
}
|
||||
}
|
||||
|
||||
public void addScorePoints(NettyClient client) {
|
||||
score.put(client, score.get(client) + POINTS_FOR_WIN);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean start(String gameType) { // TODO, rename to run
|
||||
// if (this.clients == null || clients.length < 1) return false;
|
||||
|
||||
if (server.gameTypes().stream().noneMatch(e -> e.equalsIgnoreCase(gameType))) return false;
|
||||
this.gameType = gameType;
|
||||
|
||||
new Thread(() -> {
|
||||
for (var match : matchList) {
|
||||
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 -> addScorePoints(match.getLeft());
|
||||
case 1 -> addScorePoints(match.getRight());
|
||||
default -> {}
|
||||
}
|
||||
|
||||
match.getLeft().clearGame();
|
||||
match.getRight().clearGame();
|
||||
}
|
||||
|
||||
server.endTournament(end());
|
||||
}).start();
|
||||
|
||||
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,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(NettyClient[] clients);
|
||||
boolean start(String gameType);
|
||||
HashMap<NettyClient, Integer> end();
|
||||
}
|
||||
@@ -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