-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
1229 lines (989 loc) · 37.3 KB
/
script.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
! function() {
const VERSION = 16;
const BOARD_BACKGROUND = "#555555";
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;
// max player count (currently, set to the amount of colors, available)
const MAX_PLAYERS = COLORS.length;
// 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 = 1280;
const snakeboardMaxY = 720;
// the default snake move delta and snake square size
const DELTA = 16;
// is the version checking finished?
var versionChecked = false;
// the db version
var dbVersion = 0;
// the time of the last graphics update
var timeLastGraphicsUpdate = 0;
// is the game ended?
var isGameEnded = false;
// countdown before start
var countdown = 6;
// can we send data to database (we should be invisible for other players
// in countdown sequence, but visible for ourself)
var isInvisibleForOthers = true;
// our snake color
var my_snake_col;
// the player name
var name = "";
// is the name already set and checked from db?
var nameQuerySuccess = false;
// our snake
var snake = [];
// the last score we had, to display it after death in title
var lastScore = 0;
// are we changing direction?
var changingDirection = false;
// horizontal snake move delta
var deltaX = DELTA;
// vertical snake move delta
var deltaY = 0;
// the other players
var otherSnakes = [];
// used to count online (registered) players
var allSnakes = [];
// was the other snake data initialized from db?
var firstInitOtherSnakes = false;
// food positions
var foods = [];
// how long should the snake tail stay in place, after a food was eaten?
var tailWaitCount = 0;
// color of food (it will be in rainbow mode)
var foodLightness = 0;
// if not negative, only this type of food will spawn
var forcedFoodLevel = -1;
// food count multiplied by this factor
var foodFactor = 1;
// the calculated width and height of the canvas (based on screen size)
var snakeboardCalculatedWidth;
var snakeboardCalculatedHeight;
// the web app's Firebase configuration
var 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"
};
// call main method
main();
/* -------------------------
* -------------------------
* --------- Game ----------
* -------------------------
* -------------------------
*/
// reset everything and start the game
function startGame() {
// reset the last graphics update time to now
timeLastGraphicsUpdate = Date.now();
// reset countdown
countdown = 6;
// reset snake pos to random position
isInvisibleForOthers = true;
snake = generateRandomSnake();
// reset game isn't ended
isGameEnded = false;
// start the countdown
startCountdown();
}
// show countdown
function startCountdown() {
countdown--;
if (countdown > 0 && countdown <= 3) {
// countdown visible
sendInfo(countdown);
//document.getElementById('status').innerHTML = countdown;
setTimeout(startCountdown, 500);
return;
} else if (countdown > 0) {
// "Get ready!" visible
//document.getElementById('status').innerHTML = "Get ready!";
sendInfo("Get ready!");
setTimeout(startCountdown, 500);
return;
} else {
// if there is a snake on our position, wait for it to go away
if (checkForCollisionWithOtherSnakes()) {
countdown = -1;
//document.getElementById('status').innerHTML = "Waiting for other snake to go away...";
sendInfo("Waiting for other snake to go away...", color="Red");
setTimeout(startCountdown, 50);
return;
}
// reset go direction
deltaX = DELTA;
deltaY = 0;
// countdown is finished, we don't need to wait
countdown = 0;
isInvisibleForOthers = false;
// "Go" visible for 3 secs
sendInfo("Go!", 3000);
}
}
// the game loop
function loop() {
// the current time
var timeNow = Date.now();
// the time estimated since last update
var timeEstimated = timeNow - timeLastGraphicsUpdate;
if (timeEstimated >= SNAKE_UPDATE_DELAY) {
// the time, we were waiting too long
var timeTooLong = timeEstimated - 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
var loopCount = Math.max(1, Math.round(timeTooLong / SNAKE_UPDATE_DELAY));
for (var i = 0; i < loopCount; i++) {
// tick the game
changingDirection = false;
tick();
}
// send playerdata just once after the for loop, if snake is set
if (snake.length != 0) setPlayerData(snake);
// set the last update time to now
timeLastGraphicsUpdate = Date.now();
}
updateSideBar();
clearBoard();
drawFoods();
handleOtherSnakes();
// we always need to draw the snake, so if it's there, it will be shown
drawSnake();
// retry button clicked
if (retryClicked) {
retryClicked = false;
onRetry();
}
setTimeout(loop, 1);
}
// tick the game
function tick() {
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();
}
}
// 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
var randomX = randomCoordinateX(4);
var randomY = randomCoordinateY();
// the coordinates for the snake, we will calculate
var snakeCoords = [];
// just fill the array with 5 coordinate pairs, the x is descending, the higher the key is
for (var i = 0; i<5; i++) {
var 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
var count = foodLevelToCount(handleFoodCollect()) - 1;
if (count < 0) {
// we need to remove parts
for (var 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 var is zero again
tailWaitCount += count;
}
count++;
// show the player, how many points he got/lost
if (count > 0) {
sendInfo("+" + count, 1000, "LimeGreen");
} else if (count == 0) {
sendInfo("0", 1000);
} else if (count < 0) {
sendInfo(count, 1000, "Red");
}
} else if (tailWaitCount <= 0) {
// remove the last part of snake body
snake.pop();
} else {
tailWaitCount--;
}
}
// change the "walking" direction of the snake
function changeDirection(up, left, down, right) {
// going up
if (up) {
deltaX = 0;
deltaY = -DELTA;
// going left
} else if (left) {
deltaX = -DELTA;
deltaY = 0;
// going down
} else if (down) {
deltaX = 0;
deltaY = DELTA;
// going right
} else if (right) {
deltaX = DELTA;
deltaY = 0;
}
}
// check for collission with wall, other snakes, oneself
function checkForCollision() {
// check for collsison with oneself
for (var 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 (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() {
var ateFood = false;
for (var foodKey in foods) {
var 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) {
foods[foods.length] = {
"x": x,
"y": y,
"level": level,
"uuid": crypto.randomUUID()
};
updateFoods();
}
// remove a food, this will also return the level of the food removed
function removeFood(x, y) {
// the new food data
var newFoods = [];
// the food level of the removed food
var foodLevel = FOOD_LEVEL_RANDOM;
i = 0;
for (var foodKey in foods) {
var 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
var removedOldFoodLevel = removeFood(snake[0].x, snake[0].y);
// creating new food
var foodCount = Math.max(1, Math.round(getActivePlayers() / 2)) * foodFactor;
foodCount = foodCount - foods.length;
for (var i = 0; i < foodCount; i++) {
var randomFood;
var 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 (var foodKey in foods) {
var food = foods[foodKey];
if (food.x != randomFood.x || food.y != randomFood.y)
noFoodPosFound = false;
}
}
// and add it
addFood(randomFood.x, randomFood.y, randomFoodLevel());
}
return removedOldFoodLevel;
}
// generate a new random food location
function genFood() {
// Generate a random number the food x-coordinate
var foodX = randomCoordinateX();
// Generate a random number for the food y-coordinate
var foodY = randomCoordinateY();
// if the new food location is where the snake currently is, generate a new food location
snake.forEach((part) => {
const has_eaten = part.x == foodX && part.y == foodY;
if (has_eaten) genFood();
});
// if the new food location is where another snake currently is, generate a new food location
otherSnakes.forEach((part) => {
const has_eaten = part.x == foodX && part.y == foodY;
if (has_eaten) genFood();
});
return {"x": foodX, "y": foodY}
}
function dropRandomFood() {
// don't drop, if player has score 0
if (getArrayLength(snake) <= 5)
return;
for (var key in snake) {
var 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());
}
}
/* -------------------------
* -------------------------
* --------- 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 and game over message
//document.getElementById('status').style.visibility = 'visible';
//document.getElementById('status').innerHTML = '<b><span style=\"color: tomato; display: inline;\"> Game Over!</span></b>';
sendInfo("Game Over!", 0, "Red");
document.getElementById('score').style.visibility = 'visible';
document.getElementById('score').innerHTML = 'Your score: ' + lastScore + '<button id="buttonRetry" class="button retry" onclick="onRetryClick()">Retry (r)</button>';
}
// 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;
// Prevent the snake from reversing
if (changingDirection) return;
changingDirection = true;
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
changeDirection(((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) {
var canvas = snakeboard;
// abs. size of element
var rect = canvas.getBoundingClientRect();
// relationship bitmap vs. element for X
var scaleX = snakeboardCalculatedWidth / snakeboardMaxX;
// relationship bitmap vs. element for Y
var scaleY = snakeboardCalculatedHeight / snakeboardMaxY;
const x = (e.touches[0].clientX - rect.left) / scaleX;
const y = (e.touches[0].clientY - rect.top) / scaleY;
// Prevent the snake from reversing
if (changingDirection) return;
changingDirection = true;
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
changeDirection(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() {
// calculate the max width and height
var width50Percent = 1.5 * window.innerWidth * 0.5;
var height75Percent = 1.5 * window.innerHeight * 0.75;
// calculate aspect ratio
var aspectRatio = snakeboardMaxX / snakeboardMaxY;
// only allow the smallest width, to be full size
var widthMax = snakeboardMaxX / width50Percent;
var heightMax = snakeboardMaxY / height75Percent;
// the other size (which is too big to fit on the monitor) will shrink,
// but it will also consider the aspect ratio
if (widthMax > heightMax) {
snakeboardCalculatedWidth = width50Percent;
snakeboardCalculatedHeight = width50Percent / aspectRatio;
} else if (heightMax > widthMax) {
snakeboardCalculatedWidth = height75Percent * aspectRatio;
snakeboardCalculatedHeight = height75Percent;
} else {
snakeboardCalculatedWidth = width50Percent;
snakeboardCalculatedHeight = height75Percent;
}
// set the calculated width and height
snakeboard.width = snakeboardCalculatedWidth;
snakeboard.height = snakeboardCalculatedHeight;
// set scale multiplier for x and y
snakeboardCtx.scale(snakeboardCalculatedWidth/snakeboardMaxX, snakeboardCalculatedHeight/snakeboardMaxY);
}
// draw the canvas background
function clearBoard() {
// select the color to fill the drawing
snakeboardCtx.fillStyle = BOARD_BACKGROUND;
// Draw a "filled" rectangle to cover the entire canvas
snakeboardCtx.fillRect(0, 0, snakeboardMaxX, snakeboardMaxY);
}
// Draw the snake on the canvas
function drawSnake() {
// empty
if (snake.length == 0) return;
// Draw each part
var head = true;
snake.forEach(part => {
drawSnakePart(my_snake_col, part, head);
head = false;
})
}
// Draw one snake part
function drawSnakePart(snake_col, snakePart, head) {
// 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 (head) {
snakeboardCtx.fillStyle = snake_col === "black" ? "white" : "black";
snakeboardCtx.beginPath();
if (deltaX > 0) { // Moving 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);
} else if (deltaX < 0) { // Moving 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);
} else if (deltaY > 0) { // Moving 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);
} else if (deltaY < 0) { // Moving 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);
}
snakeboardCtx.closePath();
snakeboardCtx.fill();
}
}
// draw the food
function drawFoods() {
// draw all the foods
for (var foodKey in foods) {
var 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() {
var scores = [];
var formattedScore = "";
i = 0;
// put all the scores and the player name in array
for (var playerName in allSnakes) {
var 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 (var scoreKey in scores) {
// getting the entry
var scoreData = scores[scoreKey];
// and getting player name, score and the snake data
var score = scoreData["score"];
var playerName = scoreData["playerName"];
var 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;
}
// send an info to the status display
function sendInfo(str, duration=0, color="Black") {
// show
//document.getElementById('status').style.visibility = 'visible';
// set text
var content = '<div id="innerStatus" style="color: ' + color + ';">' + str + '</div>';
document.getElementById('status').innerHTML = content;
if (duration > 0) {
setTimeout(() => {
// hide, if the innerHTML is still the given string and color
if (document.getElementById('status').innerHTML === content)
document.getElementById('status').innerHTML = '<div id="innerStatus" style="color: transparent;">42</div';
}, duration);
}
}
/* -------------------------
* -------------------------
* --------- Utils ---------
* -------------------------
* -------------------------
*/
// check if the version is equal to the version of the database
function handleVersionCheck() {
do {
if (dbVersion > VERSION) {
versionChecked = true;
// clear our snake from db
snake = [];
setPlayerData([]);
// we need to wait for the player data to be updated.
for (var playerName in allSnakes) {
otherSnake = snake[playerName];
if (playerName == name && !(otherSnake == null || getArrayLength(otherSnake) == 0)) return;
}
versionChecked = false;
// client outdated
alert("Client outdated. Please close the tab, delete all cookies and data from this page and reopen this page.\n"
+ "The easiest way is to delete all your browsing data.");
} else if (dbVersion < VERSION) {
versionChecked = true;
// clear our snake from db
snake = [];
setPlayerData([]);
// we need to wait for the player data to be updated.
for (var playerName in allSnakes) {
otherSnake = snake[playerName];
if (playerName == name && !(otherSnake == null || getArrayLength(otherSnake) == 0)) return;
}
versionChecked = false;
// db outdated
alert("Database outdated. Please wait for the database to update, then reopen this tab.");
} else {
// everything up-to-date
versionChecked = true;
}
} while (!versionChecked);
}
// get random color for our snake, that isn't used
function getRandomColor() {
var unusedColors = getUnusedColors();
var color = unusedColors[randomInt(0, unusedColors.length - 1)];
return color;
}
// get all colors, which aren't used by any player
function getUnusedColors() {
var usedColors = [];
var unusedColors = [];
// getting all used colors
var i = 0;
for (var playerName in otherSnakes) {
otherSnake = otherSnakes[playerName];
if (otherSnake == null || otherSnake["color"] == null) continue;
usedColors[i] = otherSnake["color"];
i++;
}
// looping threw all available colors, then checking if the color
// is in the list of used colors, if it isn't, the color is unused
i = 0
for (var colorName in COLORS) {
if (!Array.from(usedColors).includes(COLORS[colorName])) {
unusedColors[i] = COLORS[colorName];
i++;
}
}
// now we have a list of unused colors, which we can return
return unusedColors;
}
// get the current food color with the blink effect
function currentFoodLightness(foodColor) {
// prevent lightness from being to big
if (foodLightness == 50) {
foodLightness = -50;
}
var hsv = {
h: foodColor == FOOD_LEVEL_RANDOM_COLOR ? ((foodLightness + 50) / 99) * 360 : foodColor,
s: 100,
v: foodColor == FOOD_LEVEL_RANDOM_COLOR ? 100 : Math.abs(foodLightness) + 50,
};
var color = Color( hsv );
return color.toString();
}
// get the color for a food by the food level
function getFoodColorByLevel(level) {
switch (level) {
case FOOD_LEVEL_LESS:
return FOOD_LEVEL_LESS_COLOR;
case FOOD_LEVEL_MEDIUM:
return FOOD_LEVEL_MEDIUM_COLOR;
case FOOD_LEVEL_MUCH:
return FOOD_LEVEL_MUCH_COLOR;
case FOOD_LEVEL_RANDOM:
return FOOD_LEVEL_RANDOM_COLOR;
default:
return 0;
}
}
function randomFoodLevel() {
// if there is a food level forced by database, use it
if (forcedFoodLevel >= 0) {
return forcedFoodLevel;
}
var rnd = randomInt(0, 300);
if (rnd >= 0 && rnd < 100) {
// less and medium are most common
return FOOD_LEVEL_LESS;
} else if (rnd >= 100 && rnd < 200) {
// less and medium are most common
return FOOD_LEVEL_MEDIUM;
} else if (rnd >= 200 && rnd < 250) {
// much and random are less common
return FOOD_LEVEL_MUCH;
} else {
// much and random are less common
return FOOD_LEVEL_RANDOM;
}
}
// convert the food level count to the count of the parts that must be added/removed
function foodLevelToCount(level) {
if (level == 0) {
return randomInt(-10, 10);
}
return level;
}
// escape html specific characters (like < or >)
function htmlEntities(str) {
return String(str).replace('&', '&').replace('<', '<').replace('>', '>').replace('"', '"');
}
// generate random integer
function randomInt(min, max) {
return Math.round(Math.random() * (max-min) + min);
}
// get random coordinate for x on the board, min is the minimum distance to the wall from left
function randomCoordinateX(min) {
min = min || 0;
return Math.round(randomInt(min * DELTA, snakeboardMaxX - DELTA) / DELTA) * DELTA;
}
// get random coordinate for y on the board
function randomCoordinateY() {
return Math.round(randomInt(0, snakeboardMaxY - DELTA) / DELTA) * DELTA;
}
// get the length of an iterable object
function getArrayLength(array) {
// looping threw all content of the all snakes, to get length
var len = 0;
for (var ignored in array) len++;
return len;
}
/* -------------------------
* -------------------------
* ------ Multiplayer ------
* -------------------------
* -------------------------
*/
// get the current online players
function getOnlinePlayers() {
return getArrayLength(allSnakes);
}
// get the players, currently playing
function getActivePlayers() {
var count = 0;
// go threw all snakes
for (var playerName in allSnakes) {
var snake = allSnakes[playerName];
// check if the snake is playing, by checking if there are positions set
if (snake.pos != null && getArrayLength(snake.pos) != 0) count++;
}
return count
}
// check if there are more players online, then max player count
function checkMaxPlayerCount() {
// max 15 players
while (getOnlinePlayers() >= MAX_PLAYERS) {
alert("The game is full (15/15). Click the button, to retry.");
}