This repository has been archived by the owner on Aug 28, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
99 lines (74 loc) · 2.05 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
93
94
95
96
97
98
99
const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
let clients = [];
let rooms = [];
io.on('connection', function (socket) {
console.log('user connected: ' + socket.id);
// send client it's id
socket.emit('clientId', socket.id);
// create rooms for clients to join
let roomData = {
name: socket.id,
opponent: null
};
rooms.push(roomData);
io.emit('rooms', rooms);
socket.on('join-room', (data) => {
rooms.forEach((r,i) =>{
if(r.name === data){
r.opponent = socket.id;
}
});
removeRooms(socket.id);
io.emit('rooms', rooms);
});
socket.on("move", data => {
//data.turn = !data.turn;
io.to(data.room.opponent).emit("turn", data);
console.log(data);
data.turn = !data.turn;
io.to(data.room.name).emit("turn", data);
console.log(data);
})
socket.on("reset", data=>{
io.to(data.opponent).emit("reset", true);
io.to(data.name).emit("reset", true);
});
socket.on('leave-room', data => {
removeRooms(data.name);
removeRooms(data.opponent);
// create new room for client
let roomData = {
name: data.name,
opponent: null
}
rooms.push(roomData);
// create new room for opponent
roomData = {
name: data.opponent,
opponent: null
}
rooms.push(roomData);
io.emit('rooms', rooms);
});
socket.on('disconnect', () => {
removeRooms(socket.id);
console.log('user disconnected: ' + socket.id);
});
});
function removeRooms(id) {
let i = rooms.length;
while (i--) {
if (rooms[i].name === id) rooms.splice(i, 1);
}
}
function getClients() {
//let clients = [];
//console.log(io.clients);
//io.broadcast('players', clients);
return clients;
}
http.listen(3030, function () {
console.log('listening on *:3000');
});