GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — BotLi/botli_dataclasses.py at main · Torom/BotLi

Expand file tree

/

botli_dataclasses.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
528 lines (433 loc) · 16.6 KB
/

botli_dataclasses.py

Copy path

File metadata and controls

528 lines (433 loc) · 16.6 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
from asyncio import Task
from collections.abc import Awaitable, Callable
from dataclasses import dataclass, field, replace
from datetime import UTC, datetime, timedelta
from typing import Any, Literal
import chess
import chess.engine
from chess.polyglot import MemoryMappedReader
from enums import ChallengeColor, PerfType, Variant
from utils import PRIORITIES, find_variant, get_estimated_game_duration, parse_time_control
@dataclass(kw_only=True)
class ApiChallengeResponse:
challenge_id: str | None = None
was_accepted: bool = False
was_created: bool = False
error: str | None = None
was_declined: bool = False
invalid_initial: bool = False
invalid_increment: bool = False
has_reached_rate_limit: bool = False
wait_seconds: int | None = None
has_timed_out: bool = False
@dataclass
class BookSettings:
selection: Literal["weighted_random", "uniform_random", "best_move"] = "best_move"
max_depth: int | None = None
max_moves: int | None = None
allow_repetitions: bool | None = None
readers: dict[str, MemoryMappedReader] = field(default_factory=dict)
@dataclass
class Bot:
username: str
ratings: dict[PerfType, int]
def __eq__(self, value: object) -> bool:
if isinstance(value, Bot):
return value.username == self.username
return NotImplemented
def __hash__(self) -> int:
return hash(self.username)
@dataclass
class Challenge:
challenge_id: str
priority: int
is_correspondence: bool = False
@classmethod
def from_challenge_event(cls, challenge_event: dict[str, Any]) -> "Challenge":
challenge_id = challenge_event["id"]
title = challenge_event["challenger"].get("title")
priority = PRIORITIES.get(title, 0)
is_correspondence = challenge_event["speed"] == "correspondence"
return Challenge(challenge_id, priority, is_correspondence)
def __eq__(self, value: object) -> bool:
if isinstance(value, Challenge):
return value.challenge_id == self.challenge_id
return NotImplemented
def __hash__(self) -> int:
return hash(self.challenge_id)
@dataclass
class ChallengeRequest:
opponent_username: str
initial_time: int | None
increment: int | None
rated: bool
color: ChallengeColor
variant: Variant
timeout: int
days: int | None = None
@property
def is_correspondence(self) -> bool:
return self.initial_time is None
@classmethod
def from_challenge_event(cls, challenge_event: dict[str, Any], timeout: int) -> "ChallengeRequest":
opponent_username: str = challenge_event["challenger"]["name"]
rated: bool = challenge_event["rated"]
event_color: str = challenge_event["color"]
variant = Variant(challenge_event["variant"]["key"])
if event_color == "white":
color = ChallengeColor.BLACK
elif event_color == "black":
color = ChallengeColor.WHITE
else:
color = ChallengeColor.RANDOM
time_control = challenge_event["timeControl"]
match time_control["type"]:
case "clock":
initial_time: int | None = time_control["limit"]
increment: int | None = time_control["increment"]
days: int | None = None
case "correspondence":
initial_time = None
increment = None
days = time_control["daysPerTurn"]
case "unlimited":
initial_time = None
increment = None
days = None
case _:
raise ValueError(f'Time control "{time_control["type"]}" is not supported by BotLi.')
return cls(opponent_username, initial_time, increment, rated, color, variant, timeout, days)
@classmethod
def parse_from_command(cls, args: list[str], timeout: int) -> "ChallengeRequest":
opponent_username = None
initial_time: int | None = 60
increment: int | None = 1
days: int | None = None
color = ChallengeColor.RANDOM
rated = True
variant = Variant.STANDARD
for arg in args:
if "+" in arg:
initial_time, increment = parse_time_control(arg)
days = None
elif arg.lower() == "unlimited":
initial_time = None
increment = None
days = None
elif arg.lower().endswith("d") and arg[:-1].isdigit():
days = int(arg[:-1])
if days not in {1, 2, 3, 5, 7, 10, 14}:
raise ValueError("Days must be 1, 2, 3, 5, 7, 10, or 14.")
initial_time = None
increment = None
elif arg.lower() in {"true", "yes", "rated"}:
rated = True
elif arg.lower() in {"false", "no", "unrated", "casual"}:
rated = False
elif arg.lower() in {"white", "black", "random"}:
color = ChallengeColor(arg.lower())
elif found_variant := find_variant(arg):
variant = found_variant
elif opponent_username is None:
opponent_username = arg
else:
print(f"Unknown argument: {arg}")
if opponent_username is None:
raise ValueError("Username is required.")
return ChallengeRequest(opponent_username, initial_time, increment, rated, color, variant, timeout, days)
def replaced(self, **changes: Any) -> "ChallengeRequest":
return replace(self, **changes)
def __eq__(self, value: object) -> bool:
if isinstance(value, ChallengeRequest):
return value.opponent_username == self.opponent_username
return NotImplemented
def __hash__(self) -> int:
return hash(self.opponent_username)
@dataclass(kw_only=True)
class ChallengeResponse:
challenge_id: str | None = None
success: bool = False
was_created: bool = False
no_opponent: bool = False
has_reached_rate_limit: bool = False
wait_seconds: int | None = None
is_misconfigured: bool = False
@dataclass
class ChatMessage:
username: str
text: str
room: Literal["player", "spectator"]
@classmethod
def from_chat_line_event(cls, chat_line_event: dict[str, Any]) -> "ChatMessage":
username = chat_line_event["username"]
text = chat_line_event["text"]
room = chat_line_event["room"]
return cls(username, text, room)
@dataclass(frozen=True)
class GameInformation:
id_: str
white_title: str | None
white_name: str
white_rating: int | None
white_ai_level: int | None
white_provisional: bool
black_title: str | None
black_name: str
black_rating: int | None
black_ai_level: int | None
black_provisional: bool
initial_time_ms: int | None
increment_ms: int | None
days_per_turn: int | None
speed: str
rated: bool
variant: Variant
variant_name: str
initial_fen: str
state: dict[str, Any]
tournament_id: str | None
@classmethod
def from_game_full_event(cls, game_full_event: dict[str, Any]) -> "GameInformation":
assert game_full_event["type"] == "gameFull"
id_ = game_full_event["id"]
white_title = game_full_event["white"].get("title")
white_name = game_full_event["white"].get("name", "AI")
white_rating = game_full_event["white"].get("rating")
white_ai_level = game_full_event["white"].get("aiLevel")
white_provisional = game_full_event["white"].get("provisional", False)
black_title = game_full_event["black"].get("title")
black_name = game_full_event["black"].get("name", "AI")
black_rating = game_full_event["black"].get("rating")
black_ai_level = game_full_event["black"].get("aiLevel")
black_provisional = game_full_event["black"].get("provisional", False)
clock: dict[str, int] | None = game_full_event.get("clock")
initial_time_ms = clock["initial"] if clock else None
increment_ms = clock["increment"] if clock else None
days_per_turn = game_full_event.get("daysPerTurn")
speed = game_full_event["speed"]
rated = game_full_event["rated"]
variant = Variant(game_full_event["variant"]["key"])
variant_name = game_full_event["variant"]["name"]
initial_fen = game_full_event["initialFen"]
state = game_full_event["state"]
tournament_id = game_full_event.get("tournamentId")
return cls(
id_,
white_title,
white_name,
white_rating,
white_ai_level,
white_provisional,
black_title,
black_name,
black_rating,
black_ai_level,
black_provisional,
initial_time_ms,
increment_ms,
days_per_turn,
speed,
rated,
variant,
variant_name,
initial_fen,
state,
tournament_id,
)
@property
def id_str(self) -> str:
return f"ID: {self.id_}"
@property
def white_name_str(self) -> str:
title_str = f"{self.white_title} " if self.white_title else ""
return f"{title_str}{self.white_name}"
@property
def white_str(self) -> str:
provisional_str = "?" if self.white_provisional else ""
rating_str = f"{self.white_rating}{provisional_str}" if self.white_rating else f"Level {self.white_ai_level}"
return f"{self.white_name_str} ({rating_str})"
@property
def black_name_str(self) -> str:
title_str = f"{self.black_title} " if self.black_title else ""
return f"{title_str}{self.black_name}"
@property
def black_str(self) -> str:
provisional_str = "?" if self.black_provisional else ""
rating_str = f"{self.black_rating}{provisional_str}" if self.black_rating else f"Level {self.black_ai_level}"
return f"{self.black_name_str} ({rating_str})"
@property
def is_correspondence(self) -> bool:
return self.speed == "correspondence"
@property
def tc_str(self) -> str:
if self.initial_time_ms is None or self.increment_ms is None:
return f"{self.days_per_turn}d" if self.days_per_turn else "unlimited"
initial_time_min = self.initial_time_ms / 60_000
if initial_time_min.is_integer():
initial_time_min = int(initial_time_min)
return f"{initial_time_min}+{self.increment_ms // 1000}"
@property
def tc_format(self) -> str:
if self.initial_time_ms is None or self.increment_ms is None:
return f"TC: {'Unlimited' if self.days_per_turn is None else self.tc_str}"
initial_time_min = self.initial_time_ms / 60_000
if initial_time_min.is_integer():
initial_time_str = str(int(initial_time_min))
elif initial_time_min == 0.25:
initial_time_str = "¼"
elif initial_time_min == 0.5:
initial_time_str = "½"
elif initial_time_min == 0.75:
initial_time_str = "¾"
else:
initial_time_str = str(initial_time_min)
increment_sec = self.increment_ms // 1000
return f"TC: {initial_time_str}+{increment_sec}"
@property
def rated_str(self) -> str:
return "Rated" if self.rated else "Casual"
@property
def variant_str(self) -> str:
return f"Variant: {self.variant_name}"
@property
def white_opponent(self) -> chess.engine.Opponent:
return chess.engine.Opponent(self.white_name, self.white_title, self.white_rating, self.white_title == "BOT")
@property
def black_opponent(self) -> chess.engine.Opponent:
return chess.engine.Opponent(self.black_name, self.black_title, self.black_rating, self.black_title == "BOT")
@property
def opponent_is_bot(self) -> bool:
return self.white_title == "BOT" and self.black_title == "BOT"
@property
def opponent_is_human(self) -> bool:
return self.white_title != "BOT" or self.black_title != "BOT"
@dataclass
class LichessMove:
uci_move: str
offer_draw: bool
resign: bool
message: str = ""
@dataclass
class MatchmakingData:
release_time: datetime = datetime.min
multiplier: int = 1
color: ChallengeColor = ChallengeColor.WHITE
@classmethod
def from_dict(cls, dict_: dict[str, Any]) -> "MatchmakingData":
release_time = datetime.fromisoformat(dict_["release_time"]) if "release_time" in dict_ else datetime.now()
multiplier = dict_.get("multiplier", 1)
color = ChallengeColor(dict_["color"]) if "color" in dict_ else ChallengeColor.WHITE
return MatchmakingData(release_time, multiplier, color)
def to_dict(self) -> dict[str, Any]:
dict_ = {}
if self.release_time > datetime.now():
dict_["release_time"] = self.release_time.isoformat(timespec="seconds")
if self.multiplier == -1 and "release_time" in dict_:
dict_["multiplier"] = -1
if self.multiplier > 1:
dict_["multiplier"] = self.multiplier
if self.color == ChallengeColor.BLACK:
dict_["color"] = ChallengeColor.BLACK
return dict_
@dataclass
class MatchmakingType:
name: str
initial_time: int
increment: int
rated: bool
variant: Variant
perf_type: PerfType
config_multiplier: int | None
multiplier: int
weight: float
min_rating_diff: int | None
max_rating_diff: int | None
def __post_init__(self) -> None:
self.estimated_game_duration = timedelta(seconds=get_estimated_game_duration(self.initial_time, self.increment))
def __str__(self) -> str:
initial_time_min = self.initial_time / 60
if initial_time_min.is_integer():
initial_time_str = str(int(initial_time_min))
elif initial_time_min == 0.25:
initial_time_str = "¼"
elif initial_time_min == 0.5:
initial_time_str = "½"
elif initial_time_min == 0.75:
initial_time_str = "¾"
else:
initial_time_str = str(initial_time_min)
tc_str = f"TC: {initial_time_str}+{self.increment}"
rated_str = "Rated" if self.rated else "Casual"
variant_str = f"Variant: {self.variant}"
delimiter = 4 * " "
return delimiter.join([self.name, tc_str, rated_str, variant_str])
def __eq__(self, value: object) -> bool:
if isinstance(value, MatchmakingType):
return value.name == self.name
return NotImplemented
def __hash__(self) -> int:
return hash(self.name)
@dataclass
class MoveResponse:
move: chess.Move
public_message: str
private_message: str = field(default="", kw_only=True)
pv: list[chess.Move] = field(default_factory=list, kw_only=True)
is_draw: bool | None = field(default=None, kw_only=True)
is_lost: bool | None = field(default=None, kw_only=True)
trusted_eval: bool = field(default=False, kw_only=True)
@dataclass
class MoveSource:
method: Callable[[], Awaitable[MoveResponse | None]]
priority: int
conditions: list[bool] = field(default_factory=list)
@property
def is_available(self) -> bool:
return all(self.conditions)
@dataclass
class TablebaseResult:
move: chess.Move
wdl: Literal[-2, -1, 0, 1, 2]
distance: int
@dataclass
class TournamentRequest:
id_: str
team: str | None
password: str | None
@dataclass
class Tournament:
id_: str
start_time: datetime
end_time: datetime
name: str
allowed_to_play: bool
is_team_battle: bool
player_count: int
waiting_period: int
team: str | None = None
password: str | None = None
start_task: Task[None] | None = None
end_task: Task[None] | None = None
@classmethod
def from_tournament_info(cls, tournament_info: dict[str, Any], waiting_period: int) -> "Tournament":
return cls(
tournament_info["id"],
start_time := datetime.fromisoformat(tournament_info["startsAt"]),
start_time + timedelta(minutes=tournament_info["minutes"]),
tournament_info.get("fullName", ""),
tournament_info["verdicts"]["accepted"],
"teamBattle" in tournament_info,
tournament_info["nbPlayers"],
waiting_period,
)
@property
def seconds_to_start(self) -> float:
return (self.start_time - datetime.now(UTC)).total_seconds() - self.waiting_period * 60
@property
def seconds_to_finish(self) -> float:
return (self.end_time - datetime.now(UTC)).total_seconds()
def cancel(self) -> None:
if self.start_task:
self.start_task.cancel()
if self.end_task:
self.end_task.cancel()
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.