Working tournament

This commit is contained in:
Bas de Jong
2026-01-09 22:28:15 +01:00
parent 9c01aabbe1
commit 5e5948d1fe
9 changed files with 225 additions and 9 deletions

View File

@@ -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");

View File

@@ -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);

View File

@@ -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);

View File

@@ -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

View File

@@ -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);
}
}
}

View File

@@ -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]);
}
}
}

View File

@@ -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;
}
}

View File

@@ -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();
}

View File

@@ -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);
}
}