-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
91 lines (84 loc) · 2.65 KB
/
main.js
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
import { createBoard, playMove } from "./connect4.js";
function sendMoves(board, websocket) {
// When clicking a column, send a "play" event for a move in that column.
board.addEventListener("click", ({ target }) => {
const column = target.dataset.column;
// Ignore clicks outside a column.
if (column === undefined) {
return;
}
const event = {
type: "play",
column: parseInt(column, 10),
};
websocket.send(JSON.stringify(event));
});
}
function showMessage(message) {
// this is used because window.alert is synchronous, would screw up the game
window.setTimeout(() => window.alert(message), 50);
}
function receiveMoves(board, websocket) {
websocket.addEventListener("message", ({ data }) => {
const event = JSON.parse(data);
switch (event.type) {
case "init":
// Create link for inviting the second player.
document.querySelector(".join").href = "?join=" + event.join;
break;
case "play":
// update UI with move
playMove(board, event.player, event.column, event.row);
break;
case "win":
showMessage(`Player ${event.player} won!`);
websocket.close(1000);
break;
case "error":
showMessage(event.message);
break;
default:
throw new Error(`Unknown event type: ${event.type}`);
}
});
}
function initGame(websocket) {
websocket.addEventListener("open", () => {
const params = new URLSearchParams(window.location.search);
let event = { type: "init" };
event.params = params;
if (params.has("join")) {
// if the person is clicking the join link, add join to event
event.join = params.get("join");
} else {
// first player starts new game
}
websocket.send(JSON.stringify(event));
});
}
function getServer() {
// maybe shouldnt use hostname
const url = window.location.hostname;
if (url === "nickhonen.github.io") {
return "wss://connect4-websockets.fly.dev/";
} else if (url === "localhost") {
return "ws://localhost:8080/";
} else {
throw new Error(`Unknown server: ${url}`);
}
}
window.addEventListener("DOMContentLoaded", () => {
// Initialize the UI.
const board = document.querySelector(".board");
createBoard(board);
// open websocket connection and register event handlers
// const websocket = new WebSocket("wss://connect4-websockets.fly.dev/");
const websocket = new WebSocket(getServer());
initGame(websocket);
receiveMoves(board, websocket);
sendMoves(board, websocket);
});
// websocket.addEventListener("message", ({ data }) => {
// const event = JSON.parse(data);
// // do something with event
// });