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
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
import type { Socket } from "socket.io-client";
import { createPubSub } from "create-pubsub";
import {
  init,
  GameLoop,
  Vector,
  Text,
  Sprite,
  initPointer,
  onPointer,
  getPointer,
  degToRad,
  radToDeg,
  Pool,
} from "kontra";
import {
  BallsPositions,
  ballsPositionsUpdatesPerSecond,
  Ball,
  squareCanvasSizeInPixels,
  ServerToClientEvents,
  ClientToServerEvents,
  ballRadius,
  ClientToServerEventName,
  ServerToClientEventName,
  Scoreboard,
} from "./shared";
import { zzfx } from "zzfx";

const gameName = "YoYo Haku Pool";

const gameFramesPerSecond = 60;

const gameStateUpdateFramesInterval = gameFramesPerSecond / ballsPositionsUpdatesPerSecond;

const ballIdToBallSpriteMap = new Map<number, Sprite>();

const { canvas, context } = init(document.querySelector("#canvas") as HTMLCanvasElement);

const scoreboardTextArea = document.querySelector("#b1 textarea") as HTMLTextAreaElement;

const chatHistory = document.querySelector("#b2 textarea") as HTMLTextAreaElement;

const chatInputField = document.querySelector("#b3 input") as HTMLInputElement;

const chatButton = document.querySelector("#b4 button") as HTMLButtonElement;

const tableImage = document.querySelector("img[src='table.webp']") as HTMLImageElement;

const socket = io({ upgrade: false, transports: ["websocket"] }) as Socket<ServerToClientEvents, ClientToServerEvents>;

const [publishMainLoopUpdate, subscribeToMainLoopUpdate] = createPubSub<number>();

const [publishMainLoopDraw, subscribeToMainLoopDraw] = createPubSub<number>();

const [publishPageWithImagesLoaded, subscribeToPageWithImagesLoaded] = createPubSub<Event>();

const [publishGamePreparationComplete, subscribeToGamePreparationCompleted] = createPubSub();

const [publishPointerPressed, subscribeToPointerPressed, isPointerPressed] = createPubSub(false);

const [setOwnSprite, , getOwnSprite] = createPubSub<Sprite | null>(null);

const [setLastTimeEmittedPointerPressed, , getLastTimeEmittedPointerPressed] = createPubSub(Date.now());

const [publishSoundEnabled, , isSoundEnabled] = createPubSub(false);

const messageReceivedSound = [2.01, , 773, 0.02, 0.01, 0.01, 1, 1.14, 44, -27, , , , , 0.9, , 0.18, 0.81, 0.01];

const scoreIncreasedSound = [
  1.35,
  ,
  151,
  0.1,
  0.17,
  0.26,
  1,
  0.34,
  -4.1,
  -5,
  -225,
  0.02,
  0.14,
  0.1,
  ,
  0.1,
  0.13,
  0.9,
  0.22,
  0.17,
];

const acceleratingSound = [, , 999, 0.2, 0.04, 0.15, 4, 2.66, -0.5, 22, , , , 0.1, , , , , 0.02];

const scoreDecreasedSound = [, , 727, 0.02, 0.03, 0, 3, 0.09, 4.4, -62, , , , , , , 0.19, 0.65, 0.2, 0.51];

const tableSprite = Sprite({
  image: tableImage,
});

const scoreTextPool = Pool({
  create: Text as any,
});

function setCanvasWidthAndHeight() {
  canvas.width = canvas.height = squareCanvasSizeInPixels;
}

function prepareGame() {
  updateDocumentTitleWithGameName();
  printWelcomeMessage();
  setCanvasWidthAndHeight();
  handleWindowResized();
  initPointer({ radius: 0 });
  publishGamePreparationComplete();
}

function emitPointerPressedIfNeeded() {
  if (!isPointerPressed() || Date.now() - getLastTimeEmittedPointerPressed() < 1000 / ballsPositionsUpdatesPerSecond)
    return;
  const { x, y } = getPointer();
  socket.emit(ClientToServerEventName.Click, Math.trunc(x), Math.trunc(y));
  setLastTimeEmittedPointerPressed(Date.now());
}

function updateScene() {
  emitPointerPressedIfNeeded();

  ballIdToBallSpriteMap.forEach((sprite) => {
    const newRotationDegree = radToDeg(sprite.rotation) + (Math.abs(sprite.dx) + Math.abs(sprite.dy)) * 7;
    sprite.rotation = degToRad(newRotationDegree > 360 ? newRotationDegree - 360 : newRotationDegree);
    sprite.update();
  });

  scoreTextPool.update();
}

function drawLine(fromPoint: { x: number; y: number }, toPoint: { x: number; y: number }) {
  context.beginPath();
  context.strokeStyle = "#fff";
  context.moveTo(fromPoint.x, fromPoint.y);
  context.lineTo(toPoint.x, toPoint.y);
  context.stroke();
}

function renderOtherSprites() {
  ballIdToBallSpriteMap.forEach((sprite) => {
    if (sprite !== getOwnSprite()) sprite.render();
  });
}

function renderOwnSpritePossiblyWithWire() {
  const ownSprite = getOwnSprite();

  if (!ownSprite) return;

  if (isPointerPressed()) drawLine(ownSprite.position, getPointer());

  ownSprite.render();
}

function renderScene() {
  tableSprite.render();
  renderOtherSprites();
  renderOwnSpritePossiblyWithWire();
  scoreTextPool.render();
}

function startMainLoop() {
  return GameLoop({ update: publishMainLoopUpdate, render: publishMainLoopDraw }).start();
}

function fitCanvasInsideItsParent(canvasElement: HTMLCanvasElement) {
  if (!canvasElement.parentElement) return;
  const { width, height, style, parentElement } = canvasElement;
  const { clientWidth, clientHeight } = parentElement;
  const widthScale = clientWidth / width;
  const heightScale = clientHeight / height;
  const scale = widthScale < heightScale ? widthScale : heightScale;
  style.marginTop = `${(clientHeight - height * scale) / 2}px`;
  style.marginLeft = `${(clientWidth - width * scale) / 2}px`;
  style.width = `${width * scale}px`;
  style.height = `${height * scale}px`;
}

function handleBallsPositionsReceived(balls: Ball[]) {
  ballIdToBallSpriteMap.clear();

  balls.forEach((ball) => createSpriteForBall(ball));
}

function createSpriteForBall(ball: Ball) {
  const sprite = Sprite({
    x: squareCanvasSizeInPixels / 2,
    y: squareCanvasSizeInPixels / 2,
    anchor: { x: 0.5, y: 0.5 },
    render: () => {
      sprite.context.fillStyle = ball.color;
      sprite.context.beginPath();
      sprite.context.arc(0, 0, ballRadius, 0, 2 * Math.PI);
      sprite.context.fill();
    },
  });

  const whiteCircle = Sprite({
    anchor: { x: 0.5, y: 0.5 },
    render: () => {
      sprite.context.fillStyle = "#fff";
      sprite.context.beginPath();
      sprite.context.arc(0, 0, ballRadius / 1.5, 0, 2 * Math.PI);
      sprite.context.fill();
    },
  });
  sprite.addChild(whiteCircle);

  const ballLabel = Text({
    text: ball.label,
    font: `${ballRadius}px monospace`,
    color: "black",
    anchor: { x: 0.5, y: 0.5 },
    textAlign: "center",
  });
  sprite.addChild(ballLabel);

  ballIdToBallSpriteMap.set(ball.id, sprite);

  if (ball.ownerSocketId === socket.id) setOwnSprite(sprite);

  return sprite;
}

function setSpriteVelocity(expectedPosition: Vector, sprite: Sprite) {
  const difference = expectedPosition.subtract(sprite.position);
  sprite.dx = difference.x / gameStateUpdateFramesInterval;
  sprite.dy = difference.y / gameStateUpdateFramesInterval;
}

function stopSprite(sprite: Sprite) {
  sprite.ddx = sprite.ddy = sprite.dx = sprite.dy = 0;
}

function handleChatMessageReceived(message: string) {
  playSound(messageReceivedSound);
  chatHistory.value += `${getHoursFromLocalTime()}:${getMinutesFromLocalTime()} ${message}\n`;
  if (chatHistory !== document.activeElement) chatHistory.scrollTop = chatHistory.scrollHeight;
}

function getMinutesFromLocalTime() {
  return new Date().getMinutes().toString().padStart(2, "0");
}

function getHoursFromLocalTime() {
  return new Date().getHours().toString().padStart(2, "0");
}

function sendChatMessage() {
  const messageToSend = chatInputField.value.trim();
  chatInputField.value = "";
  if (!messageToSend.length) {
    return;
  } else if (messageToSend.startsWith("/help")) {
    return printHelpText();
  } else if (messageToSend.startsWith("/soundon")) {
    handleChatMessageReceived("📢 Sounds enabled.");
    return publishSoundEnabled(true);
  } else if (messageToSend.startsWith("/soundoff")) {
    handleChatMessageReceived("📢 Sounds disabled.");
    return publishSoundEnabled(false);
  } else {
    socket.emit(ClientToServerEventName.Message, messageToSend);
  }
}

function handleKeyPressedOnChatInputField(event: KeyboardEvent) {
  if (event.key === "Enter") sendChatMessage();
}

function updateInnerHeightProperty() {
  document.documentElement.style.setProperty("--inner-height", `${window.innerHeight}px`);
}

function handleWindowResized() {
  updateInnerHeightProperty();
  fitCanvasInsideItsParent(canvas);
}

function playSound(sound: (number | undefined)[]) {
  if (isSoundEnabled()) zzfx(...sound);
}

function enableSounds() {
  publishSoundEnabled(true);
  playSound(messageReceivedSound);
}

function handlePointerDown() {
  if (!getOwnSprite()) return;
  playSound(acceleratingSound);
  publishPointerPressed(true);
}

function handlePointerUp() {
  publishPointerPressed(false);
}

function handleObjectDeleted(id: number) {
  const spriteToDelete = ballIdToBallSpriteMap.get(id);

  if (!spriteToDelete) return;

  if (spriteToDelete === getOwnSprite()) setOwnSprite(null);

  ballIdToBallSpriteMap.delete(id);
}

function handlePositionsUpdated(positions: BallsPositions): void {
  positions.forEach(([objectId, x, y]) => {
    const sprite = ballIdToBallSpriteMap.get(objectId);
    if (sprite) {
      const expectedPosition = Vector(x, y);
      expectedPosition.distance(sprite.position) != 0
        ? setSpriteVelocity(expectedPosition, sprite)
        : stopSprite(sprite);
    }
  });
}

function handleScoreboardUpdated(overallScoreboard: Scoreboard, tableScoreboard: Scoreboard): void {
  let zeroPaddingLengthForScore = 0;

  if (overallScoreboard[0]) {
    const [, score] = overallScoreboard[0];
    zeroPaddingLengthForScore = score.toString().length;
  }

  const maxNickLength = overallScoreboard.reduce((maxLength, [nick]) => Math.max(maxLength, nick.length), 0);

  scoreboardTextArea.value = "TABLE SCOREBOARD\n\n";

  function writeScore([nick, score, tableId]: [nick: string, score: number, tableId: number]) {
    const formattedScore = String(score).padStart(zeroPaddingLengthForScore, "0");
    const formattedNick = nick.padEnd(maxNickLength, " ");
    scoreboardTextArea.value += `${formattedScore} | ${formattedNick} | Table ${tableId}\n`;
  }

  tableScoreboard.forEach(writeScore);

  scoreboardTextArea.value += "\n\nOVERALL SCOREBOARD\n\n";

  overallScoreboard.forEach(writeScore);
}

function handleScoredEvent(value: number, x: number, y: number) {
  playSound(value < 0 ? scoreDecreasedSound : scoreIncreasedSound);

  const scoreText = scoreTextPool.get({
    text: `${value > 0 ? "+" : ""}${value}${value > 0 ? "✨" : "💀"}`,
    font: "36px monospace",
    color: value > 0 ? "#F9D82B" : "#3B3B3B",
    x,
    y,
    anchor: { x: 0.5, y: 0.5 },
    textAlign: "center",
    dy: -1,
    dx: 1,
    update: () => {
      scoreText.advance();

      scoreText.opacity -= 0.01;

      if (scoreText.opacity < 0) scoreText.ttl = 0;

      if (scoreText.x > x + 2 || scoreText.x < x - 2) scoreText.dx *= -1;
    },
  }) as Text;
}

function handlePointerPressed(isPointerPressed: boolean) {
  canvas.style.cursor = isPointerPressed ? "grabbing" : "grab";
}

function printWelcomeMessage() {
  return handleChatMessageReceived(
    `👋 Welcome to ${gameName}!\n\nℹ️ New to this game? Enter /help in the message field below to learn about it.\n`
  );
}

function updateDocumentTitleWithGameName() {
  document.title = gameName;
}

function printHelpText() {
  handleChatMessageReceived(
    `ℹ️ ${gameName} puts you in control of a yoyo on a multiplayer pool table!\n\n` +
      `The goal is to keep the highest score as long as possible.\n\n` +
      `Click or touch the table to pull your yoyo.\n\n` +
      `Each ball has a value, and you should use yoyo maneuvers to bring them into the corner pockets.\n\n` +
      `If you push another yoyo into a corner pocket, you get part of their score, implying that you also lose part of your score if you end up in a corner pocket.\n\n` +
      `When the table is clean, balls are brought back to the table. Tip: Focus on pocketing the balls with high value first.\n\n` +
      `There are several tables in the room, and you can communicate with players from other tables through this chat.\n\n` +
      `You can also run the following commands here:\n\n` +
      `Command: /nick <nickname>\n` +
      `Effect: Changes your nickname.\n\n` +
      `Command: /newtable\n` +
      `Effect: Starts a new game on an empty table.\n\n` +
      `Command: /jointable <number>\n` +
      `Effect: Joins the game from a specific table.\n\n` +
      `Command: /soundon\n` +
      `Effect: Enables sounds.\n\n` +
      `Command: /soundoff\n` +
      `Effect: Disables sounds.\n`
  );
}

subscribeToMainLoopUpdate(updateScene);
subscribeToMainLoopDraw(renderScene);
subscribeToGamePreparationCompleted(startMainLoop);
subscribeToPageWithImagesLoaded(prepareGame);
subscribeToPointerPressed(handlePointerPressed);
onPointer("down", handlePointerDown);
onPointer("up", handlePointerUp);
window.addEventListener("load", publishPageWithImagesLoaded);
window.addEventListener("resize", handleWindowResized);
window.addEventListener("click", enableSounds, { once: true });
chatButton.addEventListener("click", sendChatMessage);
chatInputField.addEventListener("keyup", handleKeyPressedOnChatInputField);
socket.on(ServerToClientEventName.Message, handleChatMessageReceived);
socket.on(ServerToClientEventName.Objects, handleBallsPositionsReceived);
socket.on(ServerToClientEventName.Positions, handlePositionsUpdated);
socket.on(ServerToClientEventName.Creation, createSpriteForBall);
socket.on(ServerToClientEventName.Deletion, handleObjectDeleted);
socket.on(ServerToClientEventName.Scored, handleScoredEvent);
socket.on(ServerToClientEventName.Scoreboard, handleScoreboardUpdated);