-
Notifications
You must be signed in to change notification settings - Fork 3
/
knockout.py
1561 lines (1267 loc) · 66.7 KB
/
knockout.py
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
"""
Copyright (c) Thijs Laarhoven, 2023
Contact: [email protected]
This is an automated script to:
- Schedule knock-out tournaments;
- Listen to participants joining/leaving;
- Start the tournament automatically;
- Generate and ensure seeded pairings;
- Remove eliminated players from the event;
- Make and update visual tournament brackets;
- Synchronize everything with the cloud.
This script is further integrated with GitHub Actions,
so that the script can be run from the cloud to
automatically host tournaments at given intervals,
and so that the tournament bracket can automatically
be generated and stored in a GitHub repository.
Among others, this script makes use of:
- The Lichess API
- https://lichess.org/api
- GitHub Actions
- https://docs.github.com/en/actions
Note: This script no longer makes use of berserk,
the Python interface for the Lichess API:
- https://pypi.org/project/berserk/
- https://github.com/lichess-org/berserk
This interface is unfortunately far from complete,
and too much functionality is missing that switching
between berserk and manual requests is not worth it.
If the missing functionality related to swiss events
gets added, the script can be adapted to only use
berserk and not needing manual API requests.
"""
import configparser
import datetime
import github
import json
import math
import matplotlib as mpl
import matplotlib.pyplot as plt
import os
import random
import requests
import sys
import time
import trees
# Class to keep track of variables
class KnockOut:
"""
KnockOut class, for organizing knock-out events through Lichess Swiss events.
Handles Lichess API queries internally, providing everything needed to run
a KO tournament without further human intervention.
"""
# Class variables, independent of the object instance
# Bracket drawing: foreground colors
_Bracket_ColorName = (186/255, 186/255, 186/255)
_Bracket_ColorNameWinner = (220/255, 220/255, 220/255)
_Bracket_ColorNameLoser = (150/255, 150/255, 150/255)
_Bracket_ColorURL = (100/255, 100/255, 100/255)
_Bracket_ColorWin = ( 98/255, 153/255, 36/255)
_Bracket_ColorLoss = (204/255, 51/255, 51/255)
_Bracket_ColorLossGame = ( 71/255, 39/255, 36/255)
_Bracket_ColorGold = (255/255, 203/255, 55/255)
_Bracket_ColorSilver = (207/255, 194/255, 170/255)
_Bracket_ColorDraw = (123/255, 153/255, 153/255)
_Bracket_ColorArrow = ( 60/255, 60/255, 60/255)
# Background colors
_Bracket_ColorBGAll = ( 22/255, 21/255, 18/255)
_Bracket_ColorBGScoreBlack = ( 33/255, 31/255, 28/255)
_Bracket_ColorBGScoreWhite = ( 43/255, 41/255, 38/255)
_Bracket_ColorBGName = ( 58/255, 56/255, 51/255)
# API request parameters
_ApiDelay = 3 # Wait 3 seconds between API requests
_ApiAttempts = 5 # Retry 5 times at API endpoints before giving up
def __init__(self, LichessToken, GitHubToken, ConfigFile):
"""
Initialize a new KO tournament object.
"""
# Store arguments in object
self._ConfigFile = ConfigFile
self._LichessToken = LichessToken
self._GitHubToken = GitHubToken
# Load configuration variables
Config = configparser.ConfigParser(inline_comment_prefixes = ";")
Config.read(self._ConfigFile)
self._GitHubUserName = Config["GitHub"]["Username"].strip()
self._GitHubRepoName = Config["GitHub"]["Repository"].strip()
self._TeamId = Config["Lichess"]["TeamId"].strip()
self._MaxParticipants = int(Config["Options"]["MaxParticipants"])
self._MinParticipants = int(Config["Options"]["MinParticipants"])
self._StartAtMax = Config["Options"].getboolean("StartAtMax")
self._GamesPerMatch = int(Config["Options"]["GamesPerMatch"])
self._Rated = Config["Options"].getboolean("Rated")
self._Variant = Config["Options"]["Variant"].strip()
self._ClockInit = int(Config["Options"]["ClockInit"])
self._ClockInc = int(Config["Options"]["ClockInc"])
self._ChatFor = int(Config["Options"]["ChatFor"])
self._RandomizeSeeds = Config["Options"].getboolean("RandomizeSeeds")
self._Title = Config["Options"]["EventName"].strip()
self._MinutesToStart = int(Config["Options"]["MinutesToStart"])
self._TieBreak = Config["Options"]["TieBreak"]
# Check validity of input data, rule out PEBKAC
self._ValidateInput()
# Variables which should not be modified
self._SwissId = None
self._SwissUrl = None
self._Winner = None
self._Loser = None
self._MatchRounds = math.ceil(math.log2(self._MaxParticipants))
self._TotalRounds = self._GamesPerMatch * self._MatchRounds
self._SkippedRounds = 0 # If matches get decided early, increment by 1
self._TreeSize = 2 ** self._MatchRounds # If e.g. 5 players, it is 8
# Decide white/black in initial games in each match
# - Value 0 gives bottom player in bracket white first
# - Value 1 gives top player in bracket white first
self._TopGetsWhite = [random.randrange(0, 2) for _ in range(self._MatchRounds)]
self.tprint("Coin flips for colors in bracket: ")
self.tprint(self._TopGetsWhite)
self._Description = f"Knock-out tournament for up to {self._MaxParticipants} players. "
self._Description += f"Each match consists of {self._GamesPerMatch} game{'s' if (self._GamesPerMatch > 1) else ''}. "
self._Description += f"Registration closes 30 seconds before the start. "
if self._TieBreak == "color":
self._Description += "In case of a tie, the player with more black games advances. "
else: # if self._TieBreak == "rating":
self._Description += "In case of a tie, the lower-rated player advances. "
self._Started = False
self._UnconfirmedParticipants = dict() # The players registered on Lichess
self._Participants = dict() # The players registered, confirmed to play, with scores
self._AllowedPlayers = ""
self._CurGame = -1
self._CurMatch = -1
assert (self._TotalRounds >= 3), "Parameters indicate not enough rounds"
assert (self._TotalRounds <= 100), "Parameters indicate too many rounds"
# List of lists of implicit pairings
# Pairings = [[(A, True, [1, 1, 0, 1]), (B, False, [0, 0, 1, 0]), C, D, E, F, G, H], [A, D*, F*, H], [D*, F]]
# Means: [A-B, C-D, E-F, G-H] [A-D, F-H] [D-F]
# Based on tree pairings from trees.py
# Add * to show a player advances
self._Pairings = []
self._CurPairings = None # API string to pass to Lichess
# Start at specified in configuration, rounded to multiple of 10 minutes
self._StartTime = 1000 * round(time.time()) + 60 * 1000 * self._MinutesToStart
self._StartTime = 600000 * (self._StartTime // 600000) # Round to multiple of 10 minutes
# Create a bracket image folder, if it does not exist
if not os.path.exists("png"):
os.makedirs("png")
if not os.path.exists("logs"):
os.makedirs("logs")
# No file name known yet, so no log yet
self._LogFile = None
# Set up a github authentication workflow
while True:
try:
auth = github.Auth.Token(self._GitHubToken)
g = github.Github(auth = auth)
self._GitHubRepo = g.get_user().get_repo(self._GitHubRepoName)
break
except:
self.tprint("Failing to connect to GitHub. Retrying...")
time.sleep(self._ApiDelay)
# =======================================================
# Validating all user input before start
# =======================================================
def _ValidateInput(self):
"""
Do checks on the user-provided input, to make sure we can get started.
"""
self.tprint("Start validating user input...")
# Convenient for checking validity of various strings
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
numeric = "0123456789"
# GitHub username
NameChars = alphabet + numeric + ",.-_"
NameLength = 39
assert (all([x in NameChars for x in self._GitHubUserName])), "Invalid GitHub username"
assert (len(self._GitHubUserName) <= NameLength), "GitHub username too long"
assert (len(self._GitHubUserName) >= 1), "GitHub username too short"
# GitHub repository
RepoChars = alphabet + numeric + ".-_"
assert (all([(x in RepoChars) for x in self._GitHubRepoName])), "Invalid GitHub repository"
RepoEndpoint = f"https://api.github.com/repos/{self._GitHubUserName}/{self._GitHubRepoName}"
Response = self._RunGetRequest(RepoEndpoint, False, AuthorizeLichess=False, AuthorizeGitHub=True)
JResponse = Response.json()
assert ("id" in JResponse), "GitHub repository not found"
assert ("permissions" in JResponse), "GitHub token invalid"
assert (JResponse["permissions"].get("push", False)), "GitHub token does not permit pushing"
# Lichess user token
TokenEndpoint = "https://lichess.org/api/token/test"
Response = self._RunPostRequest(TokenEndpoint, self._LichessToken)
JResponse = Response.json()
assert (self._LichessToken in JResponse), "Invalid Lichess token"
assert ("tournament:write" in JResponse[self._LichessToken]["scopes"]), "Incorrect Lichess token scopes"
self._LichessUsername = JResponse[self._LichessToken].get("userId")
# Lichess team name
TeamChars = alphabet + numeric + "-"
assert (all([x in TeamChars for x in self._TeamId])), "Invalid Lichess team ID"
TeamEndpoint = f"https://lichess.org/api/team/{self._TeamId}"
Response = self._RunGetRequest(TeamEndpoint, False, True)
TeamResponse = Response.json()
assert ("id" in TeamResponse), "Lichess team not found"
# Cannot check if user is team leader, as it can be hidden
# Event name
EventChars = alphabet + numeric + " ,.-"
assert (all([x.lower() in EventChars for x in self._Title])), "Illegal event name"
assert ((len(self._Title) in range(2, 31)) or (self._Title == "")), "Event name has improper length"
# Tiebreak criterium
assert (self._TieBreak in {"rating", "color", "armageddon"}), "No proper tiebreak specified"
assert ((self._TieBreak not in {"color", "armageddon"}) or (self._GamesPerMatch % 2 == 1)), "Deciding winner by color only possible for odd match lengths"
# Randomizing seeds
assert (self._RandomizeSeeds in {True, False}), "RandomizeSeeds not a boolean value"
# Minutes to start
assert (self._MinutesToStart >= 5), "Minutes to start too short (less than 5 minutes)"
assert (self._MinutesToStart <= 60 * 24 * 7), "Minutes to start too long (more than a week)"
# Minimum, maximum participants
assert (self._MinParticipants >= 4), "Minimum number of participants too low (must be at least 4)"
assert (self._MinParticipants <= self._MaxParticipants), "Minimum number of participants higher than maximum"
assert (self._MaxParticipants <= 8192), "Maximum number of participants too high (must be at most 8192)"
# Starting when the participant limit has been reached
assert (self._StartAtMax in {True, False}), "StartAtMax not a boolean value"
# Games per match
assert (self._GamesPerMatch >= 1), "Need at least 1 game per match"
assert (self._GamesPerMatch <= 20), "Too many games per match"
# Rated or not
assert (self._Rated in {True, False}), "Rated not a boolean value"
# Time control
AllowedInit = {0, 15, 30, 45, 60, 90, 120, 180, 240, 300, 360, 420, 480, 600,
900, 1200, 1500, 1800, 2400, 3000, 3600, 4200, 4800, 5400, 6000,
6600, 7200, 7800, 8400, 9000, 9600, 10200, 10800}
assert (self._ClockInit in AllowedInit), "Invalid initial clock time"
assert (self._ClockInc >= 0), "Invalid increment time"
assert (self._ClockInc <= 120), "Increment too high (above 1 minute per move)"
# Specific restrictions from https://lichess.org/api#tag/Swiss-tournaments/operation/apiSwissNew
assert (self._ClockInit + self._ClockInc > 0), "Cannot play 0+0"
assert (((self._ClockInit, self._ClockInc) not in {(0, 1), (15, 0)})
or (self._Variant == "standard")
or (not self._Rated)), "Degenerate variant time controls cannot be rated"
# Chess variant
AllVariants = {"standard", "chess960", "crazyhouse", "antichess", "atomic", "horde",
"kingOfTheHill", "racingKings", "threeCheck", "fromPosition"}
assert (self._Variant in AllVariants), "Improper chess variant specified"
# Chat settings
assert (self._ChatFor in {0, 10, 20, 30}), "Improper ChatFor parameter (must be 0/10/20/30)"
self.tprint("Finished validating user input!")
# =======================================================
# Internal calculations
# =======================================================
def _GetRound(self) -> int:
return self._CurMatch * self._GamesPerMatch + self._CurGame - self._SkippedRounds
def _BracketFile(self) -> str:
return f"png{os.sep}{self._SwissId}.png"
def _MatchDecided(self, Bracket1, Bracket2) -> (bool, bool):
"""
Given two parts of the pairing tree, decide if there are winners yet.
"""
# Extract players for this game
Player1Won = False
Player2Won = False
Player1 = Bracket1[0]
Player2 = Bracket2[0]
Score1 = sum(Bracket1[2])
Score2 = sum(Bracket2[2])
User1 = self._Participants.get(Player1,
{"username": "BYE", "rating": 0, "points": 0.0, "seed": -1})
User2 = self._Participants.get(Player2,
{"username": "BYE", "rating": 0, "points": 0.0, "seed": -1})
# Player 1 won outright with more than 50% score (or opponent is a bye)
if (Score1 > self._GamesPerMatch / 2 + 0.1) or (User2["username"] == "BYE"):
Player1Won = True
# Player 2 won outright with more than 50% score (or opponent is a bye)
elif (Score2 > self._GamesPerMatch / 2 + 0.1) or (User1["username"] == "BYE"):
Player2Won = True
# Tiebreak decisions
else:
# Method 1: by rating -- lower-rated player wins
if (self._TieBreak == "rating"):
# Lower-rated player wins
if (Score1 > self._GamesPerMatch / 2 - 0.1) and (User1["rating"] <= User2["rating"]):
Player1Won = True
elif (Score2 > self._GamesPerMatch / 2 - 0.1) and (User2["rating"] <= User1["rating"]):
Player2Won = True
# Method 2: by color -- more black games wins
elif (self._TieBreak == "color"):
# Determine winner by color
if (Score1 > self._GamesPerMatch / 2 - 0.1) and (not self._TopGetsWhite[self._CurMatch]):
Player1Won = True
elif (Score2 > self._GamesPerMatch / 2 - 0.1) and (self._TopGetsWhite[self._CurMatch]):
Player2Won = True
# Method 3: Armageddon -- only last game if tie, and then decide by color
else: # if (self._TieBreak == "armageddon")
# Before Armageddon game, a score of 0.5 less also wins
if len(Bracket1[2]) < self._GamesPerMatch:
if Score1 > (self._GamesPerMatch) / 2 - 0.1:
Player1Won = True
elif Score2 > (self._GamesPerMatch) / 2 - 0.1:
Player2Won = True
# After final Armageddon game, decide tiebreak on black games
else:
if (Score1 > self._GamesPerMatch / 2 - 0.1) and (not self._TopGetsWhite[self._CurMatch]):
Player1Won = True
elif (Score2 > self._GamesPerMatch / 2 - 0.1) and (self._TopGetsWhite[self._CurMatch]):
Player2Won = True
assert (not Player1Won or not Player2Won), "How did both win?"
# Store match results in self._Pairings
return (Player1Won, Player2Won)
def _AllMatchesDecided(self):
"""
Check if all matches were decided early, in which case
no new round for this match needs to be scheduled.
"""
for i in range(len(self._Pairings[-1]) // 2):
if (not self._Pairings[-1][2*i][1]) and (not self._Pairings[-1][2*i+1][1]):
return False
return True
# =======================================================
# Logging functions
# =======================================================
def tprint(self, s):
ToPrint = f"{datetime.datetime.now().strftime('%H:%M:%S')}: {s}"
print(ToPrint)
if hasattr(self, "_LogFile") and (self._LogFile is not None):
self._LogFile.write(ToPrint + "\n")
def PrintParticipants(self):
"""
Print the list of participants to the standard output.
Assumption: The list of participants is up to date.
"""
self.tprint("")
self.tprint("=== LIST OF PARTICIPANTS ===")
if len(self._Participants) == 0:
self.tprint(" (No participants yet.)")
else:
for Seed, (ParticipantName, Participant) in enumerate(self._Participants.items()):
self.tprint(f"{(Seed + 1):>2}. {Participant['username']:<20} ({Participant['rating']:>4}) [{ParticipantName}]")
self.tprint("")
def PrintMatches(self):
"""
Print the list of matches for this round.
Assumption: The list of matches is up to date.
"""
self.tprint("")
self.tprint("=== LIST OF MATCHES ===")
if len(self._Pairings) == 0:
self.tprint(" (No matches yet.)")
else:
for i in range(len(self._Pairings[-1]) // 2):
MatchScores = ",".join([f"{x}-{1-x}" for x in self._Pairings[-1][2*i][2]])
self.tprint(f"{self._Pairings[-1][2*i][0]:>20} - {self._Pairings[-1][2*i+1][0]:<20} : {MatchScores}")
self.tprint("")
# =======================================================
# API request handling
# =======================================================
def _RunGetRequest(self, RequestEndpoint: str, KillOnFail: bool, AuthorizeLichess: bool = True, AuthorizeGitHub: bool = False):
"""
Run an API request, and handle potential errors.
If the flag KillOnFail is true, the tournament will be aborted
if no proper response is obtained from the server.
"""
self.tprint(f"GET-request to {RequestEndpoint}.")
# Try to run the request a number of times
RequestSuccess = False
for i in range(self._ApiAttempts):
try:
if AuthorizeLichess:
Response = requests.get(RequestEndpoint,
headers = {"Authorization": f"Bearer {self._LichessToken}"})
elif AuthorizeGitHub:
Response = requests.get(RequestEndpoint,
headers = {"Authorization": f"Bearer {self._GitHubToken}"})
else:
Response = requests.get(RequestEndpoint)
Response.raise_for_status()
RequestSuccess = True
break
except:
self.tprint(f"GET-request at {RequestEndpoint} failed!")
self.tprint(f"Attempt {i+1}/{self._ApiAttempts}. {f'Trying again in {self._ApiDelay} seconds...' if i < self._ApiAttempts - 1 else ''}")
time.sleep(self._ApiDelay)
# Exit if we did not succeed creating a tournament
if not RequestSuccess:
self.tprint(f"Unable to process GET-request!")
if KillOnFail:
self._Terminate()
self.tprint("Goodbye!")
sys.exit()
# Return response if everything worked successfully
self.tprint(f"GET-request succeeded! Continuing in {self._ApiDelay} seconds...")
time.sleep(self._ApiDelay)
return Response
def _RunPostRequest(self, RequestEndpoint: str, RequestData, KillOnFail: bool = False):
"""
Run an API request, and handle potential errors.
If the flag KillOnFail is set to true, the tournament will be aborted
if no proper response is obtained from the server.
"""
self.tprint(f"POST-request to {RequestEndpoint}.")
# Try to run the request a number of times
RequestSuccess = False
for i in range(self._ApiAttempts):
try:
Response = requests.post(RequestEndpoint,
headers = {"Authorization": f"Bearer {self._LichessToken}"},
data = RequestData)
Response.raise_for_status()
RequestSuccess = True
break
except:
self.tprint(f"POST-request at {RequestEndpoint} failed!")
self.tprint(Response)
self.tprint(Response.content)
self.tprint(f"Attempt {i+1}/{self._ApiAttempts}. {f'Trying again in {self._ApiDelay} seconds...' if i < self._ApiAttempts - 1 else ''}")
time.sleep(self._ApiDelay)
# Exit if we did not succeed creating a tournament
if not RequestSuccess:
self.tprint(f"Unable to process POST-request!")
if KillOnFail:
self._Terminate()
self.tprint("Goodbye!")
sys.exit()
# Return response if everything worked successfully
self.tprint(f"POST-request succeeded! Continuing in {self._ApiDelay} seconds...")
time.sleep(self._ApiDelay)
return Response
def _Terminate(self):
"""
In some cases we may wish to terminate the tournament at once.
"""
self.tprint("Attempting to end/cancel the tournament...")
RequestEndpoint = f"https://lichess.org/api/swiss/{self._SwissId}/terminate"
RequestData = dict()
self._RunPostRequest(RequestEndpoint, RequestData, False)
self.tprint("Successfully ended/cancelled the tournament.")
# =======================================================
# Bracket visualization
# =======================================================
def _Bracket_GetCoordinates(self, r, i):
"""
Get the coordinates of the i'th match in round r.
"""
x = r * self._Xw
y = (2**r - 1) * (self._Yh + self._Ys) / 2 + 2**r * i * (self._Yh + self._Ys)
return (x, y)
def _Bracket_FormatScore(self, s):
"""
Format a score without decimals and with halves.
"""
if s < 0.8:
return "½" if (round(2*s) % 2 == 1) else "0"
else:
return str(round(2*s) // 2) + ("½" if (round(2*s) % 2 == 1) else "")
def _Bracket_Initialize(self):
"""
Initialize drawing, and instantiate variables.
"""
# Bracket width parameters
self._Xn = 8 # Width of the name within the block
self._Xg = 1 # Width of a single game result in a block
self._Xs = 2 # Space left of block where line changes direction
self._Xw = self._Xn + self._GamesPerMatch * self._Xg + 4 # Total width of a gamematch block WITH PADDING
self._Xtotal = (self._MatchRounds - 1) * self._Xw + (self._Xn + self._GamesPerMatch * self._Xg)
# Bracket height parameters
self._Yh = 2 # Height of match block WITHOUT PADDING
self._Ys = 1 # Vertical spacing between blocks
self._Ytotal = self._TreeSize // 2 * (self._Yh + self._Ys) - self._Ys
self._Ytotal += 2 # Make room for round titles
# Initialize new, empty figure
plt.figure()
plt.style.use(['dark_background'])
self._fig, self._ax = plt.subplots(figsize = (self._Xtotal/2, self._Ytotal/2))
self._fig.patch.set_facecolor(self._Bracket_ColorBGAll)
# List of display information depending on win/loss/draw
self._Bracket_DisplayScores = []
self._Bracket_DisplayScores.append({
"Color": self._Bracket_ColorLoss,
"ColorGame": self._Bracket_ColorLossGame,
"Weight": "normal",
"WeightGame": "bold"})
self._Bracket_DisplayScores.append({
"Color": self._Bracket_ColorDraw,
"ColorGame": self._Bracket_ColorDraw,
"Weight": "normal",
"WeightGame": "bold"})
self._Bracket_DisplayScores.append({
"Color": self._Bracket_ColorWin,
"ColorGame": self._Bracket_ColorWin,
"Weight": "bold",
"WeightGame": "bold"})
def _Bracket_DrawMatchBlock(self, r, i):
"""
Draw the blocks representing matches.
"""
# Name box
(XBase, YBase) = self._Bracket_GetCoordinates(r, i)
self._ax.add_patch(mpl.patches.Rectangle((XBase, YBase), self._Xn, self._Yh,
facecolor = self._Bracket_ColorBGName,
fill = True,
lw = 0))
# Score box
self._ax.add_patch(mpl.patches.Rectangle((XBase + self._Xn, YBase),
self._GamesPerMatch * self._Xg + 0.2,
self._Yh,
facecolor = self._Bracket_ColorBGScoreBlack,
fill = True,
lw = 0))
# White/black: alternating shading to indicate who was white
for g in range(self._GamesPerMatch):
self._ax.add_patch(mpl.patches.Rectangle((XBase + self._Xn + g * self._Xg + (0.1 if g > 0 else 0),
YBase + ((g + 1 + self._TopGetsWhite[r]) % 2) * self._Yh / 2),
self._Xg + (0.1 if (g == 0) else 0) + (0.1 if (g == self._GamesPerMatch - 1) else 0),
self._Yh / 2,
facecolor = self._Bracket_ColorBGScoreWhite,
fill = True,
lw = 0))
def _Bracket_DrawArrow(self, r, i):
"""
Draw arrow to next round block.
"""
# Fetch base coordinates of the block with this match
(XBase, YBase) = self._Bracket_GetCoordinates(r, i)
# First go right
plt.arrow(XBase, YBase + self._Yh / 2,
self._Xw - self._Xs, 0,
width = 0.05,
head_width = 0,
head_length = 0,
color = self._Bracket_ColorArrow)
# Next go up/down depending on parity
sgn = (1 if (i % 2 == 0) else -1)
plt.arrow(XBase + (self._Xw - self._Xs),
YBase + self._Yh / 2,
0,
sgn * 2**(r-1) * (self._Yh + self._Ys),
width = 0.05,
head_width = 0,
head_length = 0,
color = self._Bracket_ColorArrow)
# Then go right
plt.arrow(XBase + (self._Xw - self._Xs),
YBase + self._Yh / 2 + sgn * 2**(r-1) * (self._Yh + self._Ys),
self._Xs,
0,
width = 0.05,
head_width = 0,
head_length = 0,
color = self._Bracket_ColorArrow)
def _Bracket_DrawURL(self):
"""
Add the URL to the tournament in the bottom right corner.
"""
plt.text((self._Xn + self._GamesPerMatch * self._Xg)/2 + (round(math.log2(self._TreeSize)) - 1) * self._Xw,
0.2,
f"https://lichess.org/swiss/{self._SwissId}",
fontsize = 12,
ha = "center",
va = "center",
color = self._Bracket_ColorURL)
def _Bracket_DrawRoundTitles(self):
"""
Draw titles above the rounds, to indicate which
rounds these are.
"""
# Initialize naming
RoundNames = {1: "Finals",
2: "Semifinals",
4: "Quarterfinals"}
for i in range(3, 15):
RoundNames[2**i] = f"Round of {2**(i+1)}"
# Draw titles for each round
for r in range(round(math.log2(self._TreeSize))):
MatchesLeft = self._TreeSize // (2 ** (r + 1))
plt.text((self._Xn + self._GamesPerMatch * self._Xg)/2 + r * self._Xw,
self._Ytotal - 0.7,
RoundNames[MatchesLeft],
fontsize = 20,
fontweight = "bold",
ha = "center",
va = "center",
color = self._Bracket_ColorName)
if self._GamesPerMatch == 1:
RoundText = f"(Round {r * self._GamesPerMatch + 1})"
else:
RoundText = f"(Rounds {r * self._GamesPerMatch + 1}-{(r + 1) * self._GamesPerMatch})"
plt.text((self._Xn + self._GamesPerMatch * self._Xg)/2 + r * self._Xw,
self._Ytotal - 1.4,
RoundText,
fontsize = 14,
ha = "center",
va = "center",
color = self._Bracket_ColorName)
def _Bracket_FillMatchBlock(self, r, i):
"""
Fill the match block at coordinate x, y with data.
"""
# Fill block starting from the top for match i
# Compute ip as the ith block from the top
ip = self._TreeSize // (2 ** (r + 1)) - i - 1
(XBase, YBase) = self._Bracket_GetCoordinates(r, ip)
# Get user information
UserName1 = self._Pairings[r][2*i][0]
User1 = self._Participants.get(UserName1,
{"username": "BYE", "rating": 0, "points": 0.0, "seed": -1})
User1Won = (2 if self._Pairings[r][2*i][1] else
0 if self._Pairings[r][2*i+1][1] else 1)
UserScores1 = self._Pairings[r][2*i][2]
UserScoreStr1 = self._Bracket_FormatScore(sum(UserScores1))
UserName2 = self._Pairings[r][2*i+1][0]
User2 = self._Participants.get(UserName2,
{"username": "BYE", "rating": 0, "points": 0.0, "seed": -1})
User2Won = (2 if self._Pairings[r][2*i+1][1] else
0 if self._Pairings[r][2*i][1] else 1)
UserScores2 = self._Pairings[r][2*i+1][2]
UserScoreStr2 = self._Bracket_FormatScore(sum(UserScores2))
MatchUsers = [User1, User2]
MatchUserWon = [User1Won, User2Won]
MatchUserScores = [UserScores1, UserScores2]
MatchUserScoreStr = [UserScoreStr1, UserScoreStr2]
if User1Won == 2:
MatchUserNameColor = [self._Bracket_ColorNameWinner, self._Bracket_ColorNameLoser]
elif User2Won == 2:
MatchUserNameColor = [self._Bracket_ColorNameLoser, self._Bracket_ColorNameWinner]
else:
MatchUserNameColor = [self._Bracket_ColorName, self._Bracket_ColorName]
# Fill in each of the two users in the match, from top to bottom
for j in range(2):
# Put name and rating
UserString = f"{MatchUsers[j]['seed']}. {MatchUsers[j]['username']} ({MatchUsers[j]['rating']})"
if MatchUsers[j]['username'].lower() == "bye":
UserString = "BYE"
plt.text(XBase + 0.3,
YBase + self._Yh - (self._Yh / 4) - j * self._Yh / 2,
UserString,
fontsize = 13,
fontweight = self._Bracket_DisplayScores[MatchUserWon[j]]["Weight"],
ha = "left",
va = "center",
color = MatchUserNameColor[j])
# Put total score, unless BYE
if ("bye" not in [MatchUsers[k]['username'].lower() for k in range(2)]):
plt.text(XBase + self._Xn - 0.8,
YBase + self._Yh - self._Yh / 4 - j * self._Yh / 2,
MatchUserScoreStr[j],
fontsize = 16,
fontweight = self._Bracket_DisplayScores[MatchUserWon[j]]["Weight"],
ha = "center",
va = "center",
color = self._Bracket_DisplayScores[MatchUserWon[j]]["Color"])
# Put game results
for g in range(len(MatchUserScores[j])):
plt.text(XBase + self._Xn + 0.1 + (self._Xg / 2) + g * self._Xg,
YBase + self._Yh - self._Yh / 4 - j * self._Yh / 2,
self._Bracket_FormatScore(MatchUserScores[j][g]),
fontsize = 16,
fontweight = self._Bracket_DisplayScores[round(2*MatchUserScores[j][g])]["WeightGame"],
ha = "center",
va = "center",
color = self._Bracket_DisplayScores[round(2*MatchUserScores[j][g])]["ColorGame"])
def _Bracket_DrawWinners(self):
"""
Draw trophies and add names of winners/losers.
Only if the tournament finished, and only if
the tournament bracket is bigger than 4 players.
"""
assert (self._CurMatch == self._MatchRounds - 1), "Not in the last match yet."
assert (self._Winner is not None), "No winner yet."
assert (self._Loser is not None), "No loser yet."
# Two cases: more than 4 players (with trophy icon), and 4 players (just text)
if self._TreeSize > 4:
# Show winner with trophy
im = f"trophies/lichess-gold.png"
img = plt.imread(im)
imgar = 1.0
Xmin = (self._Xn + self._GamesPerMatch * self._Xg)/2 + (self._MatchRounds - 1) * self._Xw
Xmin = Xmin - 1.5
Xmax = Xmin + 3
Ymin = self._Ytotal / 2 + 1.3
Ymax = Ymin + (Xmax - Xmin) / imgar
plt.imshow(img, extent = (Xmin, Xmax, Ymin, Ymax))
plt.text(Xmin + 1.5,
Ymin - 0.5,
self._Participants[self._Winner]["username"],
fontsize = 18,
fontweight = "bold",
ha = "center",
va = "center",
color = self._Bracket_ColorGold)
# Show finals loser with trophy
im2 = f"trophies/lichess-silver.png"
img2 = plt.imread(im2)
imgar2 = 1.0
Xmin = (self._Xn + self._GamesPerMatch * self._Xg)/2 + (self._MatchRounds - 1) * self._Xw
Xmin = Xmin - 1
Xmax = Xmin + 2
Ymin = self._Ytotal / 2 - 4.5
Ymax = Ymin + (Xmax - Xmin) / imgar2
plt.imshow(img2, extent = (Xmin, Xmax, Ymin, Ymax))
plt.text(Xmin + 1,
Ymin - 0.5,
self._Participants[self._Loser]["username"],
fontsize = 16,
fontweight = "bold",
ha = "center",
va = "center",
color = self._Bracket_ColorSilver)
# Only 4 players in event
else:
Xmin = (self._Xn + self._GamesPerMatch * self._Xg)/2 + (self._MatchRounds - 1) * self._Xw
Xmin = Xmin - 1.5
Ymin = self._Ytotal / 2 + 1.3
plt.text(Xmin + 1.5,
Ymin - 0.5,
self._Participants[self._Winner]["username"] + " won!",
fontsize = 18,
fontweight = "bold",
ha = "center",
va = "center",
color = self._Bracket_ColorGold)
def _Bracket_DrawEmptyScheme(self):
"""
Based on tree size, draw an empty bracket in proper style.
"""
assert (self._TreeSize <= 512), "Too big to draw!"
assert (self._TreeSize >= 4), "Too small for a tournament!"
assert (self._TreeSize in {4, 8, 16, 32, 64, 128, 256, 512}), "Tree size not a power of two!"
for r in range(round(math.log2(self._TreeSize))):
self._Bracket_DrawRoundTitles()
for i in range(self._TreeSize // (2 ** (r + 1))):
self._Bracket_DrawMatchBlock(r, i)
if r < round(math.log2(self._TreeSize)) - 1:
self._Bracket_DrawArrow(r, i)
self._Bracket_DrawURL()
def _Bracket_FillScheme(self):
"""
Based on pairing data, fill scheme with data and results.
"""
# If proper pairings exist
if self._Pairings == []:
# Before start of event, make pretend bracket
PairingList = []
for i in range(self._TreeSize):
# Get seed number
t = trees.Trees[self._TreeSize][i] - 1
# Store right player in PairingList
ListPlayers = list(self._Participants.keys())
if t < len(self._Participants):
PairingList.append([ListPlayers[t], False, []])
else:
PairingList.append(["BYE", False, []])
assert (len(PairingList) == self._TreeSize), "Weird pairing list error"
# Store pairing list
self._Pairings.append(PairingList)
# After pairings have been finalized, do things properly
for r in range(len(self._Pairings)):
for i in range(self._TreeSize // (2 ** (r + 1))):
self._Bracket_FillMatchBlock(r, i)
# Clear pairings again
self._Pairings = []
else:
# After pairings have been finalized, do things properly
for r in range(len(self._Pairings)):
for i in range(self._TreeSize // (2 ** (r + 1))):
self._Bracket_FillMatchBlock(r, i)
def _Bracket_Save(self):
"""
Once the bracket is complete, save it to a file.
"""
plt.axis("off")
plt.xlim(0, self._Xtotal)
plt.ylim(0, self._Ytotal)
self._fig.tight_layout()
plt.savefig(self._BracketFile())
plt.cla()
plt.close("all")
def _Bracket_Upload(self, New = False):
"""
Once the bracket image has been generated, upload it.
"""
# Load contents to upload
with open(self._BracketFile(), "rb") as file:
content = file.read()
image_data = bytearray(content)
image_bytes = bytes(image_data)
# Upload to github
git_file = f"png/{self._SwissId}.png"
if New:
self._GitHubRepo.create_file(git_file,
f"Creating new bracket {self._SwissId}.png",
image_bytes,
branch="main")
self.tprint("Uploaded new bracket!")
else:
contents = self._GitHubRepo.get_contents(git_file)
CommitMessage = f"Updating bracket {self._SwissId}.png"
if (self._CurMatch > -1) and (self._CurGame > -1):
CommitMessage += f" for round {self._CurMatch+1}.{self._CurGame+1}"
else:
CommitMessage += f" before tournament start"
self._GitHubRepo.update_file(contents.path,
CommitMessage,
image_bytes,
contents.sha,
branch="main")
self.tprint("Uploaded updated bracket!")
def _Bracket_MakeBracket(self):
"""
Main routine for drawing a bracket.
"""
New = True
if os.path.exists(self._BracketFile()):
New = False
self._Bracket_Initialize()
self._Bracket_DrawEmptyScheme()
self._Bracket_FillScheme()
if self._Winner is not None:
self._Bracket_DrawWinners()
self._Bracket_Save()
self._Bracket_Upload(New)
# =======================================================
# High-level functions
# =======================================================
def _Create(self):
"""
Set up a new tournament on Lichess.
"""
# Sanity check that we only do this when we should
assert (self._SwissId is None), "Non-empty tournament object!"
# Set up Lichess swiss tournament
self.tprint("Creating new Lichess Swiss tournament...")
# Create Lichess Swiss tournament with error handling
RequestEndpoint = f"https://lichess.org/api/swiss/new/{self._TeamId}"
RequestData = dict()
RequestData["name"] = self._Title
RequestData["clock.limit"] = self._ClockInit
RequestData["clock.increment"] = self._ClockInc
RequestData["nbRounds"] = self._TotalRounds
RequestData["startsAt"] = self._StartTime
RequestData["roundInterval"] = 99999999
RequestData["variant"] = self._Variant