-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
94 lines (72 loc) · 2.82 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
/**
* Created by karkkmik on 9.11.2014.
*/
var connect = require('connect');
var serveStatic = require('serve-static');
var app = connect();
var port = process.env.PORT || 1337;
app.use(serveStatic('www'));
app.use(serveStatic('bower_components'));
var http = require('http').Server(app);
var io = require('socket.io')(http);
//testing committing and pushing from my new work laptop :D
var multiplayerGame = [];
var remoteCarsSyncRate = process.env.REMOTE_CARS_SYNC_RATE || 4000;
io.on('connection', function(socket){
socket.on('join', function(playersCars) {
console.log(socket.id + ' connect ('+ socket.client.conn.transport.constructor.name +')');
var setAsRemoteCar = function (playersCar) {
playersCar.isRemote = true;
return playersCar;
};
playersCars = playersCars.map(setAsRemoteCar);
if (multiplayerGame.length === 2) {
socket.emit('gameFull');
return;
}
var others = multiplayerGame
.filter(function (player) { return player.socket.id !== socket.id })
.map(function (player) { return player.cars; });
socket.emit('otherPlayers', others);
socket.broadcast.emit('someoneJoinedGame', playersCars);
socket.emit('settings', { remoteCarSyncRate: remoteCarsSyncRate });
multiplayerGame.push({ socket: socket, cars: playersCars });
});
socket.on('spectate', function () {
var allOtherCars = multiplayerGame
.map(function (player) { return player.cars; });
socket.emit('otherPlayers', allOtherCars);
});
socket.on('raceStartClicked', function () {
socket.broadcast.emit('raceStartClicked');
});
socket.on('carMoves', function (car) {
socket.broadcast.emit('carMoves', car);
});
socket.on('carStart', function (car) {
socket.broadcast.emit('carStart', car);
});
socket.on('carStop', function (car) {
socket.broadcast.emit('carStop', car);
});
socket.on('syncPos', function (car) {
socket.broadcast.emit('syncPos', car);
});
socket.on('bestLapTime', function (data) {
socket.broadcast.emit('bestLapTime', data);
});
socket.on('lastLapTime', function (data) {
socket.broadcast.emit('lastLapTime', data);
});
socket.on('disconnect', function () {
var i = multiplayerGame.map(function (player) { return player.socket.id; }).indexOf(socket.id);
var leavingCars = [];
console.log(socket.id + ' disconnect ('+ socket.client.conn.transport.constructor.name +')');
if (i >= 0) {
leavingCars = multiplayerGame[i].cars;
multiplayerGame.splice(i, 1);
}
multiplayerGame.map(function (otherPlayer) { otherPlayer.socket.emit('playerLeft', leavingCars); });
});
});
http.listen(port);