mirror of
https://github.com/2OOP/pism.git
synced 2026-02-04 19:04:49 +00:00
Compare commits
2 Commits
9c01aabbe1
...
6a395cc40b
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6a395cc40b | ||
|
|
5e5948d1fe |
@@ -117,7 +117,9 @@ public final class Server {
|
|||||||
return;
|
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);
|
WidgetContainer.getCurrentView().transitionNextCustom(primary, "disconnect", this::disconnect);
|
||||||
|
|
||||||
a.unsubscribe("connecting");
|
a.unsubscribe("connecting");
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ 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.List;
|
import java.util.List;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
import java.util.function.Consumer;
|
import java.util.function.Consumer;
|
||||||
@@ -20,15 +21,17 @@ import org.toop.framework.networking.connection.events.NetworkEvents;
|
|||||||
public final class ServerView extends ViewWidget {
|
public final class ServerView extends ViewWidget {
|
||||||
private final String user;
|
private final String user;
|
||||||
private final Consumer<String> onPlayerClicked;
|
private final Consumer<String> onPlayerClicked;
|
||||||
|
private final Runnable tournamentRequest;
|
||||||
private final long clientId;
|
private final long clientId;
|
||||||
|
|
||||||
private final ComboBox<String> gameList;
|
private final ComboBox<String> gameList;
|
||||||
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, Runnable tournamentRequest, long clientId) {
|
||||||
this.user = user;
|
this.user = user;
|
||||||
this.onPlayerClicked = onPlayerClicked;
|
this.onPlayerClicked = onPlayerClicked;
|
||||||
|
this.tournamentRequest = tournamentRequest;
|
||||||
this.clientId = clientId;
|
this.clientId = clientId;
|
||||||
|
|
||||||
this.gameList = new ComboBox<>();
|
this.gameList = new ComboBox<>();
|
||||||
@@ -58,6 +61,17 @@ public final class ServerView extends ViewWidget {
|
|||||||
|
|
||||||
add(Pos.CENTER, playerListSection);
|
add(Pos.CENTER, playerListSection);
|
||||||
|
|
||||||
|
var tournamentButton = Primitive.vbox(
|
||||||
|
Primitive.button(
|
||||||
|
"tournament",
|
||||||
|
tournamentRequest,
|
||||||
|
false,
|
||||||
|
false
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
add(Pos.BOTTOM_CENTER, tournamentButton);
|
||||||
|
|
||||||
var disconnectButton = Primitive.button(
|
var disconnectButton = Primitive.button(
|
||||||
"disconnect", () -> transitionPrevious(), false);
|
"disconnect", () -> transitionPrevious(), false);
|
||||||
|
|
||||||
|
|||||||
@@ -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();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -77,13 +77,11 @@ public class OnlineThreadBehaviour extends AbstractThreadBehaviour implements Su
|
|||||||
}
|
}
|
||||||
logger.info("Successfully collected current turn's player");
|
logger.info("Successfully collected current turn's player");
|
||||||
|
|
||||||
moveExecutor.submit(() -> {
|
long move = player.getMove(gameCopy);
|
||||||
long move = player.getMove(gameCopy);
|
logger.info("Move set: {}", move);
|
||||||
logger.info("Move set: {}", move);
|
logger.info("Completed onYourTurn");
|
||||||
logger.info("Completed onYourTurn");
|
|
||||||
|
|
||||||
sendMove(clientId, move);
|
sendMove(clientId, move);
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -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.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.BasicTournament;
|
||||||
|
import org.toop.framework.networking.server.tournaments.Tournament;
|
||||||
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
|
||||||
@@ -226,7 +229,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 +263,19 @@ public class Server implements GameServer<TurnBasedGame, NettyClient, Long> {
|
|||||||
|
|
||||||
return true;
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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(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