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
This commit is contained in:
Stef
2025-12-03 20:35:37 +01:00
committed by GitHub
parent 040287ad70
commit 8d77f51355
68 changed files with 524 additions and 2702 deletions

View File

@@ -3,9 +3,7 @@ package org.toop.app;
public class GameInformation {
public enum Type {
TICTACTOE(2, 5),
REVERSI(2, 10),
CONNECT4(2, 7),
BATTLESHIP(2, 5);
REVERSI(2, 10);
private final int playerCount;
private final int maxDepth;

View File

@@ -2,9 +2,9 @@ package org.toop.app;
import javafx.application.Platform;
import javafx.geometry.Pos;
import org.toop.app.game.Connect4Game;
import org.toop.app.game.ReversiGame;
import org.toop.app.game.TicTacToeGame;
import org.toop.app.gameControllers.AbstractGameController;
import org.toop.app.gameControllers.ReversiController;
import org.toop.app.gameControllers.TicTacToeController;
import org.toop.app.widget.Primitive;
import org.toop.app.widget.WidgetContainer;
import org.toop.app.widget.complex.LoadingWidget;
@@ -13,9 +13,15 @@ import org.toop.app.widget.popup.ErrorPopup;
import org.toop.app.widget.popup.SendChallengePopup;
import org.toop.app.widget.view.ServerView;
import org.toop.framework.eventbus.EventFlow;
import org.toop.framework.gameFramework.model.player.Player;
import org.toop.framework.networking.clients.TournamentNetworkingClient;
import org.toop.framework.networking.events.NetworkEvents;
import org.toop.framework.networking.types.NetworkingConnector;
import org.toop.game.players.ArtificialPlayer;
import org.toop.game.players.OnlinePlayer;
import org.toop.game.games.reversi.ReversiAIR;
import org.toop.game.games.reversi.ReversiR;
import org.toop.game.games.tictactoe.TicTacToeAIR;
import org.toop.local.AppContext;
import java.util.List;
@@ -26,6 +32,7 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
public final class Server {
// TODO: Keep track of listeners. Remove them on Server connection close so reference is deleted.
private String user = "";
private long clientId = -1;
@@ -35,24 +42,27 @@ public final class Server {
private ServerView primary;
private boolean isPolling = true;
private AbstractGameController<?> gameController;
private final AtomicBoolean isSingleGame = new AtomicBoolean(false);
private ScheduledExecutorService scheduler;
private EventFlow eventFlow = new EventFlow();
public static GameInformation.Type gameToType(String game) {
if (game.equalsIgnoreCase("tic-tac-toe")) {
return GameInformation.Type.TICTACTOE;
} else if (game.equalsIgnoreCase("reversi")) {
return GameInformation.Type.REVERSI;
} else if (game.equalsIgnoreCase("connect4")) {
return GameInformation.Type.CONNECT4;
// } else if (game.equalsIgnoreCase("battleship")) {
// return GameInformation.Type.BATTLESHIP;
}
return null;
}
// Server has to deal with ALL network related listen events. This "server" can then interact with the manager to make stuff happen.
// This prevents data races where events get sent to the game manager but the manager isn't ready yet.
public Server(String ip, String port, String user) {
if (ip.split("\\.").length < 4) {
new ErrorPopup("\"" + ip + "\" " + AppContext.getString("is-not-a-valid-ip-address"));
@@ -136,9 +146,13 @@ public final class Server {
)
.postEvent();
new EventFlow()
.listen(NetworkEvents.ChallengeResponse.class, this::handleReceivedChallenge, false)
.listen(NetworkEvents.GameMatchResponse.class, this::handleMatchResponse, false);
eventFlow.listen(NetworkEvents.ChallengeResponse.class, this::handleReceivedChallenge, false)
.listen(NetworkEvents.GameMatchResponse.class, this::handleMatchResponse, false)
.listen(NetworkEvents.GameResultResponse.class, this::handleGameResult, false)
.listen(NetworkEvents.GameMoveResponse.class, this::handleReceivedMove, false)
.listen(NetworkEvents.YourTurnResponse.class, this::handleYourTurn, false);
startPopulateScheduler();
populateGameList();
}
private void sendChallenge(String opponent) {
@@ -151,10 +165,16 @@ public final class Server {
}
private void handleMatchResponse(NetworkEvents.GameMatchResponse response) {
if (!isPolling) return;
// TODO: Redo all of this mess
if (gameController != null) {
gameController.stop();
}
gameController = null;
//if (!isPolling) return;
String gameType = extractQuotedValue(response.gameType());
if (response.clientId() == clientId) {
isPolling = false;
onlinePlayers.clear();
@@ -175,21 +195,56 @@ public final class Server {
information.players[0].computerThinkTime = 1;
information.players[1].name = response.opponent();
Runnable onGameOverRunnable = isSingleGame.get()? null: this::gameOver;
Player[] players = new Player[2];
players[(myTurn + 1) % 2] = new OnlinePlayer<ReversiR>(response.opponent());
switch (type){
case TICTACTOE ->{
players[myTurn] = new ArtificialPlayer<>(new TicTacToeAIR(), user);
}
case REVERSI ->{
players[myTurn] = new ArtificialPlayer<>(new ReversiAIR(), user);
}
}
switch (type) {
case TICTACTOE ->
new TicTacToeGame(information, myTurn, this::forfeitGame, this::exitGame, this::sendMessage, onGameOverRunnable);
case TICTACTOE ->{
gameController = new TicTacToeController(players, false);
}
case REVERSI ->
new ReversiGame(information, myTurn, this::forfeitGame, this::exitGame, this::sendMessage, onGameOverRunnable);
case CONNECT4 ->
new Connect4Game(information, myTurn, this::forfeitGame, this::exitGame, this::sendMessage, onGameOverRunnable);
gameController = new ReversiController(players, false);
default -> new ErrorPopup("Unsupported game type.");
}
if (gameController != null){
gameController.start();
}
}
}
private void handleYourTurn(NetworkEvents.YourTurnResponse response) {
if (gameController == null) {
return;
}
gameController.onYourTurn(response);
}
private void handleGameResult(NetworkEvents.GameResultResponse response) {
if (gameController == null) {
return;
}
gameController.gameFinished(response);
}
private void handleReceivedMove(NetworkEvents.GameMoveResponse response) {
if (gameController == null) {
return;
}
gameController.onMoveReceived(response);
}
private void handleReceivedChallenge(NetworkEvents.ChallengeResponse response) {
if (!isPolling) return;

View File

@@ -1,7 +1,7 @@
package org.toop.app.canvas;
import javafx.scene.paint.Color;
import org.toop.framework.gameFramework.abstractClasses.TurnBasedGameR;
import org.toop.framework.gameFramework.model.game.AbstractGame;
import java.util.function.Consumer;
@@ -11,7 +11,7 @@ public class Connect4Canvas extends GameCanvas {
}
@Override
public void drawPlayerHover(int player, int move, TurnBasedGameR game) {
public void drawPlayerHover(int player, int move, AbstractGame game) {
}
}

View File

@@ -1,7 +1,7 @@
package org.toop.app.canvas;
import org.toop.framework.gameFramework.abstractClasses.TurnBasedGameR;
import org.toop.framework.gameFramework.model.game.AbstractGame;
public interface DrawPlayerHover {
void drawPlayerHover(int player, int move, TurnBasedGameR game);
void drawPlayerHover(int player, int move, AbstractGame game);
}

View File

@@ -8,11 +8,11 @@ import javafx.scene.input.MouseButton;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.util.Duration;
import org.toop.framework.gameFramework.abstractClasses.TurnBasedGameR;
import org.toop.framework.gameFramework.model.game.AbstractGame;
import java.util.function.Consumer;
public abstract class GameCanvas<T extends TurnBasedGameR> implements DrawPlayerMove, DrawPlayerHover {
public abstract class GameCanvas<T extends AbstractGame> implements DrawPlayerMove, DrawPlayerHover {
protected record Cell(float x, float y, float width, float height) {
public boolean isInside(double x, double y) {
return x >= this.x && x <= this.x + width &&

View File

@@ -1,9 +1,9 @@
package org.toop.app.canvas;
import javafx.scene.paint.Color;
import org.toop.framework.gameFramework.abstractClasses.TurnBasedGameR;
import org.toop.game.records.Move;
import org.toop.game.reversi.ReversiR;
import org.toop.framework.gameFramework.model.game.AbstractGame;
import org.toop.game.Move;
import org.toop.game.games.reversi.ReversiR;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
@@ -90,7 +90,7 @@ public final class ReversiCanvas extends GameCanvas<ReversiR> {
}
@Override
public void drawPlayerHover(int player, int move, TurnBasedGameR game) {
public void drawPlayerHover(int player, int move, AbstractGame game) {
}
}

View File

@@ -1,8 +1,8 @@
package org.toop.app.canvas;
import javafx.scene.paint.Color;
import org.toop.framework.gameFramework.abstractClasses.TurnBasedGameR;
import org.toop.game.tictactoe.TicTacToeR;
import org.toop.framework.gameFramework.model.game.AbstractGame;
import org.toop.game.games.tictactoe.TicTacToeR;
import java.util.function.Consumer;
@@ -48,7 +48,7 @@ public final class TicTacToeCanvas extends GameCanvas<TicTacToeR> {
}
@Override
public void drawPlayerHover(int player, int move, TurnBasedGameR game) {
public void drawPlayerHover(int player, int move, AbstractGame game) {
}
}

View File

@@ -1,122 +0,0 @@
package org.toop.app.game;
import org.toop.app.GameInformation;
import org.toop.app.widget.WidgetContainer;
import org.toop.app.widget.view.GameView;
import org.toop.framework.eventbus.EventFlow;
import org.toop.framework.networking.events.NetworkEvents;
import org.toop.game.Game;
import org.toop.game.records.Move;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
public abstract class BaseGameThread<TGame extends Game, TAI, TCanvas> {
protected final GameInformation information;
protected final int myTurn;
protected final Runnable onGameOver;
protected final BlockingQueue<Move> moveQueue;
protected final TGame game;
protected final TAI ai;
protected final GameView primary;
protected final TCanvas canvas;
protected final AtomicBoolean isRunning = new AtomicBoolean(true);
protected BaseGameThread(
GameInformation information,
int myTurn,
Runnable onForfeit,
Runnable onExit,
Consumer<String> onMessage,
Runnable onGameOver,
Supplier<TGame> gameSupplier,
Supplier<TAI> aiSupplier,
Function<Consumer<Integer>, TCanvas> canvasFactory) {
this.information = information;
this.myTurn = myTurn;
this.onGameOver = onGameOver;
this.moveQueue = new LinkedBlockingQueue<>();
this.game = gameSupplier.get();
this.ai = aiSupplier.get();
String type = information.type.getTypeToString();
if (onForfeit == null || onExit == null) {
primary = new GameView(null, () -> {
isRunning.set(false);
WidgetContainer.getCurrentView().transitionPrevious();
}, null, type);
} else {
primary = new GameView(onForfeit, () -> {
isRunning.set(false);
onExit.run();
}, onMessage, type);
}
this.canvas = canvasFactory.apply(this::onCellClicked);
addCanvasToPrimary();
WidgetContainer.getCurrentView().transitionNext(primary);
if (onForfeit == null || onExit == null)
new Thread(this::localGameThread).start();
else
new EventFlow()
.listen(NetworkEvents.GameMoveResponse.class, this::onMoveResponse, false)
.listen(NetworkEvents.YourTurnResponse.class, this::onYourTurnResponse, false);
setGameLabels(myTurn == 0);
}
private void onCellClicked(int cell) {
if (!isRunning.get()) return;
final int currentTurn = getCurrentTurn();
if (!information.players[currentTurn].isHuman) return;
final char value = getSymbolForTurn(currentTurn);
try {
moveQueue.put(new Move(cell, value));
} catch (InterruptedException _) {}
}
protected void gameOver() {
if (onGameOver != null) {
isRunning.set(false);
onGameOver.run();
}
}
protected void setGameLabels(boolean isMe) {
final int currentTurn = getCurrentTurn();
final String turnName = getNameForTurn(currentTurn);
primary.nextPlayer(
isMe,
information.players[isMe ? 0 : 1].name,
turnName,
information.players[isMe ? 1 : 0].name
);
}
protected abstract void addCanvasToPrimary();
protected abstract int getCurrentTurn();
protected abstract char getSymbolForTurn(int turn);
protected abstract String getNameForTurn(int turn);
protected abstract void onMoveResponse(NetworkEvents.GameMoveResponse response);
protected abstract void onYourTurnResponse(NetworkEvents.YourTurnResponse response);
protected abstract void localGameThread();
}

View File

@@ -1,265 +0,0 @@
package org.toop.app.game;
import javafx.geometry.Pos;
import javafx.scene.paint.Color;
import org.toop.app.App;
import org.toop.app.GameInformation;
import org.toop.app.canvas.Connect4Canvas;
import org.toop.app.widget.view.GameView;
import org.toop.app.widget.WidgetContainer;
import org.toop.framework.eventbus.EventFlow;
import org.toop.framework.networking.events.NetworkEvents;
import org.toop.game.Connect4.Connect4;
import org.toop.game.Connect4.Connect4AI;
import org.toop.framework.gameFramework.GameState;
import org.toop.game.records.Move;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
public class Connect4Game {
private final GameInformation information;
private final int myTurn;
private Runnable onGameOver;
private final BlockingQueue<Move> moveQueue;
private final Connect4 game;
private final Connect4AI ai;
private final int columnSize = 7;
private final int rowSize = 6;
private final GameView primary;
private final Connect4Canvas canvas;
private final AtomicBoolean isRunning;
public Connect4Game(GameInformation information, int myTurn, Runnable onForfeit, Runnable onExit, Consumer<String> onMessage, Runnable onGameOver) {
this.information = information;
this.myTurn = myTurn;
this.onGameOver = onGameOver;
moveQueue = new LinkedBlockingQueue<Move>();
game = new Connect4();
ai = new Connect4AI();
isRunning = new AtomicBoolean(true);
if (onForfeit == null || onExit == null) {
primary = new GameView(null, () -> {
isRunning.set(false);
WidgetContainer.getCurrentView().transitionPrevious();
}, null, "Connect4");
} else {
primary = new GameView(onForfeit, () -> {
isRunning.set(false);
onExit.run();
}, onMessage, "Connect4");
}
canvas = new Connect4Canvas(Color.GRAY,
(App.getHeight() / 4) * 3, (App.getHeight() / 4) * 3,
(cell) -> {
if (onForfeit == null || onExit == null) {
if (information.players[game.getCurrentTurn()].isHuman) {
final char value = game.getCurrentTurn() == 0? 'X' : 'O';
try {
moveQueue.put(new Move(cell%columnSize, value));
} catch (InterruptedException _) {}
}
} else {
if (information.players[0].isHuman) {
final char value = myTurn == 0? 'X' : 'O';
try {
moveQueue.put(new Move(cell%columnSize, value));
} catch (InterruptedException _) {}
}
}
});
primary.add(Pos.CENTER, canvas.getCanvas());
WidgetContainer.getCurrentView().transitionNext(primary);
if (onForfeit == null || onExit == null) {
new Thread(this::localGameThread).start();
setGameLabels(information.players[0].isHuman);
} else {
new EventFlow()
.listen(NetworkEvents.GameMoveResponse.class, this::onMoveResponse, false)
.listen(NetworkEvents.YourTurnResponse.class, this::onYourTurnResponse, false);
setGameLabels(myTurn == 0);
}
updateCanvas();
}
public Connect4Game(GameInformation information) {
this(information, 0, null, null, null, null);
}
private void localGameThread() {
while (isRunning.get()) {
final int currentTurn = game.getCurrentTurn();
final String currentValue = currentTurn == 0? "RED" : "BLUE";
final int nextTurn = (currentTurn + 1) % information.type.getPlayerCount();
primary.nextPlayer(information.players[currentTurn].isHuman,
information.players[currentTurn].name,
currentValue,
information.players[nextTurn].name);
Move move = null;
if (information.players[currentTurn].isHuman) {
try {
final Move wants = moveQueue.take();
final Move[] legalMoves = game.getLegalMoves();
for (final Move legalMove : legalMoves) {
if (legalMove.position() == wants.position() &&
legalMove.value() == wants.value()) {
move = wants;
break;
}
}
} catch (InterruptedException _) {}
} else {
final long start = System.currentTimeMillis();
move = ai.findBestMove(game, information.players[currentTurn].computerDifficulty);
if (information.players[currentTurn].computerThinkTime > 0) {
final long elapsedTime = System.currentTimeMillis() - start;
final long sleepTime = Math.abs(information.players[currentTurn].computerThinkTime * 1000L - elapsedTime);
try {
Thread.sleep((long)(sleepTime * Math.random()));
} catch (InterruptedException _) {}
}
}
if (move == null) {
continue;
}
final GameState state = game.play(move);
updateCanvas();
/*
if (move.value() == 'X') {
canvas.drawX(Color.INDIANRED, move.position());
} else if (move.value() == 'O') {
canvas.drawO(Color.ROYALBLUE, move.position());
}
*/
if (state != GameState.NORMAL) {
if (state == GameState.WIN) {
primary.gameOver(true, information.players[currentTurn].name);
} else if (state == GameState.DRAW) {
primary.gameOver(false, "");
}
isRunning.set(false);
}
}
}
private void onMoveResponse(NetworkEvents.GameMoveResponse response) {
if (!isRunning.get()) {
return;
}
char playerChar;
if (response.player().equalsIgnoreCase(information.players[0].name)) {
playerChar = myTurn == 0? 'X' : 'O';
} else {
playerChar = myTurn == 0? 'O' : 'X';
}
final Move move = new Move(Integer.parseInt(response.move()), playerChar);
final GameState state = game.play(move);
if (state != GameState.NORMAL) {
if (state == GameState.WIN) {
if (response.player().equalsIgnoreCase(information.players[0].name)) {
primary.gameOver(true, information.players[0].name);
gameOver();
} else {
primary.gameOver(false, information.players[1].name);
gameOver();
}
} else if (state == GameState.DRAW) {
primary.gameOver(false, "");
gameOver();
}
}
if (move.value() == 'X') {
canvas.drawDot(Color.INDIANRED, move.position());
} else if (move.value() == 'O') {
canvas.drawDot(Color.ROYALBLUE, move.position());
}
updateCanvas();
setGameLabels(game.getCurrentTurn() == myTurn);
}
private void gameOver() {
if (onGameOver == null){
return;
}
isRunning.set(false);
onGameOver.run();
}
private void onYourTurnResponse(NetworkEvents.YourTurnResponse response) {
if (!isRunning.get()) {
return;
}
moveQueue.clear();
int position = -1;
if (information.players[0].isHuman) {
try {
position = moveQueue.take().position();
} catch (InterruptedException _) {}
} else {
final Move move = ai.findBestMove(game, information.players[0].computerDifficulty);
assert move != null;
position = move.position();
}
new EventFlow().addPostEvent(new NetworkEvents.SendMove(response.clientId(), (short)position))
.postEvent();
}
private void updateCanvas() {
canvas.clearAll();
for (int i = 0; i < game.getBoard().length; i++) {
if (game.getBoard()[i] == 'X') {
canvas.drawDot(Color.RED, i);
} else if (game.getBoard()[i] == 'O') {
canvas.drawDot(Color.BLUE, i);
}
}
}
private void setGameLabels(boolean isMe) {
final int currentTurn = game.getCurrentTurn();
final String currentValue = currentTurn == 0? "RED" : "BLUE";
primary.nextPlayer(isMe,
information.players[isMe? 0 : 1].name,
currentValue,
information.players[isMe? 1 : 0].name);
}
}

View File

@@ -1,333 +0,0 @@
package org.toop.app.game;
import javafx.animation.SequentialTransition;
import org.toop.app.App;
import org.toop.app.GameInformation;
import org.toop.app.canvas.ReversiCanvas;
import org.toop.app.widget.WidgetContainer;
import org.toop.app.widget.view.GameView;
import org.toop.framework.eventbus.EventFlow;
import org.toop.framework.networking.events.NetworkEvents;
import org.toop.framework.gameFramework.GameState;
import org.toop.game.records.Move;
import org.toop.game.reversi.Reversi;
import org.toop.game.reversi.ReversiAI;
import javafx.geometry.Pos;
import javafx.scene.paint.Color;
import java.awt.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
public final class ReversiGame {
private final GameInformation information;
private final int myTurn;
private final Runnable onGameOver;
private final BlockingQueue<Move> moveQueue;
private final Reversi game;
private final ReversiAI ai;
private final GameView primary;
private final ReversiCanvas canvas;
private final AtomicBoolean isRunning;
private final AtomicBoolean isPaused;
public ReversiGame(GameInformation information, int myTurn, Runnable onForfeit, Runnable onExit, Consumer<String> onMessage, Runnable onGameOver) {
this.information = information;
this.myTurn = myTurn;
this.onGameOver = onGameOver;
moveQueue = new LinkedBlockingQueue<>();
game = new Reversi();
ai = new ReversiAI();
isRunning = new AtomicBoolean(true);
isPaused = new AtomicBoolean(false);
if (onForfeit == null || onExit == null) {
primary = new GameView(null, () -> {
isRunning.set(false);
WidgetContainer.getCurrentView().transitionPrevious();
}, null, "Reversi");
} else {
primary = new GameView(onForfeit, () -> {
isRunning.set(false);
onExit.run();
}, onMessage, "Reversi");
}
canvas = new ReversiCanvas(Color.BLACK,
(App.getHeight() / 4) * 3, (App.getHeight() / 4) * 3,
(cell) -> {
if (onForfeit == null || onExit == null) {
if (information.players[game.getCurrentTurn()].isHuman) {
final char value = game.getCurrentTurn() == 0? 'B' : 'W';
try {
moveQueue.put(new Move(cell, value));
} catch (InterruptedException _) {}
}
} else {
if (information.players[0].isHuman) {
final char value = myTurn == 0? 'B' : 'W';
try {
moveQueue.put(new Move(cell, value));
} catch (InterruptedException _) {}
}
}
},this::highlightCells);
primary.add(Pos.CENTER, canvas.getCanvas());
WidgetContainer.getCurrentView().transitionNext(primary);
if (onForfeit == null || onExit == null) {
new Thread(this::localGameThread).start();
setGameLabels(information.players[0].isHuman);
} else {
new EventFlow()
.listen(NetworkEvents.GameMoveResponse.class, this::onMoveResponse, false)
.listen(NetworkEvents.YourTurnResponse.class, this::onYourTurnResponse, false);
setGameLabels(myTurn == 0);
}
updateCanvas(false);
}
public ReversiGame(GameInformation information) {
this(information, 0, null, null, null,null);
}
private void localGameThread() {
while (isRunning.get()) {
if (isPaused.get()) {
try {
Thread.sleep(200);
} catch (InterruptedException _) {}
continue;
}
final int currentTurn = game.getCurrentTurn();
final String currentValue = currentTurn == 0? "BLACK" : "WHITE";
final int nextTurn = (currentTurn + 1) % information.type.getPlayerCount();
primary.nextPlayer(information.players[currentTurn].isHuman,
information.players[currentTurn].name,
currentValue,
information.players[nextTurn].name);
Move move = null;
if (information.players[currentTurn].isHuman) {
try {
final Move wants = moveQueue.take();
final Move[] legalMoves = game.getLegalMoves();
for (final Move legalMove : legalMoves) {
if (legalMove.position() == wants.position() &&
legalMove.value() == wants.value()) {
move = wants;
break;
}
}
} catch (InterruptedException _) {}
} else {
final long start = System.currentTimeMillis();
move = ai.findBestMove(game, information.players[currentTurn].computerDifficulty);
if (information.players[currentTurn].computerThinkTime > 0) {
final long elapsedTime = System.currentTimeMillis() - start;
final long sleepTime = information.players[currentTurn].computerThinkTime * 1000L - elapsedTime;
try {
Thread.sleep((long) (sleepTime * Math.random()));
} catch (InterruptedException _) {}
}
}
if (move == null) {
continue;
}
canvas.setCurrentlyHighlightedMovesNull();
final GameState state = game.play(move);
updateCanvas(true);
if (state != GameState.NORMAL) {
if (state == GameState.TURN_SKIPPED){
continue;
}
int winningPLayerNumber = getPlayerNumberWithHighestScore();
if (state == GameState.WIN && winningPLayerNumber > -1) {
primary.gameOver(true, information.players[winningPLayerNumber].name);
} else if (state == GameState.DRAW || winningPLayerNumber == -1) {
primary.gameOver(false, "");
}
isRunning.set(false);
}
}
}
private int getPlayerNumberWithHighestScore(){
Reversi.Score score = game.getScore();
if (score.player1Score() > score.player2Score()) return 0;
if (score.player1Score() < score.player2Score()) return 1;
return -1;
}
private void onMoveResponse(NetworkEvents.GameMoveResponse response) {
if (!isRunning.get()) {
return;
}
char playerChar;
if (response.player().equalsIgnoreCase(information.players[0].name)) {
playerChar = myTurn == 0? 'B' : 'W';
} else {
playerChar = myTurn == 0? 'W' : 'B';
}
final Move move = new Move(Integer.parseInt(response.move()), playerChar);
final GameState state = game.play(move);
if (state != GameState.NORMAL) {
if (state == GameState.WIN) {
if (response.player().equalsIgnoreCase(information.players[0].name)) {
primary.gameOver(true, information.players[0].name);
gameOver();
} else {
primary.gameOver(false, information.players[1].name);
gameOver();
}
} else if (state == GameState.DRAW) {
primary.gameOver(false, "");
game.play(move);
}
}
updateCanvas(false);
setGameLabels(game.getCurrentTurn() == myTurn);
}
private void gameOver() {
if (onGameOver == null){
return;
}
isRunning.set(false);
onGameOver.run();
}
private void onYourTurnResponse(NetworkEvents.YourTurnResponse response) {
if (!isRunning.get()) {
return;
}
moveQueue.clear();
int position = -1;
if (information.players[0].isHuman) {
try {
position = moveQueue.take().position();
} catch (InterruptedException _) {}
} else {
final Move move = ai.findBestMove(game, information.players[0].computerDifficulty);
assert move != null;
position = move.position();
}
new EventFlow().addPostEvent(new NetworkEvents.SendMove(response.clientId(), (short) position))
.postEvent();
}
private void updateCanvas(boolean animate) {
// Todo: this is very inefficient. still very fast but if the grid is bigger it might cause issues. improve.
canvas.clearAll();
for (int i = 0; i < game.getBoard().length; i++) {
if (game.getBoard()[i] == 'B') {
canvas.drawDot(Color.BLACK, i);
} else if (game.getBoard()[i] == 'W') {
canvas.drawDot(Color.WHITE, i);
}
}
final Move[] flipped = game.getMostRecentlyFlippedPieces();
final SequentialTransition animation = new SequentialTransition();
isPaused.set(true);
final Color fromColor = game.getCurrentPlayer() == 'W'? Color.WHITE : Color.BLACK;
final Color toColor = game.getCurrentPlayer() == 'W'? Color.BLACK : Color.WHITE;
if (animate && flipped != null) {
for (final Move flip : flipped) {
canvas.clear(flip.position());
canvas.drawDot(fromColor, flip.position());
animation.getChildren().addFirst(canvas.flipDot(fromColor, toColor, flip.position()));
}
}
animation.setOnFinished(_ -> {
isPaused.set(false);
if (information.players[game.getCurrentTurn()].isHuman) {
final Move[] legalMoves = game.getLegalMoves();
for (final Move legalMove : legalMoves) {
canvas.drawLegalPosition(legalMove.position(), game.getCurrentPlayer());
}
}
});
animation.play();
}
private void setGameLabels(boolean isMe) {
final int currentTurn = game.getCurrentTurn();
final String currentValue = currentTurn == 0? "BLACK" : "WHITE";
primary.nextPlayer(isMe,
information.players[isMe? 0 : 1].name,
currentValue,
information.players[isMe? 1 : 0].name);
}
private void highlightCells(int cellEntered) {
if (information.players[game.getCurrentTurn()].isHuman) {
Move[] legalMoves = game.getLegalMoves();
boolean isLegalMove = false;
for (Move move : legalMoves) {
if (move.position() == cellEntered){
isLegalMove = true;
break;
}
}
if (cellEntered >= 0){
Move[] moves = null;
if (isLegalMove) {
moves = game.getFlipsForPotentialMove(
new Point(cellEntered%game.getColumnSize(),cellEntered/game.getRowSize()),
game.getCurrentPlayer());
}
canvas.drawHighlightDots(moves);
}
}
}
}

View File

@@ -1,250 +0,0 @@
package org.toop.app.game;
import org.toop.app.App;
import org.toop.app.GameInformation;
import org.toop.app.canvas.TicTacToeCanvas;
import org.toop.app.widget.WidgetContainer;
import org.toop.app.widget.view.GameView;
import org.toop.framework.eventbus.EventFlow;
import org.toop.framework.networking.events.NetworkEvents;
import org.toop.framework.gameFramework.GameState;
import org.toop.game.records.Move;
import org.toop.game.tictactoe.TicTacToe;
import org.toop.game.tictactoe.TicTacToeAI;
import javafx.geometry.Pos;
import javafx.scene.paint.Color;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
public final class TicTacToeGame {
private final GameInformation information;
private final int myTurn;
private final Runnable onGameOver;
private final BlockingQueue<Move> moveQueue;
private final TicTacToe game;
private final TicTacToeAI ai;
private final GameView primary;
private final TicTacToeCanvas canvas;
private final AtomicBoolean isRunning;
public TicTacToeGame(GameInformation information, int myTurn, Runnable onForfeit, Runnable onExit, Consumer<String> onMessage, Runnable onGameOver) {
this.information = information;
this.myTurn = myTurn;
this.onGameOver = onGameOver;
moveQueue = new LinkedBlockingQueue<Move>();
game = new TicTacToe();
ai = new TicTacToeAI();
isRunning = new AtomicBoolean(true);
if (onForfeit == null || onExit == null) {
primary = new GameView(null, () -> {
isRunning.set(false);
WidgetContainer.getCurrentView().transitionPrevious();
}, null, "TicTacToe");
} else {
primary = new GameView(onForfeit, () -> {
isRunning.set(false);
onExit.run();
}, onMessage, "TicTacToe");
}
canvas = new TicTacToeCanvas(Color.GRAY,
(App.getHeight() / 4) * 3, (App.getHeight() / 4) * 3,
(cell) -> {
if (onForfeit == null || onExit == null) {
if (information.players[game.getCurrentTurn()].isHuman) {
final char value = game.getCurrentTurn() == 0? 'X' : 'O';
try {
moveQueue.put(new Move(cell, value));
} catch (InterruptedException _) {}
}
} else {
if (information.players[0].isHuman) {
final char value = myTurn == 0? 'X' : 'O';
try {
moveQueue.put(new Move(cell, value));
} catch (InterruptedException _) {}
}
}
});
primary.add(Pos.CENTER, canvas.getCanvas());
WidgetContainer.getCurrentView().transitionNext(primary);
if (onForfeit == null || onExit == null) {
new Thread(this::localGameThread).start();
} else {
new EventFlow()
.listen(NetworkEvents.GameMoveResponse.class, this::onMoveResponse, false)
.listen(NetworkEvents.YourTurnResponse.class, this::onYourTurnResponse, false);
setGameLabels(myTurn == 0);
}
}
public TicTacToeGame(GameInformation information) {
this(information, 0, null, null, null, null);
}
private void localGameThread() {
while (isRunning.get()) {
final int currentTurn = game.getCurrentTurn();
final String currentValue = currentTurn == 0? "X" : "O";
final int nextTurn = (currentTurn + 1) % information.type.getPlayerCount();
primary.nextPlayer(information.players[currentTurn].isHuman,
information.players[currentTurn].name,
currentValue,
information.players[nextTurn].name);
Move move = null;
if (information.players[currentTurn].isHuman) {
try {
final Move wants = moveQueue.take();
final Move[] legalMoves = game.getLegalMoves();
for (final Move legalMove : legalMoves) {
if (legalMove.position() == wants.position() &&
legalMove.value() == wants.value()) {
move = wants;
break;
}
}
} catch (InterruptedException _) {}
} else {
final long start = System.currentTimeMillis();
move = ai.findBestMove(game, information.players[currentTurn].computerDifficulty);
if (information.players[currentTurn].computerThinkTime > 0) {
final long elapsedTime = System.currentTimeMillis() - start;
final long sleepTime = information.players[currentTurn].computerThinkTime * 1000L - elapsedTime;
try {
Thread.sleep((long)(sleepTime * Math.random()));
} catch (InterruptedException _) {}
}
}
if (move == null) {
continue;
}
final GameState state = game.play(move);
if (move.value() == 'X') {
//canvas.drawPlayer('X', Color.INDIANRED, move.position());
} else if (move.value() == 'O') {
//canvas.drawPlayer('O', Color.ROYALBLUE, move.position());
}
if (state != GameState.NORMAL) {
if (state == GameState.WIN) {
primary.gameOver(true, information.players[currentTurn].name);
} else if (state == GameState.DRAW) {
primary.gameOver(false, "");
}
isRunning.set(false);
}
}
}
private void onMoveResponse(NetworkEvents.GameMoveResponse response) {
if (!isRunning.get()) {
return;
}
char playerChar;
if (response.player().equalsIgnoreCase(information.players[0].name)) {
playerChar = myTurn == 0? 'X' : 'O';
} else {
playerChar = myTurn == 0? 'O' : 'X';
}
final Move move = new Move(Integer.parseInt(response.move()), playerChar);
final GameState state = game.play(move);
if (state != GameState.NORMAL) {
if (state == GameState.WIN) {
if (response.player().equalsIgnoreCase(information.players[0].name)) {
primary.gameOver(true, information.players[0].name);
gameOver();
} else {
primary.gameOver(false, information.players[1].name);
gameOver();
}
} else if (state == GameState.DRAW) {
if(game.getLegalMoves().length == 0) { //only return draw in online multiplayer if the game is actually over.
primary.gameOver(false, "");
gameOver();
}
}
}
if (move.value() == 'X') {
//canvas.drawPlayer('X', Color.RED, move.position());
} else if (move.value() == 'O') {
//canvas.drawPlayer('O', Color.BLUE, move.position());
}
setGameLabels(game.getCurrentTurn() == myTurn);
}
private void gameOver() {
if (onGameOver == null){
return;
}
isRunning.set(false);
onGameOver.run();
}
private void onYourTurnResponse(NetworkEvents.YourTurnResponse response) {
if (!isRunning.get()) {
return;
}
moveQueue.clear();
int position = -1;
if (information.players[0].isHuman) {
try {
position = moveQueue.take().position();
} catch (InterruptedException _) {}
} else {
final Move move;
move = ai.findBestMove(game, information.players[0].computerDifficulty);
assert move != null;
position = move.position();
}
new EventFlow().addPostEvent(new NetworkEvents.SendMove(response.clientId(), (short)position))
.postEvent();
}
private void setGameLabels(boolean isMe) {
final int currentTurn = game.getCurrentTurn();
final String currentValue = currentTurn == 0? "X" : "O";
primary.nextPlayer(isMe,
information.players[isMe? 0 : 1].name,
currentValue,
information.players[isMe? 1 : 0].name);
}
}

View File

@@ -1,176 +0,0 @@
package org.toop.app.game;
import org.toop.app.App;
import org.toop.app.GameInformation;
import org.toop.app.canvas.TicTacToeCanvas;
import org.toop.framework.eventbus.EventFlow;
import org.toop.framework.networking.events.NetworkEvents;
import org.toop.framework.gameFramework.GameState;
import org.toop.game.records.Move;
import org.toop.game.tictactoe.TicTacToe;
import org.toop.game.tictactoe.TicTacToeAI;
import java.util.function.Consumer;
import javafx.geometry.Pos;
import javafx.scene.paint.Color;
public final class TicTacToeGameThread extends BaseGameThread<TicTacToe, TicTacToeAI, TicTacToeCanvas> {
public TicTacToeGameThread(GameInformation info, int myTurn, Runnable onForfeit, Runnable onExit, Consumer<String> onMessage, Runnable onGameOver) {
super(info, myTurn, onForfeit, onExit, onMessage, onGameOver,
TicTacToe::new,
TicTacToeAI::new,
clickHandler -> new TicTacToeCanvas(Color.GRAY, (App.getHeight() / 4) * 3, (App.getHeight() / 4) * 3, clickHandler)
);
}
public TicTacToeGameThread(GameInformation info) {
this(info, 0, null, null, null, null);
}
@Override
protected void addCanvasToPrimary() {
primary.add(Pos.CENTER, canvas.getCanvas());
}
@Override
protected int getCurrentTurn() {
return game.getCurrentTurn();
}
@Override
protected char getSymbolForTurn(int turn) {
return turn == 0 ? 'X' : 'O';
}
@Override
protected String getNameForTurn(int turn) {
return turn == 0 ? "X" : "O";
}
private void drawMove(Move move) {
//if (move.value() == 'X') canvas.drawPlayer('X', Color.RED, move.position());
//else canvas.drawPlayer('O', Color.BLUE, move.position());
}
@Override
protected void onMoveResponse(NetworkEvents.GameMoveResponse response) {
if (!isRunning.get()) {
return;
}
char playerChar;
if (response.player().equalsIgnoreCase(information.players[0].name)) {
playerChar = myTurn == 0? 'X' : 'O';
} else {
playerChar = myTurn == 0? 'O' : 'X';
}
final Move move = new Move(Integer.parseInt(response.move()), playerChar);
final GameState state = game.play(move);
if (state != GameState.NORMAL) {
if (state == GameState.WIN) {
if (response.player().equalsIgnoreCase(information.players[0].name)) {
primary.gameOver(true, information.players[0].name);
gameOver();
} else {
primary.gameOver(false, information.players[1].name);
gameOver();
}
} else if (state == GameState.DRAW) {
if (game.getLegalMoves().length == 0) {
primary.gameOver(false, "");
gameOver();
}
}
}
drawMove(move);
setGameLabels(game.getCurrentTurn() == myTurn);
}
@Override
protected void onYourTurnResponse(NetworkEvents.YourTurnResponse response) {
if (!isRunning.get()) {
return;
}
moveQueue.clear();
int position = -1;
if (information.players[0].isHuman) {
try {
position = moveQueue.take().position();
} catch (InterruptedException _) {}
} else {
final Move move;
if (information.players[1].name.equalsIgnoreCase("pism")) {
move = ai.findWorstMove(game,9);
}else{
move = ai.findBestMove(game, information.players[0].computerDifficulty);
}
assert move != null;
position = move.position();
}
new EventFlow().addPostEvent(new NetworkEvents.SendMove(response.clientId(), (short)position))
.postEvent();
}
@Override
protected void localGameThread() {
while (isRunning.get()) {
final int currentTurn = game.getCurrentTurn();
setGameLabels(currentTurn == myTurn);
Move move = null;
if (information.players[currentTurn].isHuman) {
try {
final Move wants = moveQueue.take();
final Move[] legalMoves = game.getLegalMoves();
for (final Move legalMove : legalMoves) {
if (legalMove.position() == wants.position() &&
legalMove.value() == wants.value()) {
move = wants;
break;
}
}
} catch (InterruptedException _) {}
} else {
final long start = System.currentTimeMillis();
move = ai.findBestMove(game, information.players[currentTurn].computerDifficulty);
if (information.players[currentTurn].computerThinkTime > 0) {
final long elapsedTime = System.currentTimeMillis() - start;
final long sleepTime = information.players[currentTurn].computerThinkTime * 1000L - elapsedTime;
try {
Thread.sleep((long)(sleepTime * Math.random()));
} catch (InterruptedException _) {}
}
}
if (move == null) {
continue;
}
final GameState state = game.play(move);
drawMove(move);
if (state != GameState.NORMAL) {
if (state == GameState.WIN) {
primary.gameOver(information.players[currentTurn].isHuman, information.players[currentTurn].name);
} else if (state == GameState.DRAW) {
primary.gameOver(false, "");
}
isRunning.set(false);
}
}
}
}

View File

@@ -1,24 +1,24 @@
package org.toop.app.game.gameControllers;
package org.toop.app.gameControllers;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.toop.framework.gameFramework.interfaces.UpdatesGameUI;
import org.toop.framework.gameFramework.GUIEvents;
import org.toop.framework.gameFramework.controller.UpdatesGameUI;
import org.toop.framework.gameFramework.view.GUIEvents;
import org.toop.app.canvas.GameCanvas;
import org.toop.framework.networking.events.NetworkEvents;
import org.toop.game.GameThreadBehaviour.GameThreadStrategy;
import org.toop.framework.gameFramework.model.game.threadBehaviour.ThreadBehaviour;
import org.toop.app.widget.view.GameView;
import org.toop.framework.eventbus.EventFlow;
import org.toop.game.GameThreadBehaviour.OnlineThreadBehaviour;
import org.toop.framework.gameFramework.abstractClasses.TurnBasedGameR;
import org.toop.framework.gameFramework.interfaces.SupportsOnlinePlay;
import org.toop.game.players.AbstractPlayer;
import org.toop.game.gameThreads.OnlineThreadBehaviour;
import org.toop.framework.gameFramework.model.game.AbstractGame;
import org.toop.framework.gameFramework.model.game.SupportsOnlinePlay;
import org.toop.framework.gameFramework.model.player.Player;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
public abstract class AbstractGameController<T extends TurnBasedGameR> implements UpdatesGameUI, GameThreadStrategy, SupportsOnlinePlay {
public abstract class AbstractGameController<T extends AbstractGame<T>> implements UpdatesGameUI, ThreadBehaviour<T> {
protected final EventFlow eventFlow = new EventFlow();
protected final List<Consumer<?>> listeners = new ArrayList<>();
@@ -32,13 +32,13 @@ public abstract class AbstractGameController<T extends TurnBasedGameR> implement
// Reference to game canvas
protected final GameCanvas<T> canvas;
private final AbstractPlayer[] players; // List of players, can't be changed.
private final Player<T>[] players; // List of players, can't be changed.
protected final T game; // Reference to game instance
private final GameThreadStrategy gameThreadBehaviour;
private final ThreadBehaviour<T> gameThreadBehaviour;
// TODO: Change gameType to automatically happen with either dependency injection or something else.
// TODO: Make visualisation of moves a behaviour.
protected AbstractGameController(GameCanvas<T> canvas, AbstractPlayer[] players, T game, GameThreadStrategy gameThreadBehaviour, String gameType) {
protected AbstractGameController(GameCanvas<T> canvas, Player<T>[] players, T game, ThreadBehaviour<T> gameThreadBehaviour, String gameType) {
logger.info("Creating AbstractGameController");
// Make sure player list matches expected size
if (players.length != game.getPlayerCount()){
@@ -51,11 +51,6 @@ public abstract class AbstractGameController<T extends TurnBasedGameR> implement
this.game = game;
this.gameThreadBehaviour = gameThreadBehaviour;
// Let players know who they are
for(int i = 0; i < players.length; i++){
players[i].setPlayerIndex(i);
}
primary = new GameView(null, null, null, gameType);
addListeners();
}
@@ -71,12 +66,12 @@ public abstract class AbstractGameController<T extends TurnBasedGameR> implement
gameThreadBehaviour.stop();
}
public AbstractPlayer getCurrentPlayer(){
return gameThreadBehaviour.getCurrentPlayer();
public Player<T> getCurrentPlayer(){
return game.getPlayer(getCurrentPlayerIndex());
};
public int getCurrentPlayerIndex(){
return getCurrentPlayer().getPlayerIndex();
return game.getCurrentTurn();
}
private void addListeners(){
@@ -100,7 +95,7 @@ public abstract class AbstractGameController<T extends TurnBasedGameR> implement
stop();
}
public AbstractPlayer getPlayer(int player){
public Player<T> getPlayer(int player){
if (player < 0 || player >= players.length){
logger.error("Invalid player index");
throw new IllegalArgumentException("player out of range");
@@ -112,24 +107,21 @@ public abstract class AbstractGameController<T extends TurnBasedGameR> implement
return this.gameThreadBehaviour instanceof SupportsOnlinePlay;
}
@Override
public void yourTurn(NetworkEvents.YourTurnResponse event){
public void onYourTurn(NetworkEvents.YourTurnResponse event){
if (isOnline()){
((OnlineThreadBehaviour) this.gameThreadBehaviour).yourTurn(event);
((OnlineThreadBehaviour<T>) this.gameThreadBehaviour).onYourTurn(event);
}
}
@Override
public void moveReceived(NetworkEvents.GameMoveResponse event){
public void onMoveReceived(NetworkEvents.GameMoveResponse event){
if (isOnline()){
((OnlineThreadBehaviour) this.gameThreadBehaviour).moveReceived(event);
((OnlineThreadBehaviour<T>) this.gameThreadBehaviour).onMoveReceived(event);
}
}
@Override
public void gameFinished(NetworkEvents.GameResultResponse event){
if (isOnline()){
((OnlineThreadBehaviour) this.gameThreadBehaviour).gameFinished(event);
((OnlineThreadBehaviour<T>) this.gameThreadBehaviour).gameFinished(event);
}
}
}

View File

@@ -1,4 +1,4 @@
package org.toop.app.game.gameControllers;
package org.toop.app.gameControllers;
import javafx.animation.SequentialTransition;
import javafx.geometry.Pos;
@@ -7,23 +7,23 @@ import org.toop.app.App;
import org.toop.app.canvas.ReversiCanvas;
import org.toop.app.widget.WidgetContainer;
import org.toop.framework.eventbus.EventFlow;
import org.toop.framework.gameFramework.abstractClasses.GameR;
import org.toop.framework.gameFramework.GUIEvents;
import org.toop.game.GameThreadBehaviour.LocalFixedRateThreadBehaviour;
import org.toop.game.GameThreadBehaviour.OnlineThreadBehaviour;
import org.toop.game.players.AbstractPlayer;
import org.toop.framework.gameFramework.model.game.AbstractGame;
import org.toop.framework.gameFramework.view.GUIEvents;
import org.toop.game.gameThreads.LocalFixedRateThreadBehaviour;
import org.toop.game.gameThreads.OnlineThreadBehaviour;
import org.toop.game.players.LocalPlayer;
import org.toop.game.reversi.ReversiR;
import org.toop.framework.gameFramework.model.player.Player;
import org.toop.game.games.reversi.ReversiR;
public class ReversiController extends AbstractGameController<ReversiR> {
// TODO: Refactor GUI update methods to follow designed system
public ReversiController(AbstractPlayer[] players, boolean local) {
ReversiR ReversiR = new ReversiR();
public ReversiController(Player<ReversiR>[] players, boolean local) {
ReversiR ReversiR = new ReversiR(players);
super(
new ReversiCanvas(Color.GRAY, (App.getHeight() / 4) * 3, (App.getHeight() / 4) * 3,(c) -> {new EventFlow().addPostEvent(GUIEvents.PlayerAttemptedMove.class, c).postEvent();}, (c) -> {new EventFlow().addPostEvent(GUIEvents.PlayerMoveHovered.class, c).postEvent();}),
players,
ReversiR,
local ? new LocalFixedRateThreadBehaviour(ReversiR, players) : new OnlineThreadBehaviour(ReversiR, players), // TODO: Player order matters here, this won't work atm
local ? new LocalFixedRateThreadBehaviour<>(ReversiR, players) : new OnlineThreadBehaviour<>(ReversiR, players), // TODO: Player order matters here, this won't work atm
"Reversi");
eventFlow.listen(GUIEvents.PlayerAttemptedMove.class, event -> {if (getCurrentPlayer() instanceof LocalPlayer lp){lp.setMove(event.move());}}, false);
eventFlow.listen(GUIEvents.PlayerMoveHovered.class, this::onHoverMove, false);
@@ -56,7 +56,7 @@ public class ReversiController extends AbstractGameController<ReversiR> {
//}*/
}
public ReversiController(AbstractPlayer[] players) {
public ReversiController(Player<ReversiR>[] players) {
this(players, true);
}
@@ -130,7 +130,7 @@ public class ReversiController extends AbstractGameController<ReversiR> {
// Draw each square
for (int i = 0; i < board.length; i++){
// If square isn't empty, draw player move
if (board[i] != GameR.EMPTY){
if (board[i] != AbstractGame.EMPTY){
canvas.drawPlayerMove(board[i], i);
}
}

View File

@@ -1,28 +1,28 @@
package org.toop.app.game.gameControllers;
package org.toop.app.gameControllers;
import javafx.geometry.Pos;
import javafx.scene.paint.Color;
import org.toop.app.App;
import org.toop.app.canvas.TicTacToeCanvas;
import org.toop.framework.eventbus.EventFlow;
import org.toop.framework.gameFramework.GUIEvents;
import org.toop.framework.gameFramework.abstractClasses.GameR;
import org.toop.game.GameThreadBehaviour.LocalThreadBehaviour;
import org.toop.game.GameThreadBehaviour.OnlineThreadBehaviour;
import org.toop.framework.gameFramework.model.player.Player;
import org.toop.framework.gameFramework.view.GUIEvents;
import org.toop.framework.gameFramework.model.game.AbstractGame;
import org.toop.game.gameThreads.LocalThreadBehaviour;
import org.toop.game.gameThreads.OnlineThreadBehaviour;
import org.toop.game.players.LocalPlayer;
import org.toop.game.players.AbstractPlayer;
import org.toop.app.widget.WidgetContainer;
import org.toop.game.tictactoe.TicTacToeR;
import org.toop.game.games.tictactoe.TicTacToeR;
public class TicTacToeController extends AbstractGameController<TicTacToeR> {
public TicTacToeController(AbstractPlayer[] players, boolean local) {
TicTacToeR ticTacToeR = new TicTacToeR();
public TicTacToeController(Player<TicTacToeR>[] players, boolean local) {
TicTacToeR ticTacToeR = new TicTacToeR(players);
super(
new TicTacToeCanvas(Color.GRAY, (App.getHeight() / 4) * 3, (App.getHeight() / 4) * 3,(c) -> {new EventFlow().addPostEvent(GUIEvents.PlayerAttemptedMove.class, c).postEvent();}),
players,
ticTacToeR,
local ? new LocalThreadBehaviour(ticTacToeR, players) : new OnlineThreadBehaviour(ticTacToeR, players), // TODO: Player order matters here, this won't work atm
local ? new LocalThreadBehaviour(ticTacToeR, players) : new OnlineThreadBehaviour<>(ticTacToeR, players), // TODO: Player order matters here, this won't work atm
"TicTacToe");
initUI();
@@ -31,7 +31,7 @@ public class TicTacToeController extends AbstractGameController<TicTacToeR> {
//new EventFlow().listen(GUIEvents.PlayerAttemptedMove.class, event -> {if (getCurrentPlayer() instanceof LocalPlayer lp){lp.setMove(event.move());}});
}
public TicTacToeController(AbstractPlayer[] players) {
public TicTacToeController(Player<TicTacToeR>[] players) {
this(players, true);
}
@@ -55,7 +55,7 @@ public class TicTacToeController extends AbstractGameController<TicTacToeR> {
// Draw each square
for (int i = 0; i < board.length; i++){
// If square isn't empty, draw player move
if (board[i] != GameR.EMPTY){
if (board[i] != AbstractGame.EMPTY){
canvas.drawPlayerMove(board[i], i);
}
}

View File

@@ -2,22 +2,18 @@ package org.toop.app.widget.view;
import javafx.application.Platform;
import org.toop.app.GameInformation;
import org.toop.app.game.*;
import org.toop.app.game.gameControllers.AbstractGameController;
import org.toop.app.game.gameControllers.ReversiController;
import org.toop.app.game.gameControllers.TicTacToeController;
import org.toop.app.gameControllers.AbstractGameController;
import org.toop.app.gameControllers.ReversiController;
import org.toop.app.gameControllers.TicTacToeController;
import org.toop.framework.gameFramework.model.player.Player;
import org.toop.game.players.ArtificialPlayer;
import org.toop.game.players.LocalPlayer;
import org.toop.game.players.AbstractPlayer;
import org.toop.app.game.gameControllers.ReversiController;
import org.toop.app.game.gameControllers.TicTacToeController;
import org.toop.app.widget.Primitive;
import org.toop.app.widget.WidgetContainer;
import org.toop.app.widget.complex.PlayerInfoWidget;
import org.toop.app.widget.complex.ViewWidget;
import org.toop.app.widget.popup.ErrorPopup;
import org.toop.game.reversi.ReversiAIR;
import org.toop.game.tictactoe.TicTacToeAIR;
import org.toop.game.games.reversi.ReversiAIR;
import org.toop.game.games.tictactoe.TicTacToeAIR;
import org.toop.app.widget.tutorial.*;
import org.toop.local.AppContext;
@@ -29,7 +25,7 @@ import org.toop.local.AppSettings;
public class LocalMultiplayerView extends ViewWidget {
private final GameInformation information;
private AbstractGameController gameController;
private AbstractGameController<?> gameController;
public LocalMultiplayerView(GameInformation.Type type) {
this(new GameInformation(type));
@@ -49,46 +45,46 @@ public class LocalMultiplayerView extends ViewWidget {
}
// TODO: Fix this temporary ass way of setting the players (Only works for TicTacToe)
AbstractPlayer[] players = new AbstractPlayer[2];
Player[] players = new Player[2];
switch (information.type) {
case TICTACTOE:
if (information.players[0].isHuman){
players[0] = new LocalPlayer(information.players[0].name);
}
else {
if (information.players[0].isHuman) {
players[0] = new LocalPlayer<>(information.players[0].name);
} else {
players[0] = new ArtificialPlayer<>(new TicTacToeAIR(), information.players[0].name);
}
if (information.players[1].isHuman){
players[1] = new LocalPlayer(information.players[1].name);
}
else {
if (information.players[1].isHuman) {
players[1] = new LocalPlayer<>(information.players[1].name);
} else {
players[1] = new ArtificialPlayer<>(new TicTacToeAIR(), information.players[1].name);
}
if (AppSettings.getSettings().getTutorialFlag() && AppSettings.getSettings().getFirstTTT()) {
new ShowEnableTutorialWidget(
() -> new TicTacToeTutorialWidget(() -> {gameController = new TicTacToeController(players);
gameController.start();}),
() -> Platform.runLater(() -> {gameController = new TicTacToeController(players);
gameController.start();}),
new ShowEnableTutorialWidget(
() -> new TicTacToeTutorialWidget(() -> {
gameController = new TicTacToeController(players);
gameController.start();
}),
() -> Platform.runLater(() -> {
gameController = new TicTacToeController(players);
gameController.start();
}),
() -> AppSettings.getSettings().setFirstTTT(false)
);
);
} else {
gameController = new TicTacToeController(players);
gameController.start();
}
break;
case REVERSI:
if (information.players[0].isHuman){
players[0] = new LocalPlayer(information.players[0].name);
}
else {
if (information.players[0].isHuman) {
players[0] = new LocalPlayer<>(information.players[0].name);
} else {
players[0] = new ArtificialPlayer<>(new ReversiAIR(), information.players[0].name);
}
if (information.players[1].isHuman){
players[1] = new LocalPlayer(information.players[1].name);
}
else {
if (information.players[1].isHuman) {
players[1] = new LocalPlayer<>(information.players[1].name);
} else {
players[1] = new ArtificialPlayer<>(new ReversiAIR(), information.players[1].name);
}
if (AppSettings.getSettings().getTutorialFlag() && AppSettings.getSettings().getFirstReversi()) {
@@ -108,19 +104,7 @@ public class LocalMultiplayerView extends ViewWidget {
gameController.start();
}
break;
case CONNECT4:
if (AppSettings.getSettings().getTutorialFlag() && AppSettings.getSettings().getFirstConnect4()) {
new ShowEnableTutorialWidget(
() -> new Connect4TutorialWidget(() -> new Connect4Game(information)),
() -> Platform.runLater(() -> new Connect4Game(information)),
() -> AppSettings.getSettings().setFirstConnect4(false)
);
} else {
new Connect4Game(information);
}
break;
}
// case BATTLESHIP -> new BattleshipGame(information);
});
var playerSection = setupPlayerSections();

View File

@@ -16,14 +16,9 @@ public class LocalView extends ViewWidget {
transitionNext(new LocalMultiplayerView(GameInformation.Type.REVERSI));
});
var connect4Button = Primitive.button("connect4", () -> {
transitionNext(new LocalMultiplayerView(GameInformation.Type.CONNECT4));
});
add(Pos.CENTER, Primitive.vbox(
ticTacToeButton,
reversiButton,
connect4Button
reversiButton
));
}
}