-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
1338 lines (1058 loc) · 36.9 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
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
var app = require('express')();
var express = require('express');
var http = require('http').Server(app);
var io = require('socket.io')(http);
var paper = require('paper');
var port = process.env.PORT || 61161;
try {
console.log(require.resolve("paper"));
console.log('paper found');
} catch (e) {
console.error("paper is not found");
process.exit(e.code);
}
app.get('/', function (req, res) {
res.sendFile(__dirname + '/paperoids.html');
});
app.get('/mobile', function (req, res) {
res.sendFile(__dirname + '/mobile.html');
});
app.use('/', express.static(__dirname + '/public/'));
app.use('/paper', express.static(__dirname + '/node_modules/paper/dist/'));
app.use('/js', express.static(__dirname + '/node_modules/'));
http.listen(port, function () {
console.log('Server running on port %s', port);
});
//console.log(paper.Group);
//DEBUG FUNCTIONS
var SHOW_PERFORMANCE = false;
/** Game Server logic **/
var LIFES = 3; // Lifes per player
var ASTEROIDS = 10; // Number of Asteroids on screen
var SHOT_DELAY = 200; // delay between shots in ms
var SHOT_SPEED = 5; // How many px does a shot move per tick
var SHOT_LIFESPAN = 120; // How long a shot lives
var SHOT_INHERIT_FACTOR = 0.7; // How much speed should a shot inherit from the firing ship
var SHIP_TOPSPEED = 6; // Topspeed of ship
var SHIP_ACCELERATION = 0.22; // Acceleration of ship
var SHIP_TURNRATE = 3; // Turnrate of ship
var SHIP_SIZE = 48;
var SHIP_RESPAWN_TIME = 2000; // in milliseconds
var SHIP_SPAWN_PROTECTION = 3000; // in milliseconds
var POINTS_PER_KILL = 100;
var POINTS_PER_DEATH = -20;
var POINTS_PER_ASTEROID = 10;
var map_width = 1920;
var map_height = 1080;
var GAME_ROUND_LENGTH = 60 * 3 * 1000 // Duration of one round (in Milliseconds)
//var GAME_ROUND_LENGTH = 10 * 1000 // DEBUG Duration of one round (in Milliseconds)
var GAME_ROUND_INBETWEEN = 16 * 1000 // Time between two rounds (in Milliseconds)
var GAME_ROUND_START_TIMESTAMP = 0;
var GAME_ROUND_END_TIMESTAMP = 0;
var CLIENT_TIMEOUT_PERIOD = 10000;
var UP = 0;
var RIGHT = 1;
var DOWN = 2;
var LEFT = 3;
var FIRE = 4;
var presets = {
speed: 0.2,
maxRockSpeed: 4.5,
rockCount: 6,
lives: 3,
freeShipScore: 10000,
freeShipIncrement: 10000
};
paper.install(this);
paper.setup([map_width, map_height]);
/** Receive movement of ships
* Receive new shots
*
* Update position of ships, asteroids, shots
*
* Check collision
*
* Game logic like killing and respawning stuff
*/
function toRadians(angle) {
return angle * (Math.PI / 180);
}
function rgb2hex(rgb) {
rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
return (rgb && rgb.length === 4) ? "#" +
("0" + parseInt(rgb[1], 10).toString(16)).slice(-2) +
("0" + parseInt(rgb[2], 10).toString(16)).slice(-2) +
("0" + parseInt(rgb[3], 10).toString(16)).slice(-2) : '';
}
function minimumBrightness(h, s, l, min) {
return [h, s, Math.max(l, min)]
}
function hsvToRgb(h, s, v) {
var r, g, b;
var i = Math.floor(h * 6);
var f = h * 6 - i;
var p = v * (1 - s);
var q = v * (1 - f * s);
var t = v * (1 - (1 - f) * s);
switch (i % 6) {
case 0:
r = v, g = t, b = p;
break;
case 1:
r = q, g = v, b = p;
break;
case 2:
r = p, g = v, b = t;
break;
case 3:
r = p, g = q, b = v;
break;
case 4:
r = t, g = p, b = v;
break;
case 5:
r = v, g = p, b = q;
break;
}
return [r * 255, g * 255, b * 255];
}
function hexToRgb(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
function rgbToHsv(r, g, b) {
r /= 255, g /= 255, b /= 255;
var max = Math.max(r, g, b), min = Math.min(r, g, b);
var h, s, v = max;
var d = max - min;
s = max == 0 ? 0 : d / max;
if (max == min) {
h = 0; // achromatic
} else {
switch (max) {
case r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / d + 2;
break;
case b:
h = (r - g) / d + 4;
break;
}
h /= 6;
}
return [h, s, v];
}
function serializeShip(ship) {
var serialized = {
angle: ship.angle,
color: ship.color,
group: ship.item,
id: ship.id,
name: ship.name,
pos: ship.position
};
//console.log('serialized angle: ' + serialized.angle);
return serialized;
}
io.on('connection', function (socket) {
console.log('a user connected! | ' + socket.id);
// Send game info 'players' to new player
//console.log(game.ships);
var shipsToPlayer = [];
game.ships.forEach(function (ship) {
//console.log(ship);
var shipToPlayer = serializeShip(ship);
shipsToPlayer.push(shipToPlayer);
});
socket.emit('game state ships', shipsToPlayer);
//console.log(score.getPlayers());
score.getPlayers().forEach(function (player) {
//console.log('+1');
socket.emit('scoreboard add player', player);
});
var remaining_time = GAME_ROUND_LENGTH - (new Date().getTime() - GAME_ROUND_START_TIMESTAMP);
var gameinfo = {
SHOT_SPEED: SHOT_SPEED,
SHOT_LIFESPAN: SHOT_LIFESPAN,
SHIP_RESPAWN_TIME: SHIP_RESPAWN_TIME,
SHIP_SPAWN_PROTECTION: SHIP_SPAWN_PROTECTION,
SHIP_SIZE: SHIP_SIZE,
map_width: map_width,
map_height: map_height,
remaining_time: remaining_time
};
//socket.emit('gameinfo', remaining_time);
socket.emit('game state variables', gameinfo);
socket.on('debug message', function (message) {
console.log(message);
});
socket.on('new player', function (player) {
player = JSON.parse(player);
//console.log(player);
// Add new player to shiplist
console.log('new player "' + player.name + '" connected.');
//console.log(player.ship);
// Give color a minimum lightness to prevent exploiting dark, hardly visible ships
// This color conversion is cancer, but I'm too lazy to think of a more effective way to do it.
var color = player.color;
color = hexToRgb(color);
//console.log('rgb', color);
color = rgbToHsv(color.r, color.g, color.b);
//console.log('hsv', color);
color = minimumBrightness(color[0] * 360, color[1] * 100, color[2] * 100, 35);
//console.log('hsv minimum Brightness', color);
color = hsvToRgb(color[0] / 360, color[1] / 100, color[2] / 100);
color = [Math.floor(color[0]), Math.floor(color[1]), Math.floor(color[2])];
color = rgb2hex('rgb(' + color[0] + ', ' + color[1] + ', ' + color[2] + ')');
var ship = {
id: socket.id,
color: color,
name: player.name,
group: player.ship,
movement: {
up: false,
down: false,
left: false,
right: false,
shooting: false
},
pos: {
x: Math.floor(Math.random() * map_width),
y: Math.floor(Math.random() * map_height)
},
angle: Math.floor(Math.random() * 360),
speed: 0
};
socket.emit('acknowledge new player');
//socket.emit('game state players', game.ships);
// Add ship to the server
game.addShip(ship);
// Track last shots to enforce delay between shots
game.canshoot[socket.id] = true;
// Initialize timeout
game.keepalive[socket.id] = true;
// Add player to scoreboard
score.addPlayer(socket.id, player.name, color);
// console.log('server angle: ' + ship.angle);
// Get the ship
//console.log(socket.id);
var client_ship = game.getShip(socket.id);
//console.log('client angle: ' + client_ship.angle);
// Add player to the clientsgame
io.emit('game add player', serializeShip(client_ship));
//console.log(ship.group);
});
// Received keepalive: Refresh client timeout
socket.on('keepalive', function() {
game.keepalive[socket.id] = true;
//console.log(socket.id + ' sent keepalive');
});
socket.on('player movement', function (dir) {
if (!game.running) return;
//console.log('received player ' + socket.id + ' movement: ' + movement.up + ' ' + movement.down + ' ' + movement.left + ' ' + movement.right + ' ' + movement.shooting);
// Update player movement
//console.log('player ' + socket.id + ' now going ' + dir);
game.updateShipMovement(socket.id, dir, true);
});
socket.on('request round state', function() {
if(game.running) {
var remaining_time = GAME_ROUND_LENGTH - (new Date().getTime() - GAME_ROUND_START_TIMESTAMP);
socket.emit('game round info', {
running: true,
remaining_time: remaining_time
});
} else {
var remaining_time = GAME_ROUND_INBETWEEN - (new Date().getTime() - GAME_ROUND_END_TIMESTAMP);
socket.emit('game round info', {
running: false,
remaining_time: remaining_time
});
}
});
socket.on('request game state ships', function() {
var shipsToPlayer = [];
game.ships.forEach(function (ship) {
//console.log(ship);
var shipToPlayer = serializeShip(ship);
shipsToPlayer.push(shipToPlayer);
});
socket.emit('game state ships', shipsToPlayer);
});
socket.on('request ships number', function() {
socket.emit('game ships number', game.ships.length);
});
socket.on('player movement stop', function (dir) {
if (!game.running) return;
//console.log('received player ' + socket.id + ' movement: ' + movement.up + ' ' + movement.down + ' ' + movement.left + ' ' + movement.right + ' ' + movement.shooting);
// Update player movement
//game.updateShip(socket.id, movement);
//console.log('player ' + socket.id + ' stopped going ' + dir);
game.updateShipMovement(socket.id, dir, false);
});
socket.on('disconnect', function () {
// Delete player stuff
removePlayer(socket.id);
})
setInterval(function() {
socket.emit('h')
}, 2000);
});
var checkClientTimeouts = function() {
//console.log('checking for timeouts...');
// Loop through players stored in keepalive
//console.log(game.keepalive);
for(var key in game.keepalive) {
if(game.keepalive.hasOwnProperty(key)) {
// If client hasn't send a heartbeat, kick them out
if(!game.keepalive[key]) {
console.log('removing player ' + key + ' because he did not send a heartbeat in time');
removePlayer(key);
}
else {
// Set all heartbeats to false
game.keepalive[key] = false;
}
}
}
};
var timeouts = setInterval(checkClientTimeouts, CLIENT_TIMEOUT_PERIOD);
/* TODO In Gameserver verschieben */
function removePlayer(id) {
game.removeShip(id);
game.removeShots(id);
score.removePlayer(id);
delete game.keepalive[id];
//console.log(game.keepalive);
delete game.canshoot[id];
io.emit('player disconnected', id);
console.log('player "' + id + '" disconnected.');
}
function GameServer() {
// ships obj: id, color, movement, pos.x, pos.y, pos.angle
this.ships = [];
// shots obj: owner-id, color, pos.x, pos.y, angle
this.shots = [];
this.canshoot = {};
this.keepalive = {};
this.lastShotId = 0;
// asteroids obj: asteroid-id, owner-id, color, pos.x, pos.y, movement
this.asteroids = [];
// Game is currently running
this.running = false;
}
GameServer.prototype = {
// Add ship on player entrance
addShip: function (ship) {
var newship = new Ship(ship);
newship.spawnProtection();
this.ships.push(newship);
//console.log(ship);
},
// Get a ship via its id
getShip: function (id) {
var result;
this.ships.forEach(function (ship) {
if (id === ship.id) {
result = ship;
}
});
return result;
},
updateShip: function (shipid, movement) {
this.ships.forEach(function (ship) {
if (ship.id == shipid) {
ship.movement = movement;
// If shooting: add shot
// TODO Consider delay
if (ship.movement.shooting) {
//TODO calculate angle & position
var shot = {
owner: ship.id,
color: ship.color,
pos: ship.position,
angle: ship.angle,
time_to_live: SHOT_LIFESPAN
};
//this.addShot(shot);
}
//console.log('updated ' + ship.id);
}
});
},
updateShipMovement: function (shipid, dir, move) {
this.ships.forEach(function (ship) {
if (ship.id === shipid) {
if (dir === UP) {
ship.movement.up = move;
} else if (dir === DOWN) {
ship.movement.down = move;
} else if (dir === LEFT) {
ship.movement.left = move;
} else if (dir === RIGHT) {
ship.movement.right = move;
} else if (dir === FIRE && move && game.canshoot[ship.id]) {
ship.movement.shooting = move;
//console.log('adding shot');
game.addShot(ship);
game.canshoot[ship.id] = false;
setTimeout(function() {
game.canshoot[ship.id] = true;
}, SHOT_DELAY);
}
//ship.movement = movement;
//console.log(ship.movement);
// If shooting: add shot
// TODO Consider delay
//console.log('updated ' + ship.id);
}
});
},
stopShipMovement: function (ship) {
ship.movement.up = false;
ship.movement.down = false;
ship.movement.left = false;
ship.movement.right = false;
ship.movement.shooting = false;
},
// Add shot
addShot: function (ship) {
// If the ship is dieing or dead you can't fire
if (ship.dying || ship.isInvincible()) {
return false;
}
// Add shot to game server
this.shots.push(new Shot(ship));
// Refresh shotdelay for shooter
this.canshoot[ship.id] = SHOT_DELAY;
//console.log('shot added');
},
// Remove ship on player exit
removeShip: function (shipID) {
this.ships = this.ships.filter(function (t) {
return t.id !== shipID
})
},
removeShots: function (shipID) {
this.shots = this.shots.filter(function (t) {
return t.owner !== shipID
});
},
// Synchronize ships
moveShips: function () {
this.ships.forEach(function (ship) {
// Update ship angle
if (ship.movement.left) {
//ship.angle -= SHIP_TURNRATE;
ship.turnLeft();
}
if (ship.movement.right) {
//ship.angle += SHIP_TURNRATE;
ship.turnRight();
}
// Update ship speed
if (ship.movement.up) {
//ship.speed = Math.max(SHIP_TOPSPEED);
//ship.speed = SHIP_TOPSPEED;
ship.thrust();
} else {
//ship.speed = 0;
ship.coast();
}
ship.move();
//console.log(ship.item.position.x + ' ' + ship.item.position.y);
//ship.pos
// Calculate x and y movement based on angle
// Bei angle = 0 -> X = 1, Y = 0
// Bei angle = 90 -> X = 0, y = 1
//x -> cos
//y -> sin
//var rad = toRadians(ship.angle);
//var dx = Math.cos(rad) * ship.speed;
//var dy = Math.sin(rad) * ship.speed;
//console.log('dx: ' + dx + ', dy: ' + dy + ', angle: ' + ship.angle);
//ship.pos.x += dx;
//ship.pos.y += dy;
//ship.papergroup.position = new paper.Point(ship.pos.x, ship.pos.y);
//ship.papergroup.rotation = ship.angle;
//console.log('x: ' + ship.pos.x + ', y: ' + ship.pos.y + ', angle: ' + ship.angle);
// Update ship position (based on speed & angle
});
},
// Synchronize shots
moveShots: function () {
// Update shot position
this.shots.forEach(function (shot, i) {
if (shot.expired()) {
shot.remove();
game.shots.splice(i, 1);
return;
}
shot.move();
//var rad = toRadians(shot.angle);
//var dx = Math.cos(rad) * SHOT_SPEED;
//var dy = Math.sin(rad) * SHOT_SPEED;
//console.log('dx: ' + dx + ', dy: ' + dy + ', angle: ' + ship.angle);
//shot.pos.x += dx;
//shot.pos.y += dy;
//console.log(shot.time_to_live);
});
},
// Detect shot collision
detectShotCollision: function () {
// ...
},
moveAsteroids: function () {
// ...
},
// Update game objects
update: function () {
// Update shots;
this.moveShots();
// Update ship movement;
this.moveShips();
// Update Asteroid movement;
this.moveAsteroids();
},
// Check for collisions
checks: function () {
//checkCollisions
this.checkCollisions();
//checkHits
this.checkHits();
},
//Check if any ship is colliding with asteroids
checkCollisions: function () {
},
//Check if any shot is colliding with ships or asteroids
checkHits: function () {
// If the game is over, no hitchecks
if (!game.running) return;
game.shots.forEach(function (shot) {
// Ship hits
game.ships.forEach(function (ship) {
if (ship.id === shot.owner) {
return;
}
var check = ship.item.bounds.contains(shot.bullet.position)
//console.log(check);
if (check && !ship.isDieing() && !ship.isInvincible()) {
console.log(ship.name + ' hit by ' + shot.owner);
ship.hitBy(shot.owner);
}
});
});
},
//Send data to clients
//See "Optimisations" in trello list for possible improvements over sending game state
sendData: function () {
var ships_position = [];
game.ships.forEach(function (ship) {
//console.log(ship.item.position.x + ' ' + ship.item.position.y);
//console.log(ship.item.position.x + ' ' + ship.position.x);
ships_position.push([
ship.id,
Math.round(ship.item.position.x),
Math.round(ship.item.position.y),
ship.angle
]);
//console.log('updated angle: ' + ship.angle);
});
//console.log(ships_position);
io.emit('ships position', ships_position);
},
// When the round is started
startRound: function () {
// Reenable player control & hitchecks
this.running = true;
console.log('Round has started');
var game = this;
// Reset Scoreboard
score.reset();
// Respawn Ships
this.ships.forEach(function (ship) {
ship.respawn();
});
// Send "game round start" to clients
io.emit('game round start', GAME_ROUND_LENGTH);
//DEBUG
//io.emit('gameinfo', 'Round has started');
// Save round start timestamp
GAME_ROUND_START_TIMESTAMP = new Date().getTime();
// Tell the game when it's over
setTimeout(function () {
game.endRound();
}, GAME_ROUND_LENGTH);
},
// When the round is over
endRound: function () {
// Disable player control & hitchecks
this.running = false;
var game = this;
console.log('Round has ended');
// Send "game round end" to clients
io.emit('game round end', GAME_ROUND_INBETWEEN);
// DEBUG
//io.emit('gameinfo', 'Round has ended');
// Let ships movement fade out
this.ships.forEach(function(ship) {
game.stopShipMovement(ship);
});
// Set round end timestamp
GAME_ROUND_END_TIMESTAMP = new Date().getTime();
// Tell the game when to start again
setTimeout(function () {
game.startRound();
}, GAME_ROUND_INBETWEEN);
}
};
game = new GameServer();
score = new Scoreboard();
//Start a new round
game.startRound();
setInterval(function () {
var perf = process.hrtime();
//console.log(perf)
game.update();
game.checks();
game.sendData();
if (SHOW_PERFORMANCE) {
console.log('executed in ' + ((process.hrtime()[1] - perf[1]) * 0.000001) + 'ms')
}
}, 1000 / 60);
/* Merge singleplayer version */
var assets = {
destroyedShip: new function () {
var group = new paper.Group(
new paper.Path([-10, -8], [10, 0]),
new paper.Path([10, 0], [-10, 8]),
new paper.Path([-8, 4], [-8, -4])
);
group.visible = false;
return group;
},
explosion: new function () {
var explosionPath = new paper.Path.Circle(new paper.Point(), 1);
explosionPath.fillColor = 'white';
explosionPath.strokeColor = null;
return new paper.SymbolDefinition(explosionPath);
},
spawnProtection: new function () {
var circle = new paper.Path.Circle(new paper.Point(), 20);
circle.visible = false;
return circle;
}
};
// PaperJS has no absolute scaling.
//You can calculate the scaling by dividing the intended width/height of your rectangle with the current width/height of your rectangle.
//Then you can use that scaling 'coefficient' to apply the scaling.
function normalizeGroup(group) {
//group.bounds
// Get the larger of width & height
var longside = Math.max(group.bounds.width, group.bounds.height);
// Get the scaling factor by dividing the the desired size by the current size
var factor = SHIP_SIZE / longside;
group = group.scale(factor);
//console.log(group.bounds.width);
return group;
}
function Scoreboard() {
//array of objects
//object: Player ID, name, score, kills, deaths
//Add player on join
//Remove player on leave
//Add points, kills, deaths to player-id
var players = [];
return {
score: players,
getPlayers: function () {
return players;
},
addPlayer: function (id, name, color) {
var player = {
id: id,
name: name,
color: color,
score: 0,
kills: 0,
deaths: 0
};
players.push(player);
//console.log(players);
//Send new player to clients
io.emit('scoreboard add player', player);
},
removePlayer: function (id) {
players = players.filter(function (t) {
return t.id !== id
})
//Remove player from clients
io.emit('scoreboard remove player', id);
},
updateScore: function (id, points, kills, deaths) {
var player = players.find(function (player) {
return player.id === id
});
player.score += points;
player.kills += kills;
player.deaths += deaths;
//console.log(player);
//Send score to clients
io.emit('scoreboard update player', player);
},
// Resets all scores to 0
reset: function () {
players.forEach(function (player) {
player.score = 0;
player.kills = 0;
player.deaths = 0;
});
}
}
}
function Ship(options) {
var path = new paper.Group().importJSON(options.group);
//path.closed = true;
//var thrust = new paper.Path([-8, -4], [-14, 0], [-8, 4]);
var group = new paper.Group(path);
//console.log(group.bounds.width);
group = normalizeGroup(group);
//console.log(group.bounds.width);
group.applyMatrix = false;
//console.log(options.ship);
//var group = new paper.Group().importJSON(options.group);
//console.log(group);
group.position = new paper.Point(options.pos.x, options.pos.y);
//group.position = new paper.Point(options.pos.x, options.pos.y);
//console.log(group.position.x + ', ' + group.position.y);
var hit = false;
//var id = options.id;
return {
item: group,
angle: options.angle,
color: options.color,
movement: options.movement,
id: options.id,
name: options.name,
position: group.position,
vector: new paper.Point({
angle: 0.2,
length: 1
}),
destroyedShip: assets.destroyedShip.clone(),
turnLeft: function () {
group.rotate(-SHIP_TURNRATE);
this.angle -= SHIP_TURNRATE;
//console.log('group.rotation = ' + group.rotation + ', this.angle = ' + this.angle);
},
turnRight: function () {
group.rotate(SHIP_TURNRATE);
this.angle += SHIP_TURNRATE;
//console.log('group.rotation = ' + group.rotation + ', this.angle = ' + this.angle);
},
thrust: function () {
//thrust.visible = true;
this.vector = this.vector.add(new paper.Point({
angle: this.angle,
length: SHIP_ACCELERATION
}));
//console.log(this.vector);
if (this.vector.length > SHIP_TOPSPEED) {
this.vector.length = SHIP_TOPSPEED;
}
},
isInvincible: function () {
return this.invincible;