-
Notifications
You must be signed in to change notification settings - Fork 109
Expand file tree
/
Copy pathopponents.py
More file actions
182 lines (143 loc) · 7.08 KB
/
opponents.py
File metadata and controls
182 lines (143 loc) · 7.08 KB
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
import json
import os
from collections import defaultdict
from datetime import datetime, timedelta
from typing import Any
from botli_dataclasses import Bot, MatchmakingData, MatchmakingType
from enums import ChallengeColor, PerfType
from exceptions import NoOpponentError
class Opponents:
def __init__(self, delay: int, username: str) -> None:
self.delay = timedelta(seconds=delay)
self.matchmaking_file = f"{username}_matchmaking.json"
self.opponent_dict = self._load(self.matchmaking_file)
self.busy_bots: list[Bot] = []
self.last_opponent: tuple[str, ChallengeColor, MatchmakingType]
def get_opponent(
self, online_bots: list[Bot], matchmaking_type: MatchmakingType
) -> tuple[Bot, ChallengeColor] | None:
for bot in self._filter_bots(online_bots, matchmaking_type):
if bot in self.busy_bots:
continue
data = self.opponent_dict[bot.username][matchmaking_type.perf_type]
if data.color == ChallengeColor.BLACK or data.release_time <= datetime.now():
self.last_opponent = (bot.username, data.color, matchmaking_type)
return bot, data.color
self.busy_bots.clear()
def add_timeout(self, success: bool, game_duration: timedelta) -> None:
username, color, matchmaking_type = self.last_opponent
data = self.opponent_dict[username][matchmaking_type.perf_type]
data.multiplier = 1 if success else abs(data.multiplier * 2)
timeout = (game_duration + self.delay) * matchmaking_type.multiplier * data.multiplier
if data.release_time > datetime.now():
data.release_time += timeout
else:
data.release_time = datetime.now() + timeout
release_str = data.release_time.isoformat(sep=" ", timespec="seconds")
print(f"{username} will not be challenged to a new game pair before {release_str}.")
if success and color == ChallengeColor.WHITE:
data.color = ChallengeColor.BLACK
else:
data.color = ChallengeColor.WHITE
self.busy_bots.clear()
self._save(self.matchmaking_file)
def set_timeout(self, wait_seconds: int) -> None:
username, _, matchmaking_type = self.last_opponent
data = self.opponent_dict[username][matchmaking_type.perf_type]
if data.multiplier == 1:
data.multiplier = -1
data.release_time = max(data.release_time, datetime.now() + timedelta(seconds=wait_seconds))
release_str = data.release_time.isoformat(sep=" ", timespec="seconds")
print(f"{username} will not be challenged to a new game pair before {release_str}.")
data.color = ChallengeColor.WHITE
self.busy_bots.clear()
self._save(self.matchmaking_file)
def reset_release_time(self, perf_type: PerfType) -> None:
for perf_types in self.opponent_dict.values():
perf_types[perf_type].release_time = datetime.now()
self.busy_bots.clear()
@staticmethod
def _filter_bots(bots: list[Bot], matchmaking_type: MatchmakingType) -> list[Bot]:
def bot_filter(bot: Bot) -> bool:
if matchmaking_type.perf_type not in bot.rating_diffs:
return False
if (
matchmaking_type.max_rating_diff
and abs(bot.rating_diffs[matchmaking_type.perf_type]) > matchmaking_type.max_rating_diff
):
return False
if (
matchmaking_type.min_rating_diff
and abs(bot.rating_diffs[matchmaking_type.perf_type]) < matchmaking_type.min_rating_diff
):
return False
return True
bots = sorted(filter(bot_filter, bots), key=lambda bot: abs(bot.rating_diffs[matchmaking_type.perf_type]))
if not bots:
raise NoOpponentError
return bots
def _load(self, matchmaking_file: str) -> defaultdict[str, defaultdict[PerfType, MatchmakingData]]:
if not os.path.isfile(matchmaking_file):
return defaultdict(lambda: defaultdict(MatchmakingData))
with open(matchmaking_file, encoding="utf-8") as file:
try:
dict_ = json.load(file)
if isinstance(dict_, list):
return self._update_format(dict_)
except json.JSONDecodeError as e:
print(f'Error while processing the file "{matchmaking_file}": {e}')
return defaultdict(lambda: defaultdict(MatchmakingData))
except PermissionError:
print("Loading the matchmaking file failed due to missing read permissions.")
return defaultdict(lambda: defaultdict(MatchmakingData))
return defaultdict(
lambda: defaultdict(MatchmakingData),
{
username: defaultdict(
MatchmakingData,
{
PerfType(perf_type): MatchmakingData.from_dict(matchmaking_dict)
for perf_type, matchmaking_dict in perf_types.items()
},
)
for username, perf_types in dict_.items()
},
)
def _min_opponent_dict(self) -> dict[str, dict[PerfType, dict[str, Any]]]:
return {
username: user_dict
for username, perf_types in self.opponent_dict.items()
if (
user_dict := {
perf_type: matchmaking_dict
for perf_type, matchmaking_data in perf_types.items()
if (matchmaking_dict := matchmaking_data.to_dict())
}
)
}
def _save(self, matchmaking_file: str) -> None:
min_opponent_dict = self._min_opponent_dict()
if not min_opponent_dict:
return
try:
with open(matchmaking_file, "w", encoding="utf-8") as json_output:
json.dump(min_opponent_dict, json_output)
except PermissionError:
print("Saving the matchmaking file failed due to missing write permissions.")
@staticmethod
def _update_format(list_format: list[dict[str, Any]]) -> defaultdict[str, defaultdict[PerfType, MatchmakingData]]:
dict_format: defaultdict[str, defaultdict[PerfType, MatchmakingData]] = defaultdict(
lambda: defaultdict(MatchmakingData)
)
for old_dict in list_format:
username = old_dict.pop("username")
perf_types: defaultdict[PerfType, MatchmakingData] = defaultdict(MatchmakingData)
for perf_type, value in old_dict.items():
release_time = (
datetime.fromisoformat(value["release_time"]) if "release_time" in value else datetime.now()
)
multiplier = value.get("multiplier", 1)
color = ChallengeColor(value["color"]) if "color" in value else ChallengeColor.WHITE
perf_types[PerfType(perf_type)] = MatchmakingData(release_time, multiplier, color)
dict_format[username] = perf_types
return dict_format