-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1467 lines (1162 loc) · 44.8 KB
/
script.js
File metadata and controls
1467 lines (1162 loc) · 44.8 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
! function() {
const VERSION = 36;
// the program will attempt to achieve these FPS. max is 1000
const TARGET_FPS = 125;
const COLORS = ["Aqua", "Yellow", "Red", "Black", "White", "DeepPink", "LawnGreen", "Orange",
"SaddleBrown", "OrangeRed", "DarkViolet", "Gold", "Indigo", "Silver", "DarkGreen"];
// the delay between snake updates in ms
const SNAKE_UPDATE_DELAY = 100;
// the food levels
const FOOD_LEVEL_RANDOM = 0;
const FOOD_LEVEL_LESS = 1;
const FOOD_LEVEL_MEDIUM = 2;
const FOOD_LEVEL_MUCH = 3;
// the food colors for the levels
const FOOD_LEVEL_LESS_COLOR = 175;
const FOOD_LEVEL_MEDIUM_COLOR = 110;
const FOOD_LEVEL_MUCH_COLOR = 0;
const FOOD_LEVEL_RANDOM_COLOR = -1;
// the maximum amount of food that will spawn
const MAX_FOOD_AMOUNT = 50;
// max player count (currently, set to the amount of colors, available)
const MAX_PLAYERS = COLORS.length;
// the meaning of the headDir field in the snake object
const HEAD_DIR_NO_CHANGE = -1;
const HEAD_DIR_UP = 0;
const HEAD_DIR_LEFT = 1;
const HEAD_DIR_DOWN = 2;
const HEAD_DIR_RIGHT = 3;
// Get the canvas element
const snakeboard = document.getElementById("snakeboard");
// Return a two dimensional drawing context
const snakeboardCtx = snakeboard.getContext("2d");
// set the coordinate system dimensions (always 16:9)
const snakeboardMaxX = 1920;
const snakeboardMaxY = 1080;
// the default snake move delta and snake square size
const DELTA = 30;
// the amount of ticks a snake will have spawn protection after game start
const SPAWN_PROTECTION_TICKS = 3 * 1000 / SNAKE_UPDATE_DELAY;
// is the version checking finished?
let versionChecked = false;
// the db version
let dbVersion = 0;
// the time of the last game tick
let timeLastTick = 0;
// the amount of ticks since game started
let tickCount = 0;
// is the game ended?
let isGameEnded = false;
// countdown before start
let countdown = 4;
// the amount of ticks the snake still has spawn protection
let spawnProtectionRemainingTicks = SPAWN_PROTECTION_TICKS;
// can we send data to database (we should be invisible for other players
// in countdown sequence, but visible for ourself)
let isInvisibleForOthers = true;
// our snake color
let mySnakeCol;
// in which direction our head is facing
let myHeadDir = HEAD_DIR_RIGHT;
// the head dir that will be applied at the next move
let requestedHeadDir = HEAD_DIR_NO_CHANGE;
// the head dir that will be applied at the next next move, used to cache input to make input smoother
let requestedNextHeadDir = HEAD_DIR_NO_CHANGE;
// the player name
let name = "";
// is the name already set and checked from db?
let nameQuerySuccess = false;
// our snake
let snake = [];
// the last score we had, to display it after death in title
let lastScore = 0;
// horizontal snake move delta
let deltaX = DELTA;
// vertical snake move delta
let deltaY = 0;
// the other players
let otherSnakes = [];
// the last snake updates with timestamps from this browser, so a wrong browser time does not affect offline kicking
let otherSnakesLastUpdates = [];
// used to count online (registered) players
let allSnakes = [];
// was the other snake data initialized from db?
let firstInitOtherSnakes = false;
// food positions
let foods = [];
// the last collected scores for foods with remaining time to be displayed
let collectedFoodScores = [];
// how long should the snake tail stay in place, after a food was eaten?
let tailWaitCount = 0;
// color of food (it will be in rainbow mode)
let foodLightness = 0;
// if not negative, only this type of food will spawn
let forcedFoodLevel = -1;
// food count multiplied by this factor
let foodFactor = 1;
// the amount of updates since the last fps counter update, used to calculate average fps since the last five ticks
let fpsData = {timeLastFPSUpdate: 0, count: 0};
// the last update we received from the db (to check if other player is lagging or we are)
let lastOwnDBUpdate = -1;
// the web app's Firebase configuration
let firebaseConfig = {
apiKey: "AIzaSyBbRpK_BcltEmRQzLAUCFykMHEq5PQWWz4",
authDomain: "psyched-canto-311609.firebaseapp.com",
databaseURL: "https://psyched-canto-311609-default-rtdb.europe-west1.firebasedatabase.app",
projectId: "psyched-canto-311609",
storageBucket: "psyched-canto-311609.appspot.com",
messagingSenderId: "556381649934",
appId: "1:556381649934:web:af27169882d8297d78d05f"
};
// main connection to the firebase database
let firebaseMain;
// used to check if other player or ourself is lagging
let firebaseOnlineChecker;
// call main method
main();
/* -------------------------
* -------------------------
* --------- Game ----------
* -------------------------
* -------------------------
*/
// reset everything and start the game
function startGame() {
// reset the last graphics update time to now
timeLastTick = performance.now();
// reset countdown
countdown = 4;
// make sure spawn protection stays on during countdown
spawnProtectionRemainingTicks = 9999;
// reset snake pos to random position
isInvisibleForOthers = true;
snake = generateRandomSnake();
// reset game isn't ended
isGameEnded = false;
// reset go direction
changeDir(true, HEAD_DIR_RIGHT);
// start the countdown
startCountdown();
}
// show countdown
function startCountdown() {
countdown--;
if (countdown > 0) {
// countdown visible
setTimeout(startCountdown, 1000);
return;
} else {
// countdown is finished, we don't need to wait
countdown = 0;
// reset spawn protection
spawnProtectionRemainingTicks = SPAWN_PROTECTION_TICKS;
setPlayerData(snake);
isInvisibleForOthers = false;
}
}
// the game loop
function loop() {
// the current time
let timeNow = performance.now();
// the time elapsed since last tick
let timespanSinceLastTick = timeNow - timeLastTick;
// calculate the fps for the last shown frame
fpsData.count++;
if (timespanSinceLastTick >= SNAKE_UPDATE_DELAY) {
// the time, we were waiting too long
let timeTooLong = timespanSinceLastTick - SNAKE_UPDATE_DELAY;
// the count, how often we have to call the tick method, based on the time, we were waiting too long, at least one time
let loopCount = Math.max(1, Math.round(timeTooLong / SNAKE_UPDATE_DELAY));
for (let i = 0; i < loopCount; i++) {
// tick the game
tick(timeNow);
}
// send playerdata just once after the for loop, if snake is set
if (snake.length != 0) setPlayerData(snake);
// set the last tick time to now
timeLastTick = performance.now();
// send last tick time to DB so that other players know if this player is still active
setLastUpdate(timeLastTick);
// only run if we are not behind the db ourself
if (Math.round(performance.now() / 1000) - lastOwnDBUpdate < 5) {
// check if all other players are actually still active. If not, we delete the entries from the DB.
for (let playerName in otherSnakesLastUpdates) {
// inactive for 10 seconds
if (Math.round(performance.now() / 1000) - otherSnakesLastUpdates[playerName] > 10) {
// delete the entry
firebaseMain.ref("snake/players/" + playerName).remove();
}
}
} else {
alert("Connection lost.");
location.reload();
return;
}
}
updateSideBar();
clearBoard();
drawFoods();
handleOtherSnakes();
// we always need to draw the snake, so if it's there, it will be shown
drawSnake();
// text should be always on top
drawText();
// attempt to always run the loop around the target fps by subtracting the time this function took to run from the target
let nextUpdateIn = Math.max(0, (1000 / TARGET_FPS) - (performance.now() - timeNow));
setTimeout(loop, nextUpdateIn);
}
// tick the game
function tick(timeNow) {
// add food, if there is no food on the map
if (foods.length == 0) {
addFood(randomCoordinateX(), randomCoordinateY(), randomFoodLevel());
}
if (countdown != 0) {
// wait for countdown finsih
} else if (isGameEnded || snake.length <= 0 || checkForCollision()) {
// game ended for us
// first call, then call onGameEnd()
if (!isGameEnded) onGameEnd();
} else {
// we are still in
// move the snake (change values in array, and handle key presses)
move_snake();
}
if (spawnProtectionRemainingTicks > 0) spawnProtectionRemainingTicks--;
// decrease the remaining visible time of the food score displays and remove expired ones
for (let i = collectedFoodScores.length - 1; i >= 0; i--) {
let score = collectedFoodScores[i];
score.ticksRemaining--;
if (score.ticksRemaining <= 0) {
collectedFoodScores.splice(i, 1);
}
}
// update fps counter every 5 ticks and reset the fps sum
if (tickCount % 5 == 0) {
document.getElementById("fpsCounter").innerText = Math.round(fpsData.count / ((timeNow - fpsData.timeLastFPSUpdate) / 1000)) + " FPS";
fpsData.count = 0;
fpsData.timeLastFPSUpdate = timeNow;
}
tickCount++;
}
// generate a random snake array which is 5 long (only start point is random, other 4 are relative to start point)
function generateRandomSnake() {
// getting random coordinates, in x direction with a distance of min 4 gaps to the wall
let randomX = randomCoordinateX(4);
let randomY = randomCoordinateY();
// the coordinates for the snake, we will calculate
let snakeCoords = [];
// just fill the array with 5 coordinate pairs, the x is descending, the higher the key is
for (let i = 0; i<5; i++) {
let currentPart = i * DELTA;
snakeCoords[i] = {x: randomX - currentPart, y: randomY};
}
return snakeCoords;
}
// move the snake
function move_snake() {
// create the new Snake's head, based on snake move delta
const head = {x: snake[0].x + deltaX, y: snake[0].y + deltaY};
// add the new head to the beginning of snake body
snake.unshift(head);
// did we ate food?
const ateFood = hasEatenFood();
if (ateFood) {
// handle collection of food and get the count, how many parts must be added
let count = addCollectedFoodScoreToDB(foodLevelToCount(handleFoodCollect())) - 1;
if (count < 0) {
// we need to remove parts
for (let i = 0; i > count; i--) {
// but if the snake has just a length of 1, we don't remove more
if (getArrayLength(snake) == 1) break;
snake.pop();
}
} else {
// we need to add parts, so add the count to our wait count so the end will stop
// and wait until the variable is zero again
tailWaitCount += count;
}
} else if (tailWaitCount <= 0) {
// remove the last part of snake body
snake.pop();
} else {
tailWaitCount--;
}
requestedHeadDir = requestedNextHeadDir;
requestedNextHeadDir = HEAD_DIR_NO_CHANGE;
changeDir(false);
}
// change the "walking" direction of the snake
function userChangeDirection(up, left, down, right) {
let newHeadDir;
// going up
if (up) {
newHeadDir = HEAD_DIR_UP;
// going left
} else if (left) {
newHeadDir = HEAD_DIR_LEFT;
// going down
} else if (down) {
newHeadDir = HEAD_DIR_DOWN;
// going right
} else if (right) {
newHeadDir = HEAD_DIR_RIGHT;
}
changeDir(false, newHeadDir);
}
function changeDir(force, newHeadDir = HEAD_DIR_NO_CHANGE) {
// if game is not started yet
if (countdown != 0) {
force = true;
}
if (!force && newHeadDir != HEAD_DIR_NO_CHANGE) {
// save the requested input. if there already is one saved, save also one future requested input to make input smoother
if (requestedHeadDir == HEAD_DIR_NO_CHANGE) {
requestedHeadDir = newHeadDir;
} else {
requestedNextHeadDir = newHeadDir;
}
newHeadDir = requestedHeadDir;
} else if (force) {
requestedHeadDir = HEAD_DIR_NO_CHANGE;
requestedNextHeadDir = HEAD_DIR_NO_CHANGE;
} else {
newHeadDir = requestedHeadDir;
}
switch (newHeadDir) {
case HEAD_DIR_UP:
deltaX = 0;
deltaY = -DELTA;
break;
case HEAD_DIR_LEFT:
deltaX = -DELTA;
deltaY = 0;
break;
case HEAD_DIR_DOWN:
deltaX = 0;
deltaY = DELTA;
break;
case HEAD_DIR_RIGHT:
deltaX = DELTA;
deltaY = 0;
break;
default:
break;
}
myHeadDir = newHeadDir == HEAD_DIR_NO_CHANGE ? myHeadDir : newHeadDir;
}
// check for collission with wall, other snakes, oneself
function checkForCollision() {
// check for collsison with oneself
for (let i = 4; i < snake.length; i++) {
if (snake[i].x === snake[0].x && snake[i].y === snake[0].y) return true;
}
// check for collisions with other players
if (spawnProtectionRemainingTicks <= 0 && checkForCollisionWithOtherSnakes()) return true;
// check for collission with wall
const hitLeftWall = snake[0].x < 0;
const hitRightWall = snake[0].x > snakeboardMaxX - DELTA;
const hitToptWall = snake[0].y < 0;
const hitBottomWall = snake[0].y > snakeboardMaxY - DELTA;
return hitLeftWall || hitRightWall || hitToptWall || hitBottomWall;
}
// check if a player has eaten a food
function hasEatenFood() {
let ateFood = false;
for (let foodKey in foods) {
let food = foods[foodKey];
if(snake[0].x === food.x && snake[0].y === food.y) {
ateFood = true;
break;
}
}
return ateFood;
}
// save a new food position
function addFood(x, y, level) {
if (foods.length >= MAX_FOOD_AMOUNT) {
return false;
}
foods[foods.length] = {
"x": x,
"y": y,
"level": level,
"uuid": crypto.randomUUID()
};
updateFoods();
return true;
}
// remove a food, this will also return the level of the food removed
function removeFood(x, y) {
// the new food data
let newFoods = [];
// the food level of the removed food
let foodLevel = FOOD_LEVEL_RANDOM;
i = 0;
for (let foodKey in foods) {
let food = foods[foodKey];
// getting the data of the other food
foodX = food.x;
foodY = food.y;
// if the data isn't equal to our data, we will add it to the new list
if (x != foodX || y != foodY) {
newFoods[i] = food;
i++;
} else foodLevel = food.level;
}
// update the food array
foods = newFoods;
updateFoods();
return foodLevel;
}
// handle the collection of food, this will also return the level of the removed food
function handleFoodCollect() {
// removing old food
let removedOldFoodLevel = removeFood(snake[0].x, snake[0].y);
// creating new food
let foodCount = Math.max(1, Math.round(getActivePlayers() / 2)) * foodFactor;
foodCount = foodCount - foods.length;
for (let i = 0; i < foodCount; i++) {
let randomFood;
let noFoodPosFound = true;
// search for a food pos, which isn't in use
while (noFoodPosFound) {
randomFood = genFood();
// there are no positions to check
if (foods.length == 0)
noFoodPosFound = false;
// check all other food positions to avoid overlap
for (let foodKey in foods) {
let food = foods[foodKey];
if (food.x != randomFood.x || food.y != randomFood.y)
noFoodPosFound = false;
}
}
// and add it
if (!addFood(randomFood.x, randomFood.y, randomFoodLevel())) {
return;
}
}
return removedOldFoodLevel;
}
// generate a new random food location
function genFood() {
// Generate a random number the food x-coordinate
let foodX = randomCoordinateX();
// Generate a random number for the food y-coordinate
let foodY = randomCoordinateY();
// if the new food location is where the snake currently is, generate a new food location
snake.forEach((part) => {
const isOccupied = part.x == foodX && part.y == foodY;
if (isOccupied) return genFood();
});
// if the new food location is where another snake currently is, generate a new food location
for (let playerName in otherSnakes) {
let otherSnakePos = otherSnakes[playerName]["pos"];
if (otherSnakePos) {
otherSnakePos.forEach((part) => {
const isOccupied = part.x == foodX && part.y == foodY;
if (isOccupied) return genFood();
});
}
}
return {"x": foodX, "y": foodY}
}
function dropRandomFood() {
// don't drop, if player has score 0
if (getArrayLength(snake) <= 5)
return;
for (let key in snake) {
let pos = snake[key];
// ignore this pos, if it is in the wall...
if ((pos.x < 0 || pos.x > (snakeboardMaxX - DELTA))
|| (pos.y < 0 || pos.y > (snakeboardMaxY - DELTA)))
continue;
// drop random food at random positions in snake, ca. 16,67% probability to drop for each
if (randomInt(0, 5) == 0 && !addFood(pos.x, pos.y, randomFoodLevel())) {
return;
}
}
}
/* -------------------------
* -------------------------
* --------- Event ---------
* -------------------------
* -------------------------
*/
// called when the game ends
function onGameEnd() {
isGameEnded = true;
// remove our snake from the board
setPlayerData([]);
// drop random food from out snake
dropRandomFood();
snake = [];
// show retry button
document.getElementById('score').style.visibility = 'visible';
document.getElementById('score').innerHTML = 'Your score: ' + lastScore + '<button id="buttonRetry" class="button retry">Retry (r)</button>';
document.getElementById('buttonRetry').addEventListener("click", () => onRetry());
}
// called, when the window is resized by user
function onResizeWindow() {
resizeSnakeboard();
}
// called, when the player presses a key on keyboard
function onKeyPress(event) {
// all keys for going up
const UP_KEY = 38;
const W_KEY = 87;
// all keys for going left
const LEFT_KEY = 37;
const A_KEY = 65;
// all keys for going down
const DOWN_KEY = 40;
const S_KEY = 83;
// all keys for going right
const RIGHT_KEY = 39;
const D_KEY = 68;
// all keys for pressing the retry button
const ENTER_KEY = 13;
const R_KEY = 82;
const keyPressed = event.keyCode;
const goingUp = deltaY === -DELTA;
const goingDown = deltaY === DELTA;
const goingRight = deltaX === DELTA;
const goingLeft = deltaX === -DELTA;
// change direction based on pressed key
userChangeDirection(((keyPressed === UP_KEY || keyPressed === W_KEY) && !goingDown),
((keyPressed === LEFT_KEY || keyPressed === A_KEY) && !goingRight),
((keyPressed === DOWN_KEY || keyPressed === S_KEY) && !goingUp),
((keyPressed === RIGHT_KEY || keyPressed === D_KEY) && !goingLeft));
// retry
if (keyPressed === ENTER_KEY || keyPressed === R_KEY) {
onRetry();
}
}
// if the snakeboard is clicked, get the pos of the click and send it
function onSnakeboardClick(e) {
let canvas = snakeboard;
// abs. size of element
let rect = canvas.getBoundingClientRect();
// relationship bitmap vs. element for X
let scaleX = snakeboard.width / snakeboardMaxX;
// relationship bitmap vs. element for Y
let scaleY = snakeboard.height / snakeboardMaxY;
const x = (e.touches[0].clientX - rect.left) / scaleX;
const y = (e.touches[0].clientY - rect.top) / scaleY;
const goingUp = deltaY === -DELTA;
const goingDown = deltaY === DELTA;
const goingRight = deltaX === DELTA;
const goingLeft = deltaX === -DELTA;
// is the upper part of the canvas pressed and aren't we going down?
const upPressed = (((snakeboardMaxY / 2) > y) && !((snakeboardMaxX / 4) > x) && !((snakeboardMaxX - (snakeboardMaxX / 4)) < x)) && !goingDown;
// is the left part of the canvas pressed and aren't we going right?
const leftPressed = ((snakeboardMaxX / 4) > x) && !goingRight;
// is the down part of the canvas pressed and aren't we going up?
const downPressed = (((snakeboardMaxY / 2) < y) && !((snakeboardMaxX / 4) > x) && !((snakeboardMaxX - (snakeboardMaxX / 4)) < x)) && !goingUp;
// is the right part of the canvas pressed and aren't we going left?
const rightPressed = ((snakeboardMaxX - (snakeboardMaxX / 4)) < x) && !goingLeft;
// change direction based on the values
userChangeDirection(upPressed, leftPressed, downPressed, rightPressed);
}
// called when the retry button is clicked
function onRetry() {
// if the player isn't alive, restart
if (isGameEnded) {
document.getElementById('score').style.visibility = 'hidden';
startGame();
}
}
/* -------------------------
* -------------------------
* ------- Graphics --------
* -------------------------
* -------------------------
*/
// resize the snakeboard, based on the size of the window
function resizeSnakeboard() {
// get the actual "on-screen" size of the canvas element which CSS has already calculated for us
const displayWidth = snakeboard.clientWidth;
const displayHeight = snakeboard.clientHeight;
// set the canvas's internal resolution to match. prevents stretching and blurriness
snakeboard.width = displayWidth;
snakeboard.height = displayHeight;
// re-apply context scaling
snakeboardCtx.scale(displayWidth / snakeboardMaxX, displayHeight / snakeboardMaxY);
}
// draw the canvas background
function clearBoard() {
// Clear canvas
snakeboardCtx.clearRect(0, 0, snakeboardMaxX, snakeboardMaxY);
}
// get the color of a snake, this also adds blinking effect if spawn protect is active
function getSnakeColorWithBrightness(colorName, hasSpawnProtection) {
let color;
try {
color = new Color(colorName.toLowerCase());
} catch {
color = new Color("red");
}
if (hasSpawnProtection) color.alpha = Math.abs(foodLightness) * 2 / 100;
return color;
}
// Draw the snake on the canvas
function drawSnake() {
// empty
if (snake.length == 0) return;
color = getSnakeColorWithBrightness(mySnakeCol, spawnProtectionRemainingTicks > 0);
// Draw each part
let headDir = myHeadDir;
snake.forEach(part => {
drawSnakePart(color, part, headDir);
headDir = undefined;
})
}
function getMaxContrastColor(colorName) {
let color = new Color(colorName);
let withBlack = color.contrastWCAG21(new Color( '#000' ));
let withWhite = color.contrastWCAG21(new Color( '#fff' ));
let hex = ( withBlack >= withWhite ) ? '#000' : '#fff';
return new Color( hex );
}
// Draw one snake part
function drawSnakePart(snake_col, snakePart, headDir) {
// Set the color of the snake part
snakeboardCtx.fillStyle = snake_col;
// Set the border color of the snake part
snakeboardCtx.strokestyle = "black";
// Draw a "filled" rectangle to represent the snake part at the coordinates
// the part is located
snakeboardCtx.fillRect(snakePart.x, snakePart.y, DELTA, DELTA);
// Draw a border around the snake part
snakeboardCtx.strokeRect(snakePart.x, snakePart.y, DELTA, DELTA);
if (headDir != undefined) {
snakeboardCtx.fillStyle = getMaxContrastColor(snake_col);
snakeboardCtx.beginPath();
switch (headDir) {
case HEAD_DIR_UP:
snakeboardCtx.moveTo(snakePart.x + DELTA / 2, snakePart.y + 1);
snakeboardCtx.lineTo(snakePart.x, snakePart.y + DELTA * 0.25 + 1);
snakeboardCtx.lineTo(snakePart.x + DELTA, snakePart.y + DELTA * 0.25 + 1);
break;
case HEAD_DIR_LEFT:
snakeboardCtx.moveTo(snakePart.x + 1, snakePart.y + DELTA / 2);
snakeboardCtx.lineTo(snakePart.x + DELTA * 0.25 + 1, snakePart.y);
snakeboardCtx.lineTo(snakePart.x + DELTA * 0.25 + 1, snakePart.y + DELTA);
break;
case HEAD_DIR_DOWN:
snakeboardCtx.moveTo(snakePart.x + DELTA / 2, snakePart.y + DELTA - 1);
snakeboardCtx.lineTo(snakePart.x, snakePart.y + DELTA * 0.75 - 1);
snakeboardCtx.lineTo(snakePart.x + DELTA, snakePart.y + DELTA * 0.75 - 1);
break;
case HEAD_DIR_RIGHT:
snakeboardCtx.moveTo(snakePart.x + DELTA - 1, snakePart.y + DELTA / 2);
snakeboardCtx.lineTo(snakePart.x + DELTA * 0.75 - 1, snakePart.y);
snakeboardCtx.lineTo(snakePart.x + DELTA * 0.75 - 1, snakePart.y + DELTA);
break;
default:
break;
}
snakeboardCtx.closePath();
snakeboardCtx.fill();
}
}
// draw the food
function drawFoods() {
// draw all the foods
for (let foodKey in foods) {
let food = foods[foodKey];
snakeboardCtx.fillStyle = currentFoodLightness(getFoodColorByLevel(food.level));
snakeboardCtx.strokestyle = 'black';
snakeboardCtx.fillRect(food.x, food.y, DELTA, DELTA);
snakeboardCtx.strokeRect(food.x, food.y, DELTA, DELTA);
}
// increase lightness
foodLightness++;
}
// update side status bar
function updateSideBar() {
let scores = [];
let formattedScore = "";
i = 0;
// put all the scores and the player name in array
for (let playerName in allSnakes) {
let score = ((getArrayLength(allSnakes[playerName]["pos"]) - 5));
lastScore = score >= 0 && playerName == name ? score : lastScore;
scores[i] = {
"score": score,
"playerName": playerName
};
i++;
}
// sort the array descending
scores.sort((a, b) => b.score - a.score);
// loop threw the sorted array
for (let scoreKey in scores) {
// getting the entry
let scoreData = scores[scoreKey];
// and getting player name, score and the snake data
let score = scoreData["score"];
let playerName = scoreData["playerName"];
let snakeData = allSnakes[playerName];
// add the data as html to the score string
formattedScore += "<span id=\"scoreboard\" style=\"color:" + snakeData["color"] + ";\">"
+ htmlEntities(playerName) + "</span>: " + (score < -4 ? "Spectator" : score) + "<br>";
}
document.getElementById('sidebar').innerHTML = "Online: " + getOnlinePlayers() + "/15<br><br>"
+ formattedScore;
}
function drawText() {
// draw countdown if there
if (countdown > 0) {
snakeboardCtx.font = "150px 'Outfit', sans-serif";
snakeboardCtx.fillStyle = "white";
let cntText = countdown.toString();
let textSize = snakeboardCtx.measureText(cntText);
let textWidth = textSize.width;
snakeboardCtx.fillText(cntText, snakeboardMaxX/2 - textWidth/2, snakeboardMaxY/2);
}
// draw the collected food text for all snakes
for (let playerName in allSnakes) {
let sn = allSnakes[playerName];
let scores = sn["collectedFoodScores"];
//scores = [{score: 1}, {score: 4}, {score: 0}, {score: -3}];
if (!scores || !sn["pos"] || !sn["pos"][0]) continue;
snakeboardCtx.font = "bold 32px 'Outfit', sans-serif";
let headPos = sn["pos"][0];
// calculate constants
const PADDING_X = 6;
const PADDING_Y = 6;
const CORNER_RADIUS = 7;
// determine direction based on head position
const isBelowCenter = headPos.y > snakeboardMaxY / 2;
let currentYOffset = isBelowCenter ? DELTA + 2 : -DELTA - PADDING_Y - 2;
for (let key in scores) {
const scoreObj = scores[key];
const scoreText = (scoreObj.score >= 0 ? "+" : "") + scoreObj.score.toString();
// measure text dimensions
const metrics = snakeboardCtx.measureText(scoreText);
const textWidth = metrics.width;
const textHeight = metrics.actualBoundingBoxDescent + metrics.actualBoundingBoxAscent;
// calculate rectangle position with bounds checking
let rectX = headPos.x + DELTA/2 - textWidth/2 - PADDING_X;
rectX = Math.max(PADDING_X, Math.min(snakeboardMaxX - textWidth - PADDING_X*3, rectX));
let rectY = headPos.y - currentYOffset - PADDING_Y;
const rectWidth = textWidth + (PADDING_X*2);
const rectHeight = textHeight + (PADDING_Y*2);
// draw background rectangle
snakeboardCtx.fillStyle = "#444444";
snakeboardCtx.beginPath();
snakeboardCtx.roundRect(rectX, rectY, rectWidth, rectHeight, CORNER_RADIUS);
snakeboardCtx.fill();
// draw text
snakeboardCtx.fillStyle = scoreObj.score > 0 ? "lime" : (scoreObj.score == 0 ? "white" : "red");
snakeboardCtx.fillText(scoreText, rectX + PADDING_X, rectY + textHeight + PADDING_Y);
currentYOffset += isBelowCenter ? rectHeight + 2 : -rectHeight - 2;
}
}
}
/* -------------------------
* -------------------------
* --------- Utils ---------
* -------------------------
* -------------------------
*/
// check if the version is equal to the version of the database
function handleVersionCheck() {
if (dbVersion > VERSION) {
// clear our snake from db
snake = [];
setPlayerData([]);
// client outdated
alert("Client outdated. Click OK to reload the page and try again.\n\n"
+ "If reloading doesn't work after some waiting, try pressing CTRL+SHIFT+R or delete all cookies and data from this page.");
try {
location.reload(true);
} catch {
location.reload();
}
} else if (dbVersion < VERSION) {
// clear our snake from db
snake = [];
setPlayerData([]);
// db outdated
alert("Database outdated. Please wait for the database to update.");