-
Notifications
You must be signed in to change notification settings - Fork 110
Expand file tree
/
Copy pathgame_manager.py
More file actions
337 lines (259 loc) · 13.1 KB
/
game_manager.py
File metadata and controls
337 lines (259 loc) · 13.1 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
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
import asyncio
from asyncio import Event, Task
from collections import deque
from typing import Any
from api import API
from botli_dataclasses import Challenge, ChallengeRequest, Tournament, TournamentRequest
from challenger import Challenger
from config import Config
from game import Game
from matchmaking import Matchmaking
from utils import get_future_timestamp
class GameManager:
def __init__(self, api: API, config: Config, username: str) -> None:
self.api = api
self.config = config
self.username = username
self.challenger = Challenger(api)
self.changed_event = Event()
self.matchmaking = Matchmaking(api, config, username)
self.challenge_requests: deque[ChallengeRequest] = deque()
self.current_matchmaking_game_id: str | None = None
self.is_rate_limited = False
self.is_running = True
self.matchmaking_enabled = False
self.next_matchmaking: float | None = None
self.open_challenges: deque[Challenge] = deque()
self.reserved_game_spots = 0
self.started_game_events: deque[dict[str, Any]] = deque()
self.tasks: dict[Task[None], Game] = {}
self.tournament_requests: deque[TournamentRequest] = deque()
self.tournament_ids_to_leave: deque[str] = deque()
self.unstarted_tournaments: dict[str, Tournament] = {}
self.tournaments_to_join: deque[Tournament] = deque()
self.tournaments: dict[str, Tournament] = {}
def stop(self):
self.is_running = False
self.changed_event.set()
async def run(self) -> None:
while self.is_running:
try:
async with asyncio.timeout_at(self.next_matchmaking):
await self.changed_event.wait()
except TimeoutError:
await self._check_matchmaking()
continue
self.changed_event.clear()
while started_game_event := self._get_next_started_game_event():
await self._start_game(started_game_event)
while self.tournament_ids_to_leave:
await self._leave_tournament_id(self.tournament_ids_to_leave.popleft())
while self.tournament_requests:
await self._process_tournament_request(self.tournament_requests.popleft())
while tournament := self._get_next_tournament_to_join():
await self._join_tournament(tournament)
while challenge := self._get_next_challenge():
await self._accept_challenge(challenge)
while challenge_request := self._get_next_challenge_request():
await self._create_challenge(challenge_request)
for tournament in self.unstarted_tournaments.values():
tournament.cancel()
for tournament in self.tournaments.values():
tournament.cancel()
await self.api.withdraw_tournament(tournament.id_)
for task in list(self.tasks):
await task
@property
def is_busy(self) -> bool:
return len(self.tasks) + len(self.tournaments) + self.reserved_game_spots >= self.config.challenge.concurrency
def add_challenge(self, challenge: Challenge) -> None:
if challenge not in self.open_challenges:
self.open_challenges.append(challenge)
self.changed_event.set()
def request_challenge(self, *challenge_requests: ChallengeRequest) -> None:
self.challenge_requests.extend(challenge_requests)
self.changed_event.set()
def remove_challenge(self, challenge: Challenge) -> None:
if challenge in self.open_challenges:
self.open_challenges.remove(challenge)
self.changed_event.set()
def on_game_started(self, game_event: dict[str, Any]) -> None:
if game_event["id"] in {started_game_event["id"] for started_game_event in self.started_game_events}:
return
if game_event["id"] in {game.game_id for game in self.tasks.values()}:
return
self.started_game_events.append(game_event)
self.changed_event.set()
def start_matchmaking(self) -> None:
self.matchmaking_enabled = True
self._set_next_matchmaking(1, force=True)
self.changed_event.set()
def stop_matchmaking(self) -> bool:
if not self.matchmaking_enabled:
return False
self.matchmaking_enabled = False
self.next_matchmaking = None
self.changed_event.set()
return True
def request_tournament_joining(self, tournament_id: str, team: str | None, password: str | None) -> None:
self.tournament_requests.append(TournamentRequest(tournament_id, team, password))
self.changed_event.set()
def request_tournament_leaving(self, tournament_id: str) -> None:
self.tournament_ids_to_leave.append(tournament_id)
self.changed_event.set()
async def _process_tournament_request(self, tournament_request: TournamentRequest) -> None:
if tournament_request.id_ in self.unstarted_tournaments:
return
if tournament_request.id_ in self.tournaments:
return
if tournament_request.id_ in {tournament.id_ for tournament in self.tournaments_to_join}:
return
tournament_info = await self.api.get_tournament_info(tournament_request.id_)
if not tournament_info:
print(f'Tournament "{tournament_request.id_}" not found.')
return
tournament = Tournament.from_tournament_info(tournament_info)
tournament.team = tournament_request.team
tournament.password = tournament_request.password
if not tournament.bots_allowed:
print(f'BOTs are not allowed in tournament "{tournament.name}".')
return
if tournament.seconds_to_start <= 0.0:
self.tournaments_to_join.append(tournament)
return
tournament.start_task = asyncio.create_task(self._tournament_start_task(tournament))
self.unstarted_tournaments[tournament.id_] = tournament
print(f'Added tournament "{tournament.name}". Waiting for its start time to join.')
async def _join_tournament(self, tournament: Tournament) -> None:
if tournament.seconds_to_finish <= 0.0:
print(f'Tournament "{tournament.name}" is already finished.')
return
if await self.api.join_tournament(tournament.id_, tournament.team, tournament.password):
tournament.end_task = asyncio.create_task(self._tournament_end_task(tournament))
self.tournaments[tournament.id_] = tournament
print(f'Joined tournament "{tournament.name}". Awaiting games ...')
async def _leave_tournament_id(self, tournament_id: str) -> None:
if tournament := self.unstarted_tournaments.pop(tournament_id, None):
tournament.cancel()
print(f'Removed unstarted tournament "{tournament.name}".')
if tournament := self.tournaments.pop(tournament_id, None):
await self.api.withdraw_tournament(tournament_id)
tournament.cancel()
print(f'Left tournament "{tournament.name}".')
for tournament in list(self.tournaments_to_join):
if tournament.id_ == tournament_id:
self.tournaments_to_join.remove(tournament)
print(f'Removed unjoined tournament "{tournament.name}".')
self._set_next_matchmaking(1)
async def _tournament_start_task(self, tournament: Tournament) -> None:
await asyncio.sleep(tournament.seconds_to_start)
del self.unstarted_tournaments[tournament.id_]
self.tournaments_to_join.append(tournament)
print(f'Tournament "{tournament.name}" has started.')
self.changed_event.set()
async def _tournament_end_task(self, tournament: Tournament) -> None:
await asyncio.sleep(tournament.seconds_to_finish)
del self.tournaments[tournament.id_]
print(f'Tournament "{tournament.name}" has ended.')
self._set_next_matchmaking(self.config.matchmaking.delay)
self.changed_event.set()
def _set_next_matchmaking(self, delay: int, force: bool = False) -> None:
if not self.matchmaking_enabled:
return
if self.is_rate_limited and not force:
return
self.next_matchmaking = asyncio.get_running_loop().time() + delay
def _task_callback(self, task: Task[None]) -> None:
game = self.tasks.pop(task)
if game.game_id == self.current_matchmaking_game_id:
self.matchmaking.on_game_finished(game.was_aborted)
self.current_matchmaking_game_id = None
if game.ejected_tournament in self.tournaments:
self.tournaments[game.ejected_tournament].cancel()
del self.tournaments[game.ejected_tournament]
print(f'Ignoring tournament "{game.ejected_tournament}" after failure to start the game.')
self._set_next_matchmaking(self.config.matchmaking.delay)
self.changed_event.set()
async def _start_game(self, game_event: dict[str, Any]) -> None:
if self.reserved_game_spots > 0:
self.reserved_game_spots -= 1
if "tournamentId" in game_event and game_event["tournamentId"] not in self.tournaments:
tournament_info = await self.api.get_tournament_info(game_event["tournamentId"])
tournament = Tournament.from_tournament_info(tournament_info)
tournament.end_task = asyncio.create_task(self._tournament_end_task(tournament))
self.tournaments[tournament.id_] = tournament
print(f'External joined tournament "{tournament.name}" detected.')
game = Game(self.api, self.config, self.username, game_event["id"])
task = asyncio.create_task(game.run())
task.add_done_callback(self._task_callback)
self.tasks[task] = game
def _get_next_challenge(self) -> Challenge | None:
if not self.open_challenges:
return
if self.is_busy:
return
return self.open_challenges.popleft()
async def _accept_challenge(self, challenge: Challenge) -> None:
if await self.api.accept_challenge(challenge.challenge_id):
self.reserved_game_spots += 1
async def _check_matchmaking(self) -> None:
self.next_matchmaking = None
self.is_rate_limited = False
if self.current_matchmaking_game_id:
return
if self.is_busy:
return
challenge_response = await self.matchmaking.create_challenge()
if challenge_response is None:
self._set_next_matchmaking(1)
return
if challenge_response.success:
self.reserved_game_spots += 1
self.current_matchmaking_game_id = challenge_response.challenge_id
return
if challenge_response.no_opponent:
self._set_next_matchmaking(self.config.matchmaking.delay)
elif challenge_response.has_reached_rate_limit:
wait_seconds = 3600 if challenge_response.wait_seconds is None else challenge_response.wait_seconds
self._set_next_matchmaking(wait_seconds)
print(f"Matchmaking has reached rate limit, next attempt at {get_future_timestamp(wait_seconds)}.")
self.is_rate_limited = True
elif challenge_response.is_misconfigured:
print("Matchmaking stopped due to misconfiguration.")
self.stop_matchmaking()
else:
self._set_next_matchmaking(1)
def _get_next_challenge_request(self) -> ChallengeRequest | None:
if not self.challenge_requests:
return
if self.is_busy:
return
return self.challenge_requests.popleft()
def _get_next_started_game_event(self) -> dict[str, Any] | None:
if not self.started_game_events:
return
if len(self.tasks) >= self.config.challenge.concurrency:
print("Max number of concurrent games exceeded. Ignoring already started game for now.")
return
return self.started_game_events.popleft()
def _get_next_tournament_to_join(self) -> Tournament | None:
if not self.tournaments_to_join:
return
if self.is_busy:
return
return self.tournaments_to_join.popleft()
async def _create_challenge(self, challenge_request: ChallengeRequest) -> None:
print(f"Challenging {challenge_request.opponent_username} ...")
response = await self.challenger.create(challenge_request)
if response.success:
self.reserved_game_spots += 1
elif response.has_reached_rate_limit:
if response.wait_seconds is not None:
print(f"Don't create new challenges before {get_future_timestamp(response.wait_seconds)}!")
if self.challenge_requests:
print("Challenge queue cleared due to rate limiting.")
self.challenge_requests.clear()
elif challenge_request in self.challenge_requests:
print(f"Challenges against {challenge_request.opponent_username} removed from queue.")
while challenge_request in self.challenge_requests:
self.challenge_requests.remove(challenge_request)