@@ -2,6 +2,10 @@ import { Peer, type DataConnection } from 'peerjs';
22import type { PlayerAction } from "./player" ;
33import { getRole } from "../device" ;
44
5+ type Events = {
6+ action : ( action : PlayerAction ) => void
7+ }
8+
59export class GameServer {
610
711 static readonly baseId = 'lpedwin_winterboard'
@@ -13,7 +17,22 @@ export class GameServer {
1317 private otherId ?: string ;
1418 private peer ?: Peer ;
1519
16- onAction ?: ( action : PlayerAction ) => void ;
20+
21+ private listeners : { [ k in keyof Events ] ?: Set < Events [ k ] > } = { }
22+
23+ private emit < K extends keyof Events > ( k : K , ...args : Parameters < Events [ K ] > ) {
24+ const set = this . listeners [ k ] as Set < Events [ K ] > | undefined ;
25+ set ?. forEach ( fn => {
26+ ( fn as ( ...a : Parameters < Events [ K ] > ) => void ) ( ...args ) ;
27+ } ) ;
28+ }
29+
30+ on < K extends keyof Events > ( k : K , fn : Events [ K ] ) {
31+ ( this . listeners [ k ] ??= new Set ( ) ) . add ( fn ) ;
32+ return ( ) => this . listeners [ k ] ! . delete ( fn ) ;
33+ }
34+
35+
1736
1837
1938 static async host ( ) : Promise < GameServer > {
@@ -24,7 +43,7 @@ export class GameServer {
2443 host . on ( 'error' , err => console . error ( 'Host error' , err ) ) ;
2544
2645 host . on ( 'connection' , conn => {
27- conn . on ( 'data' , d => game . onAction ?. ( d as PlayerAction ) ) ;
46+ conn . on ( 'data' , d => game . emit ( 'action' , d as PlayerAction ) ) ;
2847 conn . on ( 'close' , ( ) => {
2948 console . log ( 'Connection closed.' ) ;
3049 if ( game . conn === conn ) game . conn = undefined ;
@@ -52,7 +71,7 @@ export class GameServer {
5271 client . on ( 'open' , ( ) => {
5372 const conn = client . connect ( this . hostId ) ;
5473
55- conn . on ( 'data' , d => game . onAction ?. ( d as PlayerAction ) ) ;
74+ conn . on ( 'data' , d => game . emit ( 'action' , d as PlayerAction ) ) ;
5675 conn . on ( 'close' , ( ) => {
5776 console . log ( 'Connection closed.' ) ;
5877 if ( game . conn === conn ) game . conn = undefined ;
0 commit comments