-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.js
677 lines (543 loc) · 19.1 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
/*
règles de syntaxe :
- tous les noms de variables en camelCase
- ajouter Selector derrière le nom de la variable quand celle-ci est un élément du DOM
*/
/* ---------------
common variables
------------------ */
var activeScreen = "menu";
/* -------------------------
menu variables & listeners
---------------------------- */
var menuScreenSelector = document.querySelector("#menu-screen");
var playerNumberSelector = document.querySelector("#player-number");
var playerNumber = playerNumberSelector.options[playerNumberSelector.selectedIndex].value;
playerNumberSelector.addEventListener('change', changePlayerNumber);
var playerHolderSelector = document.querySelector("#players-holder");
/*buttons*/
var buttonRules = document.querySelector("#button-rules");
buttonRules.addEventListener('click', showRules);
var buttonStart = document.querySelector("#button-start");
buttonStart.addEventListener('click', startRace);
var buttonTop = document.querySelector("#button-top");
buttonTop.addEventListener('click', goToTop);
var rulesSelector = document.querySelector("#rules");
var playersData = [];
/* -------------------------------
game board variables & listeners
---------------------------------- */
var gameScreenSelector = document.querySelector("#game-screen");
var nextTurnAvailable = true; /*cooldown to wait before toggling next turn*/
/*variables to insert cards in deck*/
var decksSelector = document.getElementsByClassName("deck-card-holder");
var deckStyle = window.getComputedStyle(decksSelector[0]);
var deckWidth = deckStyle.getPropertyValue('width');
var deckCardsSelector = document.getElementsByClassName('deck-card');
var deckCardStyle = window.getComputedStyle(deckCardsSelector[0]);
var deckCardWidth = deckCardStyle.getPropertyValue('width');
/*variables to insert cards in holders*/
var cardHoldersSelector = document.getElementsByClassName("card-holder");
var cardHolderStyle = window.getComputedStyle(cardHoldersSelector[0]);
var cardHolderWidth = cardHolderStyle.getPropertyValue('width');
var cardsSelector = document.getElementsByClassName('card');
var cardStyle = window.getComputedStyle(cardsSelector[0]);
var cardWidth = cardStyle.getPropertyValue('width');
/*deck variables*/
var deckDiv = document.querySelector("#deck-face-down");
deckDiv.addEventListener('click', nextTurn);
var deckCardPick = document.querySelector("#deck-face-down .top-card");
var deckCardDropTop = document.querySelector("#deck-face-up .top-card");
var deckCardDropBottom = document.querySelector("#deck-face-up .bottom-card");
var deckCardId = 0; //Id of the next card to draw from the API deck
var gameBoardSelector = document.querySelector("#game-board");
/*track side variables*/
var trackSideCardsBottom = document.querySelectorAll('.track-card .bottom-card');
var trackSideCardsTop = document.querySelectorAll('.track-card .top-card');
/*Aces variables*/
var aceHoldersSelector = document.querySelectorAll('.track .card-holder');
var acesSelector = document.querySelectorAll('.track .card');
/*API variables*/
var deckId = "";
var APIState; //var to control the state of the API & decide what to do next
var deckCards = []; //API data about the deck cards
var aces = []; //API data about the four aces
var sideTrackDeck = []; //API data about the cards on the side of the track
var request = new XMLHttpRequest();
var requestData;
var raceInfos = {
/*infos sur la course pour
-savoir si une carte doit aller en arrière
-déterminer la victoire
-écrire les commentaires*/
firstId:0,
lastId:0,
nextSideCard:-1,
nbTurns:0,
raceGoing:false,
raceOver:false
}
var prevRaceInfos = {};
Object.assign(prevRaceInfos,raceInfos); //copy
//infos du tour précedent,
//pour comparer et faire des commentaires
/*comments variable*/
var gameCommentary = document.querySelector('#game-commentary');
var comment = ""; //the comment that will be displayed
var commentPrefix = ["Attention attention, ",
"Oh lala ",
"Regardez ce qu'il ce passe ! C'est que ",
"Et ce tour, ",
"Ah, ",
"Oh, ",
"Et "];
var horseName = ""; //how will be called the horse that is being commented : by suit or track ?
var suitInFrench = {"CLUBS": "trèfle",
"DIAMONDS": "carreau",
"HEARTS": "coeur",
"SPADES": "pique"
}
var suitInSymbols = {"CLUBS": "♣",
"DIAMONDS": "♦",
"HEARTS": "♥",
"SPADES": "♠"
}
var commentMade = false; //has the comment already been calculated ?
/*buttons*/
var buttonNextTurn = document.querySelector("#next-turn");
buttonNextTurn.addEventListener('click', nextTurn);
var buttonSeeResults = document.querySelector("#see-results");
buttonSeeResults.addEventListener('click', seeResults);
/* ---------------------------------
results screen variables & listeners
------------------------------------ */
var resultsScreenSelector = document.querySelector("#results-screen");
/*result board text elements*/
var winnerHorse = document.querySelector("#winner-horse");
var playerLineResults = document.getElementsByClassName("player-line-result");
var playerNameResults = document.getElementsByClassName("player-name-result");
var giveOrTakes = document.getElementsByClassName("give-or-take");
var playerBetResults = document.getElementsByClassName("player-bet-result");
/*buttons*/
var buttonBackToRace = document.querySelector("#back-to-race");
buttonBackToRace.addEventListener('click', backToRace);
var buttonNewRace = document.querySelector("#new-race");
buttonNewRace.addEventListener('click', backToMenu);
/* ---------------
common functions
------------------ */
window.onresize = function(event) {
if (activeScreen == "game") {
insertCardsinDesk();
insertCardsinHolders();
resizeGameBoard();
}
};
function insertCardsinDesk() {
/*compute the CSS style for the deck card
(because it's been rotated so it sucks)*/
deckStyle = window.getComputedStyle(decksSelector[0]);
deckWidth = deckStyle.getPropertyValue('width');
for(i=0; i<deckCardsSelector.length; i++) {
deckCardsSelector[i].style.height = deckWidth;
}
deckCardStyle = window.getComputedStyle(deckCardsSelector[0]);
deckCardWidth = deckCardStyle.getPropertyValue('width');
for(i=0; i<decksSelector.length; i++) {
decksSelector[i].style.height = deckCardWidth;
}
}
function insertCardsinHolders() {
/*compute the CSS style for the card on the board
(because it's been rotated so it sucks)*/
cardHolderStyle = window.getComputedStyle(cardHoldersSelector[0]);
cardHolderWidth = cardHolderStyle.getPropertyValue('width');
for(i=0; i<cardsSelector.length; i++) {
cardsSelector[i].style.height = cardHolderWidth;
}
cardStyle = window.getComputedStyle(cardsSelector[0]);
cardWidth = cardStyle.getPropertyValue('width');
for(i=0; i<cardHoldersSelector.length; i++) {
cardHoldersSelector[i].style.height = cardWidth;
}
}
function resizeGameBoard() {
gameBoardSelector.style.width = (parseInt(cardStyle.getPropertyValue('height'))*7)+"px";
}
/* -------------
menu functions
---------------- */
function changePlayerNumber() {
playerNumber = playerNumberSelector.options[playerNumberSelector.selectedIndex].value;
for(var i=0; i<8; i++) {
if (i < playerNumber) {
showMenuPlayer(i);
} else {
hideMenuPlayer(i);
}
}
}
function showMenuPlayer(i) {
//shows the menu line for player i
var waitTime = 80 * i;
setTimeout(function () {
playerHolderSelector.children[i].classList.remove("hidden");
playerHolderSelector.children[i].classList.remove("pick-line");
}, waitTime);
}
function hideMenuPlayer(i) {
//hide the menu line for player i
var waitTime = 80 * (8 - Math.max(0, i - playerNumber));
setTimeout(function () {
playerHolderSelector.children[i].classList.add("pick-line");
}, waitTime);
setTimeout(function () {
playerHolderSelector.children[i].classList.add("hidden");
}, waitTime + 400);
}
function showRules () {
/*show the game rules at the bottom of the menu screen*/
rulesSelector.classList.remove("hidden");
rulesSelector.scrollIntoView({ behavior: 'smooth' });
}
function goToTop () {
document.querySelector('#site-title').scrollIntoView({ behavior: 'smooth' });
}
function startRace () {
/*go to game screen & start the race*/
getPlayersData();
hideMenuScreen();
initGameScreen();
}
function getPlayersData () {
//store players names, horses & bets
for(var i=0; i<playerNumber; i++) {
var playerName = document.querySelector("#menu-player"+(i+1)+" .player-name").value;
if (playerName == "") {
playerName = "Joueur "+(i+1);
}
var playerHorseSelector = document.querySelector("#menu-player"+(i+1)+" .player-horse");
var playerBetSelector = document.querySelector("#menu-player"+(i+1)+" .player-bet");
var currPlayer = {
name: playerName,
horse: playerHorseSelector.options[playerHorseSelector.selectedIndex].value,
bet: playerBetSelector.options[playerBetSelector.selectedIndex].value,
};
playersData.push(currPlayer);
}
}
function hideMenuScreen() {
menuScreenSelector.classList.add("exit-screen-left");
setTimeout(function () {
menuScreenSelector.classList.add("hidden");
}, 200);
}
/* -------------
game functions
---------------- */
function initGameScreen () {
activeScreen = "game";
menuScreenSelector.classList.remove("enter-screen-right");
menuScreenSelector.classList.remove("enter-screen-left");
setTimeout(function () {
gameScreenSelector.classList.remove("hidden");
insertCardsinDesk();
insertCardsinHolders();
resizeGameBoard();
},200);
setupAPI();
}
function setupAPI() {
/*create a deck of cards with the API*/
APIState = "init";
request.open('GET', "https://deckofcardsapi.com/api/deck/new/shuffle/?deck_count=1", true);
request.send();
}
request.onreadystatechange = function() {
/*API request came back*/
if (request.readyState == 4 && request.status == 200) {
requestAnswered();
}
};
function requestAnswered(){
/*do stuff with the request - is also used as part 2 of initGameScreen function*/
requestData = JSON.parse(request.responseText);
switch (APIState) {
case "init":
deckId = requestData.deck_id;
drawCards(52);
break;
case "gameDrawn":
deckCards = requestData.cards;
makeAcesPile();
makeSideTrackPile();
loadSideTrackCards();
loadAces();
raceInfos.raceGoing = true; //the race can start
break;
default:
break;
}
}
function drawCards(x) {
//request the api to draw x cards from the deck
//(no deckId is given as parameter because it is global and we will use only one deck)
APIState = "gameDrawn";
request.open('GET', "https://deckofcardsapi.com/api/deck/"+deckId+"/draw/?count="+x, true);
request.send();
}
function makeAcesPile() {
//store the 4 aces in a separate list
var tmpCard;
for (i=deckCards.length-1; i>=0; i--) { //reverse loop because splice changes superior indexes
if (deckCards[i].value == "ACE") {
tmpCard = deckCards.splice(i, 1)[0];
tmpCard.position = 0; //the position property will give info about the position of the card/horse during the race
aces.push(tmpCard);
}
}
}
function makeSideTrackPile() {
//store the 5 cards on the side of the track in a separate list
sideTrackDeck = deckCards.splice(0, 5);
}
function loadSideTrackCards() {
for (i=0; i<5; i++) {
trackSideCardsTop[i].src = sideTrackDeck[i].images.png;
}
}
function loadAces() {
for (i=0; i<4; i++) { //causes bugs for unknown reason -> normally fixed
acesSelector[i].src = aces[i].image;
acesSelector[i].classList.remove("hidden");
}
}
function nextTurn () {
if (nextTurnAvailable && raceInfos.raceGoing) {
nextTurnAvailable = false;
raceInfos.nbTurns++;
loadDropCard();
updateDeck();
setTimeout(function () {
moveAceFwd();
updateRaceInfos();
setTimeout(function () {
if (raceInfos.nextSideCard > prevRaceInfos.nextSideCard) {
updateTrackSide();
setTimeout(function () {
moveAceBkw();
updateRaceInfos();
},800);
}
checkIfRaceIsOver();
sayAComment();
if (!raceInfos.raceGoing) {
endRace();
} else {
Object.assign(prevRaceInfos,raceInfos); //copy
}
},800);
coolDownNextTurn();
},800);
}
if (raceInfos.raceOver) {
gameCommentary.innerHTML = "La course est finie, allez donc voir les résultats au lieu de rester plantés là !";
}
}
function loadDropCard() {
/*load the next card to draw from the deck API*/
deckCardDropTop.src = deckCards[deckCardId].images.png;
deckCardId++;
}
function updateDeck () {
/*animation for taking a card from the deck*/
deckCardPick.classList.remove("pick-deck-card");
setTimeout(function () {
/*20ms of delay to prevent stupid lag*/
deckCardPick.classList.add("pick-deck-card");
},20);
setTimeout(function () {
/*animation to drop the card face up on the deck*/
deckCardDropTop.classList.remove("drop-deck-card");
},420);
setTimeout(function () {
/*20ms of delay to prevent stupid lag*/
deckCardDropTop.classList.remove("hidden");
deckCardDropTop.classList.add("drop-deck-card");
copyTopBottomDeckCards();
},440);
}
function copyTopBottomDeckCards () {
/*copy the top card face up of the deck to bottom card face up
to prepare for next turn animation*/
setTimeout(function () {
deckCardDropBottom.src = deckCardDropTop.src;
deckCardDropTop.classList.add("hidden");
},400);
}
function moveAceFwd() {
//checks wich Ace needs to move fwd & moves it
for (i=0; i<4; i++) {
if (deckCards[deckCardId-1].suit == aces[i].suit) {
aces[i].position++;
aceHoldersSelector[i].classList.remove("move-card-right");
aceHoldersSelector[i].classList.remove("move-card-left");
setTimeout(function (i) {
/*20ms of delay to prevent stupid lag*/
var marginLeftTmp = 14.29*aces[i].position;
aceHoldersSelector[i].style.marginLeft = ""+marginLeftTmp+"%";
aceHoldersSelector[i].classList.add("move-card-right");
},20,i);
}
}
}
function updateRaceInfos () {
for (i=0; i<4; i++) {
if (aces[raceInfos.lastId].position > aces[i].position) {
raceInfos.lastId = i;
}
if (aces[raceInfos.firstId].position < aces[i].position) {
raceInfos.firstId = i;
}
}
raceInfos.nextSideCard = Math.max(raceInfos.nextSideCard, aces[raceInfos.lastId].position-1);
}
function updateTrackSide() {
if (raceInfos.nextSideCard < 5) {
trackSideCardsBottom[raceInfos.nextSideCard].classList.add("pick-track-card");
setTimeout(function () {
trackSideCardsTop[raceInfos.nextSideCard].classList.remove("hidden");
},400);
}
}
function moveAceBkw() {
//checks which Ace needs to move bkw & moves it
for (i=0; i<4; i++) {
if (sideTrackDeck[raceInfos.nextSideCard].suit == aces[i].suit) {
aces[i].position--;
aceHoldersSelector[i].classList.remove("move-card-right");
aceHoldersSelector[i].classList.remove("move-card-left");
setTimeout(function (i) {
/*20ms of delay to prevent stupid lag*/
var marginLeftTmp = 14.29*aces[i].position;
aceHoldersSelector[i].style.marginLeft = ""+marginLeftTmp+"%";
aceHoldersSelector[i].classList.add("move-card-left");
},20,i);
}
}
}
function checkIfRaceIsOver () {
if (aces[raceInfos.firstId].position >= 6) {
raceInfos.raceGoing = false;
}
}
function sayAComment() {
commentMade = false;
comment = commentPrefix[Math.floor(Math.random() * commentPrefix.length)];
if (raceInfos.nbTurns == 1) {
comment += callHorse(raceInfos.firstId) + " démarre sur les chapeaux de roues !";
commentMade = true;
} else if (!raceInfos.raceGoing) {
comment += callHorse(raceInfos.firstId) + " gagne la course !!!";
commentMade = true;
} else if (raceInfos.firstId != prevRaceInfos.firstId) {
comment += callHorse(raceInfos.firstId) + " prend la tête de course !!";
commentMade = true;
} else if (raceInfos.lastId != prevRaceInfos.lastId && Math.random() < 0.4) {
comment += callHorse(raceInfos.lastId) + " passe dernier...";
commentMade = true;
}
else {
for (i=0; i<4; i++) {
if (i != raceInfos.firstId && aces[i].position == aces[raceInfos.firstId].position && !commentMade && Math.random() < 0.8) {
comment += callHorse(i) + " et " + callHorse(raceInfos.firstId) + " se battent pour la première place ! Allez !!";
commentMade = true;
}
if (i != raceInfos.lastId && aces[i].position == aces[raceInfos.lastId].position && !commentMade && Math.random() < 0.4) {
comment += callHorse(i) + " et " + callHorse(raceInfos.lastId) + " sont tous les 2 derniers ... Il faut se ressaisir !";
commentMade = true;
}
}
}
if (!commentMade && Math.random() < 0.7) {
comment += callHorse(raceInfos.firstId) + " conserve sa première place...";
} else if (!commentMade) {
comment += callHorse(raceInfos.lastId) + " est dernier... Du nerf l'ami !";
}
gameCommentary.innerHTML = comment;
}
function callHorse (i) {
//return a name for the horse with id i
if (Math.random() < 0.7) {
return ("l'as de " + suitInFrench[aces[i].suit]);
} else {
return ("le poulain de la piste " + (i+1));
}
}
function endRace() {
raceInfos.raceOver = true;
}
function coolDownNextTurn() {
/*wait some time before enabling the next turn*/
setTimeout(function () {
nextTurnAvailable = true;
},820);
}
function seeResults() {
/*Load the results screen when button is pressed*/
if (raceInfos.raceOver) {
activeScreen = "results";
loadResults();
gameScreenSelector.classList.remove("enter-screen-left");
gameScreenSelector.classList.remove("enter-screen-right");
gameScreenSelector.classList.add("exit-screen-left");
resultsScreenSelector.classList.add("enter-screen-right");
setTimeout(function () {
gameScreenSelector.classList.add("hidden");
resultsScreenSelector.classList.remove("hidden");
}, 200);
} else {
gameCommentary.innerHTML = "Pas si vite l'ami, attendez que la course soit finie !";
}
}
/* ----------------
results functions
------------------- */
function loadResults() {
var tmpWinSuit = aces[raceInfos.firstId].suit
winnerHorse.innerHTML = "" + suitInSymbols[tmpWinSuit] + " Le gagnant de la course est le " + suitInFrench[tmpWinSuit] + " ! " + suitInSymbols[tmpWinSuit];
for (i=0; i<playersData.length; i++) {
playerNameResults[i].innerHTML = playersData[i].name;
if (playersData[i].horse == tmpWinSuit) {
giveOrTakes[i].innerHTML = " distribue " + (playersData[i].bet * 2) + " coups ";
giveOrTakes[i].classList.add("give-number");
} else {
giveOrTakes[i].innerHTML = " boit " + (playersData[i].bet) + " coups ";
giveOrTakes[i].classList.add("drink-number");
}
playerBetResults[i].innerHTML = "(il a misé " + playersData[i].bet + " sur le " + suitInFrench[playersData[i].horse] + ")";
playerLineResults[i].classList.remove("hidden");
}
}
function backToRace() {
activeScreen = "game";
resultsScreenSelector.classList.remove("enter-screen-left");
resultsScreenSelector.classList.remove("enter-screen-right");
resultsScreenSelector.classList.add("exit-screen-right");
gameScreenSelector.classList.add("enter-screen-left");
setTimeout(function () {
resultsScreenSelector.classList.add("hidden");
gameScreenSelector.classList.remove("hidden");
}, 200);
}
function backToMenu () {
activeScreen = "menu";
resultsScreenSelector.classList.remove("enter-screen-left");
resultsScreenSelector.classList.remove("enter-screen-right");
resultsScreenSelector.classList.add("exit-screen-right");
menuScreenSelector.classList.add("enter-screen-left");
setTimeout(function () {
resultsScreenSelector.classList.add("hidden");
location.reload();
}, 400);
}