/
tick.py
479 lines (360 loc) · 13.8 KB
/
tick.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
# ../listeners/tick.py
"""Provides tick listener based functionality."""
# =============================================================================
# >> IMPORTS
# =============================================================================
# Python Imports
# Contextlib
from contextlib import suppress
# Enum
from enum import IntEnum
# Threading
from threading import Thread
# Time
import bisect
import time
# Source.Python Imports
# Core
from core import AutoUnload
from core import WeakAutoUnload
# Hooks
from hooks.exceptions import except_hooks
# Listeners
from listeners import listeners_logger
from listeners import on_tick_listener_manager
# =============================================================================
# >> ALL DECLARATION
# =============================================================================
__all__ = ('Delay',
'GameThread',
'TickRepeat',
'TickRepeatStatus',
)
# =============================================================================
# >> GLOBAL VARIABLES
# =============================================================================
# Get the sp.listeners.tick logger
listeners_tick_logger = listeners_logger.tick
# =============================================================================
# >> THREAD WORKAROUND
# =============================================================================
class GameThread(Thread):
"""Workaround for :class:`threading.Thread`."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
on_tick_listener_manager.register_listener(self._tick)
def __del__(self):
on_tick_listener_manager.unregister_listener(self._tick)
def _bootstrap_inner(self):
try:
super()._bootstrap_inner()
finally:
on_tick_listener_manager.unregister_listener(self._tick)
def _tick(self):
pass
# =============================================================================
# >> DELAY CLASSES
# =============================================================================
class _DelayManager(list):
"""A class that is responsible for executing delays."""
def _tick(self):
"""Internal tick listener."""
current_time = time.time()
while self and self[0].exec_time <= current_time:
try:
self.pop(0).execute()
except:
except_hooks.print_exception()
self._unregister_if_empty()
def _register_if_empty(self):
"""Register the internal tick listener if the list is empty."""
if not self:
on_tick_listener_manager.register_listener(self._tick)
def _unregister_if_empty(self):
"""Unregister the internal tick listener if the list is empty."""
if not self:
on_tick_listener_manager.unregister_listener(self._tick)
def add(self, delay):
"""Add a delay to the list.
:param Delay delay: The delay to add.
"""
self._register_if_empty()
bisect.insort_left(self, delay)
_delay_manager = _DelayManager()
class Delay(WeakAutoUnload):
"""Execute a callback after a given delay."""
def __init__(self, delay, callback, *args, **kwargs):
"""Initialize the delay.
:param int delay: The delay in seconds.
:param callback: A callable object that should be called after the
delay expired.
:param args: Arguments that should be passed to the callback.
:param kwargs: Keyword arguments that should be passed to the
callback.
"""
if not callable(callback):
raise ValueError('Given callback is not callable.')
self.delay = delay
self.exec_time = time.time() + delay
self.callback = callback
self.args = args
self.kwargs = kwargs
_delay_manager.add(self)
def __lt__(self, other):
"""Return True if this :attr:`exec_time` is less than the other's."""
return self.exec_time < other.exec_time
def __call__(self):
"""Cancel the delay and immediately call the callback."""
self.cancel()
return self.execute()
def execute(self):
"""Call the callback."""
return self.callback(*self.args, **self.kwargs)
def cancel(self):
"""Cancel the delay.
:raise ValueError: Raised if the delay is not running.
"""
_delay_manager.remove(self)
@property
def running(self):
"""Return True if the delay running."""
return self in _delay_manager
def _unload_instance(self):
with suppress(ValueError):
self.cancel()
# =============================================================================
# >> REPEAT CLASSES
# =============================================================================
class TickRepeatStatus(IntEnum):
"""Class used to store TickRepeatStatus values."""
STOPPED = 1
RUNNING = 2
PAUSED = 3
class TickRepeat(AutoUnload):
"""Class used to create and call repeats."""
def __init__(self, callback, *args, **kwargs):
"""Store all instance attributes."""
# Store the base attributes
self.callback = callback
self.args = args
self.kwargs = kwargs
# Log the __init__ message
listeners_tick_logger.log_debug(
'TickRepeat.__init__: <{0}> <{1}> <{2}>'.format(
self.callback, self.args, self.kwargs))
# Set up private attributes
self._interval = 0
self._limit = 0
self._count = 0
self._adjusted = 0
self._status = TickRepeatStatus.STOPPED
self._delay = None
self._loop_time = None
def start(self, interval, limit):
"""Start the repeat loop."""
# Log the start message
listeners_tick_logger.log_debug(
'TickRepeat.start: <{0}> <{1}>'.format(interval, limit))
# Is the repeat already running?
if self._status is TickRepeatStatus.RUNNING:
# Log the status
listeners_tick_logger.log_debug(
'TickRepeat.start - TickRepeatStatus.RUNNING')
# Do not start the repeat
return
# Log starting the repeat
listeners_tick_logger.log_debug(
'TickRepeat.start - !TickRepeatStatus' +
'.RUNNING - Starting TickRepeat')
# Set the status to running
self._status = TickRepeatStatus.RUNNING
# Set the given attributes
self._interval = interval
self._limit = limit
# Reset base counting attributes
self._count = 0
self._adjusted = 0
# Start the delay
self._delay = Delay(self._interval, self._execute)
def stop(self):
"""Stop the repeat loop."""
# Log the stop message
listeners_tick_logger.log_debug('TickRepeat.stop')
# Is the repeat running?
if self._status is not TickRepeatStatus.RUNNING:
# Log the status
listeners_tick_logger.log_debug(
'TickRepeat.stop - !TickRepeatStatus.RUNNING')
# No need to stop it
return
# Log stopping the repeat
listeners_tick_logger.log_debug(
'TickRepeat.stop - TickRepeatStatus.RUNNING - Stopping TickRepeat')
# Set the status to stopped
self._status = TickRepeatStatus.STOPPED
# Cancel the delay
self._delay.cancel()
def restart(self):
"""Restart the repeat."""
# Log restarting the repeat
listeners_tick_logger.log_debug('TickRepeat.restart')
# Stop the repeat
self.stop()
# Start the repeat
self.start(self._interval, self._limit)
def pause(self):
"""Pause the repeat.
Pausing allows the repeat to be resumed.
"""
# Log the pause message
listeners_tick_logger.log_debug('TickRepeat.pause')
# Is the repeat running?
if self._status is not TickRepeatStatus.RUNNING:
# Log the status
listeners_tick_logger.log_debug(
'TickRepeat.pause - !TickRepeatStatus.RUNNING')
# No need to pause
return
# Log pausing the repeat
listeners_tick_logger.log_debug(
'TickRepeat.pause - TickRepeatStatus.RUNNING - Pausing TickRepeat')
# Set the status to paused
self._status = TickRepeatStatus.PAUSED
# Set the remaining time in the current loop
self._loop_time = self._delay.exec_time - time.time()
# Cancel the delay
self._delay.cancel()
def resume(self):
"""Resume the repeat.
Can only resume if in paused status.
"""
# Log the resume message
listeners_tick_logger.log_debug('TickRepeat.resume')
# Is the repeat paused?
if self._status is not TickRepeatStatus.PAUSED:
# Log the status
listeners_tick_logger.log_debug(
'TickRepeat.resume - !TickRepeatStatus.PAUSED')
# Do not resume
return
# Log resuming the repeat
listeners_tick_logger.log_debug(
'TickRepeat.resume - TickRepeatStatus.' +
'PAUSED - Resuming TickRepeat')
# Set the status to running
self._status = TickRepeatStatus.RUNNING
# Start the delay
self._delay = Delay(self._loop_time, self._execute)
def extend(self, adjustment):
"""Add to the number of loops to be made."""
# Log the extend message
listeners_tick_logger.log_debug('TickRepeat.extend')
# Is there a limit for this repeat?
if not self.limit:
# Log a message about no reducing
listeners_tick_logger.log_debug(
'Unable to extend, TickRepeat instance has no limit.')
# No need to go further
return
# Was a positive integer given?
if adjustment < 1 or not isinstance(adjustment, int):
# Raise an error
raise ValueError('Adjusted value must be a positive integer')
# Add to the adjusted number
self._adjusted += adjustment
def reduce(self, adjustment):
"""Reduce the number of loops to be made."""
# Log the reduce message
listeners_tick_logger.log_debug('TickRepeat.reduce')
# Is there a limit for this repeat?
if not self.limit:
# Log a message about no reducing
listeners_tick_logger.log_debug(
'Unable to reduce, TickRepeat instance has no limit.')
# No need to go further
return
# Was a positive integer given?
if adjustment < 1 or not isinstance(adjustment, int):
# Raise an error
raise ValueError('Adjusted value must be a positive integer')
# Subtract from the adjusted number
self._adjusted -= adjustment
# Are no more loops to be made?
if (self.remaining <= 0 and
self.status is TickRepeatStatus.RUNNING):
# Log the reduce-stopping message
listeners_tick_logger.log_debug(
'TickRepeat.reduce - Reduce caused repeat to stop')
# Stop the repeat
self.stop()
def _execute(self):
"""Execute the repeat's callback with its arguments and keywords."""
# Log the _execute message
listeners_tick_logger.log_debug('TickRepeat._execute')
# Add one to the current count
self._count += 1
# Are any more loops to be made?
if self.remaining or not self._limit:
# Is there no limit?
if not self._limit:
# Log continuing the loop
listeners_tick_logger.log_debug(
'TickRepeat._execute - No limit')
# Is there a limit?
else:
# Log continuing the loop
listeners_tick_logger.log_debug(
'TickRepeat._execute - Remaining - {0}'.format(
self.remaining))
# Call the delay again
self._delay = Delay(self._interval, self._execute)
# Are no more loops to be made?
else:
# Log stopping the repeat
listeners_tick_logger.log_debug(
'TickRepeat._execute - Stopping the loop')
# Set the status to stopped
self._status = TickRepeatStatus.STOPPED
# Call the repeat's callback
self.callback(*self.args, **self.kwargs)
@property
def remaining(self):
"""Return the remaining number of loops in the repeat."""
# Is there no limit?
if not self._limit:
# Return the limit
return self._limit
# Return the remaining number of loops
return self.limit - self._count
@property
def count(self):
"""Return the current number of loops made in the repeat."""
return self._count
@property
def limit(self):
"""Return the total number of loops to be made."""
# Is there no limit?
if not self._limit:
# Return the limit
return self._limit
# Return the adjusted limit
return self._limit + self._adjusted
@property
def timeleft(self):
"""Return the remaining time till the end of the repeat."""
return self.remaining * self._interval
@property
def elapsed(self):
"""Return the elapsed time since the repeat started."""
return self._count * self._interval
@property
def total_time(self):
"""Return the total time it will take to complete the repeat."""
return self.limit * self._interval
@property
def status(self):
"""Return the status of the repeat."""
return self._status
def _unload_instance(self):
"""Stop the repeat with being unloaded."""
self.stop()