forked from jfd/wpilot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wpilots.js
executable file
·1164 lines (1004 loc) · 31.7 KB
/
wpilots.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
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
//
// wpilots.js
// WPilot server
//
// Read README for instructions and LICENSE license.
//
// Copyright (c) 2010 Johan Dahlberg
//
var path = require('path'),
fs = require('fs'),
fu = require('./lib/fu');
ws = require('ws'),
optparse = require('./lib/optparse'),
match = require('./lib/match').Match,
go = require('./lib/gameobjects');
var WebSocketServer = ws.Server;
var inspect = require('util');
// Define aliases
var _ = match.incl;
const SERVER_VERSION = '1.0';
// Message priorities. High priority messages are sent to client no mather
// what. Low priority messages are sent only if client can afford them.
const PRIO_PASS = 0,
PRIO_LOW = 'low',
PRIO_HIGH = 'high';
// Player Connection states
const DISCONNECTED = -1;
IDLE = 0,
CONNECTED = 1;
HANDSHAKING = 3,
JOINED = 4;
// Default map. This map is used if no other map i specified.
const DEFAULT_MAP = {
name: 'Battle Royale',
author: 'Johan Dahlberg',
recommended_players: 8,
data: [
[51, 0, 0, 51, 0, 0, 51],
[ 0, 11, 11, 0, 11, 11, 0],
[ 0, 11, 52, 0, 52, 11, 0],
[51, 0, 0, 12, 0, 0, 51],
[ 0, 11, 52, 0, 52, 11, 0],
[ 0, 11, 11, 0, 11, 11, 0],
[51, 0, 0, 51, 0, 0, 51]
]
};
// Command line option parser switches
const SWITCHES = [
['-d', '--debug', 'Enables debug mode (Default: false)'],
['-H', '--help', 'Shows this help section'],
['--name NAME', 'The name of the server.'],
['--host HOST', 'The host adress (default: 127.0.0.1).'],
['--region REGION', 'Set region of this server. This info is displayed in the global server list (default: n/a).'],
['--admin_password PASSWORD', 'Admin password (default: "none").'],
['--map PATH', 'Path to world map (default: built-in map).'],
['--pub_host HOST', 'Set if the public host differs from the local one'],
['--http_port PORT', 'Port number for the HTTP server. Disable with 0 (default: 8000)'],
['--ws_port PORT', 'Port number for the WebSocket server (default: 6114)'],
['--pub_ws_port PORT', 'Set if the public WebSocket port differs from the local one'],
['--max_rate NUMBER', 'The maximum rate per client and second (default: 1000)'],
['--max_connections NUMBER', 'Max connections, including players (default: 60)'],
['--max_players NUMBER', 'Max connected players allowed in server simultaneously (default: 8)'],
['--r_ready_ratio NUMBER', 'Rule: Player ready ratio before a round start. (Default: 0.6)'],
['--r_respawn_time NUMBER', 'Rule: Player respawn time after death. (Default: 500)'],
['--r_reload_time NUMBER', 'Rule: The reload time after fire. (Default: 15)'],
['--r_shoot_cost NUMBER', 'Rule: Energy cost of shooting a bullet. (Default: 800)'],
['--r_shield_cost NUMBER', 'Rule: Energy cost of using the shield. (Default: 70)'],
['--r_energy_recovery NUMBER', 'Rule: Energy recovery unit (Default: 40)'],
['--r_round_limit NUMBER', 'Rule: Round score limit (Default: 10)'],
['--r_suicide_penelty NUMBER', 'Rule: The cost for suicides (Default: 1)'],
['--r_kill_score NUMBER', 'Rule: The price of a kill (Default: 1)'],
['--r_powerup_max NUMBER', 'Rule: Max no of powerups to spawn (Default: 3)'],
['--r_powerup_respawn NUMBER', 'Rule: Time between powerup respawns (Default: 1200)'],
['--r_powerup_spread_t NUMBER', 'Rule: Time before the spread powerup decline (Default: 700)'],
['--r_powerup_rapid_t NUMBER', 'Rule: Time before the rapid fire powerup decline (Default: 600)'],
['--r_powerup_rico_t NUMBER', 'Rule: Time before the ricoshet powerup decline (Default: 800)']
];
// Default server options
const DEFAULT_OPTIONS = {
debug: true,
name: 'WPilot Server',
host: '127.0.0.1',
region: 'n/a',
admin_password: null,
map: null,
pub_host: null,
http_port: 8000,
ws_port: 6114,
pub_ws_port: null,
max_connections: 60,
max_players: 8,
max_rate: 5000,
r_ready_ratio: 0.6,
r_respawn_time: 400,
r_reload_time: 15,
r_shoot_cost: 300,
r_shield_cost: 30,
r_energy_recovery: 30,
r_round_limit: 10,
r_suicide_penelty: 1,
r_kill_score: 1,
r_powerup_max: 2,
r_powerup_respawn: 600,
r_powerup_spread_t: 700,
r_powerup_rapid_t: 600,
r_powerup_rico_t: 600
};
// Paths to all files that should be server to client.
const CLIENT_DATA = [
'client/index.html', '',
'client/style.css', '',
'client/logo.png', '',
'client/space.jpg', '',
'client/wpilot.js', '',
'client/devices.js', '',
'lib/gameobjects.js', '',
'lib/match.js', 'lib/',
'client/sound/background.m4a', 'sound/',
'client/sound/ship_spawn.m4a','sound/',
'client/sound/ship_die.m4a', 'sound/',
'client/sound/ship_thrust.m4a', 'sound/',
'client/sound/ship_fire_1.m4a', 'sound/',
'client/sound/ship_fire_2.m4a', 'sound/',
'client/sound/ship_fire_3.m4a', 'sound/',
'client/sound/powerup_spawn.m4a', 'sound/',
'client/sound/powerup_1_die.m4a', 'sound/',
'client/sound/powerup_2_die.m4a', 'sound/',
'client/sound/powerup_3_die.m4a', 'sound/',
'client/sound/background.ogg', 'sound/',
'client/sound/ship_spawn.ogg', 'sound/',
'client/sound/ship_die.ogg', 'sound/',
'client/sound/ship_thrust.ogg', 'sound/',
'client/sound/ship_fire_1.ogg', 'sound/',
'client/sound/ship_fire_2.ogg', 'sound/',
'client/sound/ship_fire_3.ogg', 'sound/',
'client/sound/powerup_spawn.ogg', 'sound/',
'client/sound/powerup_1_die.ogg', 'sound/',
'client/sound/powerup_2_die.ogg', 'sound/',
'client/sound/powerup_3_die.ogg', 'sound/',
'client/web_socket.js', 'lib/',
'client/swfobject.js', 'lib/',
'client/FABridge.js', 'lib/',
'client/particle.js', 'lib/',
'client/WebSocketMain.swf', 'lib/',
'client/crossdomain.xml', 'lib/'
];
/**
* Entry point for server.
* @returns {undefined} Nothing.
*/
function main() {
var options = parse_options(),
shared = { get_state: function() {} },
webserver = null,
gameserver = null,
policy_server = null,
maps = null;
if (!options) return;
console.log('WPilot server ' + SERVER_VERSION);
maps = options.maps;
if (options.http_port != 0) {
webserver = start_webserver(options, shared);
}
gameserver = start_gameserver(maps, options, shared);
}
/**
* Starts the web socket game server.
* @param {GameOptions} options Game options.
* @returns {WebSocketServer} Returns the newly created WebSocket server
* instance.
*/
function start_gameserver(maps, options, shared) {
var connections = {},
no_connections = 0,
gameloop = null,
world = null,
server = null,
update_tick = 1,
next_map_index = 0;
// Is called by the web instance to get current state
shared.get_state = function() {
return {
server_name: options.name,
region: options.region,
version: SERVER_VERSION,
game_server_url: 'ws://' + (options.pub_host || options.host) + ':' +
(options.pub_ws_port || options.ws_port) + '/',
map_name: world.map_name,
max_players: options.max_players,
no_players: world.no_players,
no_ready_players: world.no_ready_players,
rules: world.rules
}
}
/**
* The acutal game loop.
* @param {Number} t Current world time.
* @param {Number} dt Current delta time,
* @return {undefined} Nothing
*/
function gameloop_tick(t, dt) {
world.update(t, dt);
check_rules(t, dt);
post_update();
flush_queues();
}
function connection_for_player(player) {
for (var connid in connections) {
var conn = connections[connid];
if (conn.player && conn.player.id == player.id) {
return conn;
}
}
return null;
}
// Create the world instance
world = new World(true);
world.max_players = options.max_players,
// Listen for round state changes
world.on_round_state_changed = function(state, winners) {
broadcast(OP_ROUND_STATE, state, winners);
}
// Listen for events on player
world.on_player_join = function(player) {
player.name = get_unique_name(world.players, player.id, player.name);
broadcast_each(
[OP_PLAYER_CONNECT, player.id, player.name],
function(msg, conn) {
if (conn.player && conn.player.id == player.id) {
return PRIO_PASS;
}
return PRIO_HIGH;
}
);
}
world.on_player_spawn = function(player, pos) {
broadcast(OP_PLAYER_SPAWN, player.id, pos);
}
world.on_player_died = function(player, old_entity, death_cause, killer) {
broadcast(OP_PLAYER_DIE, player.id, death_cause, killer ? killer.id : -1);
}
world.on_player_ready = function(player) {
broadcast(OP_PLAYER_INFO, player.id, 0, true);
}
world.on_player_name_changed = function(player, new_name, old_name) {
player.name = get_unique_name(world.players, player.id, new_name);
broadcast(OP_PLAYER_INFO, player.id, 0, 0, player.name);
}
world.on_player_fire = function(player, angle, pos, vel, powerup) {
broadcast(OP_PLAYER_FIRE, player.id, angle, pos, vel, powerup);
}
world.on_player_leave = function(player, reason) {
broadcast(OP_PLAYER_DISCONNECT, player.id, reason);
}
world.on_powerup_spawn = function(powerup) {
broadcast(OP_POWERUP_SPAWN, powerup.powerup_id,
powerup.powerup_type,
powerup.pos);
}
world.on_powerup_die = function(powerup, player) {
broadcast(OP_POWERUP_DIE, powerup.powerup_id, player.id);
}
/**
* Starts the game loop.
* @return {undefined} Nothing
*/
function start_gameloop() {
// Reset game world
world.build(world.map_data, world.rules);
gameloop = new GameLoop();
gameloop.ontick = gameloop_tick;
log('Starting game loop...');
gameloop.start();
}
/**
* Stops the game loop, disconnects all connections and resets the world.
* @param {String} reason A reason why the game loop stopped. Is sent to all
* current connections.
* @return {undefined} Nothing
*/
function stop_gameloop(reason) {
for (var id in connections) {
connections[id].kill(reason || 'Server is shutting down');
}
if (gameloop) {
gameloop.ontick = null;
gameloop.kill();
gameloop = null;
}
}
function post_update() {
update_tick++;
for (var id in connections) {
var time = get_time();
var connection = connections[id];
if (connection.state != JOINED) {
continue;
}
if (connection.last_ping + 2000 < time) {
connection.last_ping = time;
connection.send(JSON.stringify([PING_PACKET]));
}
if (update_tick % connection.update_rate != 0) {
continue;
}
for (var id in world.players) {
var player = world.players[id];
var message = [OP_PLAYER_STATE, player.id];
if (player.entity) {
message.push(pack_vector(player.entity.pos),
player.entity.angle,
player.entity.action);
connection.queue(message);
}
if (update_tick % 200 == 0) {
var player_connection = connection_for_player(player);
connection.queue([OP_PLAYER_INFO, player.id, player_connection.ping]);
}
}
}
}
/**
* Flushes all connection queues.
* @return {undefined} Nothing
*/
function flush_queues() {
for (var id in connections) {
var connection = connections[id];
if (connection.state != JOINED) {
continue;
}
connection.flush_queue();
}
}
/**
* Check game rules
* @param {Number} t Current world time.
* @param {Number} dt Current delta time,
* @return {undefined} Nothing
*/
function check_rules(t, dt) {
switch (world.r_state) {
// The world is waiting for players to be "ready". The game starts when
// 60% of the players are ready.
case ROUND_WARMUP:
if (world.no_players > 1 && world.no_ready_players >= (world.no_players * world.rules.ready_ratio)) {
world.set_round_state(ROUND_STARTING);
}
break;
// Round is starting. Server aborts if a player leaves the game.
case ROUND_STARTING:
// if (world.no_ready_players < (world.no_players * 0.6)) {
// world.set_round_state(ROUND_WARMUP);
// return;
// }
if (t >= world.r_timer) {
world.set_round_state(ROUND_RUNNING);
}
break;
// The round is running. Wait for a winner.
case ROUND_RUNNING:
var winners = [];
world.forEachPlayer(function(player) {
if (player.score == world.rules.round_limit) {
winners.push(player.id);
}
});
if (winners.length) {
world.set_round_state(ROUND_FINISHED, winners);
}
break;
// The round is finished. Wait for restart
case ROUND_FINISHED:
if (t >= world.r_timer) {
gameloop.ontick = null;
gameloop.kill();
load_map(null, true, function() {
var t = 0;
for(var id in connections) {
var conn = connections[id];
if (conn.state == JOINED) {
conn.send(JSON.stringify([OP_WORLD_RECONNECT]));
conn.set_state(HANDSHAKING);
}
}
});
}
break;
}
}
/**
* Broadcasts a game message to all current connections. Broadcast always
* set's message priority to HIGH.
* @param {String} msg The message to broadcast.
* @return {undefined} Nothing
*/
function broadcast() {
var msg = Array.prototype.slice.call(arguments);
for(var id in connections) {
connections[id].queue(msg);
}
}
/**
* Broadcast, but calls specified callback for each connection
* @param {Array} msg The message to broadcast.
* @param {Function} callback A callback function to call for each connection
* @return {undefined} Nothing
*/
function broadcast_each(msg, callback) {
for(var id in connections) {
var conn = connections[id];
if (conn.state == JOINED) {
var prio = callback(msg, conn);
if (prio) conn.queue(msg);
}
}
}
/**
* pad single digit numbers with leading zero
* @param {Integer} Number
* @return {String} padded number
*/
function pad0 (num) {
return (num < 10)
? '0'+num
: num;
}
/**
* Prints a system message on the console.
* @param {String} msg The message to print .
* @return {undefined} Nothing
*/
function log(msg) {
var now = new Date();
console.log(pad0(now.getHours()) + ':' + pad0(now.getMinutes()) + ':' +
pad0(now.getSeconds()) + ' ' + options.name + ': ' + msg);
}
/**
* Load a map
* @param path {String} path to map.
* @param default_on_fail {Boolean} loads the default map if the specified
* map failed to load.
* @return {undefined} Nothing
*/
function load_map(path, default_on_fail, callback) {
var map_path = path;
function done(err, map_data) {
if (!map_data && default_on_fail) {
map_data = DEFAULT_MAP;
}
if (map_data) {
if (gameloop) {
gameloop.ontick = null;
gameloop.kill();
}
world.build(map_data, get_rules(DEFAULT_OPTIONS, map_data.rules || {},
options.rules));
if (gameloop) {
gameloop = new GameLoop();
gameloop.ontick = gameloop_tick;
gameloop.start();
}
}
callback(err);
}
if (!map_path) {
if (maps.length == 0) {
done(null, DEFAULT_MAP);
return;
} else {
if (next_map_index >= maps.length) {
next_map_index = 0;
}
map_path = maps[next_map_index];
next_map_index++;
}
}
fs.readFile(map_path, function (err, data) {
if (err) {
done('Failed to read map: ' + err);
return;
}
try {
done(null, JSON.parse(data));
} catch(e) {
done('Map file is invalid, bad format');
return;
}
});
}
/**
* Create the web socket server.
* @param {function} callback The callback for new connections.
* @param {String} msg The message to broadcast.
* @return {undefined} Nothing
*/
server = new WebSocketServer({
port: parseInt(options.ws_port),
host: options.host
});
server.on("connection", function(conn) {
var connection_id = 0,
disconnect_reason = 'Closed by client',
message_queue = [];
/**
* Sets client's information.
*/
conn.set_client_info = function(info) {
conn.rate = Math.min(info.rate, options.max_rate);
conn.player_name = info.name;
conn.dimensions = info.dimensions;
}
conn.send_server_info = function() {
if (conn.debug) {
log('Debug: Sending server state to ' + conn);
}
conn.post([OP_SERVER_INFO, shared.get_state()]);
}
/**
* Sends a chat message
*/
conn.chat = function(message) {
if (conn.player) {
broadcast(OP_PLAYER_SAY, conn.player.id, message);
log('Chat ' + conn.player.id + ': ' + message);
}
}
conn.auth = function(password) {
conn.is_admin = password == options.admin_password ? true : false;
return conn.is_admin;
}
conn.exec = function() {
var args = Array.prototype.slice.call(arguments);
var command = args.shift();
switch (command) {
case 'map':
var path = args.shift();
load_map(path, false, function(err) {
if (err) {
conn.post([OP_SERVER_EXEC_RESP, err]);
} else {
for(var id in connections) {
var conn = connections[id];
conn.send(JSON.stringify([OP_WORLD_RECONNECT]));
conn.set_state(HANDSHAKING);
}
}
});
return 'Loading map';
case 'warmup':
switch (world.r_state) {
case ROUND_WARMUP:
return 'Already in warmup mode';
case ROUND_RUNNING:
case ROUND_STARTING:
world.set_round_state(ROUND_WARMUP);
break;
case ROUND_FINISHED:
return 'Game has already finished';
}
return 'Changed';
case 'start':
switch (world.r_state) {
case ROUND_WARMUP:
world.set_round_state(ROUND_STARTING);
break;
case ROUND_STARTING:
world.set_round_state(ROUND_RUNNING);
break;
case ROUND_RUNNING:
return 'Game is already started. Type sv_restart to restart';
case ROUND_FINISHED:
return 'Game has already finished';
}
return 'Changed';
case 'restart':
switch (world.r_state) {
case ROUND_WARMUP:
case ROUND_STARTING:
return 'Cannot restart warmup round';
case ROUND_RUNNING:
world.set_round_state(ROUND_STARTING);
break;
case ROUND_FINISHED:
world.set_round_state(ROUND_STARTING);
break;
}
return 'Changed';
case 'kick':
var name = args.shift();
var reason = args.shift();
world.forEachPlayer(function(player) {
if (player.name == name) {
var conn = connection_for_player(player);
conn.kill(reason);
return "Player kicked";
}
})
return "Player not found";
}
}
/**
* Forces a connection to be disconnected.
*/
conn.kill = function(reason) {
disconnect_reason = reason || 'Unknown Reason';
this.post([OP_DISCONNECT_REASON, disconnect_reason]);
this.close();
message_queue = [];
}
/**
* Queues the specified message and sends it on next flush.
*/
conn.queue = function(msg) {
if (conn.state == JOINED) {
message_queue.push(msg);
}
}
/**
* Stringifies specified object and sends it to remote part.
*/
conn.post = function(data) {
var packet = JSON.stringify(data);
this.send(packet);
}
/**
* Posts specified data to this instances message queue
*/
conn.flush_queue = function() {
var now = get_time();
msg = null,
data_sent = 6,
packet_data = []
while ((msg = message_queue.shift())) {
var data = JSON.stringify(msg);
packet_data.push(data);
data_sent += data.length;
}
try {
this.send('[' + GAME_PACKET + ',[' + packet_data.join(',') + ']]');
this.data_sent += data_sent;
} catch (err) {
return;
}
var diff = now - this.last_rate_check;
if (diff >= 1000) {
if (this.data_sent < this.rate && this.update_rate > 1) {
this.update_rate--;
} else if (this.data_sent > this.rate) {
this.update_rate++;
}
this.data_sent = 0;
this.last_rate_check = now;
}
message_queue = [];
}
/**
* Sets the state of the connection
*/
conn.set_state = function(new_state) {
switch (new_state) {
case CONNECTED:
if (no_connections++ > options.max_connections) {
conn.kill('server busy');
return;
}
while (connections[++connection_id]);
conn.id = connection_id;
conn.player = null;
conn.player_name = null;
conn.is_admin = false;
conn.rate = options.max_rate;
conn.update_rate = 2;
conn.max_rate = options.max_rate;
conn.last_rate_check = get_time();
conn.last_ping = 0;
conn.ping = 0;
conn.data_sent = 0;
conn.dimensions = [640, 480];
conn.state = IDLE;
conn.debug = options.debug;
connections[conn.id] = conn;
break;
case HANDSHAKING:
if (!gameloop) {
start_gameloop();
}
if (world.no_players >= world.max_players) {
conn.kill('Server is full');
} else {
conn.post([OP_WORLD_DATA, world.map_data, world.rules]);
if (conn.debug) {
log('Debug: ' + conn + ' connected to server. Sending handshake...');
}
}
break;
case JOINED:
var playeridincr = 0;
while (world.players[++playeridincr]);
conn.player = world.add_player(playeridincr, conn.player_name);
conn.post([OP_WORLD_STATE, conn.player.id].concat(world.get_repr()));
log(conn + conn.player_name + ' joined the game.');
break;
case DISCONNECTED:
if (conn.id && connections[conn.id]) {
delete connections[conn.id];
no_connections--;
if (conn.player) {
world.remove_player(conn.player.id, disconnect_reason);
conn.player = null;
log(conn + ' left the game (Reason: ' + disconnect_reason + ')');
}
if (world.no_players == 0) {
stop_gameloop();
}
if (conn.debug) {
log('Debug: ' + conn + ' disconnected (Reason: ' + disconnect_reason + ')');
}
}
break;
}
conn.state = new_state;
}
/**
* Returns a String representation for this Connection
*/
conn.toString = function() {
return this.remoteAddress + '(id: ' + this.id + ')';
}
// Connection 'receive' event handler. Occures each time that client sent
// a message to the server.
conn.on('message', function(data) {
var packet = null;
try {
packet = JSON.parse(data);
} catch(e) {
console.error('Malformed message recieved');
console.error(inspect(data));
conn.kill('Malformed message sent by client');
return;
}
switch(packet[0]) {
case GAME_PACKET:
if (world) {
process_game_message([packet[1], conn.player, world]);
}
break;
case PING_PACKET:
conn.ping = get_time() - conn.last_ping;
break;
default:
process_control_message([packet, conn]);
break;
}
});
// Connection 'close' event listener. Occures when the connection is
// closed by user or server.
conn.on('close', function() {
conn.set_state(DISCONNECTED);
});
// Connection 'connect' event handler. Challenge the player and creates
// a new PlayerSession.
conn.set_state(CONNECTED);
conn.remoteAddress = conn._socket.remoteAddress;
});
load_map(null, true, function(err) {
console.log('Starting Game Server server at ' + shared.get_state().game_server_url);
// server.listen(parseInt(options.ws_port), options.host);
});
return server;
}
/**
* Processes a control message from a connection.
*/
var process_control_message = match (
[[OP_REQ_SERVER_INFO], {'state =': CONNECTED}],
function(conn) {
conn.send_server_info();
},
/**
* MUST be sent by the client when connected to server. It's used to validate
* the session.
*/
[[OP_CLIENT_CONNECT, String], {'state =': CONNECTED}],
function(version, conn) {
if (version != SERVER_VERSION) {
conn.kill('Wrong version');
} else {
conn.set_state(HANDSHAKING);
}
},
/**
* Client has received world data. Client is now a player of the world.
*/
[[OP_CLIENT_JOIN, Object], {'state =': HANDSHAKING}],
function(info, conn) {
conn.set_client_info(info);
conn.set_state(JOINED);
},
[[OP_CLIENT_SAY, String], {'state =': JOINED}],
function(message, conn) {
if (message.length > 200) {
conn.kill('Bad chat message');
} else {
conn.chat(message);
}
},
[[OP_CLIENT_SET, 'rate', Number], {'state =': JOINED}],
function(rate, conn) {
conn.rate = Math.min(rate, conn.max_rate);
},
[[OP_CLIENT_EXEC, String, 'kick', String, String], {'state =': JOINED}],
function(password, player_name, reason, conn) {
if (conn.auth(password)) {
var resp = conn.exec('kick', player_name, reason);
conn.post([OP_SERVER_EXEC_RESP, resp]);
} else {
conn.post([OP_SERVER_EXEC_RESP, 'Wrong password']);
}
},
[[OP_CLIENT_EXEC, String, 'map', String], {'state =': JOINED}],
function(password, path, conn) {
if (conn.auth(password)) {
var resp = conn.exec('map', path);
conn.post([OP_SERVER_EXEC_RESP, resp]);
} else {
conn.post([OP_SERVER_EXEC_RESP, 'Wrong password']);
}
},
[[OP_CLIENT_EXEC, String, 'warmup'], {'state =': JOINED}],
function(password, conn) {
if (conn.auth(password)) {
var resp = conn.exec('warmup');
conn.post([OP_SERVER_EXEC_RESP, resp]);
} else {
conn.post([OP_SERVER_EXEC_RESP, 'Wrong password']);
}
},
[[OP_CLIENT_EXEC, String, 'start'], {'state =': JOINED}],
function(password, conn) {
if (conn.auth(password)) {
var resp = conn.exec('start');
} else {
conn.post([OP_SERVER_EXEC_RESP, 'Wrong password']);
}
},
[[OP_CLIENT_EXEC, String, 'restart'], {'state =': JOINED}],
function(password, conn) {
if (conn.auth(password)) {
var resp = conn.exec('restart');
conn.post([OP_SERVER_EXEC_RESP, resp]);
} else {
conn.post([OP_SERVER_EXEC_RESP, 'Wrong password']);
}
},
function(data) {
console.error(data);
console.error(data[1].state);
data[1].kill('Bad control message');
}
);
/**
* Processes a game message from specified player.
*/
var process_game_message = match (