forked from domasx2/banditracer-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
combatserver.js
807 lines (680 loc) · 24.5 KB
/
combatserver.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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
// FIXME ringojs require() broken for require('banditracer-client/world');
var world=require('./banditracer-client/world');
var settings=require('./settings');
var game_settings=require('./banditracer-client/settings');
var car_descriptions=require('./banditracer-client/car_descriptions');
try {
var log = require('ringo/logging').getLogger(module.id);
} catch(e) {};
var TIMER_LASTCALL = null;
var CALLBACKS = {};
var CALLBACKS_LASTCALL = {};
var TIMER = null;
var STARTTIME = null;
var fs=require('fs');
var PHYS_SCALE=game_settings.get('PHYS_SCALE');
var TILE_SCALE=game_settings.get('TILE_SCALE');
var fpsCallback = function(fn, thisObj, fps) {
fps = parseInt(1000/fps, 10);
if (CALLBACKS[fps] === undefined) CALLBACKS[fps] = [];
if (CALLBACKS_LASTCALL[fps] === undefined) CALLBACKS_LASTCALL[fps] = 0;
CALLBACKS[fps].push({
'rawFn': fn,
'callback': function(msWaited) {
fn.apply(thisObj, [msWaited]);
}
});
return;
};
var perInterval = function() {
var msNow = Date.now();
var lastCalls = CALLBACKS_LASTCALL;
for (var fpsKey in lastCalls) {
if (!lastCalls[fpsKey]) {
CALLBACKS_LASTCALL[fpsKey] = msNow;
}
var msWaited = msNow - lastCalls[fpsKey];
if (fpsKey <= msWaited) {
CALLBACKS_LASTCALL[fpsKey] = msNow;
CALLBACKS[fpsKey].forEach(function(fnInfo) {
fnInfo.callback(msWaited);
}, this);
}
}
return;
};
function genPlayerUID() {
//http://note19.com/2007/05/27/javascript-guid-generator/
//not a real UID!
var S4 = function() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
};
return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}
var GAME_STATUS_WAITING=1;
var GAME_STATUS_LOADING=2;
var GAME_STATUS_RUNNING=3;
var Game=exports.Game=function(id, track, leader, server){
this.id=id;
this.type='game';
this.track=track;
this.level=server.levels[track];
this.leader=leader;
this.players={};
this.server=server;
this.status=GAME_STATUS_WAITING;
this.time=0;
this.force_start_after=20000;
this.time_to_start=3001;
this.world=null;
this.max_laps=3;
this.finishers=[];
this.send_update_flip=true; //sending upates every second frame, flipping this to track.
server.log('START GAME '+id);
this.updatePlayer=function(player, payload){
player.car_obj.steer=payload.actions.steer;
player.car_obj.accelerate=payload.actions.accelerate;
player.car_obj.fire_weapon1=payload.actions.fire_weapon1;
player.car_obj.fire_weapon2=payload.actions.fire_weapon2;
player.last_event_no=payload.eventno;
};
this.update=function(msDuration){
var uid, player;
//wait to be started
if(this.status===GAME_STATUS_WAITING) return;
//no players left - destroy
if(this.countPlayers()==0){
this.server.log('NO PLAYERS LEFT '+this.id);
this.destroy();
return;
}
this.time+=msDuration;
//timeout game?
if(this.time>settings.GAME_TIMEOUT){
this.server.log('GAME TIMEOUT '+this.id);
this.destroy();
}
var update_start=(new Date()).getTime();
//start the game when all players report ready OR 6 seconds have passed
var ready=true;
for(uid in this.players){
if(!this.players[uid].ready){
ready=false;
break;
}
}
if(ready){
this.status=GAME_STATUS_RUNNING;
//if timeout time has passed, kick unready players and start anyway
}else if(this.time>this.force_start_after){
for(uid in this.players){
this.removePlayer(this.players[uid]);
}
this.status=GAME_STATUS_RUNNING;
};
if(this.status===GAME_STATUS_RUNNING){
if(this.time_to_start> -1000){
this.time_to_start-=msDuration;
if(this.time_to_start<0)this.started=true;
}
if(this.started){
this.world.b2world.Step(msDuration/1000, 10, 8);
this.world.update(msDuration);
}
}
var finished=true;
for(uid in this.players){
player=this.players[uid];
if(player.car_obj.lap>this.max_laps && (!player.finished)){
player.finished=true;
player.car_obj.teleport([0, 0]);
player.car_obj.active=false;
this.finishers.push(player);
}
if(!player.finished)finished=false;
}
if(finished){
var table=[];
for(var i=0;i<this.finishers.length;i++){
table.push({'place':String(i+1),
'id':this.finishers[i].id,
'player':this.finishers[i].alias,
'kills':String(this.finishers[i].car_obj.kills),
'deaths':String(this.finishers[i].car_obj.deaths)});
}
this.pushResponse(this.server.newResponse('GAME_OVER', {'table':table}));
this.server.log('GAME FINISHED '+this.id);
this.destroy('', true);
}
if(this.send_update_flip) this.pushUpdates(update_start);
this.send_update_flip=this.send_update_flip ? false : true;
};
this.stringifyResponse=function(events, states, t, carid, tts){
return ['{"cmd":"GAME_UPDATE", "payload":{"carid":'+carid, ',"tts":'+tts, ',"t":'+t, ',"states":', states, ',"events":[', events.join(','), ']}}'].join('');
};
this.pushUpdates=function(update_start){
try{
var player, obj, objid, state;
var states={};
//gen object states
for(objid in this.world.object_by_id){
var obj=this.world.object_by_id[objid];
state=obj.getState();
if(state){
states[objid]=state;
}
}
states=JSON.stringify(states);
for(var uid in this.players){
player=this.players[uid];
//if(player.upds_stacked<5){
var events=[];
//add events player does not know yet
var eno=player.last_event_no+1;
while(this.world.events[eno]){
if(!this.world.events[eno].json)this.world.events[eno].json=JSON.stringify(this.world.events[eno]);
events[events.length]=this.world.events[eno].json;
eno++;
}
player.last_event_no=eno-1;
player.send(this.stringifyResponse(events, states, this.time+(new Date()).getTime()-update_start, player.car_obj.id,this.time_to_start));
/*player.send(server.newResponse('GAME_UPDATE', {'states':events,
't':this.time+(new Date()).getTime()-update_start,
'events':events,
'carid':player.car.id,
'tts':this.time_to_start}));*/
player.upds_stacked++;
// }
};
}catch(e){this.server.log(e);}
};
this.addPlayer=function(player){
this.players[player.uid]=player;
player.game=this;
player.ready=false;
player.last_event_no=0;
player.finished=false;
this.server.log('GAME PLAYER JOINED '+player.uid);
};
this.pushResponse=function(response){
for(var uid in this.players){
this.players[uid].send(response);
}
};
this.countPlayers=function(){
var size = 0, id;
for (var id in this.players) {
if (this.players.hasOwnProperty(id)) size++;
}
return size;
};
this.destroy=function(text, silent){
for(uid in this.players){
this.removePlayer(this.players[uid], text, silent);
}
this.server.log('DESTROY GAME '+this.id);
delete this.server.games[this.id];
};
this.removePlayer=function(player, text, silent){
delete this.players[player.uid];
player.game=null;
this.server.log('GAME '+this.id+' PLAYER LEFT '+player.uid);
//remove self from server if there are no more players
//if player was leader, assign new leader
if(this.leader===player){
this.leader=null;
for(var uid in this.players){
this.leader=this.players[uid];
break;
}
}
if(!(silent==true)){
var resp=this.server.newResponse();
resp.payload.text=text ? text : '';
resp.cmd='LEFT_GAME';
player.send(resp);
}
};
this.start=function(){
var player, car, startpos;
this.world=world.buildWorld(this.level, world.MODE_SERVER);
var i=1;
for(var uid in this.players){
player=this.players[uid];
startpos=this.world.start_positions[i];
car=this.world.event('create', {'type':'car', 'obj_name':player.car, 'pars':{'position':[startpos.x+1, startpos.y+2],
'angle':startpos.angle,
'alias':player.alias,
'weapon1':car_descriptions[player.car].main_weapon,
'weapon2':'MineLauncher'}});
player.car_obj=car;
car.player=player;
i++;
}
this.pushResponse(this.server.newResponse('START_GAME', {'track':this.track}));
this.status=GAME_STATUS_LOADING;
}
};
var Lobby=exports.Lobby=function(id, title, track, leader, server){
/*
*/
this.id=id;
this.type='lobby';
this.title=title;
this.track=track;
this.leader=leader;
var luid=leader.uid;
this.players={};
this.players[luid]=leader;
this.state='idle';
this.server=server;
this.max_players=6;
leader.game=this;
this.server.log('START LOBBY '+this.id+' TRACK: '+this.track+' LEADER: '+this.leader.uid);
this.getPlayerInfo=function(){
var retv=[];
for(var uid in this.players){
retv[retv.length]={'player':this.players[uid].alias+(uid===this.leader.uid ? ' (leader)' : ''),
'car':this.players[uid].car ? car_descriptions[this.players[uid].car].name : 'Unknown',
'id':this.players[uid].id};
}
return retv;
};
this.countPlayers=function(){
var size = 0, id;
for (var id in this.players) {
if (this.players.hasOwnProperty(id)) size++;
}
return size;
};
this.update=function(msDuration){
};
this.getLobbyInfoResponse=function(player){
var payload={'players':this.getPlayerInfo(),
'track':this.track,
'is_leader':this.leader.uid==player.uid ? true : false};
return this.server.newResponse('LOBBY_INFO', payload);
};
this.pushUpdates=function(){
for(var uid in this.players){
this.server.log('PUSH UPDATES '+uid);
this.players[uid].send(this.getLobbyInfoResponse(this.players[uid]));
}
};
this.kick=function(player){
this.server.log('PLAYER '+player.uid+' KICKED FROM LOBBY '+this.id);
this.removePlayer(player, 'You have been kicked!');
};
this.removePlayer=function(player, text){
delete this.players[player.uid];
player.game=null;
//remove self from server if there are no more players
//if player was leader, assign new leader
if(this.leader===player){
for(uid in this.players){
this.leader=this.players[uid];
break;
}
}
this.pushUpdates();
var resp=this.server.newResponse();
resp.payload.text=text ? text : '';
resp.cmd='LEFT_LOBBY';
player.send(resp);
this.server.log('PLAYER '+player.uid+' LEFT LOBBY '+this.id);
if(this.countPlayers()===0){
this.destroy();
this.server.log('DESTROY LOBBY'+this.id)
return;
}
};
this.addPlayer=function(player){
if(this.countPlayers()>=this.max_players){
player.send(this.server.error('Lobby full.'));
}else{
this.players[player.uid]=player;
player.game=this;
player.send(this.server.newResponse('JOIN_LOBBY_OK', {'lobby_id':this.id}))
this.pushUpdates();
this.server.log('PLAYER '+player.uid+' JOINED LOBBY '+this.id);
}
};
this.destroy=function(text){
for(uid in this.players){
this.players[uid].leave(text);
}
delete this.server.lobbies[this.id];
this.server.log('DESTROY LOBBY '+this.id);
};
this.getLobbyListInfo=function(){
return {'title':this.title,
'id':this.id,
'track':this.track,
'playercount':this.countPlayers()+'/'+this.max_players};
};
};
var Player=exports.Player=function(uid, id, alias, server){
this.id=id;
this.uid=uid;
this.alias=alias;
this.state='idle';
this.socket=null;
this.game=null;
this.server=server;
this.car='Racer';
this.last_event_no=0;
this.upds_stacked=0;
this.ready=false;
this.finished=false;
this.idle=0; //seconds idle
this.send=function(message){
if(this.state!='disconnected'){
if(!(typeof(message)=='string')){
message=JSON.stringify(message);
}
try{
// var n1=(new Date()).getTime();
this.socket.send ? this.socket.send(message) : this.socket.write(message);
}catch(e){
this.server.log('SEND FAIL:'+this.uid+' ERR:'+e);
this.disconnect();
}
}
};
this.disconnect=function(){
//disconnect: leave any game/lobby, remove self from server
this.server.log("PLAYER DISCONNECTED: "+this.uid);
this.state='disconnected';
this.leave();
delete this.server.players[this.uid];
if(this.socket){
try{
this.socket.close();
}catch(e){this.server.log('DCER:'+e);}
}
};
this.update=function(msDuration){
this.idle+=msDuration;
if(this.idle>=settings.PLAYER_TIMEOUT){
this.server.log('TIMEOUT '+this.uid);
if(this.game)this.send(this.server.criticalError('Timeout!'));
this.disconnect();
}
};
this.touch=function(){
this.idle=0;
};
this.leave=function(text){
if(this.game)this.game.removePlayer(this, text);
};
this.server.log('NEW PLAYER '+this.uid+' AS '+this.alias);
};
exports.CombatServer=function(type){
this.next_player_id=1;
this.next_lobby_id=1;
this.next_game_id=1;
this.players={};
this.games={};
this.lobbies={};
this.type=type;
this.levels={};
this.tickid=1;
this.tick=function(msDuration){
for(var lobbyid in this.lobbies){
this.lobbies[lobbyid].update(msDuration);
}
for(var gameid in this.games){
this.games[gameid].update(msDuration);
}
for(var uid in this.players){
this.players[uid].update(msDuration);
}
};
this.startTimer=function(){
STARTTIME = Date.now();
if(type=='ringo'){
TIMER = require("ringo/scheduler").setInterval(perInterval, 10);
}else{
setInterval(perInterval, 10);
}
fpsCallback(this.tick, this, settings.UPDATES_PER_SECOND);
};
this.log=function(){
var msg = Array.prototype.slice.apply(arguments).join(' ');
if(this.type=='ringo'){
log.info(msg);
}else if (this.type=='node'){
console.log(((new Date())+'').substr(0, 25)+msg);
}
}
this.loadLevels=function(){
var levels=require(settings.LEVEL_DIRECTORY).levels;
for (var l in levels) {
this.levels[l] = levels[l].data;
}
};
this.getPlayerByID=function(id){
for(var uid in this.players){
if(this.players[uid].id==id) return this.players[uid];
}
return null;
};
this.newResponse=function(cmd, payload){
var resp= {'payload':{}};
if(cmd)resp.cmd=cmd;
if(payload)resp.payload=payload;
return resp;
};
this.unsecured={'HI':true,
'PING':true}; //requests servicable without being logged in
this.handle=function(message, socket){
message=JSON.parse(message);
message.socket=socket;
var cmd=message.cmd;
//assign player if possible
if(message.uid){
message.player=this.players[message.uid];
if(message.player){
message.player.touch();
}
}
//set up response object
var response=this.newResponse();
if((!message.player)&&(!this.unsecured[cmd])){
//if player is not registered and needs to be, alert
response=this.criticalError('You must be registered.', this.newResponse());
}else{
//handle
if(this['handle_'+cmd]){
response=this['handle_'+cmd](message, response);
}else{
response=this.error('Unknown command:'+cmd);
}
}
if(response){
if(message.player) message.player.send(response);
else{
response=JSON.stringify(response)
// this.log('SENDING'+response);
socket.send ? socket.send(response) : socket.write(response);
}
}
return null;
};
this.error=function(text){
//error: alert the player
this.log('ERROR: '+text);
return this.newResponse('ERR', {'text':text});
};
this.criticalError=function(text){
//critical error: alert the player, kick from lobby/game
this.log('CRITICAL ERROR: '+text);
return this.newResponse('CRITICAL_ERR', {'text':text});
};
/*
LIST LOBBIES
*/
this.handle_LIST_LOBBIES=function(message, response){
var lobbyid;
var info=[];
for(lobbyid in this.lobbies){
info[info.length]= this.lobbies[lobbyid].getLobbyListInfo();
}
response.payload.lobbies=info;
response.cmd='LOBBY_LIST';
return response;
};
/*
GET LOBBY INFO
*/
this.handle_GET_LOBBY_INFO=function(message, response){
var lobby=message.player.game;
if((!lobby) || (!(lobby.type=='lobby'))){
return this.criticalError('Failed to get lobby info: you are not in a lobby!', response);
}
var resp= lobby.getLobbyInfoResponse(message.player);
return resp;
};
/*
CREATE LOBBY
*/
this.handle_CREATE_LOBBY=function(message, response){
var lobby=new Lobby(this.next_lobby_id++, message.payload.title, message.payload.track, message.player, this);
this.lobbies[lobby.id]=lobby;
response.payload.lobby_id=lobby.id;
response.cmd='CREATE_LOBBY_OK';
return response;
};
/*
JOIN LOBBY
*/
this.handle_JOIN_LOBBY=function(message, response){
if(!this.lobbies[message.payload.lobby_id]){
return this.error('Lobby not found.');
};
var lobby=this.lobbies[message.payload.lobby_id];
lobby.addPlayer(message.player);
return null;
};
/*
KICK
*/
this.handle_KICK=function(message, response){
if(!this.lobbies[message.payload.lobby_id]){
return this.error('Lobby not found.');
}
var lobby=this.lobbies[message.payload.lobby_id];
if(!(message.player===lobby.leader)){
return this.error('You are not lobby leader!');
}
var kickee=this.getPlayerByID(message.payload.player_id); //kickee, lol
if(!lobby.players[kickee.uid]){
return this.error('Player not in lobby.');
}
if(kickee===message.player){
return this.error("You kicked yourself, oh so funny!.");
}
lobby.kick(kickee);
return null;
};
/*
LEAVE_LOBBY
*/
this.handle_LEAVE_LOBBY=function(message, response){
if(!(message.player.game&& (message.player.game.type=='lobby'))){
return this.criticalError('You are not in a lobby.', response);
}
message.player.leave();
return null;
};
/*
START GAME
*/
this.handle_START_GAME=function(message, response){
if(!(message.player.game&& (message.player.game.type=='lobby'))){
return this.criticalError('You are not in a lobby.');
}
if(!(message.player.game.leader===message.player)){
return this.error('You are not the leader.');
}
var lobby=message.player.game;
if(!(this.levels[lobby.track])){
return this.error('Unknown track.');
}
var game=new Game(this.next_game_id++, lobby.track, lobby.leader, this);
this.games[game.id]=game;
for(var uid in lobby.players){
game.addPlayer(lobby.players[uid]);
};
lobby.players={};
lobby.leader=null;
lobby.destroy();
game.start();
return null;
};
/*
PLAYER REPORTS READY INGAME
*/
this.handle_GAME_READY=function(message, response){
if(message.player.game&&message.player.game.type=='game'&&message.player.game.status==GAME_STATUS_LOADING&&(!message.player.ready)){
message.player.ready=true;
}
};
/* PLAYER SENDS HIS UPDATES */
this.handle_GAME_UPDATE=function(message, response){
if((!message.player.game)||(!(message.player.game.type=='game'))){
// return this.criticalError('Cannot update game state: you are not in a game!');
return null;
}
message.player.game.updatePlayer(message.player, message.payload);
return null;
};
/*
HI
register player
*/
this.handle_HI=function(message, response){
/*
HI:
registers player, returns id
requires alias in message
*/
if(!message.payload.alias){
return this.error('Missing alias');
}
if(message.player){
var player=message.player;
player.alias=message.payload.alias;
}else{
var uid=genPlayerUID();
while(this.players[uid]) uid=genPlayerUID();
var player=new Player(uid, this.next_player_id++, message.payload.alias, this);
this.players[player.uid]=player;
}
player.socket=message.socket;
message.socket=player;
response.payload.uid=player.uid;
response.cmd='HELLO';
return response;
};
/*
SELECT_CAR
*/
this.handle_SELECT_CAR=function(message, response){
if(!(car_descriptions.hasOwnProperty(message.payload.car))){
return this.criticalError('Unknown car.');
}
message.player.car=message.payload.car;
if(message.player.game && (message.player.game.type=='lobby')){
message.player.game.pushUpdates();
}
return null;
};
/*PING */
this.handle_PING=function(message, response){
response.cmd='PONG';
return response;
};
this.loadLevels();
this.startTimer();
};