-
Notifications
You must be signed in to change notification settings - Fork 4
/
physicsserver.js
228 lines (216 loc) · 7.89 KB
/
physicsserver.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
var serverNumber = parseInt(process.argv[2]),
port = [1337,1338,1339][serverNumber];
// Downgrade from root
if (process.getuid() === 0)
require('fs').stat(__filename, function(err, stats) {
if (err)
return console.log(err);
process.setuid(stats.uid);
});
console.log("Started physics server "+serverNumber);
var io = require('socket.io').listen(port),
redis = require('redis').createClient(),
GameLogic = require('./public/javascripts/game_logic.js').GameLogic,
GameDef = require('./public/javascripts/game_def.js').GameDef;
redis.on("error", function (err) {
console.log("Redis connection error to " + redis.host + ":" + redis.port + " - " + err);
});
var games = {},
gameBySocketId = {},
redisKeys = {},
gamesPerProcess = 4;
io.sockets.on('connection',function(socket){
socket.on('subscribe',function(type,gameId,redisKey){
gameId = gameId.toString();
var room = games[gameId];
if(typeof room === 'undefined'){
socket.emit('error',"Bad room id"+gameId);
}
if(room)
if(room.join(socket,type)){
gameBySocketId[socket.id] = gameId;
redisKeys[socket.id] = redisKey;
socket.emit('update',room.physics.getState());
}else{
socket.emit('error',"This game room is full");
}
});
socket.on('disconnect',function(){
var gameId, game;
if(gameId = gameBySocketId[socket.id]){
if(game=games[gameId]){
game.remove(socket.id);
}
delete gameBySocketId[socket.id];
}
delete redisKeys[socket.id];
});
});
Game = function(id){
this.gameId = id;
//Initialize a new physics object here
this.physics = new GameLogic(GameDef);
this.c0 = null;
this.c1 = null;
this.running = false;
this.viewers = 0;
this.controllers = 0;
this.all_sockets = id+'-all';
this.controller_sockets = id+'-control';
};
Game.prototype.join = function(socket,type){
if(type == 'viewer'){
//Probably can manage 4 viewers and 4 controllers?
if(this.viewers < 4){
socket.join(this.all_sockets);
this.viewers++;
return true;
}
}else if(type == 'controller'){
if(this.controllers < 4){
socket.join(this.all_sockets);
socket.join(this.controller_sockets);
this.controllers++;
return true;
}
}
return false;
};
Game.prototype.empty = function(){
return (this.viewers == 0 && this.controllers == 0);
};
Game.prototype.remove = function(id){
var controller_room = io.sockets.manager.rooms['/'+this.controller_sockets] || [];
if(-1 != controller_room.indexOf(id+'')){
// If this is c1 or c0, the other one wins.
if(id == this.c0){
this.c0 = null;
this.end(1);
}else if(id == this.c1){
this.c1 = null;
this.end(0);
}
this.controllers--;
}else
this.viewers--;
};
Game.prototype.end = function(winner){
// for both controller sockets (if they exist) start ignoring the paddle data
this.running = false;
if(this.c0){
var s = io.sockets.socket(this.c0);
s.removeAllListeners('paddle');
s.removeAllListeners('dbl');
}
if(this.c1){
var s = io.sockets.socket(this.c1);
s.removeAllListeners('paddle');
s.removeAllListeners('dbl');
}
winner = [this.c0,this.c1][winner];
(function(game){
redis.get(redisKeys[winner],function(err,data){
var fail = {};
io.sockets.in(game.all_sockets).emit('win',data || fail);
});
})(this);
};
Game.prototype.begin = function(){
var controllers = io.sockets.manager.rooms['/'+this.controller_sockets];
(function(game){
chooseControllers(controllers,function(a,b){
game.c0 = a;
game.c1 = b;
console.log(a);
console.log(b);
io.sockets.socket(game.c0).emit('nominate',0);
io.sockets.socket(game.c1).emit('nominate',1);
io.sockets.in(game.all_sockets).emit('time',15);
setTimeout(function(){
if(game.running){
game.physics.reset();
io.sockets.in(game.all_sockets).emit('start',game.physics.getState());
io.sockets.socket(game.c0).on('paddle',function(dat){
game.physics.setTouchPoints(0,dat);
});
io.sockets.socket(game.c1).on('paddle',function(dat){
game.physics.setTouchPoints(1,dat);
});
io.sockets.socket(game.c0).on('dbl',function(){
game.physics.doubleTouch(0);
});
io.sockets.socket(game.c1).on('dbl',function(dat){
game.physics.doubleTouch(1);
});
setupPhysics(game);
}
},15*1000);
});
})(this);
this.running = true;
};
Game.prototype.redisRecord = function(){
return {name:this.gameId,viewers:this.viewers,controllers:this.controllers,port:port};
};
for(var i = 0;i<gamesPerProcess;i++){
games[i.toString()] = new Game((i+gamesPerProcess*serverNumber).toString());
}
// Takes an array of possible controller ids and chooses two. Can map controller id to redis keys.
function chooseControllers(set,cont){
// It turns out that writing the comparison predicate for the data is just a pain in the ass. Randomly schedule, for now.
/* var keys = set.map(function(i){return redisKeys[i];});
redis.mget(keys,function(err,res){
if(err){
console.log("Redis error, with keys :"+keys);
cont(set[0],set[1]);//Just choose the first two...
}else{
res = res.map(function(obj,index){return {obj:obj,ctrl:set[index]};});
res.sort(function(a,b){
//Some predicate for the epicness.
return Math.random()-0.5;
});
cont(res[0].ctrl,res[1].ctrl);
}
});
*/
set.sort(function(a,b){return Math.random()-0.5;});
cont(set[0],set[1]);
}
// Sets up the game's physics loops
function setupPhysics(game){
var loop = function(){
// Needs some logic to terminate, however
if(game.physics.over())
game.end();
if(game.running){
// Update the physics here
var state = game.physics.step(1/30);
if(typeof state.event !== 'undefined')
io.sockets.in(game.all_sockets).emit('update',state);
else
io.sockets.in(game.all_sockets).volatile.emit('update',state);
setTimeout(loop,1000/30)
}
};
loop();
}
// Update the game room data on redis every n seconds.
setInterval(function(){
var rooms = {};
for(var i in games){
i = games[i];
rooms[i.gameId] = JSON.stringify(i.redisRecord());
}
redis.hmset('rooms',rooms,function(err,_){
if(err)
console.log('Redis-error:'+err);
});
},5000);
//This is the server's real main-loop. Checks if games can be started, and then starts them
setInterval(function(){
for(var i in games){
i = games[i];
if(!i.running && i.controllers > 1)
i.begin();
}
},250);