-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
81 lines (69 loc) · 2.65 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
var Game = require('./game.js');
var socketio = require('socket.io');
var _ = require('underscore');
var Server = function() {
var self = this;
this.game = new Game();
this.io;
this.playersBySocketId = {}; // keyed on socket.id
this.socketsBySocketId = {}; // keyed on socket.id
this.startGame = function() {
this.game.run()
.on('tick', function(){
_.each(self.playersBySocketId, function(players, sid){
var socket = self.socketsBySocketId[sid];
socket.emit('tick', {
entities: _.map(self.game.entities, function(e){
// TODO: don't be sending redundant unchanged stuff, like color or geometry
return e.descriptor();
})
});
});
})
.on('entity_removed', function(eid){
_.each(self.socketsBySocketId, function(socket){
socket.emit('entity_removed', eid)
})
})
}
this.startListening = function(server) {
this.io = socketio.listen(server);
this.io.set('log level', 1);
this.io.sockets.on('connection', function(socket){
self.socketsBySocketId[socket.id] = socket;
// Negotiation
socket.emit('welcome', 'hypercube');
// Tell client about current game state
_.each(self.game.entities, function(ent, id) {
if (ent.type == 'player') {
socket.emit('player_present', ent.descriptor());
} else {
socket.emit('entity_present', ent.descriptor())
}
});
var player = new Game.Player(self.game);
self.playersBySocketId[socket.id] = player;
_.each(self.socketsBySocketId, function(otherPlayerSocket){
otherPlayerSocket.emit('player_joined', player.descriptor())
});
// Listen forever for client commands
socket.on('disconnect', function(){
self.game.removeEntity(player.id);
delete self.socketsBySocketId[socket.id];
delete self.playersBySocketId[socket.id];
self.io.sockets.emit('player_left', {id: player.id});
});
socket.on('+forward', function(){ player.forward = true; });
socket.on('-forward', function(){ player.forward = false; });
socket.on('+back', function(){ player.back = true; });
socket.on('-back', function(){ player.back = false; });
socket.on('+left', function(){ player.left = true; });
socket.on('-left', function(){ player.left = false; });
socket.on('+right', function(){ player.right = true; });
socket.on('-right', function(){ player.right = false; });
socket.on('+attack', function(){ player.attack(true); });
socket.on('-attack', function(){ player.attack(false); });
});
}
};
module.exports = {"Server": Server};