-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
102 lines (82 loc) · 2 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
100
101
102
var SERVER_PORT = 8080,
NB_PLAYERS_MAX = 4;
GST = {
data: {
map: -1,
players: []
},
init: function (nbPlayersMax) {
for (var iPlayer = 0; iPlayer < nbPlayersMax; ++iPlayer) {
this.data.players.push(-1);
}
},
emit: function (socket) {
socket.emit('gst', this.data);
},
broadcast: function (socket) {
socket.broadcast.emit('gst', this.data);
},
emitAndBroadcast: function (socket) {
this.emit(socket);
this.broadcast(socket);
},
isAvailable: function (playerID) {
return (this.data.players[playerID] === -1);
},
setPlayer: function (playerID, socket) {
var players = this.data.players;
for (var iPlayer = 0; iPlayer < players.length; ++iPlayer) {
if (players[iPlayer] === socket.id) {
players[iPlayer] = -1;
}
}
players[playerID] = socket.id;
this.emitAndBroadcast(socket);
},
unsetPlayer: function (playerID, socket) {
this.data.players[playerID] = -1;
this.emitAndBroadcast(socket);
},
setMap: function (mapName, socket) {
this.data.map = mapName;
this.emitAndBroadcast(socket);
},
unsetMap: function (socket) {
this.data.map = -1;
this.emitAndBroadcast(socket);
}
}
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(SERVER_PORT);
app.use(express.static(__dirname));
GST.init(NB_PLAYERS_MAX);
io.sockets.on('connection', function (socket) {
GST.emit(socket);
socket.pid = -1;
socket.on('player:set', function (data) {
if (GST.isAvailable(data.id)) {
GST.setPlayer(data.id, socket);
socket.pid = data.id;
} else {
console.log('player taken');
GST.emit(socket);
}
});
socket.on('player:unset', function (data) {
GST.unsetPlayer(data.id, socket);
});
socket.on('map:set', function (data) {
GST.setMap(data.id, socket);
});
socket.on('map:unset', function (data) {
GST.unsetMap(data.id, socket);
});
socket.on('disconnect', function () {
if (socket.pid !== -1) {
GST.unsetPlayer(socket.pid, socket);
}
});
});