-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
69 lines (57 loc) · 1.96 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
const express = require("express");
const socket = require("socket.io");
const http = require("http");
const { Chess } = require("chess.js");
const path = require("path");
const { log } = require("console");
const app = express();
const server = http.createServer(app);
const io = socket(server);
const chess = new Chess();
let players = {};
let currentPlayer = "w";
app.set("view engine", "ejs");
app.use(express.static(path.join(__dirname, "public")));
app.get("/", (req, res) => {
res.render("index", { title: "Chess Game" });
});
io.on("connection", function(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", function() {
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) {
currentPlayer = chess.turn();
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("Invalid move : ", move);
}
})
});
server.listen(3000, function() {
console.log(" listening on port 3000");
});