Game Logic in Frontend

This commit is contained in:
jhim
2026-03-07 14:05:28 +01:00
committed by Jonas
parent 34f683854b
commit 919bb71f19
8 changed files with 148 additions and 54 deletions
+31 -18
View File
@@ -2,33 +2,34 @@ import type { GameSettings } from '@/scripts/interfaces/GameSettings';
import GameConnection, {
type GameIdentifier,
type GameInformationDto,
type GameEnded,
} from '../signalR/GameConnection';
class LocalGame {
public _settings: GameSettings;
public player1: GameConnection;
public player2: GameConnection;
public currentDescription: string = 'Warte auf Spielaufbau...';
private gameId: string = '';
public gameState: GameInformationDto | undefined;
public onGameStateChanged?: (gameState: GameInformationDto | undefined) => void;
public onGameEnded?: (gameEndedInfo: GameEnded) => void;
constructor(settings: GameSettings) {
this._settings = settings;
this.player1 = new GameConnection(settings.playerName1);
this.player2 = new GameConnection(settings.playerName2 ?? 'Player 2');
this.player1 = new GameConnection();
this.player2 = new GameConnection();
this.player1.onGameStarted = (gameInfo: GameInformationDto) => {
console.log('Game started for player 1', gameInfo);
this.updateState(gameInfo);
this.gameState = gameInfo;
this.onGameStateChanged?.(this.gameState);
this.changePlaceDescription();
};
this.player1.onFieldUpdated = (currentState: GameInformationDto) => {
if (this.gameState) {
this.gameState = currentState;
this.onGameStateChanged?.(this.gameState);
}
this.updateState(currentState);
this.changePlaceDescription();
};
this.player1.onGameCreated = (gameIdentifier: GameIdentifier) => {
@@ -39,18 +40,24 @@ class LocalGame {
this.player2.onGameJoined = (gameIdentifier: GameIdentifier) => {
this.gameId = gameIdentifier.gameId;
};
this.player1.onGameEnded = (gameEndedInfo: GameEnded) => {
this.onGameEnded?.(gameEndedInfo);
};
}
async start() {
await this.player1.connect();
await this.player2.connect();
async start(settings: GameSettings) {
await this.player1.connect(settings.playerName1);
await this.player2.connect(settings.playerName2 ?? 'Spieler 2');
await this.player1.createGame(this._settings.fieldSize);
await this.player1.createGame(settings.fieldSize);
}
async updateState(gameInfo: GameInformationDto) {
this.gameState = gameInfo;
this.onGameStateChanged?.(this.gameState);
async updateState(newState: GameInformationDto) {
if (this.gameState) {
this.gameState = newState;
this.onGameStateChanged?.(this.gameState);
}
}
async drop(index: number) {
@@ -60,6 +67,12 @@ class LocalGame {
this.player2.drop(this.gameId, index);
}
}
changePlaceDescription() {
const playerName =
this.gameState?.currentTurn == 1 ? this.player1.playerName : this.player2.playerName;
this.currentDescription = `${playerName} ist dran mit setzen!`;
}
}
export default LocalGame;