forked from steveseguin/social_stream
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbattle.html
1285 lines (1107 loc) · 39.2 KB
/
battle.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Battle Royale - Social Stream Ninja</title>
<meta name="title" content="Battle Royale - Social Stream Ninja" />
<link rel="icon" href="./icons/favicon.ico" />
<style>
body {
margin: 0;
padding: 0;
background-color: green;
overflow: hidden;
}
#game-container {
position: relative;
width: 100vw;
height: 100vh;
}
#game-canvas {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
image-rendering: pixelated;
}
#ui-overlay {
position: absolute;
top: 10px;
left: 10px;
font-family: 'Courier New', monospace;
font-size: 24px;
color: #fff;
text-shadow: 2px 2px #000;
}
#timer {
font-size: 36px;
font-weight: bold;
}
.hidden {
opacity:0!important;
display:none!important;
}
</style>
</head>
<body>
<div id="game-container">
<canvas id="game-canvas"></canvas>
<div id="ui-overlay">
<div id="timer">--</div>
<div id="player-count">Players: 0</div>
<div id="rules">Type !join to play</div>
</div>
</div>
<script>
window.onerror = function backupErr(errorMsg, url=false, lineNumber=false) {
console.error(errorMsg);
console.error(lineNumber);
console.error("Unhandled Error occured");
return false;
};
function getById(id) {
var el = document.getElementById(id);
if (!el) {
el = document.createElement("span");
}
return el;
}
(function (w) {
w.URLSearchParams = w.URLSearchParams || function (searchString) {
var self = this;
self.searchString = searchString;
self.get = function (name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(self.searchString);
if (results == null) {
return null;
} else {
return decodeURI(results[1]) || 0;
}
};
};
})(window);
var urlParams = new URLSearchParams(window.location.search);
try {
if (electronApi){ // fix for electron dragging.
document.body.style.width = "95%";
setTimeout(function(){
document.body.style.width = "100%";
},1000);
setTimeout(function(){
document.body.style.width = "98%";
},2000);
setTimeout(function(){
document.body.style.width = "100%";
},5000);
}
} catch(e){
}
var roomID = "test";
if (urlParams.has("session")){
roomID = urlParams.get("session");
} else if (urlParams.has("s")){
roomID = urlParams.get("s");
} else if (urlParams.has("id")){
roomID = urlParams.get("id");
} else if (window.location.protocol=="file:"){
roomID = prompt("Enter your session ID here, or add it to the URL.");
if (roomID){
var href = window.location.href;
var arr = href.split('?');
var newurl;
if (arr.length > 1 && arr[1] !== '') {
newurl = href + '&session=' + roomID;
} else {
newurl = href + '?session=' + roomID;
}
window.history.pushState({path: newurl.toString()}, '', newurl.toString());
} else {
alert("You need to provide your extension's session ID for this page to work");
}
} else {
window.location.href = "https://github.com/steveseguin/live-chat-overlay#readme";
}
var password = "false";
if (urlParams.has("password")){
password = urlParams.get("password") || "false";
}
var addComputers = true;
if (urlParams.has("nocomputers")){
addComputers = false;
}
var lobbyTimeInit = 10;
if (urlParams.has("lobbytime")) {
lobbyTimeInit = parseInt(urlParams.get("lobbytime"));
}
let hostControlled = urlParams.has("lobby");
let lobbyDuration = lobbyTimeInit // Default lobby duration in seconds
let lobbyTimer = null;
let isFirstGame = true;
let topPlayers = null;
function drawLobby() {
// Draw grass background
ctx.fillStyle = grassPattern;
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Add semi-transparent overlay
ctx.fillStyle = 'rgba(0, 0, 0, 0.3)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Calculate font sizes based on canvas width
const titleFontSize = Math.max(24, Math.floor(canvas.width / 20));
const textFontSize = Math.max(16, Math.floor(canvas.width / 40));
const textFontSizeSmall = Math.max(12, Math.floor(canvas.width / 60));
// Set up text styles
ctx.fillStyle = '#fff';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
// Draw title
ctx.font = `bold ${titleFontSize}px Arial`;
ctx.fillText('Waiting for players', canvas.width / 2, canvas.height * 0.3);
// Draw player count
ctx.font = `${textFontSizeSmall}px Arial`;
ctx.fillText(`Players in lobby: ${players.size}`, canvas.width / 2, canvas.height * 0.5);
// Draw instructions
ctx.font = `${textFontSize}px Arial`;
ctx.fillText('Type !join to enter the game', canvas.width / 2, canvas.height * 0.6);
// Draw countdown if not host controlled
if (!hostControlled) {
ctx.font = `${textFontSizeSmall}px Arial`;
ctx.fillText(`Game starts in ${lobbyDuration} seconds`, canvas.width / 2, canvas.height * 0.7);
}
}
function enterLobby() {
gameOver = true;
players.clear();
document.getElementById("ui-overlay").classList.add("hidden");
players.clear();
updatePlayerCount();
if (!hostControlled) {
startLobbyCountdown();
} else {
drawLobby();
}
}
function startLobbyCountdown() {
lobbyDuration = lobbyTimeInit;
if (lobbyDuration <= 0) {
startGame();
return;
}
if (isFirstGame && !urlParams.has("lobbytime")){
lobbyDuration+=5;
}
drawLobby();
clearInterval(lobbyTimer);
lobbyTimer = setInterval(() => {
lobbyDuration--;
if (lobbyDuration <= 0) {
clearInterval(lobbyTimer);
startGame();
} else {
drawLobby();
}
}, 1000);
}
function processData(data) {
if (data && data.chatmessage && data.chatname) {
if (data.chatmessage.toLowerCase().startsWith("!join")) {
if (!players.get(data.chatname)) {
const parts = data.chatmessage.toLowerCase().split(" ");
let weaponType = null;
if (parts.length > 1) {
const classInput = parts[1];
switch (classInput) {
case "sword":
case "shield":
case "swordshield":
case "sword_shield":
weaponType = "sword_shield";
break;
case "axe":
case "twohandedaxe":
case "two_handed_axe":
weaponType = "two_handed_axe";
break;
case "spear":
case "longspear":
case "long_spear":
weaponType = "long_spear";
break;
case "bow":
case "arrow":
case "bowarrow":
case "bow_arrow":
weaponType = "bow_arrow";
break;
default:
weaponType = null; // Random selection
}
}
addPlayer(data.chatname, data.chatimg, data.type, data.nameColor, weaponType);
}
} else if (data.chatmessage.startsWith("!say ")) {
if (players.get(data.chatname)) {
handleChatMessage(data.chatname, data.chatmessage.split("!say ")[1]);
}
}
}
}
function processInput(data){
if (data.startgame && hostControlled) {
startGame();
return;
} else if ("mid" in data){
return;
} else if ("pin" in data){
return;
} else if ("unpin" in data){
return;
} else if ("queueInit" in data){
return;
} else if ("queue" in data){
return;
} else if ("deleteMessage" in data){
return;
}
if (data.action){
} else if ("forward" in data){
} else if ("html" in data){
} else if (data.content){
processData(data.content);
} else {
processData(data );
}
}
var iframe = document.createElement("iframe"); // we can leave it called "dock", as it will get all the same messages the dock gets. This could be optimized of course..
iframe.src = "https://vdo.socialstream.ninja/?ln&salt=vdo.ninja¬mobile¬mobile&password="+password+"&solo&view="+roomID+"&novideo&noaudio&label=dock&cleanoutput&room="+roomID; // view only connection (data two way of course)
iframe.style.width = "0px";
iframe.style.height = "0px";
iframe.style.position = "fixed";
iframe.style.left = "-100px";
iframe.style.top = "-100px";
iframe.id = "frame1"
document.body.appendChild(iframe);
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod === "attachEvent" ? "onmessage" : "message";
eventer(messageEvent, function (e) {
if (e.source != iframe.contentWindow){return} // reject messages send from other iframes
if ("dataReceived" in e.data){ // raw data
if ("overlayNinja" in e.data.dataReceived){
processInput(e.data.dataReceived.overlayNinja);
}
}
});
const canvas = document.getElementById('game-canvas');
const ctx = canvas.getContext('2d');
let timeLeft = 20;
const timerElement = document.getElementById('timer');
timerElement.textContent = timeLeft;
const playerCountElement = document.getElementById('player-count');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const TILE_SIZE = 32;
const GRID_WIDTH = Math.floor(canvas.width / TILE_SIZE);
const GRID_HEIGHT = Math.floor(canvas.height / TILE_SIZE);
const COMBAT_RANGE_BASE = 10; // Base combat range in tiles
const DENSITY_THRESHOLD = 0.1; // Players per tile threshold for adjusting combat range
const WEAPONS = ['sword_shield', 'two_handed_axe', 'long_spear', 'bow_arrow'];
const arrows = [];
const ARROW_SPEED = 0.2;
const players = new Map();
const POWERUPS = ['speed', 'invincibility', 'regen', 'damage'];
const powerUps = [];
const obstacles = [];
let countdownTimer = null;
let countdownSeconds = 0;
var killed = {};
let gameOver = false;
let scoreboardData = null;
function spawnPowerUps() {
if (Math.random() < 0.005 && powerUps.length < 5) {
const x = Math.floor(Math.random() * GRID_WIDTH);
const y = Math.floor(Math.random() * GRID_HEIGHT);
const type = POWERUPS[Math.floor(Math.random() * POWERUPS.length)];
powerUps.push({ x, y, type });
}
}
function spawnObstacles() {
if (Math.random() < 0.002 && obstacles.length < 10) {
const x = Math.floor(Math.random() * GRID_WIDTH);
const y = Math.floor(Math.random() * GRID_HEIGHT);
obstacles.push({ x, y });
}
}
function checkPowerUpCollisions() {
players.forEach(player => {
if (!player.isAlive) return;
const playerX = Math.floor(player.x);
const playerY = Math.floor(player.y);
for (let i = powerUps.length - 1; i >= 0; i--) {
const powerUp = powerUps[i];
if (playerX === powerUp.x && playerY === powerUp.y) {
applyPowerUp(player, powerUp.type);
powerUps.splice(i, 1);
}
}
});
}
function checkObstacleCollisions() {
players.forEach(player => {
if (!player.isAlive) return;
const playerX = Math.floor(player.x);
const playerY = Math.floor(player.y);
obstacles.forEach(obstacle => {
if (playerX === obstacle.x && playerY === obstacle.y) {
player.speed *= 0.5; // Slow down the player
setTimeout(() => {
player.speed /= 0.5; // Restore normal speed after 3 seconds
}, 3000);
}
});
});
}
function applyPowerUp(player, type) {
switch (type) {
case 'speed':
player.speed *= 1.5;
setTimeout(() => {
player.speed /= 1.5;
}, 5000);
break;
case 'invincibility':
player.invincible = true;
setTimeout(() => {
player.invincible = false;
}, 5000);
break;
case 'regen':
player.healthRegenRate *= 3;
setTimeout(() => {
player.healthRegenRate /= 3;
}, 5000);
break;
case 'damage':
player.damageMultiplier = 1.5;
setTimeout(() => {
player.damageMultiplier = 1;
}, 5000);
break;
}
}
function createGrassPattern() {
const patternCanvas = document.createElement('canvas');
const patternCtx = patternCanvas.getContext('2d');
patternCanvas.width = 1000;
patternCanvas.height = 1000;
// Base grass color
patternCtx.fillStyle = '#228B22';
patternCtx.fillRect(0, 0, 1000, 1000);
// Add random grass blades
for (let i = 0; i < 20000; i++) {
patternCtx.strokeStyle = `rgb(${30 + Math.random() * 30}, ${100 + Math.random() * 50}, ${30 + Math.random() * 30})`;
patternCtx.beginPath();
const x = Math.random() * 1000;
const y = Math.random() * 1000;
patternCtx.moveTo(x, y);
patternCtx.lineTo(x + (Math.random() - 0.5) * 10, y + (Math.random() * 10) + 5);
patternCtx.stroke();
}
// Add some darker patches
for (let i = 0; i < 2000; i++) {
patternCtx.fillStyle = 'rgba(0, 50, 0, 0.02)';
patternCtx.beginPath();
patternCtx.arc(Math.random() * 1000, Math.random() * 1000, Math.random() * 10 + 5, 0, Math.PI * 2);
patternCtx.fill();
}
// Add stones
for (let i = 0; i < 25; i++) {
patternCtx.fillStyle = `rgb(${150 + Math.random() * 50}, ${150 + Math.random() * 50}, ${150 + Math.random() * 50})`;
patternCtx.beginPath();
patternCtx.arc(Math.random() * 1000, Math.random() * 1000, Math.random() * 3 + 1, 0, Math.PI * 2);
patternCtx.fill();
}
// Add weeds/flowers
for (let i = 0; i < 3; i++) {
const x = Math.random() * 1000;
const y = Math.random() * 1000;
patternCtx.fillStyle = 'yellow';
patternCtx.beginPath();
patternCtx.arc(x, y, 2, 0, Math.PI * 2);
patternCtx.fill();
patternCtx.strokeStyle = 'darkgreen';
patternCtx.beginPath();
patternCtx.moveTo(x, y);
patternCtx.lineTo(x, y + 5);
patternCtx.stroke();
}
return ctx.createPattern(patternCanvas, 'repeat');
}
const grassPattern = createGrassPattern();
const weaponStats = {
sword_shield: { attackDelay: 1000, attackSpeed: 1250, damage: 20, absorption: 0.5, range: 1 },
two_handed_axe: { attackDelay: 400, attackSpeed: 1800, damage: 40, absorption: 0, range: 1.2 },
long_spear: { attackDelay: 0, attackSpeed: 1400, damage: 18, absorption: 0.3, range: 2.2 },
bow_arrow: { attackDelay: 100, attackSpeed: 800, damage: 15, absorption: 0.1, range: 10 }
};
const combatMatrix = {
sword_shield: { sword_shield: 1.0, two_handed_axe: 1.4, long_spear: 0.7, bow_arrow: 1.0 },
two_handed_axe: { sword_shield: 0.8, two_handed_axe: 1.0, long_spear: 1.2, bow_arrow: 1.1 },
long_spear: { sword_shield: 1.4, two_handed_axe: 0.8, long_spear: 1.0, bow_arrow: 0.9 },
bow_arrow: { sword_shield: 1.6, two_handed_axe: 1.0, long_spear: 0.7, bow_arrow: 1.2 }
};
class Player {
constructor(name, x, y, weaponType) {
this.name = name;
this.x = x;
this.y = y;
this.weapon = weaponType;
this.health = 100;
this.kills = 0;
this.direction = Math.random() * Math.PI * 2;
this.color = `hsl(${Math.random() * 360}, 100%, 50%)`;
this.speed = 0.05;
this.inCombat = false;
this.nameColor = false;
this.animationFrame = 0;
this.joinTime = Date.now();
this.lastAttackTime = 0;
this.attackAnimationFrame = 0;
this.bloodSplatter = 0;
this.isAlive = true;
this.healthRegenRate = 0.04; // Health regen per frame
this.firstAttack = true;
this.message = null;
this.messageTimer = 0;
this.avatarImage = null;
this.avatarLoaded = false;
this.invincible = false;
this.damageMultiplier = 1;
}
setAvatar(imageUrl) {
this.avatarImage = new Image();
this.avatarImage.onload = () => {
this.avatarLoaded = true;
};
this.avatarImage.onerror = () => {
console.error(`Failed to load avatar for ${this.name}`);
this.avatarImage = null;
};
this.avatarImage.src = imageUrl;
}
setNameColor(color) {
this.nameColor = color;
}
setMessage(msg) {
if (this.isAlive && msg.length <= 50) {
this.message = msg;
this.messageTimer = 10000; // Message will display for 5 seconds
}
}
update() {
if (!this.isAlive) {
this.message = null;
return;
}
if (!this.inCombat && this.health < 100) {
this.health = Math.min(100, this.health + this.healthRegenRate);
}
if (!this.inCombat) {
this.x += Math.cos(this.direction) * this.speed;
this.y += Math.sin(this.direction) * this.speed;
if (this.x < 0 || this.x > GRID_WIDTH - 1) {
this.direction = Math.PI - this.direction;
}
if (this.y < 0 || this.y > GRID_HEIGHT - 1) {
this.direction = -this.direction;
}
this.x = Math.max(0, Math.min(GRID_WIDTH - 1, this.x));
this.y = Math.max(0, Math.min(GRID_HEIGHT - 1, this.y));
if (Math.random() < 0.005) {
this.direction = (this.direction + (Math.random() * Math.PI * 2 * 0.03)) % (Math.PI * 2);
}
}
if (this.messageTimer > 0) {
this.messageTimer -= 16; // Assuming 60 FPS, each frame is about 16ms
if (this.messageTimer <= 0) {
this.message = null;
}
}
this.animationFrame = (this.animationFrame + 1) % 60;
}
draw() {
const x = this.x * TILE_SIZE;
const y = this.y * TILE_SIZE;
ctx.globalAlpha = this.isAlive ? 1 : 0.5;
// Draw body
ctx.fillStyle = this.isAlive ? '#000000' : '#CCCCCC';
ctx.fillRect(x + 6, y + 10, 20, 20);
// Draw legs
const legOffset = this.isAlive ? Math.sin(this.animationFrame * 0.2) * 2 : 0;
ctx.fillRect(x + 8, y + 30 + legOffset, 6, 12);
ctx.fillRect(x + 18, y + 30 - legOffset, 6, 12);
// Draw head (avatar or colored box)
if (this.avatarLoaded && this.avatarImage) {
ctx.save();
ctx.beginPath();
ctx.rect(x + 6, y, 20, 20);
ctx.clip();
ctx.drawImage(this.avatarImage, x + 6, y, 20, 20);
ctx.restore();
} else {
ctx.fillStyle = this.isAlive ? this.color : '#FFFFFF';
ctx.fillRect(x + 6, y, 20, 20);
}
// Draw weapon
this.drawWeapon(x, y);
if (this.invincible) {
ctx.strokeStyle = 'purple';
ctx.lineWidth = 2;
ctx.strokeRect(x, y, TILE_SIZE, TILE_SIZE);
this.bloodSplatter = 0;
} else if (this.bloodSplatter > 0) { // Draw blood splatter
ctx.fillStyle = `rgba(255, 0, 0, ${this.bloodSplatter / 100})`;
ctx.fillRect(x, y, TILE_SIZE, TILE_SIZE);
this.bloodSplatter -= 0.5;
}
if (this.damageMultiplier > 1) {
ctx.fillStyle = 'rgba(255, 0, 0, 0.3)';
ctx.fillRect(x, y, TILE_SIZE, TILE_SIZE);
}
ctx.font = '12px Arial';
if (this.nameColor){
ctx.strokeStyle = this.nameColor;
ctx.strokeText(this.name, x, y - 5);
}
ctx.fillStyle = '#fff';
ctx.fillText(this.name, x, y - 5);
ctx.strokeStyle = "black";
// Draw health bar
ctx.fillStyle = 'red';
ctx.fillRect(x, y - 24, 32, 5);
ctx.fillStyle = 'green';
ctx.fillRect(x, y - 24, 32 * (this.health / 100), 5);
if (this.message) {
const x = this.x * TILE_SIZE;
const y = this.y * TILE_SIZE;
ctx.fillStyle = 'white';
ctx.font = '12px Arial';
ctx.textAlign = 'center';
ctx.lineWidth = 3;
ctx.strokeText(this.message, x + TILE_SIZE / 2, y - 25);
ctx.fillText(this.message, x + TILE_SIZE / 2, y - 25);
}
ctx.globalAlpha = 1;
}
drawWeapon(x, y) {
ctx.fillStyle = this.isAlive ? '#888888' : '#CCCCCC';
const weaponOffset = this.inCombat ? Math.sin(this.attackAnimationFrame * 0.2) * 10 : 0;
switch (this.weapon) {
case 'sword_shield':
// Draw sword
ctx.fillRect(x + 26 + weaponOffset, y + 15, 4, 15);
// Draw shield
ctx.fillStyle = this.isAlive ? '#A0522D' : '#CCCCCC';
ctx.fillRect(x - 2 - weaponOffset/2, y + 15, 6, 20);
break;
case 'two_handed_axe':
// Draw axe handle
ctx.fillStyle = this.isAlive ? '#8B4513' : '#CCCCCC';
ctx.fillRect(x + 26 + weaponOffset, y + 10, 4, 20);
// Draw axe head
ctx.fillStyle = this.isAlive ? '#888888' : '#CCCCCC';
ctx.beginPath();
ctx.moveTo(x + 28 + weaponOffset, y + 10);
ctx.lineTo(x + 38 + weaponOffset, y + 5);
ctx.lineTo(x + 38 + weaponOffset, y + 15);
ctx.moveTo(x + 28 + weaponOffset, y + 10);
ctx.closePath();
ctx.fill();
break;
case 'long_spear':
// Draw spear
ctx.fillStyle = this.isAlive ? '#8B4513' : '#CCCCCC';
ctx.fillRect(x + weaponOffset*2 - 5, y + 18, 50, 2);
// Draw spearhead
//ctx.fillStyle = this.isAlive ? '#888888' : '#CCCCCC';
//ctx.beginPath();
//ctx.moveTo(x + weaponOffset*2 , y +13);
//ctx.lineTo(x + weaponOffset*2+5, y + 18);
//ctx.lineTo(x + weaponOffset*2, y + 13);
//ctx.closePath();
//ctx.fill();
break;
case 'bow_arrow':
// Draw bow
ctx.lineWidth = 2;
ctx.strokeStyle = this.isAlive ? '#483224' : '#CCCCCC';
ctx.beginPath();
ctx.arc(x + 16, y + 16, 20, -Math.PI/2, Math.PI/2);
ctx.stroke();
// Draw bowstring
ctx.lineWidth = 1;
ctx.strokeStyle = this.isAlive ? 'black' : '#CCCCCC';
ctx.beginPath();
ctx.moveTo(x + 16, y - 4);
ctx.lineTo(x + 16, y + 36);
ctx.stroke();
ctx.strokeStyle = 'black';
// Draw arrow
if (this.inCombat) {
const arrowLength = 20;
const drawAngle = Math.PI / 20; // 45-degree angle
const arrowX = x + 16 + Math.cos(drawAngle) * weaponOffset;
const arrowY = y + 16 + Math.sin(drawAngle) * weaponOffset;
ctx.save();
ctx.translate(arrowX, arrowY);
ctx.rotate(drawAngle);
// Arrow shaft
ctx.fillRect(0, -1, arrowLength, 2);
// Arrow head
ctx.beginPath();
ctx.moveTo(arrowLength, 0);
ctx.lineTo(arrowLength - 5, -3);
ctx.lineTo(arrowLength - 5, 3);
ctx.fill();
// Arrow feathers
ctx.fillStyle = this.isAlive ? '#8B4513' : '#CCCCCC'; // Brown color for feathers
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(-3, -3);
ctx.lineTo(-3, 3);
ctx.fill();
ctx.restore();
}
break;
}
}
fireArrow(target) {
const dx = target.x - this.x;
const dy = target.y - this.y;
const distance = Math.sqrt(dx * dx + dy * dy);
arrows.push({
x: this.x,
y: this.y,
dx: (dx / distance) * ARROW_SPEED,
dy: (dy / distance) * ARROW_SPEED,
source: this,
target: target
});
}
meleeAttack(target) {
if (target.invincible) return false;
const damageModifier = combatMatrix[this.weapon][target.weapon];
const damage = weaponStats[this.weapon].damage * damageModifier * this.damageMultiplier;
const absorbedDamage = damage * weaponStats[target.weapon].absorption;
const actualDamage = damage - absorbedDamage;
target.health -= actualDamage;
target.bloodSplatter += actualDamage * 2;
if (target.health <= 0) {
target.isAlive = false;
this.kills++;
if (killed[this.weapon]){
killed[this.weapon]++;
} else {
killed[this.weapon] = 1;
}
this.health = Math.min(100, this.health + 25);
return true;
}
return false;
}
attack(target) {
const now = Date.now();
const weaponStat = weaponStats[this.weapon];
const requiredDelay = this.firstAttack ? weaponStat.attackDelay : weaponStat.attackSpeed;
if (now - this.lastAttackTime < requiredDelay) return false;
this.lastAttackTime = now;
this.firstAttack = false;
if (this.weapon === 'bow_arrow') {
this.fireArrow(target);
return false; // Arrow damage will be applied when it hits
} else {
return this.meleeAttack(target);
}
}
}
function initiateCombat(player1, player2) {
player1.inCombat = true;
player2.inCombat = true;
player1.firstAttack = true;
player2.firstAttack = true;
player1.combatTarget = player2;
player2.combatTarget = player1;
function moveTowardsOpponent(player, target) {
const dx = target.x - player.x;
const dy = target.y - player.y;
const distance = Math.sqrt(dx * dx + dy * dy);
const playerRange = weaponStats[player.weapon].range;
if (distance > playerRange) {
player.x += (dx / distance) * 0.04;
player.y += (dy / distance) * 0.04;
return false;
}
return true;
}
function combatRound() {
if (!player1.isAlive || !player2.isAlive || !player1.inCombat || !player2.inCombat) {
endCombat(player1, player2);
return;
}
const player1InRange = moveTowardsOpponent(player1, player2);
const player2InRange = moveTowardsOpponent(player2, player1);
const now = Date.now();
const player1ReadyToAttack = player1.firstAttack
? now - player1.lastAttackTime >= weaponStats[player1.weapon].attackDelay
: now - player1.lastAttackTime >= weaponStats[player1.weapon].attackSpeed;
const player2ReadyToAttack = player2.firstAttack
? now - player2.lastAttackTime >= weaponStats[player2.weapon].attackDelay
: now - player2.lastAttackTime >= weaponStats[player2.weapon].attackSpeed;
if (player1InRange){
player1.attackAnimationFrame++;
}
if (player1InRange && player1ReadyToAttack) {
const player1Wins = player1.attack(player2);
player1.firstAttack = false;
if (player1Wins) {
endCombat(player1, player2);
return;
}
}
if (player2InRange){
player2.attackAnimationFrame++;
}
if (player2InRange && player2ReadyToAttack) {
const player2Wins = player2.attack(player1);
player2.firstAttack = false;
if (player2Wins) {
endCombat(player2, player1);
return;
}
}
requestAnimationFrame(combatRound);
}
combatRound();
}
function showDamageIndicator(x, y) {
ctx.fillStyle = 'red';
ctx.font = '20px Arial';
ctx.fillText('Hit!', x, y - 20);
}
function endCombat(winner, loser) {
winner.inCombat = false;
loser.inCombat = false;
winner.attackAnimationFrame = 0;
loser.attackAnimationFrame = 0;
winner.combatTarget = null;
loser.combatTarget = null;
if (loser.health <= 0) {
loser.isAlive = false; // Make loser a ghost
}
winner.firstAttack = true; // Reset firstAttack for the next combat
loser.firstAttack = true; // Reset firstAttack for the next combat (if resurrected)
}
function addPlayer(name, avatarUrl, type, nameColor, weaponType) {
const x = Math.floor(Math.random() * GRID_WIDTH);
const y = Math.floor(Math.random() * GRID_HEIGHT);
if (!weaponType) {
weaponType = WEAPONS[Math.floor(Math.random() * WEAPONS.length)];
}
const player = new Player(name, x, y, weaponType);
if (avatarUrl) {
player.setAvatar(avatarUrl);
}
if (nameColor) {
player.color = nameColor;
}
players.set(name, player);
updatePlayerCount();
}
function updatePlayerCount() {
if (gameOver && (countdownSeconds<=0)) {
drawLobby();
}
playerCountElement.textContent = `Players: ${players.size}`;
}
function calculateCombatRange() {
const totalArea = GRID_WIDTH * GRID_HEIGHT;
const playerDensity = players.size / totalArea;
const densityFactor = Math.min(playerDensity / DENSITY_THRESHOLD, 1);
return COMBAT_RANGE_BASE * (1 - densityFactor * 0.7); // Reduce range up to 70% based on density
}
function checkCombat() {
const combatRange = calculateCombatRange();
const playerArray = Array.from(players.values());
for (let i = 0; i < playerArray.length; i++) {
for (let j = i + 1; j < playerArray.length; j++) {
const player1 = playerArray[i];
const player2 = playerArray[j];
if (!player1.isAlive || !player2.isAlive || player1.inCombat || player2.inCombat) continue;
const distance = Math.sqrt(
Math.pow(player1.x - player2.x, 2) + Math.pow(player1.y - player2.y, 2)
);
if (distance <= combatRange) {
initiateCombat(player1, player2);
}
}
}
}
function update() {
if (!gameOver) {
players.forEach(player => player.update());
updateArrows();
checkCombat();
// spawnPowerUps();
// spawnObstacles();
// checkPowerUpCollisions();
// checkObstacleCollisions();
}
}