forked from kubowania/battleships
-
Notifications
You must be signed in to change notification settings - Fork 19
/
server.js
92 lines (74 loc) · 2.45 KB
/
server.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
const tracer = require("dd-trace").init();
const express = require("express");
const path = require("path");
const http = require("http");
const PORT = process.env.PORT || 3000;
const socketio = require("socket.io");
const app = express();
const server = http.createServer(app);
const io = socketio(server);
// Set static folder
app.use(express.static(path.join(__dirname, "public")));
// Start server
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));
// Handle a socket connection request from web client
const connections = [null, null];
io.on("connection", (socket) => {
// console.log('New WS Connection')
// Find an available player number
let playerIndex = -1;
for (const i in connections) {
if (connections[i] === null) {
playerIndex = i;
break;
}
}
// Tell the connecting client what player number they are
socket.emit("player-number", playerIndex);
console.log(`Player ${playerIndex} has connected`);
// Ignore player 3
if (playerIndex === -1) return;
connections[playerIndex] = false;
// Tell eveyone what player number just connected
socket.broadcast.emit("player-connection", playerIndex);
// Handle Diconnect
socket.on("disconnect", () => {
console.log(`Player ${playerIndex} disconnected`);
connections[playerIndex] = null;
//Tell everyone what player numbe just disconnected
socket.broadcast.emit("player-connection", playerIndex);
});
// On Ready
socket.on("player-ready", () => {
socket.broadcast.emit("enemy-ready", playerIndex);
connections[playerIndex] = true;
});
// Check player connections
socket.on("check-players", () => {
const players = [];
for (const i in connections) {
connections[i] === null
? players.push({ connected: false, ready: false })
: players.push({ connected: true, ready: connections[i] });
}
socket.emit("check-players", players);
});
// On Fire Received
socket.on("fire", (id) => {
console.log(`Shot fired from ${playerIndex}`, id);
// Emit the move to the other player
socket.broadcast.emit("fire", id);
});
// on Fire Reply
socket.on("fire-reply", (square) => {
console.log(square);
// Forward the reply to the other player
socket.broadcast.emit("fire-reply", square);
});
// Timeout connection
setTimeout(() => {
connections[playerIndex] = null;
socket.emit("timeout");
socket.disconnect();
}, 600000); // 10 minute limit per player
});