aboutsummaryrefslogtreecommitdiff
path: root/static/src/engine/events.ts
diff options
context:
space:
mode:
authorElizabeth Hunt <elizabeth@simponic.xyz>2024-09-07 20:20:07 -0700
committerElizabeth Hunt <elizabeth@simponic.xyz>2024-09-12 17:23:30 -0700
commit8ec7f5368232d59f344e1067e1bad5e48dbcb7ae (patch)
tree1ad2df4dc00773f2307d1525cc80ac7410ea8fba /static/src/engine/events.ts
parente4e31978bae7e45be57b376415a4b925ac8cbc03 (diff)
downloadkennel.hatecomputers.club-8ec7f5368232d59f344e1067e1bad5e48dbcb7ae.tar.gz
kennel.hatecomputers.club-8ec7f5368232d59f344e1067e1bad5e48dbcb7ae.zip
get "cats" up there
Diffstat (limited to 'static/src/engine/events.ts')
-rw-r--r--static/src/engine/events.ts107
1 files changed, 107 insertions, 0 deletions
diff --git a/static/src/engine/events.ts b/static/src/engine/events.ts
new file mode 100644
index 0000000..60632f5
--- /dev/null
+++ b/static/src/engine/events.ts
@@ -0,0 +1,107 @@
+import { Entity } from "./entity";
+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: Record<string, Entity>;
+ };
+}
+
+export interface SetControllableEvent extends Event {
+ event_type: EventType.SET_CONTROLLABLE;
+ data: {
+ id: string;
+ client_id: string;
+ };
+}
+
+export interface EntityBornEvent extends Event {
+ event_type: EventType.ENTITY_BORN;
+ data: {
+ entity: Entity;
+ };
+}
+
+export interface EntityDeathEvent extends Event {
+ event_type: EventType.ENTITY_DEATH;
+ data: {
+ 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 }) => {
+ this.queue = this.queue.concat(JSON.parse(data));
+ };
+ }
+}
+
+export class WebsocketEventPublisher implements EventPublisher {
+ private queue: Event[];
+
+ constructor(private readonly websocket: WebSocket) {
+ this.queue = [];
+ }
+
+ public add(event: Event) {
+ this.queue.push(event);
+ }
+
+ public publish() {
+ if (this.queue.length === 0) {
+ return;
+ }
+ this.websocket.send(JSON.stringify(this.queue));
+ this.queue = [];
+ }
+}