diff options
| author | Elizabeth Hunt <elizabeth@simponic.xyz> | 2024-09-02 20:10:35 -0700 |
|---|---|---|
| committer | Elizabeth Hunt <elizabeth@simponic.xyz> | 2024-09-02 20:10:35 -0700 |
| commit | d35ab6cc851d3fc85f55cfb5676f8dc3552fab24 (patch) | |
| tree | bef9784e90e2e8f8f5b9e05300238747b775e618 /static/src/network.ts | |
| parent | a0a2068b66204d7d06eb3c3b4aa61b28469121f6 (diff) | |
| download | kennel.hatecomputers.club-d35ab6cc851d3fc85f55cfb5676f8dc3552fab24.tar.gz kennel.hatecomputers.club-d35ab6cc851d3fc85f55cfb5676f8dc3552fab24.zip | |
a bit more progress
Diffstat (limited to 'static/src/network.ts')
| -rw-r--r-- | static/src/network.ts | 73 |
1 files changed, 73 insertions, 0 deletions
diff --git a/static/src/network.ts b/static/src/network.ts new file mode 100644 index 0000000..0d4e216 --- /dev/null +++ b/static/src/network.ts @@ -0,0 +1,73 @@ +export enum EventType { + INITIAL_STATE = "INITIAL_STATE", + SET_CONTROLLABLE = "SET_CONTROLLABLE", + ENTITY_BORN = "ENTITY_BORN", + ENTITY_DEATH = "ENTITY_DEATH", + ENTITY_POSITION_UPDATE = "ENTITY_POSITION_UPDATE", +} + +export interface Event { + event_type: EventType; + data: any; +} + +export interface EntityPositionUpdateEvent extends Event { + event_type: EventType.ENTITY_POSITION_UPDATE; + data: { + id: string; + position: { + x: number; + y: number; + }; + }; +} + +export interface InitialStateEvent extends Event { + event_type: EventType.INITIAL_STATE; + data: { + world: { width: number; height: number }; + entities: any[]; + }; +} + +export interface SetControllableEvent extends Event { + event_type: EventType.SET_CONTROLLABLE; + data: { + id: string; + client_id: string; + }; +} + +export interface EventQueue { + peek(): Event[]; + clear(): void; +} + +export interface EventPublisher { + add(event: Event): void; + publish(): void; +} + +export class WebSocketEventQueue implements EventQueue { + private queue: Event[]; + + constructor(websocket: WebSocket) { + this.queue = []; + this.listen_to(websocket); + } + + public peek() { + return this.queue; + } + + public clear() { + this.queue = []; + } + + private listen_to(websocket: WebSocket) { + websocket.onmessage = ({ data }) => { + const [event_type, event_data] = JSON.parse(data); + this.queue.push({ event_type, data: event_data } as Event); + }; + } +} |
