mirror of
https://github.com/2OOP/pism.git
synced 2026-02-04 19:04:49 +00:00
Compare commits
5 Commits
6a395cc40b
...
96afc9543a
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
96afc9543a | ||
|
|
0c1b106da5 | ||
|
|
aca0b2dcc0 | ||
|
|
75963a891b | ||
|
|
6b644ed8fa |
@@ -22,6 +22,7 @@ import org.toop.framework.networking.server.gateway.NettyGatewayServer;
|
|||||||
import org.toop.framework.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,9 +118,8 @@ public final class Server {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
primary = new ServerView(user, this::sendChallenge, () -> {
|
primary = new ServerView(user, this::sendChallenge, user, clientId);
|
||||||
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");
|
||||||
@@ -161,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;
|
||||||
}
|
}
|
||||||
@@ -240,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;
|
||||||
@@ -339,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);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ 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.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;
|
||||||
@@ -16,41 +17,42 @@ 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 {
|
||||||
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> 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, Runnable tournamentRequest, 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.tournamentRequest = tournamentRequest;
|
|
||||||
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,
|
||||||
@@ -61,16 +63,19 @@ public final class ServerView extends ViewWidget {
|
|||||||
|
|
||||||
add(Pos.CENTER, playerListSection);
|
add(Pos.CENTER, playerListSection);
|
||||||
|
|
||||||
var tournamentButton = Primitive.vbox(
|
if (userName.equals("host")) {
|
||||||
Primitive.button(
|
var tournamentButton = Primitive.hbox(
|
||||||
"tournament",
|
gameListTour,
|
||||||
tournamentRequest,
|
Primitive.button(
|
||||||
false,
|
"tournament",
|
||||||
false
|
() -> GlobalEventBus.get().post(new NetworkEvents.SendCommand(clientId, "tournament", "start", gameListTour.getValue())),
|
||||||
)
|
false,
|
||||||
);
|
false
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
add(Pos.BOTTOM_CENTER, tournamentButton);
|
add(Pos.BOTTOM_CENTER, tournamentButton);
|
||||||
|
}
|
||||||
|
|
||||||
var disconnectButton = Primitive.button(
|
var disconnectButton = Primitive.button(
|
||||||
"disconnect", () -> transitionPrevious(), false);
|
"disconnect", () -> transitionPrevious(), false);
|
||||||
@@ -91,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);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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,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,8 +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.BasicTournament;
|
import org.toop.framework.networking.server.tournaments.*;
|
||||||
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.*;
|
||||||
@@ -221,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);
|
||||||
@@ -265,17 +264,48 @@ public class Server implements GameServer<TurnBasedGame, NettyClient, Long> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void startTournament(Tournament tournament, String gameType) {
|
public void startTournament(Tournament tournament, String gameType) {
|
||||||
tournament.init(clientStore.all().toArray(new NettyClient[0]));
|
try {
|
||||||
new Thread(() -> tournament.start(gameType)).start();
|
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) {
|
public void endTournament(Map<NettyClient, Integer> score, String gameType) {
|
||||||
IO.println("TOUNAMENT WINNER IS: "); // TODO
|
|
||||||
IO.println("SCORES");
|
List<String> u = new ArrayList<>();
|
||||||
IO.println("-----------------------------------");
|
List<Integer> s = new ArrayList<>();
|
||||||
for (var a : score.entrySet()) {
|
|
||||||
String b = "" + a.getKey().name() + ": " + a.getValue();
|
for (var entry : score.entrySet()) {
|
||||||
IO.println(b);
|
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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -116,7 +116,7 @@ public class MessageHandler implements Handler<ParsedMessage> {
|
|||||||
if (!client.name().equalsIgnoreCase("host")) return;
|
if (!client.name().equalsIgnoreCase("host")) return;
|
||||||
|
|
||||||
if (p.args()[0].equalsIgnoreCase("start") && p.args().length > 1) {
|
if (p.args()[0].equalsIgnoreCase("start") && p.args().length > 1) {
|
||||||
server.startTournament(new BasicTournament(server), p.args()[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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,127 +1,48 @@
|
|||||||
package org.toop.framework.networking.server.tournaments;
|
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.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 {
|
public class BasicTournament implements Tournament {
|
||||||
private final int POINTS_FOR_WIN = 1;
|
|
||||||
|
|
||||||
private Server server;
|
private Server server;
|
||||||
private String gameType;
|
|
||||||
private ArrayList<TournamentMatch> matchList = new ArrayList<>();
|
|
||||||
|
|
||||||
private final HashMap<NettyClient, List<NettyClient>> matches = new HashMap<>();
|
private ScoreManager scoreManager;
|
||||||
private final HashMap<NettyClient, Integer> score = new HashMap<>();
|
private MatchManager matchManager;
|
||||||
private NettyClient[] clients;
|
|
||||||
|
|
||||||
public BasicTournament(Server server) {
|
public BasicTournament() {}
|
||||||
this.server = server;
|
|
||||||
|
public void init(TournamentBuilder builder) {
|
||||||
|
server = builder.server;
|
||||||
|
scoreManager = builder.scoreManager;
|
||||||
|
matchManager = builder.matchManager;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void init(NettyClient[] clients) {
|
public boolean run(String gameType) throws RuntimeException {
|
||||||
// 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;
|
if (server.gameTypes().stream().noneMatch(e -> e.equalsIgnoreCase(gameType))) return false;
|
||||||
this.gameType = gameType;
|
|
||||||
|
|
||||||
new Thread(() -> {
|
matchManager.run(server, scoreManager, gameType);
|
||||||
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;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
// @Override
|
||||||
public HashMap<NettyClient, Integer> end() {
|
// public HashMap<NettyClient, Integer> end() {
|
||||||
|
//
|
||||||
for (var match : matchList) {
|
// for (var match : matchList) {
|
||||||
match.getLeft().clearGame(); // TODO send msg to client
|
// match.getLeft().clearGame(); // TODO send msg to client
|
||||||
match.getRight().clearGame(); // TODO send msg to client
|
// match.getRight().clearGame(); // TODO send msg to client
|
||||||
}
|
// }
|
||||||
|
//
|
||||||
gameType = null;
|
// gameType = null;
|
||||||
matchList = null;
|
// matchList = null;
|
||||||
matches.clear();
|
// matches.clear();
|
||||||
|
//
|
||||||
HashMap<NettyClient, Integer> retScore = new HashMap<>(score);
|
// HashMap<NettyClient, Integer> retScore = new HashMap<>(score);
|
||||||
|
//
|
||||||
score.clear();
|
// score.clear();
|
||||||
|
//
|
||||||
clients = null;
|
// clients = null;
|
||||||
|
//
|
||||||
return retScore;
|
// 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);
|
||||||
|
}
|
||||||
@@ -5,7 +5,7 @@ import org.toop.framework.networking.server.client.NettyClient;
|
|||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
|
|
||||||
public interface Tournament {
|
public interface Tournament {
|
||||||
void init(NettyClient[] clients);
|
void init(TournamentBuilder builder);
|
||||||
boolean start(String gameType);
|
boolean run(String gameType);
|
||||||
HashMap<NettyClient, Integer> end();
|
// 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user