summaryrefslogtreecommitdiff
path: root/server/web/game/game.js
blob: 4b0024c6cfc4aefec0a154ffe4fe2b31e00e04fc (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
"use strict";
const showGame = (g) => {
  const tmpl = document.querySelector("template#tmpl");
  const disp = document.querySelector("#game");
  const clone = document.importNode(tmpl.content, true);
  doDistance(clone, g.Distance.Value);
  doActions(clone, g.Actions);
  disp.replaceChildren(clone);
};

const doDistance = (clone, value) => {
  clone.querySelector(".distance").setAttribute("data-value", value);
  [...clone.querySelectorAll(".distance .sakura")].map((n, i) => {
    if (i < value) {
      n.checked = true;
    } else {
      n.checked = false;
    }
  });
};

const doActions = (g, actions) => {
  const actionList = g.querySelector(".actions");
  const actionTemplate = actionList.querySelector(".action").cloneNode(true);
  if (actions) {
  actionList.replaceChildren(
    ...actions.map((a, i) => {
      const newAction = actionTemplate.cloneNode(true);
      newAction.setAttribute("data-index", i);
      newAction.querySelector(".description").innerText = a.Description;
      return newAction;
    }),
  );
  } else {
    actionList.replaceChildren()
  }
};

const doAction = (idx) => {
  window.socket.send(String(idx))
}

const connect = (gameId) => {
  const connection = new WebSocket(`/api/game/${gameId}/connect`);
  window.socket = connection;
  connection.addEventListener("message", (ev) => {
    const game = JSON.parse(ev.data);
    console.debug(game);
    showGame(game);
    document.querySelector("#game-json").innerText = JSON.stringify(
      ev.data,
      null,
      2,
    );
  });
};

const init = () => {
  const id = window.location.hash.slice(1);
  connect(id);
};

init();