-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathhelpers.js
62 lines (51 loc) · 1.79 KB
/
helpers.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
const getKeys = (clients) => Object.keys(clients);
const clientsHelperFunctionGenerator = (clients, socket, io) => {
const getSocketById = (id) => io.sockets.sockets.get(id);
const addClient = (avoidOpponent) => {
const keys = getKeys(clients);
for (let i = 0; i < keys.length; i++) {
const otherSocketId = keys[i];
const otherSocketOpponent = clients[otherSocketId];
if (!otherSocketOpponent && otherSocketId !== avoidOpponent) {
clients[otherSocketId] = socket.id;
clients[socket.id] = otherSocketId;
i = keys.length;
const otherSocket = getSocketById(otherSocketId);
otherSocket.emit("opponent", socket.id);
}
}
const newKey = getKeys(clients);
if (!newKey.includes(socket.id)) {
clients[socket.id] = null;
}
socket.emit("opponent", clients[socket.id]);
};
const removeClient = () => {
const otherSocketId = clients[socket.id];
if (otherSocketId) {
clients[otherSocketId] = null;
const otherSocket = getSocketById(otherSocketId);
otherSocket.emit("opponent", null);
}
delete clients[socket.id];
};
const newGame = () => {
const opponent = clients[socket.id];
removeClient();
addClient(opponent);
};
const sendShips = (ships) => {
const opponentSocket = getSocketById(clients[socket.id]);
opponentSocket.emit("opponentShips", ships);
};
const shot = (coordinate) => {
const opponentSocket = getSocketById(clients[socket.id]);
opponentSocket.emit("shot", coordinate);
};
const end = (coordinate) => {
const opponentSocket = getSocketById(clients[socket.id]);
opponentSocket.emit("end", coordinate);
};
return { addClient, removeClient, newGame, sendShips, shot, end };
};
module.exports = { clientsHelperFunctionGenerator };