-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.js
50 lines (48 loc) · 1.57 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
const path = require('path');
const http = require('http');
const express = require('express');
const socketio = require('socket.io');
//unpairedUser stores socket.id of user
let unpairedUser = null;
const rooms = {};
const app = express();
const server = http.createServer(app);
const io = socketio(server);
app.use(express.static(path.join(__dirname, 'public')));
io.on('connection', (socket) => {
console.log('a user connected with id = ' + socket.id);
if (unpairedUser) {
socket.join(unpairedUser);
rooms[socket.id] = unpairedUser;
io.to(unpairedUser).emit('paired');
unpairedUser = null;
} else {
socket.emit('firstPlayer');
unpairedUser = socket.id;
socket.join(socket.id);
}
socket.on('move', (msg) => {
socket.broadcast.to(rooms[socket.id] || socket.id).emit('move', msg);
});
socket.on('kill', (msg) => {
socket.broadcast.to(rooms[socket.id] || socket.id).emit('kill', msg);
});
socket.on('!multiKill', (msg) => {
socket.broadcast
.to(rooms[socket.id] || socket.id)
.emit('!multiKill', msg);
});
socket.on('name', (msg) => {
socket.broadcast.to(rooms[socket.id] || socket.id).emit('name', msg);
});
socket.on('disconnect', () => {
if (unpairedUser == socket.id) {
unpairedUser = null;
}
socket.broadcast.to(rooms[socket.id] || socket.id).emit('opponentLeft');
});
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});