-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
65 lines (53 loc) · 1.72 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
const express = require("express");
const app = express();
const path = require("path");
const http = require("http");
const { Server } = require("socket.io");
const server = http.createServer(app);
const io = new Server(server);
app.use(express.static(path.resolve("client")));
let waitingPlayers = [];
let matchedPlayers = [];
// Function to handle player matching
function handlePlayerMatching(player) {
waitingPlayers.push(player);
if (waitingPlayers.length >= 2) {
const [player1, player2] = waitingPlayers.splice(0, 2);
const match = {
p1: { name: player1.name, char: player1.character, amI: false },
p2: { name: player2.name, char: player2.character, amI: true },
};
matchedPlayers.push(match);
io.emit("s", { allPlayers: matchedPlayers }, () => {
console.log(matchedPlayers);
matchedPlayers = [];
});
}
}
// Handle a new connection
io.on("connection", (socket) => {
// Listen for the "find" event from a client
socket.on("find", (playerInfo) => {
try {
// If player name provided
if (playerInfo.name != null) {
// Handle player matching
handlePlayerMatching(playerInfo);
// Listen for the "positionUpdate" event from a client
socket.on("positionUpdate", (positionInfo) => {
// Emit the updated player positions to all clients
io.emit("Update", { allPosition: positionInfo });
// Log the updated player positions
console.log(positionInfo);
});
}
} catch (error) {
console.error("Error handling player:", error.message);
}
});
});
// Start the server on port 3000
const PORT = 3300;
server.listen(PORT, () => {
console.log(`Server started on port ${PORT}`);
});