-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
147 lines (121 loc) · 4.32 KB
/
app.js
File metadata and controls
147 lines (121 loc) · 4.32 KB
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
const express = require('express');
const socket = require('socket.io');
const http = require('http');
const { Chess } = require('chess.js');
const path = require('path');
require('dotenv').config();
const app = express();
const server = http.createServer(app);
const io = socket(server);
// Store active games
let games = {};
let waitingPlayer = null;
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) => {
// Matchmaking Logic
if (!waitingPlayer) {
waitingPlayer = socket;
socket.emit("waitingForOpponent");
} else {
const gameId = `game_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
const whiteSocket = waitingPlayer;
const blackSocket = socket;
waitingPlayer = null;
const chess = new Chess();
games[gameId] = {
chess: chess,
white: whiteSocket.id,
black: blackSocket.id,
sockets: {
[whiteSocket.id]: whiteSocket,
[blackSocket.id]: blackSocket
}
};
whiteSocket.join(gameId);
blackSocket.join(gameId);
io.to(gameId).emit("startGame", null);
whiteSocket.emit("playerRole", "w");
blackSocket.emit("playerRole", "b");
io.to(gameId).emit("boardState", chess.fen());
}
socket.on('disconnect', () => {
if (waitingPlayer === socket) {
waitingPlayer = null;
} else {
const gameId = Object.keys(games).find(id =>
games[id].white === socket.id || games[id].black === socket.id
);
if (gameId) {
io.to(gameId).emit("opponentDisconnected");
delete games[gameId];
}
}
});
socket.on("move", (move) => {
const gameId = Object.keys(games).find(id =>
games[id].white === socket.id || games[id].black === socket.id
);
if (!gameId) return;
const game = games[gameId];
const chess = game.chess;
try {
if (chess.turn() === "w" && game.white !== socket.id) return;
if (chess.turn() === "b" && game.black !== socket.id) return;
const result = chess.move(move);
if (result) {
io.to(gameId).emit("move", move);
io.to(gameId).emit("boardState", chess.fen());
if (chess.isGameOver()) {
let reason = "";
if (chess.isCheckmate()) {
reason = `Checkmate! ${chess.turn() === "w" ? "Black" : "White"} wins.`;
} else if (chess.isDraw()) {
reason = "Game ended in a draw.";
} else if (chess.isStalemate()) {
reason = "Game ended in a stalemate.";
} else {
reason = "Game over.";
}
io.to(gameId).emit("gameOver", reason);
}
} else {
console.log("Invalid move: ", move);
socket.emit("invalidMove", move);
}
} catch (error) {
console.log(error);
socket.emit("invalidMove", move);
}
});
socket.on("requestEndGame", () => {
const gameId = Object.keys(games).find(id =>
games[id].white === socket.id || games[id].black === socket.id
);
if (gameId) {
socket.to(gameId).emit("opponentRequestedEndGame");
}
});
socket.on("respondEndGame", (response) => {
const gameId = Object.keys(games).find(id =>
games[id].white === socket.id || games[id].black === socket.id
);
if (!gameId) return;
if (response) {
const game = games[gameId];
const chess = new Chess();
game.chess = chess;
io.to(gameId).emit("gameEnded", "Game ended by mutual agreement. Board reset.");
io.to(gameId).emit("boardState", chess.fen());
} else {
socket.to(gameId).emit("endGameDeclined");
}
});
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, function () {
console.log(`listening on port: ${PORT}`);
});