-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGame.js
More file actions
1768 lines (1553 loc) · 50.9 KB
/
Game.js
File metadata and controls
1768 lines (1553 loc) · 50.9 KB
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
import { ClientRoomManager } from "./ClientRoomManager.js";
import { ClientUser } from "./ClientUser.js";
import { Rectangle } from "./Rectangle.js";
import { SpriteColors } from "./SpriteColors.js";
import { WHUtil } from "./WHUtil.js";
import { PortalSprite } from "./sprites/PortalSprite.js";
import { PowerupSprite } from "./sprites/PowerupSprite.js";
import { UserSprite } from "./sprites/UserSprite.js";
import { WallCrawlerSprite } from "./sprites/WallCrawlerSprite.js";
/**
* Game Class
* @description implements a Game (Wormhole) that contains a board
* world is the total renderable canvas, use this size for generating the stars
*/
export class Game {
constructor(gameNetLogic) {
// set a debug mode for displaying shapeRects
this.isDebugMode = false;
this.gameNetLogic = gameNetLogic;
this.input = {
right: false,
left: false,
up: false,
spacebar: false,
fKey: false,
};
this.colors = new SpriteColors();
this.novaInfo = [];
this.orbitDistance = 240;
this.borderShades = new Array(6);
// sprite arrays
this.allSprites = new Map();
this.badGuys = new Map();
this.goodGuys = new Map();
// track the total number of bullets here
this.nBullets = 0;
this.mode = "waiting";
this.powerups = new Array(5);
this.numPowerups = 0;
// shortcuts for the game's room and user
this.room = this.gameNetLogic.clientRoomManager.getRoomById(
this.gameNetLogic.roomId,
);
this.user = this.gameNetLogic.clientUserManager.users.get(
this.gameNetLogic.userId,
);
this.currentFighterShade = 0;
// default to using the shipType of 1
this.userShipType = 1;
this.zoomInIntro = 0;
this.incomingCycle = 0;
// array to store the user messages in
this.userMessages = [];
this.canvas = undefined;
this.context = undefined;
this.cycle = undefined;
this.refreshAll = true;
this.refreshOtherBar = true;
this.refreshUserBar = true;
// load audio files
this.fireSound = new Audio("./sound/fire.mp3");
this.explosionSound = new Audio("./sound/explosion.mp3");
this.powerupSound = new Audio("./sound/magic.mp3");
this.thrustSound = new Audio("./sound/thrust.mp3");
// only use key handlers when the game is in focus?
// key press handlers
// TODO - may need to modify to allow for chatting while in game
document.onkeydown = (e) => this.onkeydown(e);
document.onkeyup = (e) => this.onkeyup(e);
}
onkeyup(e) {
// console.log("key up " + e.code);
e.preventDefault();
if (e.code === "ArrowRight") {
this.input.right = false;
} else if (e.code === "ArrowLeft") {
this.input.left = false;
} else if (e.code === "ArrowUp") {
this.input.up = false;
} else if (e.code === "Space") {
this.input.spacebar = false;
} else if (e.code === "KeyF") {
this.input.fKey = false;
// attempt to only allow a single press for the f key
this.singlePress = true;
}
}
onkeydown(e) {
// console.log("key down " + e.code);
e.preventDefault();
if (e.code === "ArrowRight") {
this.input.right = true;
} else if (e.code === "ArrowLeft") {
this.input.left = true;
} else if (e.code === "ArrowUp") {
this.input.up = true;
} else if (e.code === "Space") {
this.input.spacebar = true;
} else if (e.code === "KeyF" && this.singlePress) {
this.input.fKey = true;
this.singlePress = false;
}
}
prepareCanvas() {
this.canvas = document.getElementById("GameCanvas");
this.canvas.addEventListener(
"mousedown",
this.processClick.bind(this),
false,
);
this.userStatusCanvas = document.getElementById("UserStatusCanvas");
this.otherStatusCanvas = document.getElementById("OtherStatusCanvas");
this.userStatusCanvas.width = 430;
this.userStatusCanvas.height = 49;
this.otherStatusCanvas.width = 144;
this.otherStatusCanvas.height = 474;
// set the other status bar so that it is aligned with the game screen
this.otherStatusCanvas.style.marginTop = this.userStatusCanvas.height;
this.userStatusContext = this.userStatusCanvas.getContext("2d");
this.otherStatusContext = this.otherStatusCanvas.getContext("2d");
this.context = this.canvas.getContext("2d");
this.context.globalCompositeOperation = "source-over";
document.body.style.margin = 0;
document.body.style.padding = 0;
// set the width and height of the game canvas
this.canvas.width = window.innerWidth - 2 * this.otherStatusCanvas.width;
this.canvas.height = window.innerHeight;
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
update() {
// console.log("gameloop updating");
const user = this.gameNetLogic.clientUserManager.users.get(
this.gameNetLogic.userId,
);
if (this.input.right) {
user.userSprite.dRotate = Math.abs(user.userSprite.dRotate);
user.userSprite.isRotating = true;
}
if (this.input.left) {
user.userSprite.dRotate = -1 * Math.abs(user.userSprite.dRotate);
user.userSprite.isRotating = true;
}
if (this.input.up) {
user.userSprite.thrustOn = true;
}
if (this.input.spacebar) {
user.userSprite.firePrimaryWeapon = true;
}
if (this.input.fKey) {
user.userSprite.fireSecondaryWeapon = true;
}
// methods from doPlayCycle
this.cycle++;
this.doBehavior();
this.doCollisions();
this.checkSidebar();
}
render() {
// the full canvas is drawn and then only a portion of it is displayed to the
// viewport canvas
// draw the game on the canvas
this.draw(this.context);
if (this.mode == "waiting") {
// ship selection area
this.drawIntro(this.context);
const room = this.gameNetLogic.clientRoomManager.getRoomById(
this.gameNetLogic.roomId,
);
if (room != null) {
// if the game is already playing, wait for the next game
if (room.status == "playing") {
this.drawStrings(this.context, "Waiting for", "Next Game");
} else if (room.status == "countdown") {
this.drawStrings(this.context, "Countdown", "" + room.countdown);
// write a message depending on how many users there are
} else if (room.numUsers() < 2) {
this.drawStrings(this.context, "Waiting for", "More Users");
} else {
this.drawStrings(this.context, "Press Play Button", "To Start");
}
}
}
// refresh the user bar after getting a powerup
if (this.refreshUserBar) {
this.drawUserBar(this.userStatusContext);
// TODO - find where to send the user state outside of the draw method
// only send the state when it is updated
// don't send every time it is redrawn
}
if (this.refreshOtherBar) {
this.drawOtherBar(this.otherStatusContext, this.refreshAll);
this.refreshAll = false;
}
}
/**
* Reset the game
*/
reset() {
this.init();
// this.wins = 0;
// this.kills = 0;
// super.slot = 0;
this.color = this.colors.colors[0][0];
if (this.user.color != null) {
this.color = this.colors.colors[this.user.slot][0];
}
// for (let i = 0; i < this.userStates.length; ++i) {
// this.userStates[i].fullReset();
// }
this.gameOver = false;
this.gameOverCycle = 0;
this.mode = "waiting";
// refresh the user and other bar
this.refreshUserBar = true;
this.refreshOtherBar = true;
}
init() {
this.prepareCanvas();
// use these to track playable board size
// world (including outside areas)
// board center
// set the board width to the canvas width
// this.board = { width: 430, height: 423 };
this.board = { width: this.canvas.width, height: this.canvas.height };
this.viewport = { width: this.canvas.width, height: this.canvas.height };
// this is the entire size of the virtual world for rendering stars
this.world = {
width: this.board.width + this.viewport.width,
height: this.board.width + this.viewport.height,
};
// this holds the upper left corner of the viewable rectangle
this.viewportRect = new Rectangle(
(this.board.width - this.viewport.width) / 2,
(this.board.height - this.viewport.height) / 2,
this.viewport.width,
this.viewport.height,
);
this.globalBoundingRect = new Rectangle(
0,
0,
this.board.width,
this.board.height,
);
// set position for the welcome screen elements
this.intro = { width: 410, height: 260 };
this.introX = (this.board.width - this.intro.width) / 2;
this.introY = this.board.height - this.intro.height - 10;
this.intro_shipX = this.introX + 5;
this.intro_shipY = this.introY + 40;
// https://stackoverflow.com/questions/16919601/html5-canvas-camera-viewport-how-to-actually-do-it
// want to render the game using a centered portal
this.portalVisibility = (this.board.width / 2) * 1.45;
this.incomingCycle = 0;
this.incomingIconCycle = 0;
this.incomingWhoStack = [];
this.fromUserId = 0;
this.currentShade = 0;
this.incomingTypeStack = [];
this.incomingIconIndex = 0;
this.incomingNukeCycle = 0;
this.numPowerups = 0;
this.flashScreenColor = "black";
// reset powerups
const room = this.gameNetLogic.clientRoomManager.getRoomById(
this.gameNetLogic.roomId,
);
room.resetPowerups();
this.gameOver = false;
this.refreshUserBar = true;
// clear sprite arrays
this.allSprites = new Map();
this.badGuys = new Map();
this.goodGuys = new Map();
this.orbitDistance = 240;
let n;
// get the start time (in ms)
this.startTime = window.performance.now();
this.msPrev = window.performance.now();
this.fps = 60;
this.msPerFrame = 1000 / this.fps;
this.frames = 0;
this.cycle = 0;
// set the orbitDistance based on the number of users
if (this.gameNetLogic.roomId != null) {
switch (room.boardSize) {
// setting local totalOpposingPlayingUsers to change the board size
case 1: {
n = 2;
this.orbitDistance = 150;
break;
}
case 2:
case 3:
n = 3;
this.orbitDistance = 240;
break;
default: {
n = 3.6;
this.orbitDistance = 280;
break;
}
}
}
// for (let i = 0; i < 60; i++) {
// this.novaInfo[i][0] = 50;
// }
// generate the stars
this.initStars(70);
this.nBullets = 0;
// set user messages to an empty array
this.userMessages = [];
this.winningUserString = null;
// create a new user that starts at the center of the board
// with the specified ship type
const user = this.gameNetLogic.clientUserManager.users.get(
this.gameNetLogic.userId,
);
// move this to the joinRoom area?
user.userSprite = new UserSprite(
this.board.width / 2,
this.board.height / 2,
this.userShipType,
this,
);
user.userSprite.addSelf();
user.userSprite.setUser(user.userId);
this.initBorderShade(user);
new WallCrawlerSprite(0, 0, this, true).addSelf();
new WallCrawlerSprite(0, 0, this, false).addSelf();
// start main game loop
window.requestAnimationFrame(this.gameLoop.bind(this));
}
/**
* Main Game loop
* checks what state the game is in (playing, waiting, gameOver)
* gets user input
* update the game
* - increment the cycle
* - do sprite behaviors
* - check collisions
* - check the sidebar
* render
* @param {number} timeStamp
* @returns
*/
gameLoop(timeStamp) {
// check if the gameNetLogic's roomId is null
if (this.gameNetLogic.roomId == null) {
// error! this should not be null
return;
}
// get the room and check if it should be removed
const room = this.gameNetLogic.clientRoomManager.getRoomById(
this.gameNetLogic.roomId,
);
if (room.shouldRemove) {
this.gameNetLogic.clientRoomManager.removeRoom(room.roomId);
this.gameNetLogic.roomId = null;
return;
}
this.msPassed = timeStamp - this.msPrev;
if (this.msPassed > this.msPerFrame) {
// return;
/**
* Game Loop state machine
* playing -> gameOver
* gameOver -> waiting
* waiting (should go to "playing"), when the "Start Game" button
* is pushed, the "startGame" packet is received,
* which sets the mode to "playing" in handleGamePacket
*/
switch (this.mode) {
case "playing": {
// get user input
// TODO separate from update()
// behavior, collisions, checkSidebar
this.update();
this.render();
break;
}
/**
* Waiting for a new game to start
*/
case "waiting": {
// checks if there is time left on any of the powerups in a
// user's area
// checkSidebar();
this.refreshOtherBar = true;
this.render();
break;
}
/** Game over, allow the sprites to keep moving
* display message that the game is over
*/
case "gameOver": {
this.render();
// reset the game and enter the waiting state
if (this.gameOverCycle++ > 120) {
// if (this.gameOverCycle++ > 12000000 || this.winningUserString != null) {
// reset the game after 120 cycles
this.reset();
}
break;
}
}
}
this.excessTime = this.msPassed % this.msPerFrame;
this.msPrev = timeStamp - this.excessTime;
this.frames++;
window.requestAnimationFrame(this.gameLoop.bind(this));
}
// add users to the room when someone joins the room
// readJoin(paramDataInput) {
// this.model.readJoin(paramDataInput);
// }
/**
* Does the behavior for all sprites in the sprite arrays
* Writes user messages
* Checks how long the game has gone on
* @returns
*/
doBehavior() {
// loop through all the sprites and remove or do the behavior
this.allSprites.forEach((sprite) => {
if (sprite.shouldRemoveSelf) {
sprite.removeSelf();
} else {
sprite.behave();
}
});
// checks the user message queue and removes messages are past due
if (
this.lastCycleForMessages < this.cycle &&
this.userMessages.length > 0
) {
this.userMessages.shift();
}
// sets the probability that an enemy will generate
const gameTimeSeconds = (window.performance.now() - this.startTime) / 1000;
let genEnemyProb = 500;
if (gameTimeSeconds > 240) {
genEnemyProb = 400;
} else if (gameTimeSeconds > 120) {
genEnemyProb = 450;
} else if (gameTimeSeconds > 80) {
genEnemyProb = 500;
} else if (gameTimeSeconds < 40) {
// don't generate enemies in the first 40 seconds of the game
return;
}
// as the game goes up in seconds, the probability that an enemy will spawn increases
if (WHUtil.randInt(genEnemyProb) == 1) {
// we are generating enemies for all users currently playing
// but this starts at a 'random' user and generates enemies for all users
// now, just loop through all users to generate enemies
// let j = WHUtil.randInt() % this.users.length;
// let userInfo = this.users[(j + b) % this.users.length];
const room = this.gameNetLogic.clientRoomManager.getRoomById(
this.gameNetLogic.roomId,
);
// remove this user's userId
let userIds = room.userIds.filter(
(userId) => userId != null && userId != this.gameNetLogic.userId,
);
// get a random user
const user = this.gameNetLogic.clientUserManager.users.get(
userIds[WHUtil.randInt(userIds.length)],
);
// set that random user's portal to generate an enemy
if (user.isPlaying() && user.portalSprite != null) {
user.portalSprite.shouldGenEnemy = true;
}
}
}
// check for collisions between good/bad sprites
doCollisions() {
this.badGuys.forEach((spriteA) => {
this.goodGuys.forEach((spriteB) => {
if (
!spriteA.hasCollided &&
!spriteB.hasCollided &&
spriteA.isCollision(spriteB)
) {
spriteB.setCollided(spriteA);
spriteA.setCollided(spriteB);
}
});
});
}
/**
* For the room check all users whether there
* is time in the powerupTimeouts matrix
* if yes, then redraw the OtherBar
*/
checkSidebar() {
const room = this.gameNetLogic.clientRoomManager.getRoomById(
this.gameNetLogic.roomId,
);
for (let i = 0; i < room.userIds.length; i++) {
if (room.userIds[i] != null) {
const user = this.gameNetLogic.clientUserManager.users.get(
room.userIds[i],
);
if (user.timeoutAttacks()) {
this.refreshOtherBar = true;
}
}
}
}
setTeam(s, b) {
if (this.gameNetLogic.username == s) {
this.teamId = b;
} else {
const room = this.gameNetLogic.clientRoomManager.getRoomById(
this.gameNetLogic.roomId,
);
for (let i = 0; i < room.userIds.length; ++i) {
if (room.userIds[i] != null) {
const user = this.gameNetLogic.clientUserManager.users.get(
room.userIds[i],
);
if (user.username == s) {
user.teamId = b;
}
user.refresh = true;
}
}
}
this.refreshOtherBar = true;
}
// remove all the zappable sprites on the screen
clearScreen() {
this.flashScreenColor = "white";
this.badGuys.forEach((sprite) => {
if (sprite.inView && (!sprite.indestructible || sprite.zappable)) {
sprite.killSelf();
}
});
}
// draw the Game to the canvas
draw(context) {
// get the user object
const user = this.gameNetLogic.clientUserManager.users.get(
this.gameNetLogic.userId,
);
if (user.userSprite != null) {
// get the viewable area for the user
let viewportRect = user.userSprite.getViewportRect();
context.clearRect(0, 0, this.canvas.width, this.canvas.height);
context.fillStyle = "black";
context.fillRect(0, 0, this.canvas.width, this.canvas.height);
this.drawStars(context, "gray", this.narrowStar);
// draw pointers to other wormholes
this.drawPointers(context);
context.translate(-viewportRect.x, -viewportRect.y);
this.drawBorder(context);
this.drawStars(context, "white", this.star);
this.drawRing(context);
const room = this.gameNetLogic.clientRoomManager.getRoomById(
this.gameNetLogic.roomId,
);
if (user.teamId != 0 && room.isTeamTable && !this.gameOver) {
this.drawTeamStuff(context);
}
if (this.incomingCycle > 0) {
this.incomingCycle--;
context.font = "40px helvetica";
let fromSlot = room.getSlot(this.fromUserId);
// the fromUserId may be a slot number
// after the lookup it will be null, just use that slot number
if (fromSlot == null) {
fromSlot = this.fromUserId;
}
context.textAlign = "center";
context.strokeStyle =
this.colors.colors[fromSlot][this.currentShade++ % 20];
context.strokeText("I N C O M I N G", this.board.width / 2, 200);
if (this.incomingNukeCycle > 0) {
this.incomingNukeCycle--;
context.strokeText("N U K E", this.board.width / 2, 240);
}
}
// draw all sprites
this.allSprites.forEach((sprite) => {
if (sprite != null) {
// check if the sprite is in the viewportRect
sprite.inView = sprite.inViewingRect(viewportRect);
if (sprite.inView) {
sprite.drawSelf(context);
// display shapeRects when in debug mode
// if (this.isDebugMode) {
// context.beginPath();
// context.strokeRect(
// sprite.shapeRect.x,
// sprite.shapeRect.y,
// sprite.shapeRect.width,
// sprite.shapeRect.height
// );
// }
}
}
});
context.translate(viewportRect.x, viewportRect.y);
if (this.incomingIconCycle > 0) {
this.incomingIconCycle--;
} else if (this.incomingIconIndex > 0) {
this.incomingIconIndex--;
this.incomingIconCycle = 50;
for (let k = 0; k < this.incomingIconIndex; k++) {
this.incomingTypeStack[k] = this.incomingTypeStack[k + 1];
this.incomingWhoStack[k] = this.incomingWhoStack[k + 1];
}
}
// draw the incoming icons
const img = document.getElementById("smallPowerupImages");
const imgWidth = 21;
const imgHeight = 17;
for (let i = 0; i < this.incomingIconIndex; i++) {
let shiftedNumber = this.incomingTypeStack[i] - 6;
let powerupNumber;
if (shiftedNumber <= 0) {
powerupNumber = 0;
} else {
powerupNumber = shiftedNumber;
}
context.drawImage(
img,
powerupNumber + powerupNumber * imgWidth + 1,
1,
imgWidth,
imgHeight - 2,
2,
i * 15 + 31,
imgWidth,
imgHeight - 2,
);
}
// draw the winning user string
if (this.winningUserString != null) {
context.beginPath();
context.font = "40px helvetica";
context.textAlign = "center";
context.fillStyle = "white";
// put the text on the center of the board
context.fillText("GAME OVER!", this.board.width / 2, 100);
context.fillText(this.winningUserString, this.board.width / 2, 150);
}
// draw the userMessages
context.fillStyle = "white";
context.font = "12px helvetica";
context.textAlign = "left";
for (let n = 0; n < this.userMessages.length; n++) {
context.fillText(this.userMessages[n], 10, 20 * (n + 1));
}
}
if (user.teamId != 0) {
context.font = "12px helvetica";
context.fillStyle = ClientRoomManager.TEAM_COLORS[user.teamId];
context.fillText(
`${ClientRoomManager.TEAM_NAMES[user.teamId]} member`,
this.board.width - 135,
13,
);
}
context.strokeStyle = "white";
context.strokeRect(0, 0, this.board.width - 1, this.board.height - 1);
}
/**
* Initialize the border shade
*
* @param {Object<ClientUser>} user
*/
initBorderShade(user) {
// initialize the border shade color
if (user.color != null) {
// reimplement the Java .darker() function
const DARKER_FACTOR = 0.251;
this.borderShades[0] = user.color;
for (let i = 0; i < this.borderShades.length - 1; i++) {
// get the rgb values of the color
let curColorRGB = WHUtil.nameToRGB(this.borderShades[i]);
// get the 3 RGB values
let rgb = curColorRGB.replace(/[^\d,]/g, "").split(",");
let tempColor = `rgb(${rgb[0] * DARKER_FACTOR}, ${
rgb[1] * DARKER_FACTOR
}, ${rgb[2] * DARKER_FACTOR})`;
this.borderShades[i + 1] = tempColor;
}
}
}
// draw a line to point to other wormholes
drawPointers(context) {
const room = this.gameNetLogic.clientRoomManager.getRoomById(
this.gameNetLogic.roomId,
);
for (let i = 0; i < room.userIds.length; i++) {
if (room.userIds[i] != null) {
const user = this.gameNetLogic.clientUserManager.users.get(
room.userIds[i],
);
if (user.isPlaying() && user.userSprite != null) {
let n = user.portalSprite.x - user.userSprite.x;
let n2 = user.portalSprite.y - user.userSprite.y;
let hyp = Math.hypot(n, n2);
if (hyp >= this.portalVisibility) {
let n3 = (180 * n) / hyp;
let n4 = (180 * n2) / hyp;
let n5 = n3 + this.viewport.width / 2;
let n6 = n4 + this.viewport.height / 2;
let atan = Math.atan(n2 / n);
let n7 = 171;
if (n < 0) {
n7 = -n7;
}
let n8 = atan + 0.04;
let n9 = atan - 0.04;
let n10 = n7 * Math.cos(n8) + this.viewport.width / 2;
let n11 = n7 * Math.sin(n8) + this.viewport.height / 2;
let n12 = n7 * Math.cos(n9) + this.viewport.width / 2;
let n13 = n7 * Math.sin(n9) + this.viewport.height / 2;
context.strokeStyle = user.color;
context.lineWidth = 1;
context.beginPath();
context.moveTo(n5, n6);
context.lineTo(
n3 * 0.9 + this.viewport.width / 2,
n4 * 0.9 + this.viewport.height / 2,
);
context.moveTo(n5, n6);
context.lineTo(n10, n11);
context.moveTo(n5, n6);
context.lineTo(n12, n13);
context.moveTo(n12, n13);
context.lineTo(n10, n11);
context.stroke();
}
}
}
}
}
/**
* drawRing
* @param context a canvas context to draw the ring
* @description draws a gray ring to place the portals on
*/
drawRing(context) {
context.strokeStyle = "gray";
WHUtil.drawCenteredCircle(
context,
this.world.width / 2,
this.world.height / 2,
this.orbitDistance,
);
}
drawEnemyTeamShape(context, x, y) {
const user = this.gameNetLogic.clientUserManager.users.get(
this.gameNetLogic.userId,
);
if (user.teamId != 0) {
user.drawTeamShape(context, x, y, 3 - user.teamId);
}
}
/**
* Draws a border around the world
* @param context a canvas context to draw the border
*/
drawBorder(context) {
// draw the outer border box
context.lineWidth = 1;
context.beginPath();
for (let i = 0; i < this.borderShades.length; i++) {
context.strokeStyle = this.borderShades[i];
context.strokeRect(
-i,
-i,
this.world.width + i * 2,
this.world.height + i * 2,
);
}
}
drawStars(context, color, starLocations) {
// set the color of the stars
context.fillStyle = color;
context.beginPath();
for (let i = 0; i < starLocations.length; i++) {
context.fillRect(
starLocations[i][0],
starLocations[i][1],
this.starSize[i],
this.starSize[i],
);
}
}
// generate locations for the stars
initStars(numStars) {
// fill out stars for the board
// randomly space them
this.star = [];
this.narrowStar = [];
this.starSize = [];
this.numStars = numStars;
for (let i = 0; i < this.numStars; i++) {
this.star.push([
WHUtil.randInt(this.world.width),
WHUtil.randInt(this.world.height),
]);
this.narrowStar.push([
WHUtil.randInt(this.world.width),
WHUtil.randInt(this.world.height),
]);
this.starSize.push(WHUtil.randInt(2) + 1);
}
}
drawStrings(context, string1, string2) {
let n = this.introY - 115;
let n2 = n + 30;
context.fillStyle = this.color;
context.strokeStyle = this.color;
context.lineWidth = 1;
context.beginPath();
context.roundRect(50, n, this.board.width - 100, 100, 30);
context.fill();
context.stroke();
context.fillStyle = this.color == "blue" ? "white" : "black";
context.strokeStyle = this.color == "blue" ? "white" : "black";
this.drawCenteredText(context, "Yet Another Wormhole Clone", n2);
this.drawCenteredText(context, string1, n2 + 28);
this.drawCenteredText(context, string2, n2 + 56);
}
drawCenteredText(context, text, y) {
let x = this.board.width / 2;
context.font = "20px helvetica";
context.textAlign = "center";
context.fillText(text, x, y);
}
drawCenteredText2(context, text, y, xOffset, elementWidth) {
// context.drawString(s,
// (n3 - graphics.getFontMetrics(graphics.getFont()).stringWidth(s)) / 2 + n2, n);
// TODO make sure alignment is centered
context.textAlign = "center";
context.fillText(
text,
(elementWidth - context.measureTest(text).width) / 2 + xOffset,
y,
);
}
drawTeamStuff(context) {
let b = 3 - this.teamId;
let s = ClientRoomManager.TEAM_NAMES[b];
let color = ClientRoomManager.TEAM_COLORS[b];
let color2 = ClientRoomManager.TEAM_BG_COLORS[b];
let boardCenterX = this.board.width / 2;
context.strokeStyle = color;
context.fillStyle = color;
// get the room
const room = this.gameNetLogic.clientRoomManager.getRoomById(
this.gameNetLogic.roomId,
);
for (let i = 0; i < room.userIds.length; ++i) {
if (room.userIds[i] != null) {
const user = this.gameNetLogic.clientUserManager.users.get(
room.userIds[i],
);
let portalSprite = user.portalSprite;