Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/websocket #56

Merged
merged 2 commits into from
Nov 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 32 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"@types/jest": "^27.4.1",
"@types/node": "^18.15.11",
"@types/uuid": "^9.0.2",
"@types/ws": "^8.5.8",
"@typescript-eslint/eslint-plugin": "^5.21.0",
"@typescript-eslint/parser": "^5.21.0",
"eslint": "^8.33.0",
Expand Down Expand Up @@ -49,6 +50,7 @@
"sqlite3": "^5.1.6",
"typeorm": "^0.3.17",
"uuid": "^9.0.0",
"winston": "^3.8.2"
"winston": "^3.8.2",
"ws": "^8.14.2"
}
}
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { BanListLoader } from "./modules/ban-list/infrastructure/BanListLoader";
import { SQLiteTypeORM } from "./modules/shared/db/postgres/infrastructure/SQLiteTypeORM";
import { Pino } from "./modules/shared/logger/infrastructure/Pino";
import { HostServer } from "./socket-server/HostServer";
import WebSocketSingleton from "./web-socket-server/WebSocketSingleton";

void start();

Expand All @@ -19,5 +20,6 @@ async function start(): Promise<void> {
await database.connect();
await database.initialize();
await server.initialize();
WebSocketSingleton.getInstance();
hostServer.initialize();
}
9 changes: 9 additions & 0 deletions src/modules/room/application/DisconnectHandler.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { YGOClientSocket } from "../../../socket-server/HostServer";
import WebSocketSingleton from "../../../web-socket-server/WebSocketSingleton";
import { PlayerChangeClientMessage } from "../../messages/server-to-client/PlayerChangeClientMessage";
import { ServerMessageClientMessage } from "../../messages/server-to-client/ServerMessageClientMessage";
import { WatchChangeClientMessage } from "../../messages/server-to-client/WatchChangeClientMessage";
Expand All @@ -21,6 +22,10 @@ export class DisconnectHandler {

if (room.clients.every((client) => client.socket.closed)) {
RoomList.deleteRoom(room);
WebSocketSingleton.getInstance().broadcast({
action: "REMOVE-ROOM",
data: room.toRealTimePresentation(),
});

return;
}
Expand All @@ -35,6 +40,10 @@ export class DisconnectHandler {

if (player.host && room.duelState === DuelState.WAITING) {
RoomList.deleteRoom(room);
WebSocketSingleton.getInstance().broadcast({
action: "REMOVE-ROOM",
data: room.toRealTimePresentation(),
});

return;
}
Expand Down
11 changes: 10 additions & 1 deletion src/modules/room/application/FinishDuelHandler.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import WebSocketSingleton from "../../../web-socket-server/WebSocketSingleton";
import { DuelEndMessage } from "../../messages/server-to-client/game-messages/DuelEndMessage";
import { SideDeckClientMessage } from "../../messages/server-to-client/game-messages/SideDeckClientMessage";
import { SideDeckWaitClientMessage } from "../../messages/server-to-client/game-messages/SideDeckWaitClientMessage";
Expand Down Expand Up @@ -27,7 +28,10 @@ export class FinishDuelHandler {
async run(): Promise<void> {
this.room.duel?.kill();
this.room.duelWinner(this.winner);

WebSocketSingleton.getInstance().broadcast({
action: "UPDATE-ROOM",
data: this.room.toRealTimePresentation(),
});
this.room.stopRoomTimer();
this.room.stopTimer(0);
this.room.stopTimer(1);
Expand Down Expand Up @@ -107,6 +111,11 @@ export class FinishDuelHandler {
})
);

WebSocketSingleton.getInstance().broadcast({
action: "REMOVE-ROOM",
data: this.room.toRealTimePresentation(),
});

return;
}

Expand Down
48 changes: 48 additions & 0 deletions src/modules/room/domain/Duel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { BanList } from "../../ban-list/domain/BanList";
import { Team } from "./Team";

export class Duel {
private _turn: number;
private readonly _lps: [number, number];
private readonly _banlist: BanList | null;

constructor(turn: number, lps: [number, number], banlist: BanList | null) {
this._turn = turn;
this._lps = lps;
this._banlist = banlist;
}

increaseTurn(): void {
this._turn++;
}

decreaseLps(team: Team, value: number): void {
if (team !== Team.OPPONENT && team !== Team.PLAYER) {
return;
}
this._lps[team] = this._lps[team] - value;

if (this._lps[team] <= 0) {
this._lps[team] = 0;
}
}

increaseLps(team: Team, value: number): void {
if (team !== Team.OPPONENT && team !== Team.PLAYER) {
return;
}
this._lps[team] = this._lps[team] + value;
}

get lps(): [number, number] {
return this._lps;
}

get turn(): number {
return this._turn;
}

get banlistName(): string | null {
return this._banlist?.name ?? "N/A";
}
}
42 changes: 38 additions & 4 deletions src/modules/room/domain/Room.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import shuffle from "shuffle-array";
import { EventEmitter } from "stream";

import { YGOClientSocket } from "../../../socket-server/HostServer";
import BanListMemoryRepository from "../../ban-list/infrastructure/BanListMemoryRepository";
import { CardSQLiteTYpeORMRepository } from "../../card/infrastructure/postgres/CardSQLiteTYpeORMRepository";
import { Client } from "../../client/domain/Client";
import { DeckCreator } from "../../deck/application/DeckCreator";
Expand All @@ -21,13 +22,15 @@ import { JoinToDuelAsSpectator } from "../application/JoinToDuelAsSpectator";
import { Reconnect } from "../application/Reconnect";
import RoomList from "../infrastructure/RoomList";
import { Match, MatchHistory, Player } from "../match/domain/Match";
import { Duel } from "./Duel";
import { DuelFinishReason } from "./DuelFinishReason";
import { RoomState } from "./RoomState";
import { ChossingOrderState } from "./states/chossing-order/ChossingOrderState";
import { DuelingState } from "./states/dueling/DuelingState";
import { RockPaperScissorState } from "./states/rps/RockPaperScissorsState";
import { SideDeckingState } from "./states/side-decking/SideDeckingState";
import { WaitingState } from "./states/waiting/WaitingState";
import { Team } from "./Team";
import { Timer } from "./Timer";

export enum Rule {
Expand Down Expand Up @@ -158,7 +161,7 @@ export class Room {
private _playerExtraDeckSize: number;
private _opponentMainDeckSize: number;
private _opponentExtraDeckSize: number;
private _turn = 0;
private readonly _turn = 0;
private _firstToPlay: number;
private readonly t0Positions: number[] = [];
private readonly t1Positions: number[] = [];
Expand All @@ -167,6 +170,7 @@ export class Room {
private roomState: RoomState | null = null;
private emitter: EventEmitter;
private logger: Logger;
private currentDuel: Duel | null = null;

private constructor(attr: RoomAttr) {
this.id = attr.id;
Expand Down Expand Up @@ -337,6 +341,10 @@ export class Room {
this._match = new Match({ bestOf: this.bestOf });
}

isFirstDuel(): boolean {
return this._match?.isFirstDuel() ?? true;
}

initializeHistoricalData(): void {
const players = this.clients.map((client) => ({
team: client.team,
Expand Down Expand Up @@ -427,6 +435,8 @@ export class Room {
// Volver a intentar la escritura después de un breve retraso
this.writeToCppProcess("¡Hola desde Node.js!", 3);
});
const banlist = BanListMemoryRepository.findByHash(this.banlistHash);
this.currentDuel = new Duel(0, [this.startLp, this.startLp], banlist);
}

get duel(): ChildProcessWithoutNullStreams | null {
Expand All @@ -440,7 +450,6 @@ export class Room {
dueling(): void {
this._state = DuelState.DUELING;
this.isStart = "start";
this._turn = 0;
this.roomState?.removeAllListener();
this.roomState = new DuelingState(
this.emitter,
Expand Down Expand Up @@ -561,11 +570,11 @@ export class Room {
}

increaseTurn(): void {
this._turn++;
this.currentDuel?.increaseTurn();
}

get turn(): number {
return this._turn;
return this.currentDuel?.turn ?? 0;
}

setFirstToPlay(team: number): void {
Expand Down Expand Up @@ -750,6 +759,14 @@ export class Room {
} ${this.playerNames(1)}`;
}

decreaseLps(team: Team, value: number): void {
this.currentDuel?.decreaseLps(team, value);
}

increaseLps(team: Team, value: number): void {
this.currentDuel?.increaseLps(team, value);
}

toPresentation(): { [key: string]: unknown } {
return {
roomid: this.id,
Expand Down Expand Up @@ -785,6 +802,23 @@ export class Room {
};
}

toRealTimePresentation(): { [key: string]: unknown } {
return {
id: this.id,
turn: this.currentDuel?.turn,
bestOf: this.bestOf,
banlist: {
name: this.currentDuel?.banlistName,
},
players: this.clients.map((client) => ({
position: client.position,
username: client.name,
lps: this.currentDuel?.lps[client.team],
score: client.team === Team.PLAYER ? this._match?.score.team0 : this._match?.score.team1,
})),
};
}

private writeToCppProcess(messageToCpp: string, retryCount: number): void {
if (retryCount <= 0) {
console.error(
Expand Down
Loading