-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
77 lines (66 loc) · 1.97 KB
/
app.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
import express from "express";
import { Server as SocketServer } from "socket.io";
import { inject } from "@vercel/analytics";
import http from "http";
import { Chess } from "chess.js";
import path from "path";
import { fileURLToPath } from "url";
import { injectSpeedInsights } from "@vercel/speed-insights";
injectSpeedInsights();
inject();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const server = http.createServer(app);
const io = new SocketServer(server);
const chess = new Chess();
let players = {};
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));
app.use(express.static(path.join(__dirname, "public")));
app.get("/", (req, res) => {
res.render("index", { title: "Chess Game" });
});
io.on("connection", (uniquesocket) => {
console.log("connected");
if (!players.white) {
players.white = uniquesocket.id;
uniquesocket.emit("playerRole", "w");
} else if (!players.black) {
players.black = uniquesocket.id;
uniquesocket.emit("playerRole", "b");
} else {
uniquesocket.emit("spectatorRole");
}
uniquesocket.on("disconnect", () => {
if (uniquesocket.id === players.white) {
delete players.white;
} else if (uniquesocket.id === players.black) {
delete players.black;
}
});
uniquesocket.on("move", (move) => {
try {
if (chess.turn() === "w" && uniquesocket.id !== players.white) return;
if (chess.turn() === "b" && uniquesocket.id !== players.black) return;
const result = chess.move(move);
if (result) {
io.emit("move", move);
io.emit("boardState", chess.fen());
} else {
console.log("Invalid move:", move);
uniquesocket.emit("invalidMove", move);
}
} catch (err) {
console.log(err);
uniquesocket.emit("invalidMove", move);
}
});
});
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send("Internal Server Error");
});
server.listen(3000, () => {
console.log("listening on port 3000");
});