domino-server/src/game/PlayerInteractionNetwork.ts
2024-07-12 16:27:52 +02:00

59 lines
2.5 KiB
TypeScript

import { PlayerInteractionInterface } from './PlayerInteractionInterface';
import { Board } from './entities/Board';
import { PlayerInterface } from './entities/player/PlayerInterface';
import { PlayerMove } from './entities/PlayerMove';
import { Tile } from './entities/Tile';
import { NetworkClientNotifier } from './NetworkClientNotifier';
import { NetworkPlayer } from './entities/player/NetworkPlayer';
import { PlayerMoveSide, PlayerMoveSideType } from './constants';
import { SocketDisconnectedError } from '../common/errors/SocketDisconnectedError';
import { InteractionService } from '../server/services/InteractionService';
export class PlayerInteractionNetwork implements PlayerInteractionInterface {
player: PlayerInterface;
interactionService: InteractionService = new InteractionService();
clientNotifier = new NetworkClientNotifier();
constructor(player: PlayerInterface) {
this.player = player;
}
askForMove(board: Board): void {
this.clientNotifier.sendEvent(this.player as NetworkPlayer, 'server:player-turn', {
freeHands: board.getFreeEnds(),
isFirstMove: board.tiles.length === 0
});
}
async makeMove(board: Board): Promise<PlayerMove | null> {
let response = undefined;
try {
response = await this.clientNotifier.sendEventWithAck(this.player as NetworkPlayer, 'ask-client-for-move', {
freeHands: board.getFreeEnds(),
isFirstMove: board.tiles.length === 0
});
} catch (error) {
throw new SocketDisconnectedError();
}
const { tile: tilePlayed, type, direction } = response;
if (type === 'pass') {
return null;
}
const { player: { hand} } = this;
const index: number = hand.findIndex(t => t.id === tilePlayed.id);
const side: PlayerMoveSideType = type === 'left' ? PlayerMoveSide.LEFT : PlayerMoveSide.RIGHT;
const tile = hand.splice(index, 1)[0];
tile.revealed = true;
return board.isValidMove(tile, side, this.player, direction);
}
async chooseTile(board: Board): Promise<Tile> {
const { player: { hand} } = this;
const response: any = await this.clientNotifier.sendEventWithAck(this.player as NetworkPlayer, 'ask-client-for-tile', { boneyard: board.boneyard })
const index: number = board.boneyard.findIndex(t => t.id === response.tileId);
const tile = board.boneyard.splice(index, 1)[0];
tile.revealed = true;
hand.push(tile);
return tile;
}
}