* Server update with new dev changes (#305)

* merge widgets with development

* readd previous game thread code

* Revert "readd previous game thread code"

This reverts commit d24feef73e.

* Revert "Merge remote-tracking branch 'origin/Development' into Development"

This reverts commit 59d46cb73c, reversing
changes made to 38681c5db0.

* Revert "merge widgets with development"

This reverts commit 38681c5db0.

* Merge 292 into development (#293)

Applied template method pattern to abstract player

* Added documentation to player classes and improved method names (#295)

* mcts v1

* bitboard optimization

* bitboard fix & mcts v2 & mcts v3. v3 still in progress and v4 coming soon

* main

* Hotfix for stuff

* Logging and fixed user input getting stuck

* Fixed merge mistakes (#307)

* fast server connection

* Fixed bugs and oversights

* Renamed asset folder to resource, made resourceLoader more robust. Completed some TODO's, formatting

* AppSettings now also get loaded into the assetmanager

* start to reversi logic

* legal moves now get highlighted in red

* Moves flip dots. all tests pass. can play reversi local.

* Working state. Split AudioManager into 3 different branches for easier testing and srp

* Reworked to now use better defined generics and easier to use API. Added AudioResource to be used in changing volume

* Made all of the updated classes more generic for better flexibility in unittesting

* Added more flexible dependency injection to MusicManager for unittesting. Moved to event driven design for less complex code and lower runtime complexity.

* Split SoundEffectManager from AudioManager. (#171)

Clips no longer create a new clip instance each time they are played.  A singular clip is made for each resource and is opened/closed when loaded/unloaded. When a clip is played that is already playing it'll stop playback and start again. Clip volume handling isn't done very well.

* Unit tests for MusicManager.java

* Hotfix for loading clip volume issue (#174)

* Fixed AudioVolumemanager, all volumes calculations are now made in VolumeTypes enum

* Added ability to remove a manager from VolumeTypes

* Removed file no longer in use

* Fixed grammer and spelling mistakes

* Renamed VOLUME to MASTERVOLUME for better naming

* Minor changes in API design

* Renamed VolumeTypes to VolumeControl. Made it thread safe. Added docs to VolumeControl and co.
removed .updateAllVolumes() in favor of auto updating inside enum instead

* Added ErrorProne for potential bugs. Fixed potential bugs.

* Small fixes.

* Removed no more needed code.

* Finished todo's

* Moved restrictedAPI to future release

* Finished todo's

* Moved restrictedAPI to future release

* Changed pom to be correct.
Fixed SnowflakeGenerator not making unique ids.
Changed naming for event implementation.
Automated id getter for events.
Added Error-Prone to all modules.
Added parents to all modules.
Added processors module.

* SoundEffectManager now generic

* Removed ResourceManager from AudioManagers

* Added linelistener to SoundEffectAsset

* commit

* commit ofzo

* Tests for SoundEffectManager

* getLegalMoves logic seems fixed //todo write better tests

* Tests toegevoegd

* punk toegevoegd

* Added shuffling on user request

* Reworked NetworkingClientManager into SRP model.

* Forgot to remove

* Improved API for dependency injection

* Some better docs.

* gui refactor

* fixed merge conflicts

* Added exceptions. Added reconnect attempts and changeable address

* Fixed event bug

* add: reversi game

* add: server chat box

* visual update

* Refactor to make Events easier to work with.

* Quick fix for closing connection.

* Documentation

* Correct client creation and user polling

* begin van audio display

* Polling music event, fires every 1 second

* Updated test.

* Updated timings

* Nuke everything on close.

* Basis Audio Display toegevoegd + standaard CSS toegevoegd

Kan nu zien hoe lang de song duurt, hoe lang ie al bezig is met draaien en de titel (-.mp3)

* Clips now also return positional information

* Skip Button

* Skip Button

* Fixes for garbage code by Omar

* Tiny fix when natural skip

* Small event fix

* Faster event schedule for PlayingMusic event

* test fix

* added method for sorting the flipped pieces by distance to Move.position

* new reversi test (both players no legal moves)

* connect4 with minimax AI

* Toegevoegd:

-Play Button + CSS + Events
-Previous Button + CSS + Events
-Changed interface for AudioResource to include a pause button which works really well with mediaplayer, however now SoundEffectAsset has an unnessescary pause

* Made it so that it indicates with the play/pause button if its paused or played

* add simple flip animations and fixed(?) server somewhat

* fixed tests

* can start game from playerlist screen

* tourney ready

* spam minder

* fixed setgamelabels

* spam minder v2

* canvas changes

* moved score out of game

* can now go to last using previous and being at the first song

* mainview false for sendchallengeview

* moved score out of game

* kleine ui fix

* updated music ma,es

* started working on the widget system

* iets met timing verkeerd temporary fix

* Fixes for garbage code by Omar

* Added replace to reduce boiler plate code

* Manually fallback to the fallback locale when a ResourceBundle is missing a resource key. Fallsback to "MISSING RESOUREC" if it's not present in the fallback.

* Removed unused import and unused parameter

* cool onhover effect for reversi

* Made the GameState enum it's own file and fixed imports

* Removed unused import

* Turned abstract methods into an interface

* Moved the Move record into it's own file, seperated from Game

* Removed unused imports

* Renamed Interface Playtable to IPlayable

* Turned Abstract Method for AI into interface

* Refactored Game to follow encapsulation principle

* Removed unused imports

* Applied encapsulation principle to TurnBasedBame.java

* Privated methods that didn't have to be public

* Reversi: made method private

* Changed checkForEarlyDraw so it doesn't need a game as input.

* Fixed warning "Warning:(27, 12) Copy constructor does not copy field 'mostRecentlyFlippedPieces'", removed unused field

* Made connect4 public method private

* half done with the widget system

* added some comments and made some methods a bit more readable

* widget system almost complete

* Functional code, is now object orientated

* Removed no more needed comments

* started a basis for the tutorials, tic tac toe is almost done with some general stuff still to do.

* rest van de tutorials toegevoegd

* resizable true

* fixed turn skip bug
fixed end score bug
now only shows legal and highlight moves when human

* Squashed commit of the following:

commit a517f2f302baa89f8ef59946a31c7bb59c56770f
Author: Stef <stbuwalda@gmail.com>
Date:   Thu Nov 27 15:43:43 2025 +0100

    Make it so the game shows "Waiting on ... to make their move". Styling isn't done but it is easier to see who's turn it is. There is a lot of structuring to do in the previous code...

* merge widgets with development

* readd previous game thread code

* Revert "readd previous game thread code"

This reverts commit d24feef73e.

* Revert "Merge remote-tracking branch 'origin/Development' into Development"

This reverts commit 59d46cb73c, reversing
changes made to 38681c5db0.

* Revert "merge widgets with development"

This reverts commit 38681c5db0.

* Fixed compilation errors

* Changed the way turns are being stored in TurnBasedGame.

* Removed views

* Added function input for enabling/disabling localization p/text

* Fix eventbus problems (#265)

* Added unsubscribe to EventFlow. ListenerHandler now functional. GlobalEventbus now user listenerHandler

* getAllListeners

* Removed nulls

* Fixed stress tests

* Added docs, no more list creation when adding events to the bus.

* Fixed unsubscribe not working.

* Moved away from deprecated functions

* moved from wildcard to typed

* Moved away from deprecated function

* Debugs for EventBus and fixed unsubscribe all (#266)

* Added unsubscribe to EventFlow. ListenerHandler now functional. GlobalEventbus now user listenerHandler

* getAllListeners

* Removed nulls

* Fixed stress tests

* Added docs, no more list creation when adding events to the bus.

* Fixed unsubscribe not working.

* Moved away from deprecated functions

* moved from wildcard to typed

* Moved away from deprecated function

* Added debugging to GlobalEventBus

* Fixed cleaning flow

* Fixed unsubscribe all

* Fixed unsubscribe all

* Removed unused import

* Fix music display not working (#267)

* Added unsubscribe to EventFlow. ListenerHandler now functional. GlobalEventbus now user listenerHandler

* getAllListeners

* Removed nulls

* Fixed stress tests

* Added docs, no more list creation when adding events to the bus.

* Fixed unsubscribe not working.

* Moved away from deprecated functions

* moved from wildcard to typed

* Moved away from deprecated function

* Added debugging to GlobalEventBus

* Fixed cleaning flow

* Fixed unsubscribe all

* Fixed unsubscribe all

* Removed unused import

* Added LoadingWidget.java for server feedback

* Replace deprecated with correct function

* Removed loading widget from Server.java

* Fixed old new EventFlow().listen() missing false as third param

* Tutorials to Dev (#264)

* Fixed garbage code

* added a pop button

* Tutorial images now use ImageAsset.java

* Added button to continue and start game. Refactors

* Refactored nextScreen runnable

* Removed unused imports

* Refactored switch statement

* Added documentation

* Removed space

* Added translations

* Added function input for enabling/disabling localization p/text

---------

Co-authored-by: ramollia <>

* Merge new framework into development (#269)

* Created a somewhat generic TurnBasedGame thread. Temporary UI that only works for TicTacToe rn. Added a LocalPlayer with the intent to add more players

* (RANDOM COMMIT) Hope it works

* Changes by bas

* Fixed dependency issues

* Fixed major issue in game deepcopy

* Merge conflict fix

* Removed unused import

* Update GTBGT branch from dev branch (#263)

* started a basis for the tutorials, tic tac toe is almost done with some general stuff still to do.

* rest van de tutorials toegevoegd

* Removed views

* Merge conflict fix

* Removed unused import

---------

Co-authored-by: michiel301b <m.brands.3@st.hanze.nl>
Co-authored-by: ramollia <>
Co-authored-by: Bas Antonius de Jong <49651652+BAFGdeJong@users.noreply.github.com>

* Revert "Update GTBGT branch from dev branch (#263)"

This reverts commit 9134d7e343.

* Fixed frontend not using GameController because of spaghetti code.

* Removed unused imports

* GameCanvas not implements a DrawPlayerMove that can be overridden for specific implementations

* Created an event that will request the controller to refresh the UI.

* ADDED DEPENDENCY. Renamed GameControllers to GameManagers, gameThread is not game controller.

* Attempt at adding an online player. I think it doesn't work because of unsubscriben after success not working

* Multiplayer is functional through OnlineThreadBehaviour. Empty slots are currently represented by -1 in the GUI.

* Removed sout spam, added logger than I can't get to work.

* Idek what these changes are

* Te lang geen commit, sorry

* Multiplayer seems to work pretty well now, hopefully I can add the other games soon.

* Added unsubscribe to EventFlow. ListenerHandler now functional. GlobalEventbus now user listenerHandler

* getAllListeners

* Removed nulls

* Inbetween commit of adding Reversi. This is a lot of spaghetti.

* Fixed stress tests

* Fixed typo in NetworkingGameClientHandler that prevented losses from being received

* Missed 2nd typo. Fixed

* Added docs, no more list creation when adding events to the bus.

* Fixed unsubscribe not working.

* Moved away from deprecated functions

* moved from wildcard to typed

* Moved away from deprecated function

* Added debugging to GlobalEventBus

* Fixed cleaning flow

* Fixed unsubscribe all

* Fixed unsubscribe all

* Removed unused import

* Works now with updated EventFlow(). Unsubscribing works. ReversiAIR has an issue where a forced move returns -1 and local play back button doesn't work properly. To be fixed

* Fixed ReversiR issue that caused skip turn desync

* Fixed color mismatch with server and online main player is now correct.

* Added a bunch of java doc and small changes

* Small changes

* Added a new Thread Behaviour to test framework.

* Fixed human error I made in TicTacToeR logic...

* Fixed broken event and wrong player being presented as winner.

* Idk changes

* Fixed PR conflicts

---------

Co-authored-by: michiel301b <m.brands.3@st.hanze.nl>
Co-authored-by: Bas Antonius de Jong <49651652+BAFGdeJong@users.noreply.github.com>

* added back button sounds because SOMEONE fucked it up.....

* 231 connecting to server feedback (#275)

* Added unsubscribe to EventFlow. ListenerHandler now functional. GlobalEventbus now user listenerHandler

* getAllListeners

* Removed nulls

* Fixed stress tests

* Added docs, no more list creation when adding events to the bus.

* Fixed unsubscribe not working.

* Moved away from deprecated functions

* moved from wildcard to typed

* Moved away from deprecated function

* Added debugging to GlobalEventBus

* Fixed cleaning flow

* Fixed unsubscribe all

* Fixed unsubscribe all

* Removed unused import

* Added LoadingWidget.java for server feedback

* Imports

* fixed loadingwidget

* Workable LoadingWidget and trying to connect to server

* Removed output

* Small bug temp fix

---------

Co-authored-by: ramollia <>

* Double loading call fix, LoadingWidget docs

* Main menu loader (#277)

* LoadingWidget main menu

* fixed garbage code

* Fixed garbage code 2

* LoadWidget fix, added loading to starting the game. Removed unnecessary console output

---------

Co-authored-by: ramollia <>

* Fixed systems starting, before assets being loaded (I am retarded)

* Added infinite boolean, fixed loading behaviour at startup

* 272 remake game framework interfaces to properly represent vmc (#278)

* Cleaned up a lot of old files and renamed/remade interfaces to better suit the framework

* Broken commit

* Fixed online play

* Better file structure and closer to MVC

* Best fix for white screen at start

* Making threads verbose regarding exceptions

* Loading circle, better loading colors.

* Event bus now testable, improved UI (#284)

* turn updates

* smalle fixes aan turn updates

* better human/ai selector with bot selection and depth on TicTacToeAIR

* depth + thinktime back to AIs, along with a a specific TicTacToeAIRSleep

* fixed overlapping back and disconnect buttons

* Changed to debug instead of info

* changed the transitionNextCustom to be easier to use

* added getAllWidgets to WidgetContainer

* Correct back view

* added replacePrevious in ViewWidget

* added removeIndexFromPreviousChain

* fixed incorrect index counting

* Fixt wrong view order

* Removed todo

* Challenge popups "Fixed"

* Popups now remove themselves

* localize the ChallengePopup text

* made the game text a header instead

* fixed getAllWidgets

* Escape popup

* fixed redundant container

* Escape remove popup

* Working escape menu

* Added find functionality

* Tutorials moved to escape menu

* Escape can't be opened in mainview now

* Can now test the event bus, created testable interfaces

* Logging errors

* Made events and handlers more generic

* Suppress

* Managers now have changeable eventbus

* Tutorials fixed

* Removed import

* Single threaded eventbus

* Fixed wrong eventbus

* Removed get

* Removed old code

* Renaming

* Optimization

* Removed useless comment

* Removed unnecessary imports

* Rename

* Renaming, refactor and type safety

* Rename

* Removed import

---------

Co-authored-by: michiel301b <m.brands.3@st.hanze.nl>
Co-authored-by: ramollia <>

* initSystems now uses latch instead of timer. Moved single threads to Executor

* Safety

* Deleted unnecessary imports

* Code cleanup

* changed "fullscreen exit key combination" from esc to F11

* shitty fix for player selector spacing issue

* shitty fix for player selector spacing issue v2

* fixed reversi colors being switched, causing multiple issues

* Merge bitboards into development (#285)

* added new classes for the games that use bitboards instead. also combined game with turnbasedgame

* (DOES NOT COMPILE) In-between commit

* turn updates

* smalle fixes aan turn updates

* Bitboard implemented with scuffed TicTacToe translation done by game. This should be done by the view.

* Almost done with implementing bitboards. Reversi is broken and artifical players don't work yet.

* better human/ai selector with bot selection and depth on TicTacToeAIR

* fixed getLegalMoves

* depth + thinktime back to AIs, along with a a specific TicTacToeAIRSleep

* fixed overlapping back and disconnect buttons

* Changed to debug instead of info

* changed the transitionNextCustom to be easier to use

* added getAllWidgets to WidgetContainer

* Correct back view

* added replacePrevious in ViewWidget

* added removeIndexFromPreviousChain

* fixed incorrect index counting

* Fixt wrong view order

* fixed? getLegalMoves

* Everything is broken

* Removed todo

* fixed getLegalMoves & getFlips

* Challenge popups "Fixed"

* Fixed local and online play for both games

* Popups now remove themselves

* Removed souts for debugging

* localize the ChallengePopup text

* made the game text a header instead

* made more classes deepClonable.

* fixed getAllWidgets

* Added comment

* Escape popup

* fixed redundant container

* Made all network events async again

* Escape remove popup

* Working escape menu

* Removed old AI and old files. Added a new generic random AI. game no longer deals with translation.

* Drawing of board on canvas is now done from bitboards rather than translating.

* Added a method getWinner() to game interface.Controller now tells gameThreads how to deal with drawing UI and sending a move to server.

* Added find functionality

* Added a ChatGPT generated MiniMaxAI based on the old MiniMaxAI but with alpha-beta pruning and heuristics for Reversi

* Removed System-Outs to clean up console

* Update BitGameCanvas.java

* Merge fixes

* Removed unused imports

---------

Co-authored-by: ramollia <>
Co-authored-by: michiel301b <m.brands.3@st.hanze.nl>
Co-authored-by: lieght <49651652+BAFGdeJong@users.noreply.github.com>

* Better limits to generic acceptance

* Will fix tests etc later

* Merge 292 into development (#293)

Applied template method pattern to abstract player

* Added documentation to player classes and improved method names (#295)

* Init server code

* Moves

* Testing code

* Removed Generics, pray nothing breaks.

* Code cleanup

* Tests and better instantiation

* Init challenges

* Working challenges

* Fixed bugs, easy to use host button

* Fixed tic tac toe naming

* Fixes

* Removed Generics, pray nothing breaks.

* Added ability to take ServerPlayer from user

* Added pairs

* Using pairs now in server.java

* Removed space in naming

* Werkt nog niet

* Fixed hasArgs

* Closable server

* Making moves works. Game notifies when game has ended.

* Partial server refactor

* Refactor done, added ability to subscribe

* Working subscription, button only subs to reversi right now

* Small improvements to usability, auto disconnect when server closes connection

* Missed a boolean

* Quick fix so more than one game can be played in succession

* Removed user from subscription if in a game

* UI fixes after game end

* TableWidget

* mcts v1

* Moved subscriptions to store

* bitboard optimization

* Collapsed interfaces from model portion

* Fixed runtime error I forgot to fix.

* Collapsed interfaces in Controller section

* Collapsed interfaces in View section

* Code readability

* bitboard fix & mcts v2 & mcts v3. v3 still in progress and v4 coming soon

* main

* 289 server demo ready (#306)

* Server update with new dev changes (#305)

* merge widgets with development

* readd previous game thread code

* Revert "readd previous game thread code"

This reverts commit d24feef73e.

* Revert "Merge remote-tracking branch 'origin/Development' into Development"

This reverts commit 59d46cb73c, reversing
changes made to 38681c5db0.

* Revert "merge widgets with development"

This reverts commit 38681c5db0.

* Merge 292 into development (#293)

Applied template method pattern to abstract player

* Added documentation to player classes and improved method names (#295)

* mcts v1

* bitboard optimization

* bitboard fix & mcts v2 & mcts v3. v3 still in progress and v4 coming soon

* main

* Hotfix for stuff

* Logging and fixed user input getting stuck

* Fixed merge mistakes

* Revert "Merge remote-tracking branch 'refs/remotes/origin/main' into Development"

This reverts commit e2132b549d, reversing
changes made to 9aefcb9b7b.

---------

Co-authored-by: ramollia <@>
Co-authored-by: Ticho Hidding <tichohidding@gmail.com>
Co-authored-by: Stef <48526421+StefBuwalda@users.noreply.github.com>
Co-authored-by: Stef <stbuwalda@gmail.com>
Co-authored-by: michiel <m.brands.3@st.hanze.nl>
Co-authored-by: ramollia <>
Co-authored-by: tichohidding <58555714+tichohidding@users.noreply.github.com>
This commit is contained in:
Bas Antonius de Jong
2026-01-09 19:30:49 +01:00
committed by GitHub
parent 8146be16ed
commit 429e5bc90b
114 changed files with 3173 additions and 671 deletions

View File

@@ -0,0 +1,111 @@
package org.toop.framework.game;
import org.toop.framework.gameFramework.GameState;
import org.toop.framework.gameFramework.model.game.PlayResult;
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
import org.toop.framework.gameFramework.model.player.Player;
import java.util.Arrays;
// There is AI performance to be gained by getting rid of non-primitives and thus speeding up deepCopy
public abstract class BitboardGame implements TurnBasedGame {
private final int columnSize;
private final int rowSize;
protected PlayResult state;
private Player[] players;
// long is 64 bits. Every game has a limit of 64 cells maximum.
private final long[] playerBitboard;
private int currentTurn = 0;
private final int playerCount;
public BitboardGame(int columnSize, int rowSize, int playerCount) {
this.columnSize = columnSize;
this.rowSize = rowSize;
this.playerCount = playerCount;
this.state = new PlayResult(GameState.NORMAL, -1);
this.playerBitboard = new long[playerCount];
Arrays.fill(playerBitboard, 0L);
}
@Override
public void init(Player[] players) {
this.players = players;
Arrays.fill(playerBitboard, 0L);
}
public BitboardGame(BitboardGame other) {
this.columnSize = other.columnSize;
this.rowSize = other.rowSize;
this.playerCount = other.playerCount;
this.state = other.state;
this.playerBitboard = other.playerBitboard.clone();
this.currentTurn = other.currentTurn;
this.players = other.players;
// TODO: Players are not deep copied, which is bad. I don't know why but deepcopying breaks it. Fix it
//this.players = Arrays.stream(other.players)
// .map(Player::deepCopy)
// .toArray(Player[]::new);
}
public int getColumnSize() {
return this.columnSize;
}
public int getRowSize() {
return this.rowSize;
}
public long getPlayerBitboard(int player) {
return this.playerBitboard[player];
}
public void setPlayerBitboard(int player, long bitboard) {
this.playerBitboard[player] = bitboard;
}
public int getPlayerCount() {
return playerBitboard.length;
}
public int getCurrentTurn() {
return getCurrentPlayerIndex();
}
public Player getPlayer(int index) {return players[index];}
public int getCurrentPlayerIndex() {
return currentTurn % playerBitboard.length;
}
public int getNextPlayer() {
return (currentTurn + 1) % playerBitboard.length;
}
public Player getCurrentPlayer(){
return players[getCurrentPlayerIndex()];
}
@Override
public PlayResult getState() {
return state;
}
@Override
public boolean isTerminal() {
return state.state() == GameState.WIN || state.state() == GameState.DRAW;
}
@Override
public long[] getBoard() {return this.playerBitboard;}
public void nextTurn() {
currentTurn++;
}
}

View File

@@ -0,0 +1,3 @@
package org.toop.framework.game;
// TODO: Remove this, only used in ReversiCanvas. Needs to not
public record Move(int position, char value) {}

View File

@@ -0,0 +1,88 @@
package org.toop.framework.game.gameThreads;
import org.toop.framework.eventbus.EventFlow;
import org.toop.framework.gameFramework.GameState;
import org.toop.framework.gameFramework.model.game.PlayResult;
import org.toop.framework.gameFramework.model.game.threadBehaviour.AbstractThreadBehaviour;
import org.toop.framework.gameFramework.view.GUIEvents;
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
import org.toop.framework.gameFramework.model.player.Player;
import java.util.function.Consumer;
/**
* Handles local turn-based game logic at a fixed update rate.
* <p>
* Runs a separate thread that executes game turns at a fixed frequency (default 60 updates/sec),
* applying player moves, updating the game state, and dispatching UI events.
*/
public class LocalFixedRateThreadBehaviour extends AbstractThreadBehaviour implements Runnable {
/**
* Creates a fixed-rate behaviour for a local turn-based game.
*
* @param game the game instance
*/
public LocalFixedRateThreadBehaviour(TurnBasedGame game) {
super(game);
}
/** Starts the game loop thread if not already running. */
@Override
public void start() {
if (isRunning.compareAndSet(false, true)) {
new Thread(this).start();
}
}
/** Stops the game loop after the current iteration. */
@Override
public void stop() {
isRunning.set(false);
}
/**
* Main loop running at a fixed rate.
* <p>
* Fetches the current player's move, applies it to the game,
* updates the UI, and handles game-ending states.
*/
@Override
public void run() {
final int UPS = 1;
final long UPDATE_INTERVAL = 1_000_000_000L / UPS;
long nextUpdate = System.nanoTime();
while (isRunning.get()) {
long now = System.nanoTime();
if (now >= nextUpdate) {
nextUpdate += UPDATE_INTERVAL;
Player currentPlayer = game.getPlayer(game.getCurrentTurn());
long move = currentPlayer.getMove(game.deepCopy());
PlayResult result = game.play(move);
updateUI();
GameState state = result.state();
switch (state) {
case WIN, DRAW -> {
isRunning.set(false);
new EventFlow().addPostEvent(GUIEvents.GameEnded.class, state == GameState.WIN, result.player()).postEvent();
}
case NORMAL, TURN_SKIPPED -> { /* continue */ }
default -> {
logger.error("Unexpected state {}", state);
isRunning.set(false);
throw new RuntimeException("Unknown state: " + state);
}
}
} else {
try {
Thread.sleep(10);
} catch (InterruptedException ignored) {}
}
}
}
}

View File

@@ -0,0 +1,76 @@
package org.toop.framework.game.gameThreads;
import org.toop.framework.eventbus.EventFlow;
import org.toop.framework.gameFramework.model.game.threadBehaviour.AbstractThreadBehaviour;
import org.toop.framework.gameFramework.view.GUIEvents;
import org.toop.framework.gameFramework.model.game.PlayResult;
import org.toop.framework.gameFramework.GameState;
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
import org.toop.framework.gameFramework.model.player.Player;
import java.util.function.Consumer;
/**
* Handles local turn-based game logic in its own thread.
* <p>
* Repeatedly gets the current player's move, applies it to the game,
* updates the UI, and stops when the game ends or {@link #stop()} is called.
*/
public class LocalThreadBehaviour extends AbstractThreadBehaviour implements Runnable {
/**
* Creates a new behaviour for a local turn-based game.
*
* @param game the game instance
*/
public LocalThreadBehaviour(TurnBasedGame game) {
super(game);
}
/** Starts the game loop in a new thread. */
@Override
public void start() {
if (isRunning.compareAndSet(false, true)) {
new Thread(this).start();
}
}
/** Stops the game loop after the current iteration. */
@Override
public void stop() {
isRunning.set(false);
}
/**
* Main game loop: gets the current player's move, applies it,
* updates the UI, and handles end-of-game states.
*/
@Override
public void run() {
while (isRunning.get()) {
Player currentPlayer = game.getPlayer(game.getCurrentTurn());
long move = currentPlayer.getMove(game.deepCopy());
PlayResult result = game.play(move);
updateUI();
GameState state = result.state();
switch (state) {
case WIN, DRAW -> {
isRunning.set(false);
new EventFlow().addPostEvent(
GUIEvents.GameEnded.class,
state == GameState.WIN,
result.player()
).postEvent();
}
case NORMAL, TURN_SKIPPED -> { /* continue normally */ }
default -> {
logger.error("Unexpected state {}", state);
isRunning.set(false);
throw new RuntimeException("Unknown state: " + state);
}
}
}
}
}

View File

@@ -0,0 +1,114 @@
package org.toop.framework.game.gameThreads;
import org.toop.framework.eventbus.EventFlow;
import org.toop.framework.gameFramework.model.game.threadBehaviour.AbstractThreadBehaviour;
import org.toop.framework.gameFramework.view.GUIEvents;
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
import org.toop.framework.gameFramework.model.game.threadBehaviour.SupportsOnlinePlay;
import org.toop.framework.gameFramework.model.player.Player;
import org.toop.framework.game.players.OnlinePlayer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Handles online multiplayer game logic.
* <p>
* Reacts to server events, sending moves and updating the game state
* for the local player while receiving moves from other players.
*/
public class OnlineThreadBehaviour extends AbstractThreadBehaviour implements SupportsOnlinePlay {
private ExecutorService moveExecutor = Executors.newSingleThreadExecutor();
/**
* Creates behaviour and sets the first local player
* (non-online player) from the given array.
*/
public OnlineThreadBehaviour(TurnBasedGame game) {
super(game);
}
/** Finds the first non-online player in the array. */
private int getFirstNotOnlinePlayer(Player[] players) {
for (int i = 0; i < players.length; i++) {
if (!(players[i] instanceof OnlinePlayer)) {
return i;
}
}
throw new RuntimeException("All players are online players");
}
/** Starts processing network events for the local player. */
@Override
public void start() {
isRunning.set(true);
}
/** Stops processing network events. */
@Override
public void stop() {
isRunning.set(false);
}
/**
* Called when the server notifies that it is the local player's turn.
* Sends the generated move back to the server.
*/
@Override
public void onYourTurn(long clientId) {
logger.info("Yourturn");
if (!isRunning.get()) {
logger.warn("Game is not running!");
return;
}
TurnBasedGame gameCopy = game.deepCopy();
if (gameCopy == null) {
logger.error("Could not deep copy game");
return;
}
logger.info("Successfully collected game copy");
Player player = gameCopy.getPlayer(game.getCurrentTurn());
if (player == null) {
logger.error("Could not find current turn's player");
return;
}
logger.info("Successfully collected current turn's player");
moveExecutor.submit(() -> {
long move = player.getMove(gameCopy);
logger.info("Move set: {}", move);
logger.info("Completed onYourTurn");
sendMove(clientId, move);
});
}
/**
* Handles a move received from the server for any player.
* Updates the game state and triggers a UI refresh.
*/
public void onMoveReceived(long move) {
if (!isRunning.get()) return;
game.play(move);
updateUI();
}
/**
* Handles the end of the game as notified by the server.
* Updates the UI to show a win or draw result for the local player.
*/
public void gameFinished(String condition) {
switch(condition.toUpperCase()){
case "WIN", "LOSS" -> new EventFlow().addPostEvent(GUIEvents.GameEnded.class, true, game.getWinner()).postEvent();
case "DRAW" -> new EventFlow().addPostEvent(GUIEvents.GameEnded.class, false, -1).postEvent();
default -> {
logger.error("Invalid condition");
throw new RuntimeException("Unknown condition");
}
}
}
}

View File

@@ -0,0 +1,39 @@
package org.toop.framework.game.gameThreads;
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
/**
* Online thread behaviour that adds a fixed delay before processing
* the local player's turn.
* <p>
* This is identical to {@link OnlineThreadBehaviour}, but inserts a
* short sleep before delegating to the base implementation.
*/
public class OnlineWithSleepThreadBehaviour extends OnlineThreadBehaviour {
/**
* Creates the behaviour and forwards the players to the base class.
*
* @param game the online-capable turn-based game
*/
public OnlineWithSleepThreadBehaviour(TurnBasedGame game) {
super(game);
}
/**
* Waits briefly before handling the "your turn" event.
*
* @param event the network event indicating it's this client's turn
*/
@Override
public void onYourTurn(long clientId) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
super.onYourTurn(clientId);
}
}

View File

@@ -0,0 +1,82 @@
package org.toop.framework.game.gameThreads;
import org.toop.framework.eventbus.EventFlow;
import org.toop.framework.gameFramework.GameState;
import org.toop.framework.gameFramework.model.game.PlayResult;
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
import org.toop.framework.gameFramework.model.game.threadBehaviour.AbstractThreadBehaviour;
import org.toop.framework.gameFramework.model.player.Player;
import org.toop.framework.gameFramework.view.GUIEvents;
import org.toop.framework.utils.ImmutablePair;
import org.toop.framework.utils.Pair;
import java.util.function.Consumer;
import static org.toop.framework.gameFramework.GameState.TURN_SKIPPED;
import static org.toop.framework.gameFramework.GameState.WIN;
public class ServerThreadBehaviour extends AbstractThreadBehaviour implements Runnable {
private final Consumer<ImmutablePair<String, Integer>> onPlayerMove;
private final Consumer<Pair<GameState, Integer>> onGameEnd;
/**
* Creates a new base behaviour for the specified game.
*
* @param game the turn-based game to control
*/
public ServerThreadBehaviour(TurnBasedGame game, Consumer<ImmutablePair<String, Integer>> onPlayerMove, Consumer<Pair<GameState, Integer>> onGameEnd) {
this.onPlayerMove = onPlayerMove;
this.onGameEnd = onGameEnd;
super(game);
}
private void notifyPlayerMove(ImmutablePair<String, Integer> pair) {
if (onPlayerMove != null) {
onPlayerMove.accept(pair);
}
}
private void notifyGameEnd(ImmutablePair<GameState, Integer> pair) {
if (onGameEnd != null) {
onGameEnd.accept(pair);
}
}
/** Starts the game loop in a new thread. */
@Override
public void start() {
if (isRunning.compareAndSet(false, true)) {
new Thread(this).start();
}
}
/** Stops the game loop after the current iteration. */
@Override
public void stop() {
isRunning.set(false);
}
@Override
public void run() {
while (isRunning.get()) {
Player currentPlayer = game.getPlayer(game.getCurrentTurn());
long move = currentPlayer.getMove(game.deepCopy());
PlayResult result = game.play(move);
GameState state = result.state();
notifyPlayerMove(new ImmutablePair<>(currentPlayer.getName(), Long.numberOfTrailingZeros(move)));
switch (state) {
case WIN, DRAW -> {
isRunning.set(false);
notifyGameEnd(new ImmutablePair<>(state, game.getWinner()));
}
case NORMAL, TURN_SKIPPED -> { /* continue normally */ }
default -> {
logger.error("Unexpected state {}", state);
isRunning.set(false);
throw new RuntimeException("Unknown state: " + state);
}
}
}
}
}

View File

@@ -0,0 +1,328 @@
package org.toop.framework.game.games.reversi;
import org.toop.framework.game.BitboardGame;
import org.toop.framework.gameFramework.GameState;
import org.toop.framework.gameFramework.model.game.PlayResult;
import org.toop.framework.gameFramework.model.player.Player;
import org.toop.framework.game.BitboardGame;
public class BitboardReversi extends BitboardGame {
public record Score(int black, int white) {}
private final long notAFile = 0xfefefefefefefefeL;
private final long notHFile = 0x7f7f7f7f7f7f7f7fL;
public BitboardReversi() {
super(8, 8, 2);
}
@Override
public void init(Player[] players) {
super.init(players);
// Black (player 0)
setPlayerBitboard(0, (1L << (3 + 4 * 8)) | (1L << (4 + 3 * 8)));
// White (player 1)
setPlayerBitboard(1, (1L << (3 + 3 * 8)) | (1L << (4 + 4 * 8)));
}
public BitboardReversi(BitboardReversi other) {
super(other);
}
public long getLegalMoves() {
long legalMoves = 0L;
final long player = getPlayerBitboard(getCurrentPlayerIndex());
final long opponent = getPlayerBitboard(getNextPlayer());
final long empty = ~(player | opponent);
long mask;
long direction;
// north
mask = opponent;
direction = (player << 8) & mask;
direction |= (direction << 8) & mask;
direction |= (direction << 8) & mask;
direction |= (direction << 8) & mask;
direction |= (direction << 8) & mask;
direction |= (direction << 8) & mask;
legalMoves |= (direction << 8) & empty;
// south
mask = opponent;
direction = (player >>> 8) & mask;
direction |= (direction >>> 8) & mask;
direction |= (direction >>> 8) & mask;
direction |= (direction >>> 8) & mask;
direction |= (direction >>> 8) & mask;
direction |= (direction >>> 8) & mask;
legalMoves |= (direction >>> 8) & empty;
// east
mask = opponent & notAFile;
direction = (player << 1) & mask;
direction |= (direction << 1) & mask;
direction |= (direction << 1) & mask;
direction |= (direction << 1) & mask;
direction |= (direction << 1) & mask;
direction |= (direction << 1) & mask;
legalMoves |= (direction << 1) & empty & notAFile;
// west
mask = opponent & notHFile;
direction = (player >>> 1) & mask;
direction |= (direction >>> 1) & mask;
direction |= (direction >>> 1) & mask;
direction |= (direction >>> 1) & mask;
direction |= (direction >>> 1) & mask;
direction |= (direction >>> 1) & mask;
legalMoves |= (direction >>> 1) & empty & notHFile;
// north-east
mask = opponent & notAFile;
direction = (player << 9) & mask;
direction |= (direction << 9) & mask;
direction |= (direction << 9) & mask;
direction |= (direction << 9) & mask;
direction |= (direction << 9) & mask;
direction |= (direction << 9) & mask;
legalMoves |= (direction << 9) & empty & notAFile;
// north-west
mask = opponent & notHFile;
direction = (player << 7) & mask;
direction |= (direction << 7) & mask;
direction |= (direction << 7) & mask;
direction |= (direction << 7) & mask;
direction |= (direction << 7) & mask;
direction |= (direction << 7) & mask;
legalMoves |= (direction << 7) & empty & notHFile;
// south-east
mask = opponent & notAFile;
direction = (player >>> 7) & mask;
direction |= (direction >>> 7) & mask;
direction |= (direction >>> 7) & mask;
direction |= (direction >>> 7) & mask;
direction |= (direction >>> 7) & mask;
direction |= (direction >>> 7) & mask;
legalMoves |= (direction >>> 7) & empty & notAFile;
// south-west
mask = opponent & notHFile;
direction = (player >>> 9) & mask;
direction |= (direction >>> 9) & mask;
direction |= (direction >>> 9) & mask;
direction |= (direction >>> 9) & mask;
direction |= (direction >>> 9) & mask;
direction |= (direction >>> 9) & mask;
legalMoves |= (direction >>> 9) & empty & notHFile;
return legalMoves;
}
public long getFlips(long move) {
long flips = 0L;
final long player = getPlayerBitboard(getCurrentPlayerIndex());
final long opponent = getPlayerBitboard(getNextPlayer());
long mask;
long direction;
// north
mask = opponent;
direction = (move << 8) & mask;
direction |= (direction << 8) & mask;
direction |= (direction << 8) & mask;
direction |= (direction << 8) & mask;
direction |= (direction << 8) & mask;
direction |= (direction << 8) & mask;
if (((direction << 8) & player) != 0) {
flips |= direction;
}
// south
mask = opponent;
direction = (move >>> 8) & mask;
direction |= (direction >>> 8) & mask;
direction |= (direction >>> 8) & mask;
direction |= (direction >>> 8) & mask;
direction |= (direction >>> 8) & mask;
direction |= (direction >>> 8) & mask;
if (((direction >>> 8) & player) != 0) {
flips |= direction;
}
// east
mask = opponent & notAFile;
direction = (move << 1) & mask;
direction |= (direction << 1) & mask;
direction |= (direction << 1) & mask;
direction |= (direction << 1) & mask;
direction |= (direction << 1) & mask;
direction |= (direction << 1) & mask;
if (((direction << 1) & player & notAFile) != 0) {
flips |= direction;
}
// west
mask = opponent & notHFile;
direction = (move >>> 1) & mask;
direction |= (direction >>> 1) & mask;
direction |= (direction >>> 1) & mask;
direction |= (direction >>> 1) & mask;
direction |= (direction >>> 1) & mask;
direction |= (direction >>> 1) & mask;
if (((direction >>> 1) & player & notHFile) != 0) {
flips |= direction;
}
// north-east
mask = opponent & notAFile;
direction = (move << 9) & mask;
direction |= (direction << 9) & mask;
direction |= (direction << 9) & mask;
direction |= (direction << 9) & mask;
direction |= (direction << 9) & mask;
direction |= (direction << 9) & mask;
if (((direction << 9) & player & notAFile) != 0) {
flips |= direction;
}
// north-west
mask = opponent & notHFile;
direction = (move << 7) & mask;
direction |= (direction << 7) & mask;
direction |= (direction << 7) & mask;
direction |= (direction << 7) & mask;
direction |= (direction << 7) & mask;
direction |= (direction << 7) & mask;
if (((direction << 7) & player & notHFile) != 0) {
flips |= direction;
}
// south-east
mask = opponent & notAFile;
direction = (move >>> 7) & mask;
direction |= (direction >>> 7) & mask;
direction |= (direction >>> 7) & mask;
direction |= (direction >>> 7) & mask;
direction |= (direction >>> 7) & mask;
direction |= (direction >>> 7) & mask;
if (((direction >>> 7) & player & notAFile) != 0) {
flips |= direction;
}
// south-west
mask = opponent & notHFile;
direction = (move >>> 9) & mask;
direction |= (direction >>> 9) & mask;
direction |= (direction >>> 9) & mask;
direction |= (direction >>> 9) & mask;
direction |= (direction >>> 9) & mask;
direction |= (direction >>> 9) & mask;
if (((direction >>> 9) & player & notHFile) != 0) {
flips |= direction;
}
return flips;
}
@Override
public BitboardReversi deepCopy() {return new BitboardReversi(this);}
public PlayResult play(long move) {
final long flips = getFlips(move);
long player = getPlayerBitboard(getCurrentPlayerIndex());
long opponent = getPlayerBitboard(getNextPlayer());
player |= move | flips;
opponent &= ~flips;
setPlayerBitboard(getCurrentPlayerIndex(), player);
setPlayerBitboard(getNextPlayer(), opponent);
nextTurn();
final long nextLegalMoves = getLegalMoves();
if (nextLegalMoves == 0) {
nextTurn();
final long skippedLegalMoves = getLegalMoves();
if (skippedLegalMoves == 0) {
int winner = getWinner();
if (winner == -1) {
state = new PlayResult(GameState.DRAW, -1);
return state;
}
state = new PlayResult(GameState.WIN, winner);
return state;
}
state = new PlayResult(GameState.TURN_SKIPPED, getCurrentPlayerIndex());
return state;
}
state = new PlayResult(GameState.NORMAL, getCurrentPlayerIndex());
return state;
}
public Score getScore() {
return new Score(
Long.bitCount(getPlayerBitboard(0)),
Long.bitCount(getPlayerBitboard(1))
);
}
public int getWinner(){
final long black = getPlayerBitboard(0);
final long white = getPlayerBitboard(1);
final int blackCount = Long.bitCount(black);
final int whiteCount = Long.bitCount(white);
if (blackCount == whiteCount){
return -1;
}
else if (blackCount > whiteCount){
return 0;
}
else{
return 1;
}
}
}

View File

@@ -0,0 +1,113 @@
package org.toop.framework.game.games.tictactoe;
import org.toop.framework.gameFramework.GameState;
import org.toop.framework.gameFramework.model.game.PlayResult;
import org.toop.framework.gameFramework.model.player.Player;
import org.toop.framework.game.BitboardGame;
public class BitboardTicTacToe extends BitboardGame {
private final long[] winningLines = {
0b111000000L, // top row
0b000111000L, // middle row
0b000000111L, // bottom row
0b100100100L, // left column
0b010010010L, // middle column
0b001001001L, // right column
0b100010001L, // diagonal
0b001010100L // anti-diagonal
};
public BitboardTicTacToe() {
super(3, 3, 2);
}
@Override
public void init(Player[] players) {
super.init(players);
}
public BitboardTicTacToe(BitboardTicTacToe other) {
super(other);
}
public long getLegalMoves() {
final long xBitboard = getPlayerBitboard(0);
final long oBitboard = getPlayerBitboard(1);
final long taken = (xBitboard | oBitboard);
return (~taken) & 0x1ffL;
}
public int getWinner(){
return getCurrentPlayerIndex();
}
public PlayResult play(long move) {
// Player loses if move is invalid
if ((move & getLegalMoves()) == 0 || Long.bitCount(move) != 1){
state = new PlayResult(GameState.WIN, getNextPlayer());
return state;
}
// Move is legal, make move
long playerBitboard = getPlayerBitboard(getCurrentPlayerIndex());
playerBitboard |= move;
setPlayerBitboard(getCurrentPlayerIndex(), playerBitboard);
// Check if current player won
if (checkWin(playerBitboard)) {
state = new PlayResult(GameState.WIN, getCurrentPlayerIndex());
return state;
}
// Proceed to next turn
nextTurn();
// Check for early draw
if (getLegalMoves() == 0L || checkEarlyDraw()) {
state = new PlayResult(GameState.DRAW, -1);
return state;
}
// Nothing weird happened, continue on as normal
state = new PlayResult(GameState.NORMAL, -1);
return state;
}
private boolean checkWin(long board) {
for (final long line : winningLines) {
if ((board & line) == line) {
return true;
}
}
return false;
}
private boolean checkEarlyDraw() {
final long xBitboard = getPlayerBitboard(0);
final long oBitboard = getPlayerBitboard(1);
final long taken = (xBitboard | oBitboard);
final long empty = (~taken) & 0x1FFL;
for (final long line : winningLines) {
if (((line & xBitboard) != 0 && (line & oBitboard) != 0)) {
continue;
}
if ((line & empty) != 0) {
return false;
}
}
return true;
}
@Override
public BitboardTicTacToe deepCopy() {
return new BitboardTicTacToe(this);
}
}

View File

@@ -0,0 +1,60 @@
package org.toop.framework.game.players;
import org.toop.framework.gameFramework.model.player.*;
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
/**
* Represents a player controlled by an AI in a game.
* <p>
* This player uses an {@link AbstractAI} instance to determine its moves. The generic
* parameter {@code T} specifies the type of {@link GameR} the AI can handle.
* </p>
*
* @param <T> the specific type of game this AI player can play
*/
public class ArtificialPlayer extends AbstractPlayer {
/** The AI instance used to calculate moves. */
private final AI ai;
/**
* Constructs a new ArtificialPlayer using the specified AI.
*
* @param ai the AI instance that determines moves for this player
*/
public ArtificialPlayer(AI ai, String name) {
super(name);
this.ai = ai;
}
public ArtificialPlayer(ArtificialPlayer other) {
super(other);
this.ai = other.ai.deepCopy();
}
/**
* Determines the next move for this player using its AI.
* <p>
* This method overrides {@link AbstractPlayer#getMove(GameR)}. Because the AI is
* typed to {@code T}, a runtime cast is required. It is the caller's
* responsibility to ensure that {@code gameCopy} is of type {@code T}.
* </p>
*
* @param gameCopy a copy of the current game state
* @return the integer representing the chosen move
* @throws ClassCastException if {@code gameCopy} is not of type {@code T}
*/
protected long determineMove(TurnBasedGame gameCopy) {
return ai.getMove(gameCopy);
}
/**
* Creates a deep copy of this AI player.
*
* @return a copy of this player
*/
@Override
public ArtificialPlayer deepCopy() {
return new ArtificialPlayer(this);
}
}

View File

@@ -0,0 +1,108 @@
package org.toop.framework.game.players;
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
import org.toop.framework.gameFramework.model.player.AbstractPlayer;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
/**
* Represents a local player who provides moves manually.
*
* @param <T> the type of turn-based game
*/
public class LocalPlayer extends AbstractPlayer {
private CompletableFuture<Long> LastMove = new CompletableFuture<>();
/**
* Creates a new local player with the given name.
*
* @param name the player's name
*/
public LocalPlayer(String name) {
super(name);
}
/**
* Creates a copy of another local player.
*
* @param other the player to copy
*/
public LocalPlayer(LocalPlayer other) {
super(other);
this.LastMove = other.LastMove;
}
/**
* Waits for and returns the player's next legal move.
*
* @param gameCopy a copy of the current game
* @return the chosen move
*/
@Override
protected long determineMove(TurnBasedGame gameCopy) {
long legalMoves = gameCopy.getLegalMoves();
long move;
try {
do {
move = getLastMove();
IO.println("GETTING MOVE");
} while ((legalMoves & move) == 0);
return move;
} catch (Exception e) {
IO.println(e);
}
return -1;
}
/**
* Sets the player's last move.
*
* @param move the move to set
*/
public void setLastMove(long move) {
LastMove.complete(move);
}
/**
* Waits for the next move from the player.
*
* @return the chosen move or 0 if interrupted
*/
private long getLastMove() {
LastMove = new CompletableFuture<>(); // Reset the future
try {
return LastMove.get();
} catch (ExecutionException | InterruptedException e) {
return 0;
}
}
/**
* Creates a deep copy of this local player.
*
* @return a copy of this player
*/
@Override
public LocalPlayer deepCopy() {
return new LocalPlayer(this);
}
/*public void register() {
// Listening to PlayerAttemptedMove
new EventFlow().listen(GUIEvents.PlayerAttemptedMove.class, event -> {
if (!LastMove.isDone()) {
LastMove.complete(event.move()); // complete the future
}
}, true); // auto-unsubscribe
}
// This blocks until the next move arrives
public int take() throws ExecutionException, InterruptedException {
int move = LastMove.get(); // blocking
LastMove = new CompletableFuture<>(); // reset for next move
return move;
}*/
}

View File

@@ -0,0 +1,51 @@
package org.toop.framework.game.players;
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
import org.toop.framework.gameFramework.model.player.AbstractPlayer;
import org.toop.framework.gameFramework.model.player.Player;
/**
* Represents a player that participates online.
*
* @param <T> the type of turn-based game
*/
public class OnlinePlayer extends AbstractPlayer {
/**
* Creates a new online player with the given name.
*
* @param name the name of the player
*/
public OnlinePlayer(String name) {
super(name);
}
/**
* Creates a copy of another online player.
*
* @param other the player to copy
*/
public OnlinePlayer(OnlinePlayer other) {
super(other);
}
/**
* {@inheritDoc}
* <p>
* This method is not supported for online players.
*
* @throws UnsupportedOperationException always
*/
@Override
protected long determineMove(TurnBasedGame gameCopy) {
throw new UnsupportedOperationException("An online player does not support determining move");
}
/**
* {@inheritDoc}
*/
@Override
public Player deepCopy() {
return new OnlinePlayer(this);
}
}

View File

@@ -0,0 +1,41 @@
package org.toop.framework.game.players;
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
import org.toop.framework.gameFramework.model.player.AbstractPlayer;
import org.toop.framework.gameFramework.model.player.Player;
import org.toop.framework.networking.server.client.NettyClient;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class ServerPlayer extends AbstractPlayer {
private NettyClient client;
private CompletableFuture<Long> lastMove;
public ServerPlayer(NettyClient client) {
super(client.name());
this.client = client;
}
public void setMove(long move) {
lastMove.complete(move);
}
@Override
public Player deepCopy() {
return null;
}
@Override
public long determineMove(TurnBasedGame game) {
lastMove = new CompletableFuture<>();
System.out.println("Sending yourturn");
client.send("SVR GAME YOURTURN {TURNMESSAGE: \"<bericht voor deze beurt>\"}\n");
try {
return lastMove.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
return 0;
}
}
}

View File

@@ -4,13 +4,13 @@ package org.toop.framework.gameFramework;
* Represents the current state of a turn-based game.
*/
public enum GameState {
/** Game is ongoing and no special condition applies. */
/** OnlineTurnBasedGame is ongoing and no special condition applies. */
NORMAL,
/** Game ended in a draw. */
/** OnlineTurnBasedGame ended in a draw. */
DRAW,
/** Game ended with a win for a player. */
/** OnlineTurnBasedGame ended with a win for a player. */
WIN,
/** Next player's turn was skipped. */

View File

@@ -1,10 +1,8 @@
package org.toop.framework.gameFramework.controller;
import org.toop.framework.gameFramework.model.game.SupportsOnlinePlay;
import org.toop.framework.gameFramework.model.game.threadBehaviour.Controllable;
import org.toop.framework.networking.events.NetworkEvents;
import org.toop.framework.networking.connection.events.NetworkEvents;
public interface GameController extends Controllable, UpdatesGameUI {
public interface GameController {
/** Called when it is this player's turn to make a move. */
void onYourTurn(NetworkEvents.YourTurnResponse event);
@@ -14,5 +12,12 @@ public interface GameController extends Controllable, UpdatesGameUI {
/** Called when the game has finished, with the final result. */
void gameFinished(NetworkEvents.GameResultResponse event);
void start();
void stop();
/** Called to refresh or update the game UI. */
void updateUI();
void sendMove(long clientId, long move);
}

View File

@@ -1,10 +0,0 @@
package org.toop.framework.gameFramework.controller;
/**
* Interface for classes that can trigger a UI update.
*/
public interface UpdatesGameUI {
/** Called to refresh or update the game UI. */
void updateUI();
}

View File

@@ -1,5 +0,0 @@
package org.toop.framework.gameFramework.model.game;
public interface BoardProvider {
long[] getBoard();
}

View File

@@ -1,24 +0,0 @@
package org.toop.framework.gameFramework.model.game;
import org.toop.framework.gameFramework.GameState;
/**
* Interface for turn-based games that can be played and queried for legal moves.
*/
public interface Playable {
/**
* Returns the moves that are currently valid in the game.
*
* @return an array of integers representing legal moves
*/
long getLegalMoves();
/**
* Plays the given move and returns the resulting game state.
*
* @param move the move to apply
* @return the {@link GameState} and additional info after the move
*/
PlayResult play(long move);
}

View File

@@ -1,7 +0,0 @@
package org.toop.framework.gameFramework.model.game;
import org.toop.framework.gameFramework.model.player.Player;
public interface PlayerProvider<T extends TurnBasedGame<T>> {
Player<T> getPlayer(int index);
}

View File

@@ -1,7 +1,16 @@
package org.toop.framework.gameFramework.model.game;
public interface TurnBasedGame<T extends TurnBasedGame<T>> extends Playable, DeepCopyable<T>, PlayerProvider<T>, BoardProvider {
import org.toop.framework.gameFramework.model.player.Player;
public interface TurnBasedGame extends DeepCopyable<TurnBasedGame> {
void init(Player[] players);
long[] getBoard();
int getCurrentTurn();
int getPlayerCount();
Player getPlayer(int index);
int getWinner();
long getLegalMoves();
PlayResult play(long move);
PlayResult getState();
boolean isTerminal();
}

View File

@@ -3,7 +3,6 @@ package org.toop.framework.gameFramework.model.game.threadBehaviour;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.toop.framework.gameFramework.LongPairConsumer;
import org.toop.framework.gameFramework.controller.GameController;
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -16,14 +15,14 @@ import java.util.function.Consumer;
* a running flag, a game reference, and a logger.
* Subclasses implement the actual game-loop logic.
*/
public abstract class AbstractThreadBehaviour<T extends TurnBasedGame<T>> implements ThreadBehaviour {
public abstract class AbstractThreadBehaviour implements ThreadBehaviour {
private LongPairConsumer onSendMove;
private Runnable onUpdateUI;
/** Indicates whether the game loop or event processing is active. */
protected final AtomicBoolean isRunning = new AtomicBoolean();
/** The game instance controlled by this behaviour. */
protected final T game;
protected final TurnBasedGame game;
/** Logger for the subclass to report errors or debug info. */
protected final Logger logger = LogManager.getLogger(this.getClass());
@@ -33,7 +32,7 @@ public abstract class AbstractThreadBehaviour<T extends TurnBasedGame<T>> implem
*
* @param game the turn-based game to control
*/
public AbstractThreadBehaviour(T game) {
public AbstractThreadBehaviour(TurnBasedGame game) {
this.game = game;
}

View File

@@ -1,7 +0,0 @@
package org.toop.framework.gameFramework.model.game.threadBehaviour;
public interface Controllable {
void start();
void stop();
}

View File

@@ -1,6 +1,4 @@
package org.toop.framework.gameFramework.model.game;
import org.toop.framework.networking.events.NetworkEvents;
package org.toop.framework.gameFramework.model.game.threadBehaviour;
/**
* Interface for games that support online multiplayer play.

View File

@@ -11,8 +11,11 @@ import java.util.function.Consumer;
* <p>
* Defines how a game's execution is started, stopped, and which player is active.
*/
public interface ThreadBehaviour extends Controllable {
public interface ThreadBehaviour {
void setOnUpdateUI(Runnable onUpdateUI);
void setOnSendMove(LongPairConsumer onSendMove);
void start();
void stop();
}

View File

@@ -3,5 +3,6 @@ package org.toop.framework.gameFramework.model.player;
import org.toop.framework.gameFramework.model.game.DeepCopyable;
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
public interface AI<T extends TurnBasedGame<T>> extends MoveProvider<T>, DeepCopyable<AI<T>> {
public interface AI extends DeepCopyable<AI> {
long getMove(TurnBasedGame game);
}

View File

@@ -12,6 +12,6 @@ import org.toop.framework.gameFramework.model.game.TurnBasedGame;
*
* @param <T> the specific type of game this AI can play, extending {@link GameR}
*/
public abstract class AbstractAI<T extends TurnBasedGame<T>> implements AI<T> {
public abstract class AbstractAI implements AI {
// Concrete AI implementations should override findBestMove(T game, int depth)
}

View File

@@ -15,16 +15,17 @@ import org.toop.framework.gameFramework.model.game.TurnBasedGame;
* specific move logic.
* </p>
*/
public abstract class AbstractPlayer<T extends TurnBasedGame<T>> implements Player<T> {
public abstract class AbstractPlayer implements Player {
private final Logger logger = LogManager.getLogger(this.getClass());
private final String name;
protected AbstractPlayer(String name) {
System.out.println("Player " + name + " has been created");
this.name = name;
}
protected AbstractPlayer(AbstractPlayer<T> other) {
protected AbstractPlayer(AbstractPlayer other) {
this.name = other.name;
}
/**
@@ -39,12 +40,29 @@ public abstract class AbstractPlayer<T extends TurnBasedGame<T>> implements Play
* @return an integer representing the chosen move
* @throws UnsupportedOperationException if the method is not overridden
*/
public long getMove(T gameCopy) {
logger.error("Method getMove not implemented.");
throw new UnsupportedOperationException("Not supported yet.");
public final long getMove(TurnBasedGame game) {
return determineMove(game.deepCopy());
}
public String getName(){
/**
* Determines the player's move using a safe copy of the game.
* <p>
* This method is called by {@link #getMove(T)} and should contain
* the player's strategy for choosing a move.
*
* @param gameCopy a deep copy of the game
* @return the chosen move
*/
protected abstract long determineMove(TurnBasedGame gameCopy);
/**
* Returns the player's name.
*
* @return the name
*/
public String getName() {
return this.name;
}
}

View File

@@ -1,7 +0,0 @@
package org.toop.framework.gameFramework.model.player;
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
public interface MoveProvider<T extends TurnBasedGame<T>> {
long getMove(T game);
}

View File

@@ -1,5 +0,0 @@
package org.toop.framework.gameFramework.model.player;
public interface NameProvider {
String getName();
}

View File

@@ -3,5 +3,7 @@ package org.toop.framework.gameFramework.model.player;
import org.toop.framework.gameFramework.model.game.DeepCopyable;
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
public interface Player<T extends TurnBasedGame<T>> extends NameProvider, MoveProvider<T>, DeepCopyable<Player<T>> {
public interface Player extends DeepCopyable<Player> {
String getName();
long getMove(TurnBasedGame game);
}

View File

@@ -1,13 +1,13 @@
package org.toop.framework.networking;
package org.toop.framework.networking.connection;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.toop.framework.SnowflakeGenerator;
import org.toop.framework.eventbus.EventFlow;
import org.toop.framework.eventbus.bus.EventBus;
import org.toop.framework.networking.events.NetworkEvents;
import org.toop.framework.networking.exceptions.ClientNotFoundException;
import org.toop.framework.networking.interfaces.NetworkingClientManager;
import org.toop.framework.networking.connection.events.NetworkEvents;
import org.toop.framework.networking.connection.exceptions.ClientNotFoundException;
import org.toop.framework.networking.connection.interfaces.NetworkingClientManager;
public class NetworkingClientEventListener {
private static final Logger logger = LogManager.getLogger(NetworkingClientEventListener.class);

View File

@@ -1,4 +1,4 @@
package org.toop.framework.networking;
package org.toop.framework.networking.connection;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
@@ -10,13 +10,13 @@ import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.toop.framework.eventbus.EventFlow;
import org.toop.framework.eventbus.bus.EventBus;
import org.toop.framework.networking.events.NetworkEvents;
import org.toop.framework.networking.exceptions.ClientNotFoundException;
import org.toop.framework.networking.exceptions.CouldNotConnectException;
import org.toop.framework.networking.interfaces.NetworkingClient;
import org.toop.framework.networking.types.NetworkingConnector;
import org.toop.framework.networking.connection.events.NetworkEvents;
import org.toop.framework.networking.connection.exceptions.ClientNotFoundException;
import org.toop.framework.networking.connection.exceptions.CouldNotConnectException;
import org.toop.framework.networking.connection.interfaces.NetworkingClient;
import org.toop.framework.networking.connection.types.NetworkingConnector;
public class NetworkingClientManager implements org.toop.framework.networking.interfaces.NetworkingClientManager {
public class NetworkingClientManager implements org.toop.framework.networking.connection.interfaces.NetworkingClientManager {
private static final Logger logger = LogManager.getLogger(NetworkingClientManager.class);
private final EventBus eventBus;

View File

@@ -1,4 +1,4 @@
package org.toop.framework.networking.clients;
package org.toop.framework.networking.connection.clients;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
@@ -12,9 +12,10 @@ import io.netty.util.CharsetUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.toop.framework.eventbus.bus.EventBus;
import org.toop.framework.networking.exceptions.CouldNotConnectException;
import org.toop.framework.networking.handlers.NetworkingGameClientHandler;
import org.toop.framework.networking.interfaces.NetworkingClient;
import org.toop.framework.networking.connection.events.NetworkEvents;
import org.toop.framework.networking.connection.exceptions.CouldNotConnectException;
import org.toop.framework.networking.connection.handlers.NetworkingGameClientHandler;
import org.toop.framework.networking.connection.interfaces.NetworkingClient;
import java.net.InetSocketAddress;
@@ -23,6 +24,7 @@ public class TournamentNetworkingClient implements NetworkingClient {
private final EventBus eventBus;
private Channel channel;
private long clientId;
public TournamentNetworkingClient(EventBus eventBus) {
this.eventBus = eventBus;
@@ -35,6 +37,7 @@ public class TournamentNetworkingClient implements NetworkingClient {
@Override
public void connect(long clientId, String host, int port) throws CouldNotConnectException {
this.clientId = clientId;
try {
Bootstrap bootstrap = new Bootstrap();
EventLoopGroup workerGroup = new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory());
@@ -75,6 +78,7 @@ public class TournamentNetworkingClient implements NetworkingClient {
logger.info("Connection {} sent message: '{}' ", this.channel.remoteAddress(), literalMsg);
} else {
logger.warn("Cannot send message: '{}', connection inactive. ", literalMsg);
eventBus.post(new NetworkEvents.ClosedConnection(clientId));
}
}

View File

@@ -1,4 +1,4 @@
package org.toop.framework.networking.events;
package org.toop.framework.networking.connection.events;
import java.util.*;
import java.util.concurrent.CompletableFuture;
@@ -6,8 +6,8 @@ import java.util.concurrent.CompletableFuture;
import org.toop.annotations.AutoResponseResult;
import org.toop.framework.eventbus.GlobalEventBus;
import org.toop.framework.eventbus.events.*;
import org.toop.framework.networking.interfaces.NetworkingClient;
import org.toop.framework.networking.types.NetworkingConnector;
import org.toop.framework.networking.connection.interfaces.NetworkingClient;
import org.toop.framework.networking.connection.types.NetworkingConnector;
/**
* Defines all event types related to the networking subsystem.
@@ -102,7 +102,7 @@ public class NetworkEvents extends EventsBase {
implements GenericEvent {}
/** Requests to accept an existing challenge. */
public record SendAcceptChallenge(long clientId, int challengeId)
public record SendAcceptChallenge(long clientId, long challengeId)
implements GenericEvent {}
/** Requests to forfeit the current game. */

View File

@@ -1,4 +1,4 @@
package org.toop.framework.networking.exceptions;
package org.toop.framework.networking.connection.exceptions;
/**
* Thrown when an operation is attempted on a networking client

View File

@@ -1,4 +1,4 @@
package org.toop.framework.networking.exceptions;
package org.toop.framework.networking.connection.exceptions;
public class CouldNotConnectException extends RuntimeException {

View File

@@ -1,4 +1,4 @@
package org.toop.framework.networking.exceptions;
package org.toop.framework.networking.connection.exceptions;
public class NetworkingInitializationException extends RuntimeException {
public NetworkingInitializationException(String message, Throwable cause) {

View File

@@ -1,4 +1,4 @@
package org.toop.framework.networking.handlers;
package org.toop.framework.networking.connection.handlers;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
@@ -9,7 +9,7 @@ import java.util.regex.Pattern;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.toop.framework.eventbus.bus.EventBus;
import org.toop.framework.networking.events.NetworkEvents;
import org.toop.framework.networking.connection.events.NetworkEvents;
public class NetworkingGameClientHandler extends ChannelInboundHandlerAdapter {
private static final Logger logger = LogManager.getLogger(NetworkingGameClientHandler.class);

View File

@@ -1,6 +1,6 @@
package org.toop.framework.networking.interfaces;
package org.toop.framework.networking.connection.interfaces;
import org.toop.framework.networking.exceptions.CouldNotConnectException;
import org.toop.framework.networking.connection.exceptions.CouldNotConnectException;
import java.net.InetSocketAddress;

View File

@@ -1,8 +1,8 @@
package org.toop.framework.networking.interfaces;
package org.toop.framework.networking.connection.interfaces;
import org.toop.framework.networking.exceptions.ClientNotFoundException;
import org.toop.framework.networking.exceptions.CouldNotConnectException;
import org.toop.framework.networking.types.NetworkingConnector;
import org.toop.framework.networking.connection.exceptions.ClientNotFoundException;
import org.toop.framework.networking.connection.exceptions.CouldNotConnectException;
import org.toop.framework.networking.connection.types.NetworkingConnector;
public interface NetworkingClientManager {
void startClient(

View File

@@ -1,4 +1,4 @@
package org.toop.framework.networking.types;
package org.toop.framework.networking.connection.types;
import java.util.concurrent.TimeUnit;

View File

@@ -1,3 +1,3 @@
package org.toop.framework.networking.types;
package org.toop.framework.networking.connection.types;
public record ServerCommand(long clientId, String command) {}

View File

@@ -0,0 +1,3 @@
package org.toop.framework.networking.connection.types;
public record ServerMessage(String message) {}

View File

@@ -0,0 +1,22 @@
package org.toop.framework.networking.server;
import java.util.List;
public interface GameServer<GAMETYPE, CLIENT, CHALLENGEIDTYPE> {
void startGame(String gameType, CLIENT... clients);
void addClient(CLIENT client);
void removeClient(CLIENT client);
void challengeClient(String fromClientName, String toClientName, String gameTypeKey);
void acceptChallenge(CHALLENGEIDTYPE challengeId);
void subscribeClient(String clientName, String gameTypeKey);
void unsubscribeClient(String clientName);
List<String> gameTypes();
List<OnlineGame<GAMETYPE>> ongoingGames();
List<CLIENT> onlineUsers();
void shutdown();
}

View File

@@ -0,0 +1,10 @@
package org.toop.framework.networking.server;
import org.toop.framework.networking.server.client.NettyClient;
public interface OnlineGame<T> {
long id();
T game();
NettyClient[] users();
void start();
}

View File

@@ -0,0 +1,67 @@
package org.toop.framework.networking.server;
import org.toop.framework.game.gameThreads.ServerThreadBehaviour;
import org.toop.framework.gameFramework.GameState;
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
import org.toop.framework.networking.server.client.NettyClient;
public class OnlineTurnBasedGame implements OnlineGame<TurnBasedGame> {
private long id;
private NettyClient[] clients;
private TurnBasedGame game;
private ServerThreadBehaviour gameThread;
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;
}
private void notifyMoveMade(String speler, int move){
for (NettyClient client : clients) {
client.send(String.format("SVR GAME MOVE {PLAYER: \"%s\", MOVE: \"%s\", DETAILS: \"<reactie spel op zet>\"}\n", speler, move));
}
}
private void notifyGameEnd(GameState state, int winner){
if (state == GameState.DRAW){
for (NettyClient client : clients) {
client.send(String.format("SVR GAME DRAW {PLAYERONESCORE: \"<score speler1>\", PLAYERTWOSCORE: \"<score speler2>\", COMMENT: \"<comment>\"}\n"));
}
}
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"));
}
// Remove game fromt clients
for(NettyClient client : clients) {
client.clearGame();
}
}
@Override
public long id() {
return id;
}
@Override
public org.toop.framework.gameFramework.model.game.TurnBasedGame game() {
return game;
}
@Override
public NettyClient[] users() {
return clients;
}
@Override
public void start(){
this.gameThread.start();
}
}

View File

@@ -0,0 +1,263 @@
package org.toop.framework.networking.server;
import org.toop.framework.game.players.ServerPlayer;
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.GameChallengeTimer;
import org.toop.framework.networking.server.client.NettyClient;
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.utils.ImmutablePair;
import java.util.*;
import java.util.concurrent.*;
import java.time.Duration;
public class Server implements GameServer<TurnBasedGame, NettyClient, Long> {
final private TurnBasedGameTypeStore gameTypesStore;
final private ClientStore<Long, NettyClient> clientStore;
final private List<GameChallenge> gameChallenges = new CopyOnWriteArrayList<>();
final private TurnBasedGameStore gameStore;
final private SubscriptionStore subscriptionStore;
final private Duration challengeDuration;
final private ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
public Server(
Duration challengeDuration,
TurnBasedGameTypeStore turnBasedGameTypeStore,
ClientStore<Long, NettyClient> clientStore,
TurnBasedGameStore gameStore,
SubscriptionStore subStore
) {
this.gameTypesStore = turnBasedGameTypeStore;
this.challengeDuration = challengeDuration;
this.clientStore = clientStore;
this.gameStore = gameStore;
this.subscriptionStore = subStore;
scheduler.schedule(this::serverTask, 0, TimeUnit.MILLISECONDS);
}
@Override
public void addClient(NettyClient client) {
clientStore.add(client);
}
@Override
public void removeClient(NettyClient client) {
clientStore.remove(client.id());
}
@Override
public List<String> gameTypes() {
return new ArrayList<>(gameTypesStore.all().keySet());
}
@Override
public List<OnlineGame<TurnBasedGame>> ongoingGames() {
return gameStore.all().stream().toList();
}
@Override
public void challengeClient(String fromUser, String toUser, String gameType) {
NettyClient from = getUser(fromUser);
if (from == null) {
return;
}
if (!gameTypesStore.all().containsKey(gameType)) {
from.send("ERR gametype not found \n");
return;
}
NettyClient to = getUser(toUser);
if (to == null) {
from.send("ERR user not found \n");
return;
}
var ch = new GameChallenge(from, to, gameType, new GameChallengeTimer(challengeDuration));
to.send(
"SVR GAME CHALLENGE {CHALLENGER: \"%s\", CHALLENGENUMBER: \"%s\", GAMETYPE: \"%s\"} \n"
.formatted(from.name(), ch.id(), gameType)
);
if (!isValidChallenge(ch)) {
warnUserExpiredChallenge(from, ch.id());
ch.forceExpire();
return;
}
gameChallenges.addLast(ch);
}
@Override
public void acceptChallenge(Long challengeId) {
for (var challenge : gameChallenges) {
if (challenge.id() == challengeId) {
startGame(challenge.acceptChallenge(), challenge.getUsers());
break;
}
}
}
@Override
public void subscribeClient(String clientName, String gameTypeKey) {
if (!gameTypesStore.all().containsKey(gameTypeKey)) {
return;
}
subscriptionStore.add(new ImmutablePair<>(gameTypeKey, clientName));
}
@Override
public void unsubscribeClient(String clientName) {
subscriptionStore.remove(clientName);
}
@Override
public void startGame(String gameType, NettyClient... clients) {
if (!gameTypesStore.all().containsKey(gameType)) return;
try {
ServerPlayer[] players = new ServerPlayer[clients.length];
var game = new OnlineTurnBasedGame(gameTypesStore.create(gameType), clients);
for (int i = 0; i < clients.length; i++) {
players[i] = new ServerPlayer(clients[i]);
clients[i].setGame(new ImmutablePair<>(game, players[i]));
}
game.game().init(players);
gameStore.add(game);
clients[0].send(String.format("SVR GAME MATCH {PLAYERTOMOVE: \"%s\", GAMETYPE: \"%s\", OPPONENT: \"%s\"}\n",
clients[0].name(),
gameType,
clients[1].name()));
clients[1].send(String.format("SVR GAME MATCH {PLAYERTOMOVE: \"%s\", GAMETYPE: \"%s\", OPPONENT: \"%s\"}\n",
clients[0].name(),
gameType,
clients[0].name()));
game.start();
} catch (Exception e) {
IO.println("ERROR: Failed to start OnlineTurnBasedGame");
e.printStackTrace();
}
}
@Override
public List<NettyClient> onlineUsers() {
return clientStore.all().stream().toList();
}
@Override
public void shutdown() {
scheduler.shutdown();
gameChallenges.clear();
}
private void serverTask() {
checkChallenges();
checkSubscriptions();
scheduler.schedule(this::serverTask, 500, TimeUnit.MILLISECONDS);
}
private void checkChallenges() {
for (int i = gameChallenges.size() - 1; i >= 0; i--) {
var challenge = gameChallenges.get(i);
if (isValidChallenge(challenge)) continue;
if (challenge.isExpired()) {
if (!challenge.isChallengeAccepted()) Arrays.stream(challenge.getUsers())
.forEach(user -> warnUserExpiredChallenge(user, challenge.id()));
gameChallenges.remove(i);
}
}
}
private void checkSubscriptions() {
if (subscriptionStore.allKeys().isEmpty()) return;
Random ran = new Random();
for (String key : subscriptionStore.allKeys()) {
List<String> userNames = (List<String>) subscriptionStore.allValues(key);
if (userNames.size() < 2) continue;
while (userNames.size() > 1) {
int left = ran.nextInt(userNames.size());
int right;
do {
right = ran.nextInt(userNames.size());
} while (left == right);
String userLeft = userNames.get(left);
String userRight = userNames.get(right);
// Remove user if he is in a game
boolean userInGame = false;
if (getUser(userLeft).game() != null) {
userNames.remove(userLeft);
userInGame = true;
} else if (getUser(userRight).game() != null) {
userNames.remove(userRight);
userInGame = true;
}
if (userInGame) { continue; }
//
int first = Math.max(left, right);
int second = Math.min(left, right);
userNames.remove(first);
userNames.remove(second);
startGame(key, getUser(userLeft), getUser(userRight));
}
}
}
private NettyClient getUser(String username) {
return clientStore.all().stream().filter(e -> e.name().equalsIgnoreCase(username)).findFirst().orElse(null);
}
private NettyClient getUser(long id) {
return clientStore.get(id);
}
private void warnUserExpiredChallenge(NettyClient client, long challengeId) {
client.send("SVR GAME CHALLENGE CANCELLED {CHALLENGENUMBER: \"" + challengeId + "\"}" + "\n");
}
private boolean isValidChallenge(GameChallenge gameChallenge) { // TODO move to challenge class
for (var user : gameChallenge.getUsers()) {
if (clientStore.get(user.id()) == null) {
return false;
}
if (user.game() != null) {
return false;
}
if (gameChallenge.isExpired()) {
return false;
}
}
return true;
}
}

View File

@@ -0,0 +1,49 @@
package org.toop.framework.networking.server.challenges.gamechallenge;
import org.toop.framework.SnowflakeGenerator;
import org.toop.framework.networking.server.client.NettyClient;
import org.toop.framework.utils.SimpleTimer;
public class GameChallenge {
private final long id = SnowflakeGenerator.nextId(); // I don't need this, but the tournament server uses it...
private final NettyClient from;
private final NettyClient to;
private final String gameType;
private final SimpleTimer timer;
private boolean isChallengeAccepted = false;
public GameChallenge(NettyClient from, NettyClient to, String gameType, SimpleTimer timer) {
this.from = from;
this.to = to;
this.gameType = gameType;
this.timer = timer;
}
public long id() {
return id;
}
public NettyClient[] getUsers() {
return new NettyClient[]{from, to};
}
public void forceExpire() {
timer.forceExpire();
}
public String acceptChallenge() {
isChallengeAccepted = true;
timer.forceExpire();
return gameType;
}
public boolean isChallengeAccepted() {
return isChallengeAccepted;
}
public boolean isExpired() {
return timer.isExpired();
}
}

View File

@@ -0,0 +1,35 @@
package org.toop.framework.networking.server.challenges.gamechallenge;
import org.toop.framework.utils.SimpleTimer;
import java.time.Instant;
import java.time.Duration;
public class GameChallengeTimer implements SimpleTimer {
private final Instant createdAt;
private final Duration timeout;
private boolean isExpired = false;
public GameChallengeTimer(Duration duration) {
this.createdAt = Instant.now();
this.timeout = duration;
}
@Override
public void forceExpire() {
this.isExpired = true;
}
@Override
public boolean isExpired() {
if (this.isExpired) return true;
return Instant.now().isAfter(createdAt.plus(timeout));
}
@Override
public long secondsRemaining() {
return Duration.between(Instant.now(), createdAt.plus(timeout)).toSeconds();
}
}

View File

@@ -0,0 +1,19 @@
package org.toop.framework.networking.server.client;
import org.toop.framework.networking.server.OnlineTurnBasedGame;
import org.toop.framework.utils.Pair;
public interface Client<G, P> {
long id();
String name();
void setName(String name);
OnlineTurnBasedGame game();
P player();
void setGame(Pair<G, P> gamePair);
void clearGame();
void send(String message);
}

View File

@@ -0,0 +1,66 @@
package org.toop.framework.networking.server.client;
import io.netty.channel.ChannelHandlerContext;
import org.toop.framework.game.players.ServerPlayer;
import org.toop.framework.networking.server.OnlineTurnBasedGame;
import org.toop.framework.utils.Pair;
public class NettyClient implements Client<OnlineTurnBasedGame, ServerPlayer> {
final private long id;
private ChannelHandlerContext ctx;
private String name;
private Pair<OnlineTurnBasedGame, ServerPlayer> gamePair;
public NettyClient(long userId, String name) {
this.id = userId;
this.name = name;
}
@Override
public long id() {
return id;
}
@Override
public String name() {
return name;
}
@Override
public void setGame(Pair<OnlineTurnBasedGame, ServerPlayer> gamePair) {
this.gamePair = gamePair;
}
@Override
public void clearGame() {
this.gamePair = null;
}
@Override
public OnlineTurnBasedGame game() {
if (this.gamePair == null) {
return null;
}
return this.gamePair.getLeft();
}
@Override
public ServerPlayer player() {
return this.gamePair.getRight();
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public void send(String message) {
IO.println(message);
ctx.channel().writeAndFlush(message + "\r\n");
}
public void setCtx(ChannelHandlerContext ctx) {
this.ctx = ctx;
}
}

View File

@@ -0,0 +1,7 @@
package org.toop.framework.networking.server.connectionHandler;
import org.toop.framework.networking.server.client.Client;
public interface ClientSession<G, P> {
Client<G, P> client();
}

View File

@@ -0,0 +1,58 @@
package org.toop.framework.networking.server.connectionHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.toop.framework.game.players.ServerPlayer;
import org.toop.framework.networking.server.OnlineTurnBasedGame;
import org.toop.framework.networking.server.client.NettyClient;
import org.toop.framework.networking.server.handlers.Handler;
import org.toop.framework.networking.server.parsing.ParsedMessage;
import org.toop.framework.networking.server.Server;
import org.toop.framework.networking.server.client.Client;
import org.toop.framework.networking.server.parsing.Parser;
public class NettyClientSession extends SimpleChannelInboundHandler<String> implements ClientSession<OnlineTurnBasedGame, ServerPlayer> {
private final NettyClient client;
private final Server server;
private final Handler<ParsedMessage> handler;
public NettyClientSession(NettyClient client, Server server, Handler<ParsedMessage> handler) {
this.client = client;
this.server = server;
this.handler = handler;
}
@Override
public Client<OnlineTurnBasedGame, ServerPlayer> client() {
return client;
}
@Override
public void channelActive(ChannelHandlerContext ctx) {
ctx.writeAndFlush("Welcome " + client.id() + " please login" + "\n");
client.setCtx(ctx);
server.addClient(client); // TODO set correct name on login
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) {
ParsedMessage p = Parser.parse(msg);
if (p == null) return;
handler.handle(p);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
@Override
public void channelInactive(ChannelHandlerContext ctx) {
server.removeClient(client);
}
}

View File

@@ -0,0 +1,7 @@
package org.toop.framework.networking.server.gateway;
public interface GatewayServer {
void start() throws Exception;
void stop();
int port();
}

View File

@@ -0,0 +1,111 @@
package org.toop.framework.networking.server.gateway;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.nio.NioIoHandler;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.toop.framework.SnowflakeGenerator;
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
import org.toop.framework.networking.server.client.NettyClient;
import org.toop.framework.networking.server.connectionHandler.NettyClientSession;
import org.toop.framework.networking.server.Server;
import org.toop.framework.networking.server.handlers.MessageHandler;
import org.toop.framework.networking.server.stores.MapSubscriptionStore;
import org.toop.framework.networking.server.stores.NettyClientStore;
import org.toop.framework.networking.server.stores.TurnBasedGameStore;
import org.toop.framework.networking.server.stores.TurnBasedGameTypeStore;
import java.time.Duration;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
public class NettyGatewayServer implements GatewayServer {
private final int port;
private final Server gs;
ChannelFuture future;
EventLoopGroup bossGroup;
EventLoopGroup workerGroup;
public NettyGatewayServer(
int port,
TurnBasedGameTypeStore turnBasedGameTypeStore,
Duration challengeDuration
) {
this.port = port;
this.gs = new Server(
challengeDuration,
turnBasedGameTypeStore,
new NettyClientStore(new ConcurrentHashMap<>()),
new TurnBasedGameStore(new CopyOnWriteArrayList<>()),
new MapSubscriptionStore(new ConcurrentHashMap<>())
);
}
@Override
public void start() throws InterruptedException {
bossGroup = new NioEventLoopGroup(1);
workerGroup = new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory());
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(workerGroup);
bootstrap.channel(NioServerSocketChannel.class);
bootstrap.option(ChannelOption.SO_BACKLOG, 128);
bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
bootstrap.handler(new LoggingHandler(LogLevel.INFO));
bootstrap.childHandler(
new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new LineBasedFrameDecoder(8192));
pipeline.addLast(new StringDecoder());
pipeline.addLast(new StringEncoder());
long userid = SnowflakeGenerator.nextId();
NettyClient client = new NettyClient(userid, ""+userid);
pipeline.addLast(new NettyClientSession(client, gs, new MessageHandler(gs, client)));
}
}
);
future = bootstrap.bind(port).sync();
future.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
@Override
public void stop() {
if (future == null) {
return;
}
future.channel().close();
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
future = null;
bossGroup = null;
workerGroup = null;
}
@Override
public int port() {
return port;
}
}

View File

@@ -0,0 +1,5 @@
package org.toop.framework.networking.server.handlers;
public interface Handler<T> {
void handle(T message);
}

View File

@@ -0,0 +1,110 @@
package org.toop.framework.networking.server.handlers;
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.parsing.ParsedMessage;
import org.toop.framework.utils.Utils;
public class MessageHandler implements Handler<ParsedMessage> {
private final Server server;
private final Client<OnlineTurnBasedGame, ServerPlayer> client;
public MessageHandler(Server server, Client<OnlineTurnBasedGame, ServerPlayer> client) {
this.server = server;
this.client = client;
}
@Override
public void handle(ParsedMessage message) {
switch (message.command()) {
case "ping" -> client.send("PONG");
case "login" -> handleLogin(message, client);
case "get" -> handleGet(message, client);
case "subscribe" -> handleSubscribe(message, client);
case "move" -> handleMove(message, client);
case "challenge" -> handleChallenge(message, client);
case "message" -> handleMessage(message, client);
case "help" -> handleHelp(message, client);
default -> client.send("ERROR Unknown command");
}
}
// DO NOT INVERT
private boolean hasArgs(String... args) {
if (args.length < 1) {
client.send("ERR not enough arguments");
return false;
}
return true;
}
private void handleLogin(ParsedMessage p, Client<OnlineTurnBasedGame, ServerPlayer> client) {
if (!hasArgs(p.args())) return;
client.setName(p.args()[0]);
}
private void handleSubscribe(ParsedMessage p, Client<OnlineTurnBasedGame, ServerPlayer> client) {
if (!hasArgs(p.args())) return;
server.subscribeClient(client.name(), p.args()[0]);
}
private void handleHelp(ParsedMessage p, Client<OnlineTurnBasedGame, ServerPlayer> client) {
// TODO
}
private void handleMessage(ParsedMessage p, Client<OnlineTurnBasedGame, ServerPlayer> client) {
// TODO
}
private void handleGet(ParsedMessage p, Client<OnlineTurnBasedGame, ServerPlayer> client) {
if (!hasArgs(p.args())) return;
switch (p.args()[0]) {
case "playerlist" -> {
var names = server.onlineUsers().stream().map(Client::name).iterator();
client.send("SVR PLAYERLIST " + Utils.returnQuotedString(names));
}
case "gamelist" -> {
var names = server.gameTypes().stream().iterator();
client.send("SVR GAMELIST " + Utils.returnQuotedString(names));
}
}
}
private void handleChallenge(ParsedMessage p, Client<OnlineTurnBasedGame, ServerPlayer> client) {
if (!hasArgs(p.args())) return;
if (p.args().length < 2) return;
if (p.args()[0].equalsIgnoreCase("accept")) {
try {
long id = Long.parseLong(p.args()[1]);
if (id <= 0) {
client.send("ERR id must be a positive number");
return;
}
server.acceptChallenge(id);
} catch (NumberFormatException e) {
client.send("ERR id is not a valid number or too big");
return;
}
return;
}
server.challengeClient(client.name(), p.args()[0], p.args()[1]);
}
private void handleMove(ParsedMessage p, Client<OnlineTurnBasedGame, ServerPlayer> client) {
if(!hasArgs(p.args())) return;
// TODO check if not number
client.player().setMove(1L << Integer.parseInt(p.args()[0]));
}
}

View File

@@ -0,0 +1,4 @@
package org.toop.framework.networking.server.parsing;
public record ParsedMessage(String command, String... args) {}

View File

@@ -0,0 +1,24 @@
package org.toop.framework.networking.server.parsing;
import java.util.LinkedList;
import java.util.List;
public class Parser {
public static ParsedMessage parse(String msg) {
// TODO, what if empty string.
if (msg.isEmpty()) return null;
msg = msg.trim().toLowerCase();
List<String> parts = new LinkedList<>(List.of(msg.split(" ")));
if (parts.size() > 1) {
String command = parts.removeFirst();
return new ParsedMessage(command, parts.toArray(String[]::new));
}
else {
return new ParsedMessage(msg);
}
}
}

View File

@@ -0,0 +1,7 @@
package org.toop.framework.networking.server.stores;
import org.toop.framework.game.players.ServerPlayer;
import org.toop.framework.networking.server.OnlineTurnBasedGame;
import org.toop.framework.networking.server.client.Client;
public interface ClientStore<ID, T extends Client<OnlineTurnBasedGame, ServerPlayer>> extends Store<ID, T> {}

View File

@@ -0,0 +1,3 @@
package org.toop.framework.networking.server.stores;
public interface GameStore<T, K> extends Store<T, K> {}

View File

@@ -0,0 +1,71 @@
package org.toop.framework.networking.server.stores;
import org.toop.framework.utils.ImmutablePair;
import java.util.*;
public class MapSubscriptionStore implements SubscriptionStore {
final private Map<String, List<String>> subscriptions;
public MapSubscriptionStore(Map<String, List<String>> initMap) {
this.subscriptions = initMap;
}
@Override
public void add(ImmutablePair<String, String> adding) {
subscriptions.forEach((_, clientNames) -> clientNames.remove(adding.getRight()));
subscriptions.computeIfAbsent(
adding.getLeft(),
_ -> new ArrayList<>())
.add(adding.getRight());
}
@Override
public void remove(String remover) {
subscriptions.forEach((_, clientNames) -> clientNames.remove(remover));
}
// TODO move server internal code to here
@Override
public ImmutablePair<String, String> get(String getter) {
String foundKey = null;
String foundName = null;
for (var key : subscriptions.keySet()) {
var a = subscriptions.get(key).stream().filter(e -> e.equals(getter)).toList();
if (!a.isEmpty()) {
foundKey = key;
foundName = a.getFirst();
break;
}
}
return new ImmutablePair<>(foundKey, foundName);
}
@Override
public Collection<ImmutablePair<String, String>> all() {
List<ImmutablePair<String, String>> a = new ArrayList<>();
for (var key : subscriptions.keySet()) {
for (var sub : subscriptions.get(key)) {
a.addLast(new ImmutablePair<>(key, sub));
}
}
return a;
}
@Override
public Collection<String> allKeys() {
return subscriptions.keySet();
}
@Override
public Collection<String> allValues(String key) {
return subscriptions.get(key);
}
}

View File

@@ -0,0 +1,34 @@
package org.toop.framework.networking.server.stores;
import org.toop.framework.networking.server.client.NettyClient;
import java.util.Collection;
import java.util.Map;
public class NettyClientStore implements ClientStore<Long, NettyClient> {
final private Map<Long, NettyClient> users;
public NettyClientStore(Map<Long, NettyClient> usersMap) {
this.users = usersMap;
}
@Override
public void add(NettyClient adding) {
users.putIfAbsent(adding.id(), adding);
}
@Override
public void remove(Long remover) {
users.remove(remover);
}
@Override
public NettyClient get(Long getter) {
return users.get(getter);
}
@Override
public Collection<NettyClient> all() {
return users.values();
}
}

View File

@@ -0,0 +1,10 @@
package org.toop.framework.networking.server.stores;
import java.util.Collection;
public interface Store<IDENTIFIER, STORED> {
void add(STORED adding);
void remove(IDENTIFIER remover);
STORED get(IDENTIFIER getter);
Collection<STORED> all();
}

View File

@@ -0,0 +1,10 @@
package org.toop.framework.networking.server.stores;
import org.toop.framework.utils.ImmutablePair;
import java.util.Collection;
public interface SubscriptionStore extends Store<String, ImmutablePair<String, String>> {
Collection<String> allKeys();
Collection<String> allValues(String key);
}

View File

@@ -0,0 +1,36 @@
package org.toop.framework.networking.server.stores;
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
import org.toop.framework.networking.server.OnlineGame;
import java.util.Collection;
import java.util.List;
public class TurnBasedGameStore implements GameStore<OnlineGame<TurnBasedGame>, OnlineGame<TurnBasedGame>> {
private List<OnlineGame<TurnBasedGame>> gameList;
public TurnBasedGameStore(List<OnlineGame<TurnBasedGame>> initGameList) {
this.gameList = initGameList;
}
@Override
public void add(OnlineGame<TurnBasedGame> adding) {
gameList.addLast(adding);
}
@Override
public void remove(OnlineGame<TurnBasedGame> remover) {
gameList.remove(remover);
}
@Override
public OnlineGame<TurnBasedGame> get(OnlineGame<TurnBasedGame> getter) {
return gameList.stream().filter(game->game.equals(getter)).findFirst().orElse(null);
}
@Override
public Collection<OnlineGame<TurnBasedGame>> all() {
return gameList;
}
}

View File

@@ -0,0 +1,32 @@
package org.toop.framework.networking.server.stores;
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
public class TurnBasedGameTypeStore {
private final Map<String, Supplier<? extends TurnBasedGame>> gameFactories = new ConcurrentHashMap<>();
public TurnBasedGameTypeStore() {}
public void register(String key, Supplier<? extends TurnBasedGame> factory) {
gameFactories.put(key, factory);
}
public void unregister(String key) {
gameFactories.remove(key);
}
public TurnBasedGame create(String key) {
Supplier<? extends TurnBasedGame> factory = gameFactories.get(key);
if (factory == null) throw new IllegalArgumentException("Unknown game type: " + key);
return factory.get();
}
public Map<String, Supplier<? extends TurnBasedGame>> all() {
return Map.copyOf(gameFactories);
}
}

View File

@@ -1,3 +0,0 @@
package org.toop.framework.networking.types;
public record ServerMessage(String message) {}

View File

@@ -0,0 +1,21 @@
package org.toop.framework.utils;
public class ImmutablePair<T, K> implements Pair<T,K> {
final T left;
final K right;
public ImmutablePair(T left, K right) {
this.left = left;
this.right = right;
}
@Override
public T getLeft() {
return left;
}
@Override
public K getRight() {
return right;
}
}

View File

@@ -0,0 +1,29 @@
package org.toop.framework.utils;
public class MutablePair<T, K> implements Pair<T,K> {
T left;
K right;
public MutablePair(T left, K right) {
this.left = left;
this.right = right;
}
@Override
public T getLeft() {
return left;
}
public void setLeft(T left) {
this.left = left;
}
@Override
public K getRight() {
return right;
}
public void setRight(K right) {
this.right = right;
}
}

View File

@@ -0,0 +1,6 @@
package org.toop.framework.utils;
public interface Pair<T, K> {
T getLeft();
K getRight();
}

View File

@@ -0,0 +1,7 @@
package org.toop.framework.utils;
public interface SimpleTimer {
void forceExpire();
boolean isExpired();
long secondsRemaining();
}

View File

@@ -0,0 +1,11 @@
package org.toop.framework.utils;
import org.apache.maven.surefire.shared.utils.StringUtils;
import java.util.Iterator;
public class Utils {
public static String returnQuotedString(Iterator<String> strings) { // TODO more places this could be useful
return "\"" + StringUtils.join(strings, "\",\"") + "\"";
}
}

View File

@@ -9,7 +9,7 @@
//import org.mockito.*;
//import org.toop.framework.SnowflakeGenerator;
//import org.toop.framework.eventbus.EventFlow;
//import org.toop.framework.networking.events.NetworkEvents;
//import org.toop.framework.networking.connection.events.NetworkEvents;
//
//class NetworkingClientManagerTest {
//

View File

@@ -1,4 +1,4 @@
//package org.toop.framework.networking.events;
//package org.toop.framework.networking.connection.events;
//
//import static org.junit.jupiter.api.Assertions.*;
//

View File

@@ -0,0 +1,167 @@
//package org.toop.framework.networking.server;
//
//import org.junit.jupiter.api.Assertions;
//import org.junit.jupiter.api.BeforeEach;
//import org.junit.jupiter.api.Test;
//import org.toop.framework.gameFramework.model.game.PlayResult;
//import org.toop.framework.gameFramework.model.game.OnlineTurnBasedGame;
//import org.toop.framework.gameFramework.model.player.Player;
//
//import java.time.Duration;
//import java.util.Arrays;
//import java.util.concurrent.ConcurrentHashMap;
//
//public class ServerTest {
//
// static class TurnBasedGameMock implements OnlineTurnBasedGame {
// private Player[] players;
//
// public TurnBasedGameMock() {}
//
// @Override
// public void init(Player[] players) {
// this.players = players;
// }
//
// @Override
// public int getCurrentTurn() {
// return 0;
// }
//
// @Override
// public int getPlayerCount() {
// return 0;
// }
//
// @Override
// public int getWinner() {
// return 0;
// }
//
// @Override
// public long[] getBoard() {
// return new long[0];
// }
//
// @Override
// public OnlineTurnBasedGame deepCopy() {
// return null;
// }
//
// @Override
// public long getLegalMoves() {
// return 0;
// }
//
// @Override
// public PlayResult play(long move) {
// return null;
// }
//
// @Override
// public Player getPlayer(int index) {
// return null;
// }
//
// }
//
// static class TestUser implements Client {
//
// final private long id;
//
// private String name;
//
// public TestUser(long id, String name) {
// this.id = id;
// this.name = name;
// }
//
// @Override
// public long id() {
// return id;
// }
//
// @Override
// public String name() {
// return name;
// }
//
// @Override
// public OnlineTurnBasedGame[] games() {
// return new OnlineTurnBasedGame[0];
// }
//
// @Override
// public void addGame(OnlineTurnBasedGame game) {
//
// }
//
// @Override
// public void removeGame(OnlineTurnBasedGame game) {
//
// }
//
// @Override
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public void sendMessage(String message) {
//
// }
// }
//
// private Server server;
// private Duration waitTime = Duration.ofSeconds(2);
//
// @BeforeEach
// void setup() {
//
// var games = new ConcurrentHashMap<String, Class<? extends OnlineTurnBasedGame>>();
// games.put("tictactoe", TurnBasedGameMock.class);
// games.put("reversi", TurnBasedGameMock.class);
//
// server = new Server(games, waitTime);
// }
//
// @Test
// void testGameTypes() {
// String[] expected = {"tictactoe", "reversi"};
// String[] actual = server.gameTypes();
//
// Arrays.sort(expected);
// Arrays.sort(actual);
//
// Assertions.assertArrayEquals(expected, actual);
// }
//
// @Test
// void testChallenge() {
// server.addUser(new TestUser(1, "test1"));
// server.addUser(new TestUser(2, "test2"));
// server.challengeUser("test1", "test2", "tictactoe");
//
// IO.println(server.gameChallenges());
//
// Assertions.assertEquals(1, server.gameChallenges().size());
//
// try {
// Thread.sleep(waitTime.plusMillis(100));
// } catch (InterruptedException e) {
// throw new RuntimeException(e);
// }
//
// Assertions.assertEquals(0, server.gameChallenges().size());
// }
//
// @Test
// void testStartGame() {
// server.startGame("tictactoe", new NettyClient(0, "A"), new NettyClient(1, "B"));
// Assertions.assertEquals(1, server.ongoingGames().size());
// server.startGame("reversi", new NettyClient(0, "A"), new NettyClient(1, "B"));
// Assertions.assertEquals(2, server.ongoingGames().size());
// }
//
//
//}

View File

@@ -0,0 +1,17 @@
$client = New-Object System.Net.Sockets.TcpClient("localhost", 6666)
$stream = $client.GetStream()
$writer = New-Object System.IO.StreamWriter($stream)
$reader = New-Object System.IO.StreamReader($stream)
$client2 = New-Object System.Net.Sockets.TcpClient("localhost", 6666)
$stream2 = $client2.GetStream()
$writer2 = New-Object System.IO.StreamWriter($stream2)
$reader2 = New-Object System.IO.StreamReader($stream2)
$writer.WriteLine("login john")
$writer.Flush()
$reader.ReadLine()
$writer2.WriteLine("login hendrik")
$writer2.Flush()
$reader2.ReadLine()