-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
1590 lines (1430 loc) · 57.3 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
// USEFUL FUNCTIONS
function hide(objJQ) {
if (objJQ.length > 1) {
for (let o in objJQ) {
if (!objJQ.hasClass('hidden')) objJQ.addClass('hidden');
};
} else {
if (!objJQ.hasClass('hidden')) objJQ.addClass('hidden');
};
};
function show(objJQ) {
if (objJQ.length > 1) {
for (let o in objJQ) {
if (objJQ.hasClass('hidden')) objJQ.removeClass('hidden');
};
} else {
if (objJQ.hasClass('hidden')) objJQ.removeClass('hidden');
};
};
function showAndHide(showObjJQ, hideObjJQ) {
hide(hideObjJQ); show(showObjJQ);
};
function goToPage(objJQ) {
DOM.allPagesJQ.each(function() {hide($(this))});
show(objJQ);
};
function intFromText(objJQ) {
return parseInt(objJQ.text());
};
function toggleBackupBtns() {
if (localStorage.getItem('twoj_turniej_backup')) {
show(DOM.loadBackupBtnJQ);
show(DOM.clearBackupBtnJQ);
} else {
hide(DOM.loadBackupBtnJQ);
hide(DOM.clearBackupBtnJQ);
};
};
// MUST BE CALL ON OBJECT by call/apply/bind methods
function addClass(className) {
if (!this.hasClass(className)) this.addClass(className);
};
function removeClass(className) {
if (this.hasClass(className)) this.removeClass(className);
};
// CHOOSE A LANGUAGE
let lang = 'pl'; // pl, en
const ERRORS = {
LACK_OF_NAME: {
en: 'You must type a team name',
pl: 'Musisz podać nazwę drużyny'
},
LACK_OF_TEAMS_IN_MATCH: {
en: 'You cannot create a match without a 2 teams',
pl: 'Nie można zdefiniować meczu bez podania 2 drużyn'
},
LACK_OF_TEAMS_IN_LEAGUE: {
en: 'You cannot create a league without teams',
pl: 'Nie można zdefiniować ligi bez podania drużyn'
},
LACK_OF_TEAMS_IN_CUP: {
en: 'You cannot create a cup without teams',
pl: 'Nie można zdefiniować pucharu bez podania drużyn'
},
LACK_OF_TEAMS_IN_TOUR: { // CHECK IF NECESSARY
en: 'You cannot create a tour without teams',
pl: 'Nie można zdefiniować turnieju bez podania drużyn'
},
LACK_OF_MATCHES_IN_ROUND: {
en: 'You cannot create a round without matches',
pl: 'Nie można zdefiniować rundy bez podania meczów'
},
BACKUP_CREATION_FAILED: {
en: 'Backup creation failed!',
pl: 'Błąd przy tworzeniu backupu. Backup nie utworzony.'
}
}
const ALERTS = {
LACK_OF_NAME: {
en: 'You must type a team name',
pl: 'Musisz podać nazwę drużyny'
},
MAX_NUMBER_OF_TEAMS: {
en: 'You cannot add more than 64 teams!',
pl: 'Nie możesz dodać więcej niż 64 drużyny!'
},
NAN_IN_ADDING_RESULT: {
en: 'You cannot add a result without typing goals!',
pl: 'Nie możesz dodać wyniku bez wypełnienia goli!'
},
TOURNAMENT_IS_FINISHED: {
en: 'This was the last match in this tour. The winner is',
pl: 'To był ostatni mecz w turnieju. Zwyciężyła drużyna'
},
PENALTIES_START: {
en: 'Penalties time!',
pl: 'Czas na rzuty karne!'
},
TOO_MUCH_TEAMS: {
en: 'It can be maximum 64 teams in the tour!',
pl: 'Maksymalnie może być 64 drużyny!'
},
DO_YOU_WANT_SAVE_BACKUP: {
en: 'Do you really want SAVE backup?',
pl: 'Czy na pewno chcesz zapisać bieżacy stan?'
},
DO_YOU_WANT_LOAD_BACKUP: {
en: 'Do you really want LOAD from backup?',
pl: 'Czy na pewno chcesz wczytać zapisany stan?'
},
DO_YOU_WANT_CLEAR_BACKUP: {
en: 'Do you really want CLEAR backup?',
pl: 'Czy na pewno chcesz usunąć zapisany stan?'
},
SOME_TEAM_HAS_SUCH_NAME: {
en: 'There is already a team with such name!',
pl: 'Już jest drużyna o tej nazwie!'
}
}
const INTERFACE = {
LEAGUE: {
en: 'league',
pl: 'liga'
},
ROUND: {
en: 'round',
pl: 'runda'
},
MATCH: {
en: 'match',
pl: 'mecz'
},
TIE: {
en: 'tie',
pl: 'dwumecz'
},
}
const DOM = {
// PAGES
allPagesJQ: $('.page'),
addingTeamsPageJQ: $('#adding-teams'),
tourSettingsPageJQ: $('#tour-settings'),
leagueViewPageJQ: $('#league-view'),
cupViewPageJQ: $('#cup-view'),
statsViewPageJQ: $('#stats-view'),
addResultBarJQ: $('#add-result'),
newTeamJQ: $('.team-name'),
addTeamBtnJQ: $('.add-team'),
teamsInTableTipJQ: $('.add-teams-tip'),
addedTeamsTableJQ: $('.added-teams-table'),
addedTeamsJQ: $('.added-teams'),
readyTeamsBtnJQ: $('.ready-teams'),
tourNameJQ: $('.tour-name'),
selectTourTypeJQ: $('#tour-type'),
selectLeagueJQ: $('.league-type'),
selectCupJQ: $('.cup-type'),
selectLeagueCupJQ: $('.league-cup-type'),
backToAddingTeamsJQ: $('.back-to-teams'),
startTourBtnJQ: $('.start-tour'),
leagueRevengeJQ: $('.league-revenge'),
leagueRevengeValJQ: $('#league-revenge-value'),
cupRevengeJQ: $('.cup-revenge'),
cupRevengeValJQ: $('#cup-revenge-value'),
leagueFixturesJQ: $('.league-fixtures'),
addingResultJQ: $('.adding-result'),
addingResultHostJQ: $('.adding-result > .host'),
addingResultHostGoalsJQ: $('.adding-result > .host-goals'),
addingResultGuestJQ: $('.adding-result > .guest'),
addingResultGuestGoalsJQ: $('.adding-result > .guest-goals'),
addResultBtnJQ: $('.add-result'),
leagueTableJQ: $('.league-table'),
cupFixturesJQ: $('.cup-fixtures'),
goToCupViewBtnJQ: $('.goto-cup-view'),
goToLeagueViewBtnJQ: $('.goto-league-view'),
saveBackupBtnJQ: $('.save-backup'),
autosaveBackupBtnJQ: $('.auto-save-backup'),
loadBackupBtnJQ: $('.load-backup'),
clearBackupBtnJQ: $('.clear-backup'),
selectHostInFastGoalsBtnJQ: $('.host-fast-goals'),
selectGuestInFastGoalsBtnJQ: $('.guest-fast-goals'),
fastGoalsBtnJQ: $('.fast-goals'),
logoJQ: $('#logo'),
resultsInFixturesJQ: $('.league-fixtures .result'),
}
// GLOBAL EMITTER OBJECTS FOR CONTROLLING OF DATA FLOW IN APP
class TourEmitter {
constructor() {
this.eventsList = {}
}
emit(event, data) {
if (!this.eventsList[event]) return; // NO LISTENERS
for (let callback of this.eventsList[event]) callback(data);
}
listen(event, callback) {
if (!this.eventsList[event]) this.eventsList[event] = [];
this.eventsList[event].push(callback);
}
}
class Team {
constructor(name) {
if (!name) throw Error(ERRORS.LACK_OF_NAME[lang]);
this.name = name;
this.won = 0;
this.draw = 0;
this.lost = 0;
this.points = 0; // HOW WITH POINTS WHEN STAGE IS CHANGING? CLEARING?
this.goalsScored = 0;
this.goalsLost = 0;
this.matches = [];
this.onTeamListJQ = $(`<tr><td>${this.name}</td><td class="delete-team"><div>×</div></td></tr>`).appendTo(DOM.addedTeamsJQ);
this.onTeamListJQ.find('.delete-team').on('click', () => {
this.onTeamListJQ.remove();
tourEmitter.emit('deletedTeam', this.name);
});
let leagueTableLength = DOM.leagueTableJQ.find('tbody > tr').length
this.onLeagueTable = $(`<tr><td class="position">${leagueTableLength+1}</td><td class="name">${this.name}</td><td class="points">${this.points}</td><td class="wins">${this.won}</td><td class="draws">${this.draw}</td><td class="lost">${this.lost}</td><td class="goals-scored">${this.goalsScored}</td><td class="goals-lost">${this.goalsLost}</td></tr>`).appendTo(DOM.leagueTableJQ);
}
getLastMatch() {
return this.matches[this.matches.length-1];
}
updateOnLeagueTable() {
let sorted = false;
// UPDATE WARTOŚCI
let id = this.onLeagueTable.find('.position');
let name = this.onLeagueTable.find('.name');
let points = this.onLeagueTable.find('.points');
points.text(this.points);
let wins = this.onLeagueTable.find('.wins');
wins.text(this.won);
let draws = this.onLeagueTable.find('.draws');
draws.text(this.draw);
let lost = this.onLeagueTable.find('.lost');
lost.text(this.lost);
let goalsScored = this.onLeagueTable.find('.goals-scored');
goalsScored.text(this.goalsScored);
let goalsLost = this.onLeagueTable.find('.goals-lost');
goalsLost.text(this.goalsLost);
let lastMatch = this.getLastMatch();
if (lastMatch.isDraw() || lastMatch.isAWinOf(this.name)) {
let aboveRow = this.onLeagueTable.prev();
let abovePoints = parseInt(aboveRow.find('.points').text());
let aboveWins = parseInt(aboveRow.find('.wins'));
let aboveDraws = parseInt(aboveRow.find('.draws'));
let aboveLost = parseInt(aboveRow.find('.lost'));
let aboveGoalsScored = parseInt(aboveRow.find('.goals-scored'));
let aboveGoalsLost = parseInt(aboveRow.find('.goals-lost'));
if (abovePoints < points) aboveRow.after(this.onLeagueTable);
} else {
// zobacz czy nie musisz przesunąć poniżej poprzednika, i patrz tylko na różnicę goli
let belowRow = this.onLeagueTable.next();
};
}
recalcStats() {
// WYZERUJ WYNIKI ZAWODKÓW
this.clearStats();
this.matches.forEach((m, i) => {
let stats = m.getTeamStats(this.name);
let {points, won, draw, lost, goalsScored, goalsLost} = stats;
this.points += points;
this.won += won;
this.draw += draw;
this.lost += lost;
this.goalsScored += goalsScored;
this.goalsLost += goalsLost;
});
}
clearStats() {
this.won = 0;
this.draw = 0;
this.lost = 0;
this.points = 0;
this.goalsScored = 0;
this.goalsLost = 0;
}
backup() {
let {name} = this; // BRAKUJE reszty właściwości
return name;
}
}
// ADD CHANGABLE POINTS FOR WIN/DRAW/LOOSE EG. IN FOOTBALL 3/1/0
class Match {
constructor(host, guest, stage, isRevenge = false) {
if (!host || !guest) throw Error(ERRORS.LACK_OF_TEAMS_IN_MATCH[lang]);
this.host = host;
this.guest = guest;
this.hostGoals = 0;
this.guestGoals = 0;
this.finished = false;
this.stage = stage;
this.penalties = false;
this.hostPenaltiesGoals = 0;
this.guestPenaltiesGoals = 0;
this.penaltiesWinner = '';
this.isRevenge = isRevenge;
this.partOfTie = false;
if (this.stage.match(/league/g)) {
this.onFixturesList = $(`<tr><td>${host.name}</td><td class="result"></td><td>${guest.name}</td><td>r${this.getRoundName()}</td></tr>`).appendTo(DOM.leagueFixturesJQ);
} else if (this.stage.match(/cup/g)) {
this.onFixturesList = $(`<tr><td>${host.name}</td><td class="result"></td><td>${guest.name}</td><td>${this.getRoundName()}</td></tr>`).appendTo(DOM.cupFixturesJQ);
if (this.partOfTie) {
if (stage.match(/cup-1\/1/g) || this.isRevenge) this.penalties = true;
} else this.penalties = true;
};
}
getRoundName() {
let {stage} = this;
let splitted = stage.split('-');
let roundName = splitted[splitted.length-1];
if (roundName === '1/1') return 'Finał'
else return roundName;
}
addResult(hostGoals, guestGoals) {
this.finished = true;
this.hostGoals = hostGoals;
this.guestGoals = guestGoals;
if (this.stage.match(/league/g)) this.updateTeamsResults();
this.onFixturesList.find('.result').text(`${hostGoals}:${guestGoals}`);
if (hostGoals === guestGoals && this.penalties) this.playPenalties();;
tourEmitter.emit('finishedMatch', this);
}
updateResultOnView() {
if (!this.finished) return;
if (this.stage.match(/league/g)) this.updateTeamsResults();
this.onFixturesList.find('.result').text(`${this.hostGoals}:${this.guestGoals}`);
}
isHost(name) {
if (this.host.name === name) return true;
else return false;
}
isDraw() {
if (this.finished) return this.hostGoals === this.guestGoals;
return -1;
}
isAWinOf(name) {
if (this.isDraw()) return false;
else {
if (this.isHost(name)) return this.hostGoals > this.guestGoals;
else return this.hostGoals < this.guestGoals;
};
}
updateTeamsResults() {
let {host, guest, hostGoals, guestGoals} = this;
for (let t of [host.name, guest.name]) {
if (this.isHost(t)) {
host.matches.push(this);
host.goalsScored += hostGoals;
host.goalsLost += guestGoals;
if (this.isDraw()) {
host.points += 1;
host.draw += 1;
} else if (hostGoals > guestGoals) {
host.points += 3;
host.won += 1;
} else {
host.lost += 1;
};
} else {
guest.matches.push(this);
guest.goalsScored += guestGoals;
guest.goalsLost += guestGoals;
if (this.isDraw()) {
guest.points += 1;
guest.draw += 1;
} else if (hostGoals < guestGoals) {
guest.points += 3;
guest.won += 1;
} else {
guest.lost += 1;
};
};
};
host.updateOnLeagueTable();
guest.updateOnLeagueTable();
}
showAsCurrentMatch() {
DOM.addingResultHostJQ.text(this.host.name);
DOM.addingResultGuestJQ.text(this.guest.name);
}
whoWon() {
// licz bramki u siebie i na wyjeździe
let {host, guest, hostGoals, guestGoals} = this;
if (hostGoals > guestGoals) return host;
else if (hostGoals < guestGoals) return guest;
else return this.penaltiesWinner;
}
getTeamStats(name) {
let {host, guest, hostGoals, guestGoals} = this;
let points, won, draw, lost, goalsScored, goalsLost;
if (name === host.name) {
goalsScored = hostGoals;
goalsLost = guestGoals;
} else if (name === guest.name) {
goalsScored = guestGoals;
goalsLost = hostGoals;
} else return {points: 0, won: 0, draw: 0, lost: 0, goalsScored: 0, goalsLost: 0};
if (goalsScored === goalsLost) {points = 1; won = 0, draw = 1, lost = 0}
else if (goalsScored>goalsLost) {points = 3; won = 1, draw = 0, lost = 0}
else if (goalsScored<goalsLost) {points = 0; won = 0, draw = 0, lost = 1};
return {points, won, draw, lost, goalsScored, goalsLost};
}
playPenalties() {
// PRZEPROWADŹ KARNE!!!
alert(`${ALERTS.PENALTIES_START[lang]}`);
let {host, guest} = this;
this.hostPenaltiesGoals = parseInt(prompt(`Podaj gole dla ${host.name}:`, 5)); // ZMIEŃ NA LEPSZĄ WERSJĘ
this.guestPenaltiesGoals = parseInt(prompt(`Podaj gole dla ${guest.name}:`, 5)); // ZMIEŃ NA LEPSZĄ WERSJĘ
let lastResultJQ = this.onFixturesList.find('.result');
lastResultJQ.text(`${lastResultJQ.text()} (${this.hostPenaltiesGoals}:${this.guestPenaltiesGoals})`);
if (this.hostPenaltiesGoals > this.guestPenaltiesGoals) {
this.penaltiesWinner = host;
return host;
} else {
this.penaltiesWinner = guest;
console.log(this);
return guest;
};
}
backup() {
let {host, guest, hostGoals, guestGoals, finished, stage, penalties, hostPenaltiesGoals, guestPenaltiesGoals, penaltiesWinner, isRevenge, partOfTie} = this;
if (penaltiesWinner) penaltiesWinner = penaltiesWinner.name;
return {
host: host.name,
guest: guest.name,
hostGoals,
guestGoals,
finished,
stage,
penalties,
hostPenaltiesGoals,
guestPenaltiesGoals,
penaltiesWinner, // podmiana na imię
isRevenge,
partOfTie
};
}
updateFromBackup(hostGoals, guestGoals, finished, stage, penalties, hostPenaltiesGoals, guestPenaltiesGoals, penaltiesWinner, partOfTie) {
this.hostGoals = hostGoals;
this.guestGoals = guestGoals;
this.finished = finished;
this.penalties = penalties;
this.hostPenaltiesGoals = hostPenaltiesGoals;
this.guestPenaltiesGoals = guestPenaltiesGoals;
this.penaltiesWinner = penaltiesWinner;
this.partOfTie = partOfTie;
this.updateResultOnView();
}
}
class Tie {
constructor(match1, match2, stage = 'cup') {
this.matches = [match1, match2];
this.stage = stage;
this.penalties = true; // BY DEFAULT IS ON
this.hostPenaltiesGoals = 0;
this.guestPenaltiesGoals = 0;
this.penaltiesWinner = '';
this.finished = false;
this.matches.forEach(m => m.partOfTie = true);
tourEmitter.listen('finishedMatch', (match) => {
if (this.finished) return;
if (this.matches[this.matches.length-1].finished) {
if (this.isDraw() && this.penalties && !this.penaltiesWinner) {this.playPenalties();};
this.finished = true;
};
});
}
isDraw() {
if (this.matches.every(v => v.finished)) {
// licz bramki u siebie i na wyjeździe
let [m1, m2] = this.matches;
let t1 = {name: m2.host.name, goalsScored: 0, goalsLost: 0};
let t2 = {name: m2.guest.name, goalsScored: 0, goalsLost: 0};
for (let m of this.matches) {
['host', 'guest'].forEach(v => {
if (m.host.name === t1.name) {
t1.goalsScored += m.host.goalsScored;
t2.goalsScored += 2*(m.guest.goalsScored);
} else {
t1.goalsScored += 2*(m.guest.goalsScored);
t2.goalsScored += m.host.goalsScored;
};
});
};
if (t1.goalsScored > t2.goalsScored || t1.goalsScored < t2.goalsScored) return false;
else return this.true;
} else return false;
}
whoWon() {
if (this.matches.every(v => v.finished)) {
// licz bramki u siebie i na wyjeździe
let [m1, m2] = this.matches;
let teams = [{name: m2.host.name, goalsScored: 0, goalsScoredWithWeight: 0}, {name: m2.guest.name, goalsScored: 0, goalsScoredWithWeight: 0}];
for (let m of this.matches) {
let host = teams.find(t => t.name === m.host.name);
let guest = teams.find(t => t.name === m.guest.name);
host.goalsScored += m.hostGoals;
host.goalsScoredWithWeight += m.hostGoals;
guest.goalsScored += m.guestGoals;
guest.goalsScoredWithWeight += 2*(m.guestGoals);
};
let [t1, t2] = teams;
if (t1.goalsScored > t2.goalsScored) return m2.host;
else if (t1.goalsScored < t2.goalsScored) return m2.guest;
else {
if (t1.goalsScoredWithWeight > t2.goalsScoredWithWeight) return m2.host;
else if (t1.goalsScoredWithWeight < t2.goalsScoredWithWeight) return m2.guest;
else return this.penaltiesWinner;
};
} else return false;
}
getNextMatch() {
if (this.finished === false) {
let found = this.matches.find(v => !v.finished);
if (!found) this.finished = false;
else return found;
} else return false;
}
showAsCurrentMatch() {
let nextMatch = this.getNextMatch();
if (nextMatch) nextMatch.showAsCurrentMatch();
}
addResult(hostGoals, guestGoals) {
let nextMatch = this.getNextMatch();
if (nextMatch) nextMatch.addResult(hostGoals, guestGoals);
nextMatch = this.getNextMatch();
if (!nextMatch) {
if (!this.whoWon() && this.penalties) this.playPenalties();
};
}
playPenalties() {
// PRZEPROWADŹ KARNE!!!
alert(`${ALERTS.PENALTIES_START[lang]}`);
let [m1, m2] = this.matches;
let t1Penalties = parseInt(prompt(`Podaj gole dla ${m2.host.name}:`, 5)); // ZMIEŃ NA LEPSZĄ WERSJĘ
let t2Penalties = parseInt(prompt(`Podaj gole dla ${m2.guest.name}:`, 5)); // ZMIEŃ NA LEPSZĄ WERSJĘ
m2.hostPenaltiesGoals = t1Penalties;
m2.guestPenaltiesGoals = t2Penalties;
let lastResultJQ = m2.onFixturesList.find('.result');
lastResultJQ.text(`${lastResultJQ.text()} (${m2.hostPenaltiesGoals}:${m2.guestPenaltiesGoals})`);
if (t1Penalties > t2Penalties) {
this.penaltiesWinner = m2.host;
return m2.host;
} else {
this.penaltiesWinner = m2.guest;
return m2.guest;
};
}
clearStats() {
this.matches.forEach(m => m.clearStats());
}
backup() {
let {matches, stage, penalties, hostPenaltiesGoals, guestPenaltiesGoals, penaltiesWinner, finished} = this;
return {
matches: matches.map(v => v.backup()),
stage,
penalties,
hostPenaltiesGoals,
guestPenaltiesGoals,
penaltiesWinner: penaltiesWinner.name,
finished
};
}
updateFromBackup(finished, penalties, hostPenaltiesGoals, guestPenaltiesGoals, penaltiesWinner, matches) {
this.matches = matches.map((m, i) => {
let {host, guest, stage, isRevenge, hostGoals, guestGoals, finished, penalties, hostPenaltiesGoals, guestPenaltiesGoals, penaltiesWinner} = m;
let newMatch = new Match(tour.getTeam(host), tour.getTeam(guest), stage, isRevenge);
newMatch.updateFromBackup(hostGoals, guestGoals, finished, stage, false, hostPenaltiesGoals, guestPenaltiesGoals, penaltiesWinner, true);
return newMatch;
});
this.finished = finished;
this.penalties = penalties;
this.hostPenaltiesGoals = hostPenaltiesGoals;
this.guestPenaltiesGoals = guestPenaltiesGoals;
this.penaltiesWinner = penaltiesWinner;
}
}
class Round {
constructor(matches) {
if (!matches) throw Error(ERRORS.LACK_OF_MATCHES_IN_ROUND[lang]);
this.matches = matches;
this.finished = false;
tourEmitter.emit('roundCreated');
tourEmitter.listen('finishedMatch', (match) => {
if (this.finished) return;
if (this.matches[this.matches.length-1].finished) {
this.finished = true;
tourEmitter.emit('roundFinished');
};
});
}
getNextMatch() {
if (this.finished === false) {
let found = this.matches.find(v => !v.finished);
if (!found) this.finished = false; // RETURNS UNDEFINED
else return found;
} else return false;
}
getWinners() {
let winners = [];
this.matches.forEach(m => {
let winner = m.whoWon();
if (winner) winners.push(winner);
else {
if (m.isDraw() && m.penalties) {
m.playPenalties();
winners.push(m.whoWon());
};
};
});
if (!winners) return console.log('There is no winners!'); // ZMIEŃ TO
winners.forEach(w => {
w.clearStats();
});
return winners;
}
backup() {
let {matches, finished} = this;
return {
matches: matches.map(v => v.backup()),
finished
};
}
}
class League {
constructor(teams, revenges) {
if (!teams) throw Error(ERRORS.LACK_OF_TEAMS_IN_LEAGUE[lang]);
this.type = 'league';
this.teams = teams;
this.revenges = revenges;
this.rounds = [];
this.finished = false;
this.generateLeague();
tourEmitter.emit('leagueCreated');
tourEmitter.emit('stageCreated');
tourEmitter.listen('finishedMatch', () => {
setTimeout(() => {
this.sortLeagueTable();
tourEmitter.emit('tableSorted');
if ($('.league-fixtures .result').length > 10) this.hideFinishedMatches();
}, 50);
});
tourEmitter.listen('roundFinished', () => {
if (this.finished === true) return;
if (this.rounds[this.rounds.length-1].finished) {
this.finished = true;
this.showAllMatches();
tourEmitter.emit('stageFinished');
};
setTimeout(() => {
this.sortLeagueTable();
tourEmitter.emit('tableSorted');
}, 50);
});
}
generateLeague() {
let repeatCount = 1;
if (this.revenges) repeatCount = 2;
for (let i=1; i<=repeatCount; i++) {
let isRevenge = false;
let generatedMatches = generateLeague(this.teams.length, this.teams);
if (i === 2) {
// REVERSE ORDER FOR REVENGE MATCHES AND TEAMS IN MATCHES
generatedMatches.reverse();
for (let r of generatedMatches) {
for (let m of r) m.reverse();
};
isRevenge = true;
};
for(let r of generatedMatches) {
let roundNumber = this.rounds.length + 1;
let matches = [];
for (let m of r) matches.push(new Match(m[0], m[1], `league-stage-${roundNumber}`, isRevenge));
this.rounds.push(new Round(matches));
};
};
}
getNextMatch() {
let round = this.rounds.find(r => !r.finished);
if (round) {
let nextMatch = round.getNextMatch();
if (nextMatch) return nextMatch;
else return false;
} else return false;
}
sortLeagueTable() {
let tbody = DOM.leagueTableJQ.find('tbody');
let ni = 0;
tbody.find('tr').sort(function(a, b) {
// ONLY DESC DIRECTION
function returnFromDelta(delta) {
if (delta > 0) return +1;
else if (delta < 0) return -1;
else return 0;
};
let pointsDelta = intFromText($('td:nth(2)', b)) - intFromText($('td:nth(2)', a));
if (pointsDelta) return returnFromDelta(pointsDelta);
let aGoalsScored = intFromText($('td:nth(7)', a));
let aGoalsLost = intFromText($('td:nth(7)', a));
let bGoalsScored = intFromText($('td:nth(6)', b));
let bGoalsLost = intFromText($('td:nth(7)', b));
let goalDelta = (bGoalsScored - bGoalsLost) - (aGoalsScored - aGoalsLost);
if (goalDelta) return returnFromDelta(goalDelta);
let winsDelta = intFromText($('td:nth(3)', b)) - intFromText($('td:nth(3)', a));
if (winsDelta) return returnFromDelta(winsDelta);
let drawDelta = intFromText($('td:nth(4)', b)) - intFromText($('td:nth(4)', a));
if (drawDelta) return returnFromDelta(drawDelta);
let moreGoalsScored = bGoalsScored - aGoalsScored;
if (moreGoalsScored) return returnFromDelta(moreGoalsScored);
let lessGoalslost = -bGoalsLost - (-aGoalsLost);
if (lessGoalslost) return returnFromDelta(lessGoalslost);
let lostDelta = -intFromText($('td:nth(5)', b)) - (-intFromText($('td:nth(5)', a)));
if (lostDelta) return returnFromDelta(lostDelta);
}).appendTo(tbody);
// UPDATE IDS
tbody.find('tr').each(function(index) {
$('td:nth(0)', this).text(index+1);
}).appendTo(tbody);
}
getBestTeamNames() {
let bestTeams = [];
let teamsInTableJQ = DOM.leagueTableJQ.find('tbody > tr').each((i, v) => {
if (i < 3) bestTeams.push($(v).find('.name').text());
});
if (bestTeams) return bestTeams;
else return false;
}
getNumberOfTeamsForCup() {
let halfTeamsInLeague = this.teams.length/2 - this.teams.length%2;
let found = [64,32,16,8,4,2].filter(n => n <= halfTeamsInLeague).find(n => halfTeamsInLeague >= n);
if (found) return found;
else return false;
}
getQualifiedTeams() {
let qualifiedTeamNames = [];
let numberOfTeamsForCup = this.getNumberOfTeamsForCup();
let teamsInTableJQ = DOM.leagueTableJQ.find('tbody > tr').each((i, v) => {
let name = $(v).find('.name').text();
if (i < numberOfTeamsForCup) qualifiedTeamNames.push(name);
});
let qualifiedTeams = qualifiedTeamNames.map(name => this.teams.find(team => name === team.name));
if (qualifiedTeams) return qualifiedTeams;
else return false;
}
backup() {
let {type, teams, revenges, rounds, finished} = this;
return {
type,
teams: teams.map(t => t.backup()),
revenges,
rounds: rounds.map(r => r.backup()),
finished
};
}
updateFromBackup(teams, rounds, finished) {
this.clearLeague();
this.teams = teams;
this.finished = finished;
rounds.forEach((r, i) => {
let {matches, finished} = r;
// popraw matches
let roundNumber = i + 1;
matches = matches.map(m => {
let newMatch = new Match(tour.getTeam(m.host), tour.getTeam(m.guest), m.stage, m.isRevenge);
let {hostGoals, guestGoals, finished, stage, penalties, hostPenaltiesGoals, guestPenaltiesGoals, penaltiesWinner, isRevenge, partOfTie} = m;
newMatch.updateFromBackup(hostGoals, guestGoals, finished, stage, penalties, hostPenaltiesGoals, guestPenaltiesGoals, penaltiesWinner, isRevenge, partOfTie);
return newMatch;
});
let round = new Round(matches, `league-stage-${roundNumber}`);
round.finished = finished;
this.rounds.push(round);
});
// PRZELICZ WYNIK ZAWODNIKÓW
this.sortLeagueTable();
tour.teams.forEach(t => t.recalcStats());
tour.decorateBestOnView();
if (!this.finished) show(DOM.addResultBarJQ);
setTimeout(() => {
if (tour.stages.length > 1) {
show(DOM.goToLeagueViewBtnJQ);
show(DOM.goToCupViewBtnJQ);
addClass.call(DOM.goToCupViewBtnJQ, 'active');
removeClass.call(DOM.goToLeagueViewBtnJQ, 'active');
};
tour.decorateBestOnView();
}, 60);
goToPage(DOM.leagueViewPageJQ);
}
clearLeague() {
this.teams = [];
this.rounds = [];
DOM.leagueFixturesJQ.find('tbody').empty();
}
getLastMatch() {
let {rounds} = this;
let round = rounds.find(r => !r.finished);
if (!round) {
round = rounds[rounds.length-1];
return round.matches[round.matches.length-1];
} else {
let finished = round.matches.filter(m => m.finished);
return finished[finished.length-1];
};
}
hideFinishedMatches() {
$('.league-fixtures .result').each(function(array) {
let resultCell = $(this);
let numberOfVisibleRows = $('.league-fixtures tbody tr:visible').length;
if (resultCell.text() && numberOfVisibleRows > 8) {
resultCell.parent().hide(300);
addClass.call(DOM.leagueFixturesJQ.find('thead'), 'hiding-something');
};
});
}
showAllMatches() {
$('.league-fixtures .result').each(function() {
let resultCell = $(this);
resultCell.parent().show();
removeClass.call(DOM.leagueFixturesJQ.find('thead'), 'hiding-something');
});
}
}
class Cup {
constructor(teams, revenges) {
if (!teams) throw Error(ERRORS.LACK_OF_TEAMS_IN_CUP[lang]);
this.type = 'cup';
this.teams = teams;
this.revenges = revenges;
this.rounds = []; // GENERATE NEW ROUND AT END OF LAST UNTIL FINAL
this.finished = false;
this.generateNextRound();
tourEmitter.emit('cupCreated');
tourEmitter.emit('stageCreated');
tourEmitter.listen('roundFinished', () => {
if (this.finished === true) return;
this.hideFinishedMatches();
if (this.rounds[this.rounds.length-1].finished) {
if (this.rounds.length === this.howMuchRounds()) {
this.finished = true;
tourEmitter.emit('stageFinished');
this.showAllMatches();
} else {
// Wyzwól sprawdzenie nowego meczu
};
};
});
}
howMuchRounds() {
let teamsLength = this.teams.length;
let numberOfRounds = 0;
let t = teamsLength;
while(t>1) {
numberOfRounds++;
t = t/2;
};
return numberOfRounds;
}
getWinnersToNextStage() {
// 1, 2, 4, 8, 16, bez 32, 64
// liczba drużyn/2 np. gdy 32 drużyny wtedy wychodzi 16
let lastRound = this.rounds[this.rounds.length-1];
if (lastRound) {
let winners = lastRound.getWinners();
if (winners) return winners;
else return false;
} else return this.teams;
}
generateNextRound() {
// prepare new table of teams which win in last round
// if last round was final then return nothing
let teams = this.getWinnersToNextStage();
if (teams.length === 0) {
// AFTER FINAL
// FIRST CHECK IF PENALTIES WASN'T PLAYED
if (this.rounds.length > 0) {
let lastMatch = this.rounds[this.rounds.length-1].matches[0];
let winner = lastMatch.whoWon();
if (winner) console.log(`Zwyciężył ${winner.name}!`);
else {
lastMatch.playPenalties();
winner = lastMatch.whoWon();
alert(`${ALERTS.TOURNAMENT_IS_FINISHED[lang]} ${winner.name}!`);
};
};
return false;
} else if (teams.length === 1) {
// komunikat o wygraniu pucharu
let [winner] = teams;
alert(`${ALERTS.TOURNAMENT_IS_FINISHED[lang]} ${winner.name}!`);
};
let matches = [];
let nextStage = `cup-${this.getNextRoundName()}`;
if (teams.length > 1) {
for (let i=0; i<teams.length; i=i+2) {
let team1 = teams[i], team2 = teams[i+1];
// DODAJ WYCZYSZCZENIE STATYSTYK DRUŻYN PRZED NOWĄ RUNDĄ
teams.forEach(t => t.clearStats());
if (this.revenges && teams.length > 2) matches.push(new Tie(new Match(team1, team2, nextStage), new Match(team2, team1, nextStage), nextStage));
else if (this.revenges && teams.length === 2) matches.push(new Match(team1, team2, nextStage));
else if (!this.revenges) matches.push(new Match(team1, team2, nextStage));
};
};
if (matches.length > 0) this.rounds.push(new Round(matches));
}
getRoundName() {
let {rounds} = this;
if (rounds) return `1/${rounds[rounds.length-1].length}`;
else return false;
}
getNextRoundName() {
let {rounds, teams} = this;
let lastRound = rounds[rounds.length-1]; // really last round not current
if (!lastRound) return `1/${teams.length/2}`; // zmien na ALERTS
else return `1/${lastRound.matches.length/2}`;
}
getLastMatch() {
let {rounds} = this;