summaryrefslogtreecommitdiff
path: root/client/src/JumpStorm.ts
blob: 01cc8d8972a25145849105082bd744983aae1466 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
import { Game } from "@engine/Game";
import { Entity } from "@engine/entities";
import { Grid } from "@engine/structures";
import {
  WallBounds,
  FacingDirection,
  Render,
  Physics,
  Input,
  Collision,
  NetworkUpdate,
} from "@engine/systems";
import {
  type MessageQueueProvider,
  type MessagePublisher,
  type MessageProcessor,
  type Message,
  type EntityAddBody,
  MessageType,
} from "@engine/network";
import { stringify, parse } from "@engine/utils";

class ClientMessageProcessor implements MessageProcessor {
  private game: Game;

  constructor(game: Game) {
    this.game = game;
  }

  public process(message: Message) {
    switch (message.type) {
      case MessageType.NEW_ENTITY:
        const entityAddBody = message.body as unknown as EntityAddBody;
        this.game.addEntity(
          Entity.from(entityAddBody.entityName, entityAddBody.args),
        );
        break;
    }

    console.log(message);
  }
}

class ClientSocketMessageQueueProvider implements MessageQueueProvider {
  private socket: WebSocket;
  private messages: Message[];

  constructor(socket: WebSocket) {
    this.socket = socket;
    this.messages = [];

    this.socket.addEventListener("message", (e) => {
      const message = parse<Message>(e.data);
      this.messages.push(message);
    });
  }

  public getNewMessages() {
    return this.messages;
  }

  public clearMessages() {
    this.messages = [];
  }
}

class ClientSocketMessagePublisher implements MessagePublisher {
  private socket: WebSocket;
  private messages: Message[];

  constructor(socket: WebSocket) {
    this.socket = socket;
    this.messages = [];
  }

  public addMessage(message: Message) {
    this.messages.push(message);
  }

  public publish() {
    this.messages.forEach((message: Message) =>
      this.socket.send(stringify(message)),
    );
  }
}

export class JumpStorm {
  private game: Game;
  private clientId: string;

  constructor(game: Game) {
    this.game = game;
  }

  public async init(
    ctx: CanvasRenderingContext2D,
    httpMethod: string,
    wsMethod: string,
    host: string,
  ) {
    await fetch(`${httpMethod}://${host}/assign`)
      .then((resp) => {
        if (resp.ok) {
          return resp.text();
        }
        throw resp;
      })
      .then((cookie) => {
        this.clientId = cookie;
      });

    const grid = new Grid();

    const socket = new WebSocket(`${wsMethod}://${host}/game`);
    const clientSocketMessageQueueProvider =
      new ClientSocketMessageQueueProvider(socket);
    const clientSocketMessagePublisher = new ClientSocketMessagePublisher(
      socket,
    );
    const clientMessageProcessor = new ClientMessageProcessor(this.game);
    [
      this.createInputSystem(),
      new FacingDirection(),
      new Physics(),
      new Collision(grid),
      new WallBounds(ctx.canvas.width),
      new NetworkUpdate(
        clientSocketMessageQueueProvider,
        clientSocketMessagePublisher,
        clientMessageProcessor,
      ),
      new Render(ctx),
    ].forEach((system) => this.game.addSystem(system));
  }

  public play() {
    this.game.start();

    const loop = (timestamp: number) => {
      this.game.doGameLoop(timestamp);
      requestAnimationFrame(loop); // tail call recursion! /s
    };
    requestAnimationFrame(loop);
  }

  private createInputSystem(): Input {
    const inputSystem = new Input(this.clientId);

    window.addEventListener("keydown", (e) => {
      if (!e.repeat) {
        inputSystem.keyPressed(e.key);
      }
    });

    window.addEventListener("keyup", (e) => inputSystem.keyReleased(e.key));

    return inputSystem;
  }
}