-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
66 lines (56 loc) · 1.87 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
const express = require("express");
const socketIO = require("socket.io");
const http = require("http");
const { Chess } = require("chess.js");
const path = require("path");
const app = express();
const server = http.createServer(app);
const io = socketIO(server); // Make sure you use io here
const chess = new Chess();
let players = {};
let currentPlayer = "w"; // Fixed the initial player to "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", (socket) => { // Changed 'uniquesocket' to 'socket'
console.log("connected");
if (!players.white) {
players.white = socket.id;
socket.emit("playerRole", "w");
} else if (!players.black) {
players.black = socket.id;
socket.emit("playerRole", "b");
} else {
socket.emit("spectatorRole");
}
socket.on("disconnect", () => {
if (socket.id === players.white) {
delete players.white;
} else if (socket.id === players.black) {
delete players.black;
}
});
socket.on("move", (move) => {
try {
if (chess.turn() === 'w' && socket.id !== players.white) return;
if (chess.turn() === 'b' && socket.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);
socket.emit("invalidMove", move);
}
} catch (err) {
console.log(err);
socket.emit("invalidMove", move);
}
});
});
server.listen(3000, () => {
console.log("Server is running on port 3000");
});