-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.js
76 lines (63 loc) · 1.85 KB
/
game.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
var _ = require('./utils');
var Universe = require('./universe').Universe;
var ClientHandler = require('./clienthandler');
var Game = function(){
this.init.apply(this, arguments);
};
Game.prototype = {
clients: [],
universe: null,
init: function() {
this.universe = new Universe();
this.universe.newObject('ship', 400, 200, {});
this.universe.on('new', _.proxy(this, this.onNewObject));
},
newConnection: function(connection){
var client = new ClientHandler(connection, this);
var playerShip = this.universe.newObject('ship', _.randInt(800), _.randInt(400), {});
this.sendUniverse(client);
client.setShip(playerShip);
this.clients.push(client);
},
sendUniverse: function(client){
universeData = this.universe.serialize();
universeMessage = {
type: 'universe',
universe: universeData
}
console.log(universeData);
client.send(universeMessage);
},
onNewObject: function(uObject){
objectData = uObject.serialize();
newObjectMessage = {
type: 'newObject',
object: objectData
}
this.broadcast(newObjectMessage);
},
goLeft: function(shipID){
var ship = this.universe.getObjectByID(shipID);
ship.x -= 10;
this.broadcast({
type:'update',
object:ship
});
},
goRight: function(shipID){
var ship = this.universe.getObjectByID(shipID);
ship.x += 10;
this.broadcast({
type:'update',
object:ship
});
},
broadcast: function(data){
console.log('broadcast: ')
console.log(data);
for (var i = this.clients.length - 1; i >= 0; i--) {
this.clients[i].send(data);
};
}
};
module.exports = Game;