-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.js
14737 lines (12638 loc) · 521 KB
/
main.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
"use strict";
//
// Realms of Antorax canvas code
// Jake Thakur 2018-2024
//
// initially based on https://developer.mozilla.org/en-US/docs/Games/Techniques/Tilemaps
//
// Game object
//
var Game = {
// function objects
statusEffects: {},
spells: {},
secondary: {},
tag: {},
displayedStats: 0, // number of stats displayed at the top left
};
Game.canvas = document.getElementById("game");
Game.secondary.canvas = document.getElementById("secondary");
Game.canvasLight = document.getElementById("light");
Game.canvasDayNight = document.getElementById("dayNight");
// run game
// anything that needs to be done before images are loaded
Game.run = function (context, contextSecondary, contextDayNight, contextLight) {
this.ctx = context;
this.ctxDayNight = contextDayNight;
this.ctxLight = contextLight;
this.secondary.ctx = contextSecondary;
// ctx settings
this.ctx.imageSmoothingEnabled = false;
this.previousElapsed = 0;
this.loadPlayer(); // load the player from local storage
this.initWebSocket(); // init the web socket if the user is on the Heroku version
// projectile name for hero (for use with projectile image loading)
//this.heroProjectileName = Skins[Player.class][Player.skin].projectile;
//this.heroProjectile2Name = Skins[Player.class][Player.skin].projectile2; // currently just for knight's ranged attack - now removed
//this.heroProjectileAdjust = Skins[Player.class][Player.skin].projectileAdjust;
this.heroProjectileName = Player.baseProjectile; // currently set in savedata
this.heroProjectileAdjust = Player.baseProjectileAdjust;
this.heroProjectileInfo = {}; // any additional info
this.heroBobberName = "bobber";
this.nextEntityId = 0; // unique entity ids are assigned using this variable, which is never reset
if (typeof Player.oldPosition !== "undefined" && Player.oldPosition.reason === "tag") {
// teleport them back to their old location because they were in the middle of a tag game (but have now left it)
Player.areaName = Player.oldPosition.area;
Player.x = Player.oldPosition.x;
Player.y = Player.oldPosition.y;
Player.oldPosition = undefined;
}
// load area and images
this.loadArea(Player.areaName, {x: Player.x, y: Player.y});
};
// load the player by setting the necessary variables (either from local storage or from template if class is new)
Game.loadPlayer = function () {
if (localStorage.getItem(Player.class) !== null) {
// load existing class
let savedPlayer = JSON.parse(localStorage.getItem(Player.class));
// add anything new that has been added in savedata to Player (fixees out of date properties)
savedPlayer.bossesKilled = Object.assign(Player.bossesKilled, savedPlayer.bossesKilled);
savedPlayer.stats = Object.assign(Player.stats, savedPlayer.stats);
savedPlayer.quests = Object.assign(Player.quests, savedPlayer.quests);
savedPlayer.reputation = Object.assign(Player.reputation, savedPlayer.reputation);
// update inventory:
savedPlayer.inventory = Object.assign(Player.inventory, savedPlayer.inventory);
if (Player.inventory.items[5].type === "bag" && typeof Player.inventory.bag.type === "undefined") { // put bag in bag slot
Player.inventory.bag = Player.inventory.items[5];
Player.inventory.items[5] = {};
}
// assign spells their functions (which will not have been saved in the json)
// TBD make saving only save the id and type, and load everything from spelldata/itemdata here
for (let i = 0; i < Player.spells.length; i++) {
let spellObj = Player.spells[i];
if (typeof spellObj.class !== "undefined") {
// spell exists
spellObj.func = Spells[spellObj.class][spellObj.id].func;
}
}
for (let i = 0; i < Player.spellArsenal.length; i++) {
let spellObj = Player.spellArsenal[i];
spellObj.func = Spells[spellObj.class][spellObj.id].func;
}
Player = Object.assign(Player, savedPlayer);
}
// the following are done based on selection screen, done here rather than savedata because they can be changed on each play
Player.name = playerName;
Player.race = Skins.skinTone[customisation.skinTone].race;
// customisation:
// replaces the skindata ids (stored in the variable customisation, which is set in savedata) with the file addresses from skindata
Player.skinTone = Skins.skinTone[customisation.skinTone].src;
Player.clothing = Skins[playerClassName+"Clothing"][customisation.clothing].src;
if (!Skins.beard[customisation.beard].blank) {
Player.beard = Skins.beard[customisation.beard].src + customisation.hairColour;
}
else {
Player.beard = Skins.beard[customisation.beard].src; // src is "null", so don't include colour
// tbd maybe don't draw the beard image at all if it's null?
}
if (!Skins.hair[customisation.hair].blank) {
Player.hair = Skins.hair[customisation.hair].src + customisation.hairColour;
}
else {
Player.hair = Skins.hair[customisation.hair].src; // src is "null", so don't include colour
// tbd maybe don't draw the hair image at all if it's null?
}
Player.hat = Skins.hat[customisation.hat].src;
// face is hard coded for now
if (Skins.skinTone[customisation.skinTone].race === "Orc") {
// orc face (with teeth etc)
Player.face = "baseOrc";
}
else {
Player.face = "base";
}
}
//
// WebSocket
//
var ws = false; // false means it has not been set (user is on local version)
Game.initWebSocket = function () {
this.hasConnectedToWebSocket = false;
// https://devcenter.heroku.com/articles/node-websockets
if (location.origin.includes("http")) {
// not on a local version
let hostURI = location.origin.replace(/^http/, "ws"); // websocket URI
ws = new WebSocket(hostURI);
// WebSocket functions
// connection established
ws.onopen = function () {
if (Game.hasConnectedToWebSocket) {
// was attempting to reconnect and has now connected
Dom.chat.insert("Successfully reconnected!");
}
else {
// first time connecting
Game.hasConnectedToWebSocket = true; // so it knows you have connected to websocket before
}
// send username so the user is saved under a particular name in the websocket
ws.send(JSON.stringify({
type: "userInformation",
name: Player.name,
class: Player.class,
level: Player.level,
area: Player.areaName,
displayArea: Player.displayAreaName,
x: Player.x,
y: Player.y,
direction: 3,
equipment: {
helm: Player.inventory.helm,
chest: Player.inventory.chest,
greaves: Player.inventory.greaves,
boots: Player.inventory.boots,
weapon: Player.inventory.weapon
},
achievementPoints: User.achievementPoints.total,
// customisation
skinTone: Player.skinTone,
face: Player.face,
clothing: Player.clothing,
hair: Player.hair,
beard: Player.beard,
//ears: Player.skinTone,
hat: Player.hat,
}));
// show other players online in chat (because player is connected to server)
Dom.chat.showPlayersOnline("show");
}
// message received
ws.onmessage = function (event) {
let message = JSON.parse(event.data);
switch (message.type) {
case "playerLocation":
// multiplayer player location
// find which player it is
let user;
if (Game.players !== undefined) { // check user has loaded enough to have loaded Game.players
for (let i = 0; i < Game.players.length; i++) {
if (Game.players[i].userID === message.userID) {
user = Game.players[i];
break;
}
}
}
// if user is undefined, either the user is not in the player's area or there has been an error
if (user !== undefined) {
let distanceTravelled = 0;
if (typeof user.x !== "undefined" && typeof user.y !== "undefined" && typeof message.x !== "undefined" && typeof message.y !== "undefined") {
distanceTravelled = Game.distance(user, message);
}
user.totalDistanceWalked += distanceTravelled; // for anim
user.x = message.x;
user.y = message.y;
if (message.direction !== user.direction) {
// direction changed
user.direction = message.direction;
user.updateRotation();
}
if (message.expand !== undefined && message.expand !== user.expand) {
// expand changed
user.setExpandZ(message.expand);
}
user.updateFootHitbox();
}
break;
case "userID":
// set ws.userID (i.e. for excepting oneself in some future broadcasts)
ws.userID = message.content;
break;
case "msg": // for private message from someone (the name being sender -> target is handled in server)
Dom.chat.replyTo = message.sender;
// no break because the same is done as chat for the rest
case "chat":
// do not allow user ta use < or > in chat (stop HTML injection)
let messageContent = message.content.replace(/[<>]/g, "");
// insert in chat
Dom.chat.insert(Dom.chat.say(message.name, messageContent));
// notification if user has given permission
if (message.sender !== undefined) {
// private message ("msg") - because message.name contains a unicode icon that does not display on notification, it should be changed
message.name = message.sender + " (private message)";
}
Dom.chat.notification(message.name, messageContent);
break;
case "info":
Dom.chat.insert(message.content);
break;
case "keepAlive":
// used to stop the connection dying after 55s (Heroku)
ws.send(JSON.stringify({
type: "keepAlive",
}));
break;
case "playersOnline":
// update display of players online in chat DOM
// message.action tells DOM what to update
Dom.chat.players(message, message.action); // passes in whole object
// update information in Game.players
// addPlayer checks if the player should be added to Game.players (e.g. if they are in right area)
switch (message.action) {
case "join":
case "retroactive":
Game.addPlayer(message);
break;
case "area":
// find the player from DOM and only add it if they have moved to the player's current area
if (message.area === Player.areaName) {
Game.addPlayerByID(message.userID);
}
else {
// if they used to be in the player's area, remove them
Game.removePlayerByID(message.userID);
}
break;
case "leave":
Game.removePlayerByID(message.userID);
break;
}
break;
case "ping":
// pong received (for server response time checking)
Dom.chat.insert(Dom.chat.say("Server", "Pong received from server in " + (Date.now()-message.content) + "ms."));
break;
case "trade":
switch (message.action) {
// trade requests
case "request":
// trade request received
// find player in Game.players for DOM currentNPC
let currentNPC;
for (let i = 0; i < Game.players.length; i++) {
if (Game.players[i].userID === message.userID) {
currentNPC = {
id: Game.players[i].id,
type: Game.players[i].type
};
}
}
if (currentNPC !== undefined) {
Dom.trade.requestReceived(message.userID, message.name, currentNPC);
Dom.chat.notification("You have received a trade request from " + message.name + ".");
}
else {
console.error("Trade request received from a player that isn't in the same area.")
}
break;
case "accept":
// trade accepted by user that player is waiting on to accept/decline
Dom.trade.page();
Dom.chat.notification("Your trade request with " + message.name + " has been accepted.");
break;
case "decline":
// trade declined by user that player is waiting on to accept/decline
Dom.currentlyDisplayed = "";
Dom.chat.insert("Your trade request with " + message.name + " has been declined.");
Dom.chat.notification("Your trade request with " + message.name + " has been declined.");
break;
case "busy":
// trade could not be started because the user requested was currently occupied
Dom.currentlyDisplayed = "";
Dom.chat.insert(message.name + " is currently busy doing something else. Come back later.");
break;
// trade page
case "update":
// other user's trade inventory is updated
Dom.trade.updateTheirInventory(message.content);
break;
case "confirm":
// trade confirmed by another user
Dom.trade.confirmOther();
Dom.chat.notification(message.name + " has confirmed the trade.");
break;
case "close":
// close trade (true = called by other person)
Dom.trade.close(true);
Dom.chat.insert(message.name + " has cancelled the trade.");
Dom.chat.notification(message.name + " has cancelled the trade.");
break;
case "walkAway":
// other player walked away
// if this player was off the tab, they would not have closed their page/alert/pending request
// so close it ...
if (Dom.trade.requested || Dom.trade.received || Dom.trade.active) {
Dom.closeNPCPages();
}
break;
}
break;
case "tagGame":
switch (message.action) {
case "request":
// invited to a tag game
// set current minigame variable even if player has not joined
Game.minigameInProgress = {
game: "tag",
area: message.area,
playing: false,
status: "starting",
immunePlayers: []
};
// find player who started game and update their playing game in DOm.players, and which areas they appear in
// find their full object
let initialJoinPlayer = Dom.players.find(player => player.userID === message.startedBy);
// update properties that Dom might not have had a chance to update
initialJoinPlayer.area = message.spawnArea;
// make other players know they joined the game ...
Game.tag.playerJoin(initialJoinPlayer);
// only ask them to join if their setting is on
if (Dom.elements.minigamesOn.checked) {
// alert to ask them if they want to join
Dom.alert.page("A game of tag has been started in " + message.displayAreaName + ". Would you like to join?", 2, undefined, undefined, {
target: Game.tag.join, // function to be called if they click yes
ev: [message.spawnArea, message.spawnX, message.spawnY], // parameters for function
});
// notifiction
Dom.chat.notification("A game of tag has been started in " + message.displayAreaName + ".");
}
break;
case "playerJoin":
// find their full object
let joinedPlayer = Dom.players.find(player => player.userID === message.userID);
// update properties that Dom might not have had a chance to update
joinedPlayer.area = message.area;
Game.tag.playerJoin(joinedPlayer);
break;
case "start":
// game started
Game.minigameInProgress.status = "started";
if (!Game.minigameInProgress.playing) {
// not playing
// close alert for people who still have it open
let alert = Dom.alert.array.find(alert => alert.target === Game.tag.join);
if (alert !== undefined) { // showing the function to join the game still (so the wrong one isn't closed by accident)
Dom.alert.close(alert.id);
Dom.chat.insert("You missed the start of the tag game :(");
}
}
else {
// playing game!
Dom.chat.insert("The game has started!");
// notifiction for if they're not on the tab
Dom.chat.notification("The game of tag has started!");
// length of game (displayed on infoBar by newTaggedPlayer)
Game.minigameInProgress.timeRemaining = TimeDisplay(message.gameLength);
// tagged player
Game.tag.newTaggedPlayer(message.taggedPlayer);
}
break;
case "taggedPlayer":
if (Game.minigameInProgress.playing) {
if (message.reason === "playerLeave") {
Dom.chat.insert("The currently tagged player left the game. A random player has been tagged instead.")
}
// new tagged player
Game.tag.newTaggedPlayer(message.taggedPlayer);
}
break;
case "timeRemaining":
// convert time to mm:ss format
Game.minigameInProgress.timeRemaining = TimeDisplay(message.content);
// update infobar time display
if (Game.minigameInProgress.status === "started") {
// just overwrite time to maintain other information
document.getElementById("tagTimeRemaining").innerHTML = Game.minigameInProgress.timeRemaining;
}
else {
// no other information - completely overwrite
Dom.infoBar.page(Game.minigameInProgress.timeRemaining + " until game start");
}
break;
case "finish":
// end of game
Game.minigameInProgress.status = "finished";
// show scores if they were in game
if (Game.minigameInProgress.playing) {
Game.tag.finish(message.leaderboardData);
}
// hide infobar
Dom.infoBar.page("");
break;
case "fizzle":
// game couldn't start properly due to not enough players
// close alert for people who still have it open
if (!Game.minigameInProgress.playing) {
// not playing
// close alert if it wasn't already closed
let alert = Dom.alert.array.find(alert => alert.target === Game.tag.join);
if (alert !== undefined) { // showing the function to join the game still (checked so the wrong one isn't closed by accident)
Dom.alert.close(alert.id);
}
}
else {
// return player that started game back to their initial location
Game.hero.temporaryAreaTeleportReturn();
if (message.returnGauntlet) {
// user that is still in game is host
Dom.inventory.give(Items.consumable[22]);
}
else {
Dom.chat.insert("There were not enough players to start the game because the game host left.");
}
Dom.chat.notification("There were not enough players to start the game."); // in case they were not on the tab
}
// hide infobar
Dom.infoBar.page("");
// reset minigameInProgress
Game.minigameReset();
break;
case "close":
// tag game closed
if (Game.minigameInProgress.playing) {
// clear firework interval
Game.clearInterval(Game.tag.fireworkWinnerInterval);
Game.hero.temporaryAreaTeleportReturn();
}
Game.minigameReset();
case "retroactive":
// information received about it on player join
// users in tag game is received by playersOnline
Game.minigameInProgress = {
game: "tag",
area: message.area,
playing: false,
status: message.status
};
}
break;
default:
console.error("Message type " + message.type + " is not recognised");
}
};
ws.onerror = function (event) {
console.error("WebSocket error observed:", event);
};
// user disconnected (readyState has been set to 3)
ws.onclose = function (event) {
// offline
// remove all existing players in the area
Dom.players = [];
if (Game.players !== undefined) {
for (let i = 0; i < Game.players.length; i++) {
Game.removeObject(Game.players[i].id, "players", i);
}
}
if (Game.hasConnectedToWebSocket) {
// if they have connected before to the websocket (thus a possible connection exists), try to reconnect them
// if the reconnect fails, this will be called again straight away
Dom.chat.showPlayersOnline("reconnecting");
Dom.chat.insert("You lost connection to the websocket. Attempting to reconnect in 5 seconds.");
// reset websocket
ws = false;
// try to reconnect in 5 seconds
Game.setTimeout(Game.initWebSocket, 5000)
}
else {
// websocket hasn't connected before - we can assume a 404 error because they are on a single player version
Dom.chat.showPlayersOnline("hide");
}
};
}
else {
console.info("Playing on a local version. Multiplayer features are not available.");
// hide option for notifications
Dom.elements.settingNotifsHolder.innerHTML = "";
}
}
// for adding another player to Game.players and checking the conditions required
Game.addPlayer = function (player) {
// if players is undefined, don't add player (because the player will be added anyway from Dom.players when Game.players is defined in loadArea)
// if players IS defined and is receiving retroactive player additions (action="retroactive"), this must mean that they were sent after loadArea (where Dom.players had nothing anyway)
if (this.players !== undefined) {
// deep copy player (because it could have come from Dom.players)
let copiedPlayer = Object.assign({}, player);
let addPlayer = true; // if set to false do not add the npc
if (copiedPlayer.area !== Player.areaName) {
// player is not in same area
addPlayer = false;
}
else if (copiedPlayer.userID === ws.userID) {
// player is Game.hero
addPlayer = false;
}
else if (this.minigameInProgress !== undefined && // minigame in progress
((this.minigameInProgress.playing && copiedPlayer.playingGame === undefined) || // you're in game but they're not playing
(!this.minigameInProgress.playing && copiedPlayer.playingGame !== undefined))) { // you're not in game but they are
addPlayer = false;
}
if (addPlayer) {
// check the player has not already been added
let playerAlreadyAdded = this.players.findIndex(existingPlayer => existingPlayer.userID === copiedPlayer.userID);
copiedPlayer = this.prepareNPC(copiedPlayer, "players");
if (playerAlreadyAdded === -1 && copiedPlayer !== false) {
// object properties (to stop attacker breaking)
copiedPlayer.stats = {};
copiedPlayer.stats.maxHealth = 50 + (copiedPlayer.level-1) * 5;
copiedPlayer.projectile = {};
// name colour
if (this.minigameInProgress !== undefined && this.minigameInProgress.playing && this.minigameInProgress.taggedPlayer === copiedPlayer.userID) {
// tagged in minigame that user is playing
copiedPlayer.hostility = "gameHostile";
}
else {
copiedPlayer.hostility = "friendly";
}
copiedPlayer.animation = {
type: "spritesheet",
frameTime: 18,
imagesPerRow: 4,
totalImages: 4,
animateBasis: "walk"
}
copiedPlayer.spritesheetRotate = true,
// add the player
// tbd the images should be loaded first THEN the player object should be added ??
this.players.push(new UserControllable(copiedPlayer));
let addedPlayer = this.players[this.players.length-1];
// load its image
Promise.all(addedPlayer.init()).then(function () {
// set the image
addedPlayer.setImage("playerSkin_"+addedPlayer.skinTone, {
x: 0,
y: 0,
width: 52,
height: 127
});
addedPlayer.setAdditionalImages([{imageName: "playerFace_"+addedPlayer.face, doNotAnimate: true}, {imageName: "playerClothing_"+addedPlayer.clothing}, {imageName: "playerBeard_"+addedPlayer.beard, doNotAnimate: true}, {imageName: "playerHair_"+addedPlayer.hair, doNotAnimate: true}, {imageName: "playerEars_"+addedPlayer.skinTone, doNotAnimate: true}, {imageName: "playerHat_"+addedPlayer.hat, doNotAnimate: true}]);
addedPlayer.updateRotation();
// allow player to be shown
addedPlayer.hidden = false;
});
}
}
}
}
Game.addPlayerByID = function (userID) {
let player = Dom.players.find(player => player.userID === userID);
this.addPlayer(player);
}
// player does not necessarily need to exist - this function checks that they do first
Game.removePlayerByID = function (userID) {
let player = this.players.find(player => player.userID === userID);
if (player !== undefined) {
// a player in the area should be removed
this.removeObject(player.id, "players");
}
}
// get a player's object in Game (i.e. in the same area) from their user id
Game.getPlayerFromID = function (userID) {
if (ws.userID === userID) {
// player is this player
// must be checked separately because they are not in Game.players
return Game.hero;
}
else {
return this.players.find(player => player.userID === userID);
}
}
//
// Start up function
//
window.onload = function () {
let context = Game.canvas.getContext('2d');
let contextSecondary = Game.secondary.canvas.getContext('2d');
let contextDayNight = Game.canvasDayNight.getContext('2d');
let contextLight = Game.canvasLight.getContext('2d');
Game.run(context, contextSecondary, contextDayNight, contextLight);
};
//
// Map
//
// Information about how the map origin works:
// columns/rows are always considered as being from 0 to the number of columns
// so getting coordinates from columns needs to involve the origin
// origin should only be used by map functions when dealing with convering columns (i.e. in a for loop, or from getCol) to coordinates
// OR when dealing with camera / player clamping (i.e. the limit coordinates)
// ctrl-f to find all the uses of map.origin if confused !
var map = {
// validate that row/col exist on the map
// if they do not, return the closest existing row/col
validateCol: function (col) {
if (col < 0) {
return 0;
}
if (col >= this.cols) {
return this.cols-1;
}
return col;
},
validateRow: function (row) {
if (row < 0) {
return 0;
}
if (row >= this.rows) {
return this.rows-1;
}
return row;
},
getTile: function (layer, col, row) {
col = this.validateCol(col);
row = this.validateRow(row);
return this.layers[layer][row * map.cols + col];
},
// gets tiles of all layers at location, returning an array
getTiles: function (col, row) {
col = this.validateCol(col);
row = this.validateRow(row);
let tileArray = [];
for (let layer = 0; layer < this.layers.length; layer++) {
tileArray.push(this.getTile(layer, col, row));
}
return tileArray;
},
getCol: function (x) {
let col = Math.floor((x+this.origin.x) / this.tsize);
return this.validateCol(col);
},
getRow: function (y) {
let row = Math.floor((y+this.origin.y) / this.tsize);
return this.validateRow(row);
},
// top/left of tile
getX: function (col) {
col = this.validateCol(col);
return col * this.tsize - this.origin.x;
},
getY: function (row) {
row = this.validateRow(row);
return row * this.tsize - this.origin.y;
},
isSolidTileAtXY: function (x, y) {
let col = this.getCol(x);
let row = this.getRow(y);
let isSolid = false; // set to true if any tile is unpassable (on any layer)
// loop through all layers and return TRUE if any tile is solid
for (let layer = 0; layer < this.layers.length; layer++) {
let tile = this.getTile(layer, col, row);
if (typeof this.solidTiles !== "undefined") { // check that this map contains solidTiles
for (let i = 0; i < this.solidTiles.length; i++) {
// looping through solid tiles
if (tile === this.solidTiles[i]) {
// solid tile found
isSolid = true;
break;
}
}
}
}
return isSolid;
},
isSlowTileAtXY: function (x, y) {
let col = this.getCol(x);
let row = this.getRow(y);
// find layer to check - we want the highest layer with a non-transparent tile
let layer = this.layers.length - 1;
let foundLayer = false;
while(layer >= 1 && !foundLayer) {
let tileNum = this.getTile(layer, col, row);
if (tileNum !== 0 && !this.transparentTiles.includes(tileNum)) {
// this is the tile we are considering! (i.e. highest up in player's view)
foundLayer = true;
}
else {
layer--;
}
}
// check first layer only and return TRUE if any tile is a slowing tile
let tile = this.getTile(layer, col, row);
let isSlow = null; // set to a string for any slow/fast tile being touched
// move slower in water
if (typeof this.waterTiles !== "undefined") { // check that this map contains waterTiles
for (let i = 0; i < this.waterTiles.length; i++) {
if (tile === this.waterTiles[i]) {
// water tile found
isSlow = "water";
break;
}
}
}
// move slower in mud
if (typeof this.mudTiles !== "undefined") {
for (let i = 0; i < this.mudTiles.length; i++) {
if (tile === this.mudTiles[i]) {
// mud tile found
isSlow = "mud";
break;
}
}
}
// move faster on ice
if (typeof this.iceTiles !== "undefined") {
for (let i = 0; i < this.iceTiles.length; i++) {
if (tile === this.iceTiles[i]) {
// ice tile found
isSlow = "ice";
break;
}
}
}
// move faster on paths
if (typeof this.pathTiles !== "undefined") {
for (let i = 0; i < this.pathTiles.length; i++) {
if (tile === this.pathTiles[i]) {
// path tile found
isSlow = "path";
break;
}
}
}
// some tiles are irrespective of layer !
let tileArray = this.getTiles(col, row);
// move slower in tall grass
if (typeof this.tallGrassBottoms !== "undefined") {
for (let i = 0; i < this.tallGrassBottoms.length; i++) {
if (tileArray.includes(this.tallGrassBottoms[i])) {
// tall grass found
isSlow = "tallGrass";
break;
}
}
}
// move slower and require air when underwater
if (typeof this.underwaterTiles !== "undefined") { // check that this map contains waterTiles
for (let i = 0; i < this.underwaterTiles.length; i++) {
if (tileArray.includes(this.underwaterTiles[i])) {
// water tile found
isSlow = "underwater";
break;
}
}
}
return isSlow;
},
setTile: function (layer, col, row, newTileNum) {
this.layers[layer][row * map.cols + col] = newTileNum;
},
// set tiles to day or night versions (called on time update by weather interval)
setDayNightTiles: function () {
// tiles changed to night versions if darkness > 0.2 (due to weather or night)
if (this.nightTiles !== undefined) {
// tiles to be changed
if (this.nightTiles.length === this.dayTiles.length) {
// iterate through tiles to replace
for (let replaceIndex = 0; replaceIndex < this.nightTiles.length; replaceIndex++) {
// iterate through layers
for (let layer = 0; layer < this.layers.length; layer++) {
// iterate through area's tiles to find those that need replacing
for (let tileIndex = 0; tileIndex < this.layers[layer].length; tileIndex++) {
// check day or night versions
if (Event.darkness >= 0.2) {
// night time
if (this.layers[layer][tileIndex] === this.dayTiles[replaceIndex]) {
// tile needs replacing
this.layers[layer][tileIndex] = this.nightTiles[replaceIndex];
}
}
else {
// day time
if (this.layers[layer][tileIndex] === this.nightTiles[replaceIndex]) {
// tile needs replacing
this.layers[layer][tileIndex] = this.dayTiles[replaceIndex];
}
}
}
}
}
}
else {
console.error("dayTiles and nightTiles should have the same length in areadata.js for area " + areaName + ", but do not");
}
}
},
// animates tiles based on this.animateTiles
initTileAnimation: function () {
// clear intervals from last time
if (Array.isArray(this.tileAnimationIntervals)) {
for (let i = 0; i < this.tileAnimationIntervals.length; i++) {
Game.clearInterval(this.tileAnimationIntervals[i]);
}
}
this.tileAnimationIntervals = [];
// set new intervals if there are tiles to be animated
if (this.animateTiles !== undefined) {
for (let animateIndex = 0; animateIndex < this.animateTiles.length; animateIndex++) {
let animateObj = this.animateTiles[animateIndex];
if (typeof animateObj.animateCondition === "undefined" || animateObj.animateCondition()) {
if (animateObj.requireContinuity) {
// these tiles should be animated at all moments, even if not shown on the screen, in order to preserve continuity between tiles !
// find the location of all tiles to be animated
// animateTilesLocations[animateIndex] contains all
animateObj.tileLocations = [];
for (let layer = 0; layer < this.layers.length; layer++) {
for (let c = 0; c <= this.cols; c++) {
for (let r = 0; r <= this.rows; r++) {
let tileNum = map.getTile(layer, c, r); // tile number
// see if tile should be animated due to appearing in animateObj
let index = animateObj.tiles.findIndex(tile => tile === tileNum);
if (index >= 0) {
// tile should be animated!
animateObj.tileLocations.push({layer: layer, col: c, row: r});
}
}
}
}
}
let intervalNumber = Game.setInterval(this.animateTilesFunction.bind(this), this.animateTiles[animateIndex].animateTime, [animateIndex]);
this.tileAnimationIntervals.push(intervalNumber);
this.animateTiles[animateIndex].intervalNumber = intervalNumber;
}
}
}
},
// animates tiles based on this.animateTiles
// called by intervals set by initTileAnimation
// parameter is the index to be animated of the array map.animateTimes
// if requireContinuity is true for this animateIndex, all tiles in the area are animated
// otherwise, just those on the screen are animated
animateTilesFunction: function(animateIndex) {
let animateObj = this.animateTiles[animateIndex];
if (animateObj.requireContinuity) {
// all tiles in the area are animated - an array of their locations was generated in map.initTileAnimation
for (let i = 0; i < animateObj.tileLocations.length; i++) {
let tileLocation = animateObj.tileLocations[i];
let tileNum = this.getTile(tileLocation.layer, tileLocation.col, tileLocation.row);
// find new value of tile
let index = animateObj.tiles.findIndex(tile => tile === tileNum);
if (index >= 0) {
index++;
if (index === animateObj.tiles.length) {
// wrap around to start of animate array
index = 0;
}
// set the tile
// could use map.setTile? not sure if necessary
this.setTile(tileLocation.layer, tileLocation.col, tileLocation.row, animateObj.tiles[index]);
}
else {
console.error("Tile was in tileLocations, but does not have a tileNum that should be animated",animateObj)
}
}
}