mirror of
https://github.com/2OOP/pism.git
synced 2026-02-05 03:14:50 +00:00
Compare commits
5 Commits
96afc9543a
...
28791fcc8a
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
28791fcc8a | ||
|
|
97657b01c9 | ||
|
|
a5bf6ca9fb | ||
|
|
fc25c15736 | ||
|
|
d4cad3311e |
2
.idea/inspectionProfiles/Project_Default.xml
generated
2
.idea/inspectionProfiles/Project_Default.xml
generated
@@ -2,7 +2,7 @@
|
||||
<profile version="1.0">
|
||||
<option name="myName" value="Project Default" />
|
||||
<inspection_tool class="AutoCloseableResource" enabled="true" level="WARNING" enabled_by_default="true">
|
||||
<option name="METHOD_MATCHER_CONFIG" value="java.util.Formatter,format,java.io.Writer,append,com.google.common.base.Preconditions,checkNotNull,org.hibernate.Session,close,java.io.PrintWriter,printf,java.io.PrintStream,printf,java.lang.foreign.Arena,ofAuto,java.lang.foreign.Arena,global,org.toop.framework.audio.AudioPlayer,play,java.util.Map,remove,java.util.concurrent.Executors,newSingleThreadScheduledExecutor" />
|
||||
<option name="METHOD_MATCHER_CONFIG" value="java.util.Formatter,format,java.io.Writer,append,com.google.common.base.Preconditions,checkNotNull,org.hibernate.Session,close,java.io.PrintWriter,printf,java.io.PrintStream,printf,java.lang.foreign.Arena,ofAuto,java.lang.foreign.Arena,global,org.toop.framework.audio.AudioPlayer,play,java.util.Map,remove,java.util.concurrent.Executors,newSingleThreadScheduledExecutor|newFixedThreadPool|newSingleThreadExecutor" />
|
||||
</inspection_tool>
|
||||
<inspection_tool class="WriteOnlyObject" enabled="false" level="WARNING" enabled_by_default="false" />
|
||||
</profile>
|
||||
|
||||
@@ -45,6 +45,19 @@ public final class ServerView extends ViewWidget {
|
||||
private void setupLayout(String userName) {
|
||||
var playerHeader = Primitive.header(user, false);
|
||||
|
||||
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);
|
||||
} else {
|
||||
subscribeButton = Primitive.button(
|
||||
"subscribe",
|
||||
() -> new EventFlow().addPostEvent(new NetworkEvents.SendSubscribe(clientId, gameListSub.getValue())).postEvent(),
|
||||
@@ -63,25 +76,12 @@ public final class ServerView extends ViewWidget {
|
||||
|
||||
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(
|
||||
"disconnect", () -> transitionPrevious(), false);
|
||||
|
||||
add(Pos.BOTTOM_LEFT, Primitive.vbox(disconnectButton));
|
||||
}
|
||||
}
|
||||
|
||||
public void update(List<String> players) {
|
||||
Platform.runLater(() -> {
|
||||
|
||||
@@ -123,16 +123,29 @@ public class NetworkingGameClientHandler extends ChannelInboundHandlerAdapter {
|
||||
String usersRaw = extract(rec, "USERS");
|
||||
String scoresRaw = extract(rec, "SCORES");
|
||||
|
||||
String[] users = Arrays.stream(usersRaw.substring(1, usersRaw.length() - 1).split(","))
|
||||
if (usersRaw == null) return;
|
||||
|
||||
String[] users;
|
||||
if (usersRaw.length() > 2) {
|
||||
users = Arrays.stream(usersRaw.substring(1, usersRaw.length() - 1).split(","))
|
||||
.map(s -> s.trim().replace("\"", ""))
|
||||
.toArray(String[]::new);
|
||||
} else {
|
||||
users = new String[]{};
|
||||
}
|
||||
|
||||
if (scoresRaw == null) return;
|
||||
if (scoresRaw.length() > 2) {
|
||||
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));
|
||||
} else {
|
||||
eventBus.post(new NetworkEvents.TournamentResultResponse(this.connectionId, gameTypeRaw, users, new Integer[]{}));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void gameMoveHandler(String rec) {
|
||||
|
||||
@@ -5,18 +5,21 @@ 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.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
public class OnlineTurnBasedGame implements OnlineGame<TurnBasedGame> {
|
||||
|
||||
private long id;
|
||||
private NettyClient[] clients;
|
||||
private NettyClient[] admins;
|
||||
private TurnBasedGame game;
|
||||
private ServerThreadBehaviour gameThread;
|
||||
|
||||
private CompletableFuture<Void> futureOrNull = null;
|
||||
private final CompletableFuture<Void> futureOrNull;
|
||||
|
||||
public OnlineTurnBasedGame(TurnBasedGame game, CompletableFuture<Void> futureOrNull, NettyClient... clients) {
|
||||
public OnlineTurnBasedGame(NettyClient[] admins, TurnBasedGame game, CompletableFuture<Void> futureOrNull, NettyClient... clients) {
|
||||
this.game = game;
|
||||
this.gameThread = new ServerThreadBehaviour(
|
||||
game,
|
||||
@@ -25,37 +28,40 @@ public class OnlineTurnBasedGame implements OnlineGame<TurnBasedGame> {
|
||||
);
|
||||
this.futureOrNull = futureOrNull;
|
||||
this.clients = clients;
|
||||
this.admins = admins;
|
||||
}
|
||||
|
||||
public OnlineTurnBasedGame(TurnBasedGame game, NettyClient... clients) {
|
||||
this.game = game;
|
||||
this.gameThread = new ServerThreadBehaviour(
|
||||
game,
|
||||
(pair) -> notifyMoveMade(pair.getLeft(), pair.getRight()),
|
||||
(pair) -> notifyGameEnd(pair.getLeft(), pair.getRight())
|
||||
);
|
||||
this.clients = clients;
|
||||
public OnlineTurnBasedGame(NettyClient[] admins, TurnBasedGame game, NettyClient... clients) {
|
||||
this(admins, game, null, clients);
|
||||
}
|
||||
|
||||
private void notifyMoveMade(String speler, int move){
|
||||
for (NettyClient admin : admins) {
|
||||
admin.send(String.format("SVR GAME MOVE {PLAYER: \"%s\", MOVE: \"%s\", DETAILS: \"<reactie spel op zet>\"}", speler, move));
|
||||
}
|
||||
for (NettyClient client : clients) {
|
||||
client.send(String.format("SVR GAME MOVE {PLAYER: \"%s\", MOVE: \"%s\", DETAILS: \"<reactie spel op zet>\"}\n", speler, move));
|
||||
client.send(String.format("SVR GAME MOVE {PLAYER: \"%s\", MOVE: \"%s\", DETAILS: \"<reactie spel op zet>\"}", speler, move));
|
||||
}
|
||||
}
|
||||
|
||||
private void notifyGameEnd(GameState state, int winner){
|
||||
if (state == GameState.DRAW){
|
||||
if (state == GameState.DRAW) {
|
||||
Arrays.stream(admins).forEach(a -> a.send(
|
||||
String.format("SVR GAME END")
|
||||
));
|
||||
|
||||
for (NettyClient client : clients) {
|
||||
client.send(String.format("SVR GAME DRAW {PLAYERONESCORE: \"<score speler1>\", PLAYERTWOSCORE: \"<score speler2>\", COMMENT: \"<comment>\"}\n"));
|
||||
client.send(String.format("SVR GAME DRAW {PLAYERONESCORE: \"<score speler1>\", PLAYERTWOSCORE: \"<score speler2>\", COMMENT: \"<comment>\"}"));
|
||||
}
|
||||
}
|
||||
else{
|
||||
clients[winner].send(String.format("SVR GAME WIN {PLAYERONESCORE: \"<score speler1>\", PLAYERTWOSCORE: \"<score speler2>\", COMMENT: \"<comment>\"}\n"));
|
||||
clients[(winner + 1)%2].send(String.format("SVR GAME LOSS {PLAYERONESCORE: \"<score speler1>\", PLAYERTWOSCORE: \"<score speler2>\", COMMENT: \"<comment>\"}\n"));
|
||||
} else {
|
||||
Arrays.stream(admins).forEach(a -> a.send("SVR GAME END"));
|
||||
clients[winner].send(String.format("SVR GAME WIN {PLAYERONESCORE: \"<score speler1>\", PLAYERTWOSCORE: \"<score speler2>\", COMMENT: \"<comment>\"}"));
|
||||
clients[1-winner].send(String.format("SVR GAME LOSS {PLAYERONESCORE: \"<score speler1>\", PLAYERTWOSCORE: \"<score speler2>\", COMMENT: \"<comment>\"}"));
|
||||
}
|
||||
|
||||
// Remove game fromt clients
|
||||
for(NettyClient client : clients) {
|
||||
// Remove game from clients
|
||||
for (NettyClient client : clients) {
|
||||
admins = null;
|
||||
client.clearGame();
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,8 @@ import org.toop.framework.networking.server.stores.SubscriptionStore;
|
||||
import org.toop.framework.networking.server.stores.TurnBasedGameStore;
|
||||
import org.toop.framework.networking.server.stores.TurnBasedGameTypeStore;
|
||||
import org.toop.framework.networking.server.tournaments.*;
|
||||
import org.toop.framework.networking.server.tournaments.matchmakers.RoundRobinMatchMaker;
|
||||
import org.toop.framework.networking.server.tournaments.scoresystems.BasicScoreSystem;
|
||||
import org.toop.framework.utils.ImmutablePair;
|
||||
|
||||
import java.util.*;
|
||||
@@ -29,6 +31,8 @@ public class Server implements GameServer<TurnBasedGame, NettyClient, Long> {
|
||||
final private Duration challengeDuration;
|
||||
final private ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
|
||||
|
||||
private final List<NettyClient> admins = new ArrayList<>();
|
||||
|
||||
public Server(
|
||||
Duration challengeDuration,
|
||||
TurnBasedGameTypeStore turnBasedGameTypeStore,
|
||||
@@ -47,11 +51,13 @@ public class Server implements GameServer<TurnBasedGame, NettyClient, Long> {
|
||||
|
||||
@Override
|
||||
public void addClient(NettyClient client) {
|
||||
if (admins.isEmpty()) admins.addLast(client);
|
||||
clientStore.add(client);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeClient(NettyClient client) {
|
||||
admins.remove(client);
|
||||
clientStore.remove(client.id());
|
||||
}
|
||||
|
||||
@@ -131,7 +137,7 @@ public class Server implements GameServer<TurnBasedGame, NettyClient, Long> {
|
||||
|
||||
try {
|
||||
ServerPlayer[] players = new ServerPlayer[clients.length];
|
||||
var game = new OnlineTurnBasedGame(gameTypesStore.create(gameType), futureOrNull, clients);
|
||||
var game = new OnlineTurnBasedGame(getAdmins().toArray(NettyClient[]::new), gameTypesStore.create(gameType), futureOrNull, clients);
|
||||
|
||||
for (int i = 0; i < clients.length; i++) {
|
||||
players[i] = new ServerPlayer(clients[i]);
|
||||
@@ -163,6 +169,10 @@ public class Server implements GameServer<TurnBasedGame, NettyClient, Long> {
|
||||
return clientStore.all().stream().toList();
|
||||
}
|
||||
|
||||
public List<NettyClient> getAdmins() {
|
||||
return new ArrayList<>(admins); // Clone so the list can't be edited.
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown() {
|
||||
scheduler.shutdown();
|
||||
@@ -263,22 +273,28 @@ public class Server implements GameServer<TurnBasedGame, NettyClient, Long> {
|
||||
return true;
|
||||
}
|
||||
|
||||
public void startTournament(Tournament tournament, String gameType) {
|
||||
try {
|
||||
var tb = new TournamentBuilder();
|
||||
var cTournament = tb.create(
|
||||
tournament,
|
||||
onlineUsers(),
|
||||
public void startTournament(String gameType, NettyClient requestor) {
|
||||
if (!admins.contains(requestor)) {
|
||||
requestor.send("ERR you do not have the privileges to start a tournament");
|
||||
return;
|
||||
}
|
||||
|
||||
var tournamentUsers = new ArrayList<>(onlineUsers());
|
||||
tournamentUsers.removeIf(admins::contains);
|
||||
|
||||
Tournament tournament = new BasicTournament(new TournamentBuilder(
|
||||
this,
|
||||
new BasicScoreManager(new HashMap<>()),
|
||||
new BasicMatchManager(),
|
||||
new RandomShuffle()
|
||||
);
|
||||
new Thread(() -> cTournament.run(gameType)).start();
|
||||
new BasicTournamentRunner(),
|
||||
new RoundRobinMatchMaker(tournamentUsers),
|
||||
new BasicScoreSystem(tournamentUsers)
|
||||
));
|
||||
|
||||
try {
|
||||
new Thread(() -> tournament.run(gameType)).start();
|
||||
} catch (IllegalArgumentException e) {
|
||||
getUser("host").send("ERR not enough clients to start a tournament");
|
||||
admins.forEach(c -> c.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");
|
||||
admins.forEach(c -> c.send("ERR no matches could be created to start a tournament with"));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,16 +4,17 @@ import org.toop.framework.game.players.ServerPlayer;
|
||||
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.client.NettyClient;
|
||||
import org.toop.framework.networking.server.parsing.ParsedMessage;
|
||||
import org.toop.framework.networking.server.tournaments.BasicTournament;
|
||||
import org.toop.framework.networking.server.tournaments.*;
|
||||
import org.toop.framework.utils.Utils;
|
||||
|
||||
public class MessageHandler implements Handler<ParsedMessage> {
|
||||
|
||||
private final Server server;
|
||||
private final Client<OnlineTurnBasedGame, ServerPlayer> client;
|
||||
private final NettyClient client;
|
||||
|
||||
public MessageHandler(Server server, Client<OnlineTurnBasedGame, ServerPlayer> client) {
|
||||
public MessageHandler(Server server, NettyClient client) {
|
||||
this.server = server;
|
||||
this.client = client;
|
||||
}
|
||||
@@ -43,27 +44,27 @@ public class MessageHandler implements Handler<ParsedMessage> {
|
||||
return true;
|
||||
}
|
||||
|
||||
private void handleLogin(ParsedMessage p, Client<OnlineTurnBasedGame, ServerPlayer> client) {
|
||||
private void handleLogin(ParsedMessage p, NettyClient client) {
|
||||
if (!hasArgs(p.args())) return;
|
||||
|
||||
client.setName(p.args()[0]);
|
||||
}
|
||||
|
||||
private void handleSubscribe(ParsedMessage p, Client<OnlineTurnBasedGame, ServerPlayer> client) {
|
||||
private void handleSubscribe(ParsedMessage p, NettyClient client) {
|
||||
if (!hasArgs(p.args())) return;
|
||||
|
||||
server.subscribeClient(client.name(), p.args()[0]);
|
||||
}
|
||||
|
||||
private void handleHelp(ParsedMessage p, Client<OnlineTurnBasedGame, ServerPlayer> client) {
|
||||
private void handleHelp(ParsedMessage p, NettyClient client) {
|
||||
// TODO
|
||||
}
|
||||
|
||||
private void handleMessage(ParsedMessage p, Client<OnlineTurnBasedGame, ServerPlayer> client) {
|
||||
private void handleMessage(ParsedMessage p, NettyClient client) {
|
||||
// TODO
|
||||
}
|
||||
|
||||
private void handleGet(ParsedMessage p, Client<OnlineTurnBasedGame, ServerPlayer> client) {
|
||||
private void handleGet(ParsedMessage p, NettyClient client) {
|
||||
if (!hasArgs(p.args())) return;
|
||||
|
||||
switch (p.args()[0]) {
|
||||
@@ -75,10 +76,14 @@ public class MessageHandler implements Handler<ParsedMessage> {
|
||||
var names = server.gameTypes().stream().iterator();
|
||||
client.send("SVR GAMELIST " + Utils.returnQuotedString(names));
|
||||
}
|
||||
case "admins" -> {
|
||||
var names = server.getAdmins().stream().map(Client::name).iterator();
|
||||
client.send("SVR ADMINS " + Utils.returnQuotedString(names));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void handleChallenge(ParsedMessage p, Client<OnlineTurnBasedGame, ServerPlayer> client) {
|
||||
private void handleChallenge(ParsedMessage p, NettyClient client) {
|
||||
if (!hasArgs(p.args())) return;
|
||||
if (p.args().length < 2) return;
|
||||
|
||||
@@ -103,20 +108,18 @@ public class MessageHandler implements Handler<ParsedMessage> {
|
||||
server.challengeClient(client.name(), p.args()[0], p.args()[1]);
|
||||
}
|
||||
|
||||
private void handleMove(ParsedMessage p, Client<OnlineTurnBasedGame, ServerPlayer> client) {
|
||||
private void handleMove(ParsedMessage p, NettyClient client) {
|
||||
if(!hasArgs(p.args())) return;
|
||||
|
||||
// TODO check if not number
|
||||
client.player().setMove(1L << Integer.parseInt(p.args()[0]));
|
||||
}
|
||||
|
||||
private void handleTournament(ParsedMessage p, Client<OnlineTurnBasedGame, ServerPlayer> client) {
|
||||
private void handleTournament(ParsedMessage p, NettyClient 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]);
|
||||
server.startTournament(p.args()[1], client);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,85 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
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,48 +1,29 @@
|
||||
package org.toop.framework.networking.server.tournaments;
|
||||
|
||||
import org.toop.framework.networking.server.Server;
|
||||
import org.toop.framework.networking.server.tournaments.matchmakers.MatchMaker;
|
||||
import org.toop.framework.networking.server.tournaments.scoresystems.ScoreSystem;
|
||||
|
||||
public class BasicTournament implements Tournament {
|
||||
private Server server;
|
||||
private final Server server;
|
||||
|
||||
private ScoreManager scoreManager;
|
||||
private MatchManager matchManager;
|
||||
private final ScoreSystem scoreSystem;
|
||||
private final TournamentRunner tournamentRunner;
|
||||
private final MatchMaker matchMaker;
|
||||
|
||||
public BasicTournament() {}
|
||||
|
||||
public void init(TournamentBuilder builder) {
|
||||
public BasicTournament(TournamentBuilder builder) {
|
||||
server = builder.server;
|
||||
scoreManager = builder.scoreManager;
|
||||
matchManager = builder.matchManager;
|
||||
scoreSystem = builder.scoreSystem;
|
||||
tournamentRunner = builder.tournamentRunner;
|
||||
matchMaker = builder.matchMaker;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean run(String gameType) throws RuntimeException {
|
||||
if (server.gameTypes().stream().noneMatch(e -> e.equalsIgnoreCase(gameType))) return false;
|
||||
|
||||
matchManager.run(server, scoreManager, gameType);
|
||||
tournamentRunner.run(server, matchMaker, scoreSystem, 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,46 @@
|
||||
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.tournaments.matchmakers.MatchMaker;
|
||||
import org.toop.framework.networking.server.tournaments.scoresystems.ScoreSystem;
|
||||
|
||||
import java.util.concurrent.*;
|
||||
|
||||
public class BasicTournamentRunner implements TournamentRunner {
|
||||
|
||||
public BasicTournamentRunner() {}
|
||||
|
||||
@Override
|
||||
public void run(Server server, MatchMaker matchMaker, ScoreSystem scoreSystem, String gameType) {
|
||||
ExecutorService threadPool = Executors.newSingleThreadExecutor();
|
||||
try {
|
||||
threadPool.execute(() -> {
|
||||
for (var match : matchMaker) {
|
||||
final CompletableFuture<Void> finished = new CompletableFuture<>();
|
||||
|
||||
// Play game and await the results
|
||||
OnlineGame<TurnBasedGame> game = server.startGame(gameType, finished, match.getClient0(), match.getClient1()); // TODO can possibly create a race condition
|
||||
finished.join();
|
||||
// End
|
||||
|
||||
// Get result and calculate new score
|
||||
switch (game.game().getWinner()) {
|
||||
case 0 -> scoreSystem.addScore(match.getClient0());
|
||||
case 1 -> scoreSystem.addScore(match.getClient1());
|
||||
default -> {
|
||||
}
|
||||
}
|
||||
|
||||
match.getClient0().clearGame();
|
||||
match.getClient1().clearGame();
|
||||
}
|
||||
|
||||
server.endTournament(scoreSystem.getScore(), gameType);
|
||||
});
|
||||
} finally {
|
||||
threadPool.shutdown();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
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);
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import org.toop.framework.networking.server.client.NettyClient;
|
||||
import java.util.HashMap;
|
||||
|
||||
public interface Tournament {
|
||||
void init(TournamentBuilder builder);
|
||||
// void init(TournamentBuilder builder);
|
||||
boolean run(String gameType);
|
||||
// HashMap<NettyClient, Integer> end();
|
||||
}
|
||||
|
||||
@@ -1,39 +1,24 @@
|
||||
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;
|
||||
import org.toop.framework.networking.server.tournaments.matchmakers.MatchMaker;
|
||||
import org.toop.framework.networking.server.tournaments.scoresystems.ScoreSystem;
|
||||
|
||||
public class TournamentBuilder {
|
||||
public Server server;
|
||||
public ScoreManager scoreManager;
|
||||
public MatchManager matchManager;
|
||||
public ScoreSystem scoreSystem;
|
||||
public TournamentRunner tournamentRunner;
|
||||
public MatchMaker matchMaker;
|
||||
|
||||
public TournamentBuilder() {}
|
||||
|
||||
public Tournament create(
|
||||
Tournament tournament,
|
||||
List<NettyClient> clients,
|
||||
public TournamentBuilder(
|
||||
Server server,
|
||||
ScoreManager scoreManager,
|
||||
MatchManager matchManager,
|
||||
Shuffler shuffler
|
||||
TournamentRunner tournamentRunner,
|
||||
MatchMaker matchMaker,
|
||||
ScoreSystem scoreSystem
|
||||
) {
|
||||
|
||||
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;
|
||||
this.tournamentRunner = tournamentRunner;
|
||||
this.matchMaker = matchMaker;
|
||||
this.scoreSystem = scoreSystem;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,4 +7,12 @@ public class TournamentMatch extends ImmutablePair<NettyClient, NettyClient> {
|
||||
public TournamentMatch(NettyClient a, NettyClient b) {
|
||||
super(a, b);
|
||||
}
|
||||
|
||||
NettyClient getClient0() {
|
||||
return getLeft();
|
||||
}
|
||||
|
||||
NettyClient getClient1() {
|
||||
return getRight();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
package org.toop.framework.networking.server.tournaments;
|
||||
|
||||
import org.toop.framework.networking.server.Server;
|
||||
import org.toop.framework.networking.server.tournaments.matchmakers.MatchMaker;
|
||||
import org.toop.framework.networking.server.tournaments.scoresystems.ScoreSystem;
|
||||
|
||||
public interface TournamentRunner {
|
||||
void run(Server server, MatchMaker matchMaker, ScoreSystem scoreSystem, String gameType);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package org.toop.framework.networking.server.tournaments.matchmakers;
|
||||
|
||||
import org.toop.framework.networking.server.tournaments.TournamentMatch;
|
||||
|
||||
public interface MatchMaker extends Iterable<TournamentMatch> {}
|
||||
@@ -0,0 +1,65 @@
|
||||
package org.toop.framework.networking.server.tournaments.matchmakers;
|
||||
|
||||
import org.toop.framework.networking.server.client.NettyClient;
|
||||
import org.toop.framework.networking.server.tournaments.TournamentMatch;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
public class RoundRobinMatchMaker implements MatchMaker {
|
||||
|
||||
private final List<NettyClient> players;
|
||||
|
||||
public RoundRobinMatchMaker(List<NettyClient> players) {
|
||||
this.players = players;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterator<TournamentMatch> iterator() {
|
||||
return new Iterator<>() {
|
||||
|
||||
private int i = 0;
|
||||
private int j = 1;
|
||||
private boolean reverse = false;
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
return players.size() > 1
|
||||
&& i < players.size() - 1
|
||||
&& j < players.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public TournamentMatch next() {
|
||||
if (!hasNext()) {
|
||||
throw new NoSuchElementException();
|
||||
}
|
||||
|
||||
NettyClient home = players.get(i);
|
||||
NettyClient away = players.get(j);
|
||||
|
||||
TournamentMatch match = reverse ? new TournamentMatch(away, home) : new TournamentMatch(home, away);
|
||||
|
||||
advance();
|
||||
return match;
|
||||
}
|
||||
|
||||
private void advance() {
|
||||
j++;
|
||||
if (j >= players.size()) {
|
||||
i++;
|
||||
j = i + 1;
|
||||
|
||||
if (i >= players.size() - 1) {
|
||||
if (!reverse) {
|
||||
reverse = true;
|
||||
i = 0;
|
||||
j = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package org.toop.framework.networking.server.tournaments.scoresystems;
|
||||
|
||||
import org.toop.framework.networking.server.client.NettyClient;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class BasicScoreSystem implements ScoreSystem {
|
||||
|
||||
private final Map<NettyClient, Integer> scores = new HashMap<>();
|
||||
|
||||
public BasicScoreSystem(List<NettyClient> store) {
|
||||
for (NettyClient c : store) {
|
||||
scores.putIfAbsent(c, 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,11 +1,10 @@
|
||||
package org.toop.framework.networking.server.tournaments;
|
||||
package org.toop.framework.networking.server.tournaments.scoresystems;
|
||||
|
||||
import org.toop.framework.networking.server.client.NettyClient;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public interface ScoreManager {
|
||||
void addClient(NettyClient client);
|
||||
public interface ScoreSystem {
|
||||
void addScore(NettyClient client);
|
||||
Map<NettyClient, Integer> getScore();
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package org.toop.framework.networking.server.tournaments;
|
||||
package org.toop.framework.networking.server.tournaments.shufflers;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
@@ -1,4 +1,4 @@
|
||||
package org.toop.framework.networking.server.tournaments;
|
||||
package org.toop.framework.networking.server.tournaments.shufflers;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
Reference in New Issue
Block a user