Files
hitstar/src/server-deno/domain/models/Player.ts

80 lines
1.4 KiB
TypeScript

import type { ID, Player } from '../types.ts';
/**
* Player domain model
* Represents a player in the game with their connection state
*/
export class PlayerModel implements Player {
id: ID;
sessionId: ID;
name: string;
connected: boolean;
roomId: ID | null;
spectator?: boolean;
constructor(
id: ID,
sessionId: ID,
name?: string,
connected = true,
roomId: ID | null = null,
) {
this.id = id;
this.sessionId = sessionId;
this.name = name || `Player-${id.slice(0, 4)}`;
this.connected = connected;
this.roomId = roomId;
}
/**
* Update player's connection status
*/
setConnected(connected: boolean): void {
this.connected = connected;
}
/**
* Update player's name
*/
setName(name: string): void {
if (name && name.trim().length > 0) {
this.name = name.trim();
}
}
/**
* Join a room
*/
joinRoom(roomId: ID): void {
this.roomId = roomId;
}
/**
* Leave current room
*/
leaveRoom(): void {
this.roomId = null;
}
/**
* Toggle spectator mode
*/
setSpectator(spectator: boolean): void {
this.spectator = spectator;
}
/**
* Create a safe representation for serialization
*/
toJSON(): Player {
return {
id: this.id,
sessionId: this.sessionId,
name: this.name,
connected: this.connected,
roomId: this.roomId,
spectator: this.spectator,
};
}
}