Skip to content

Commit cd3806d

Browse files
committed
Reimplement server events
1 parent 213ea9f commit cd3806d

2 files changed

Lines changed: 23 additions & 4 deletions

File tree

src/game/game-match.ts

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@ import { Peer, type DataConnection } from 'peerjs';
22
import type { PlayerAction } from "./player";
33
import { getRole } from "../device";
44

5+
type Events = {
6+
action: (action: PlayerAction) => void
7+
}
8+
59
export 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;

src/main.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ const oddMat = new THREE.MeshStandardMaterial({
9090
async function init() {
9191
const server = await createMatchAsync();
9292
if (server) {
93-
server.onAction = action => playActionLocal(action);
93+
server.on('action', action => playActionLocal(action));
9494
window.addEventListener('pagehide', () => server.dispose(), { once: true });
9595
}
9696

0 commit comments

Comments
 (0)