StarRailCopilot/module/base/timer.py
LmeSzinc 61aa7d8340 Fix: 修复截图速度过慢时出现的问题
当使用像以下结构的代码时, 需要增加触发计数
否则当截图耗时大于计时器触发时间时, 会触发错误的结果
if self.appear(MAIN_CHECK):
    if confirm_timer.reached():
        pass
    else:
        confirm_timer.reset()
2020-04-28 14:37:13 +08:00

90 lines
2.3 KiB
Python

import time
from datetime import datetime, timedelta
from functools import wraps
from module.logger import logger
def timer(function):
@wraps(function)
def function_timer(*args, **kwargs):
t0 = time.time()
result = function(*args, **kwargs)
t1 = time.time()
print('%s: %s s' % (function.__name__, str(round(t1 - t0, 10))))
return result
return function_timer
def future_time(string):
"""
Args:
string (str): Such as 14:59.
Returns:
datetime: Time with given hour, minute, second in the future.
"""
hour, minute = [int(x) for x in string.split(':')]
future = datetime.now().replace(hour=hour, minute=minute, second=0, microsecond=0)
future = future + timedelta(days=1) if future < datetime.now() else future
return future
class Timer:
def __init__(self, limit, count=0):
"""
Args:
limit (int, float): Timer limit
count (int): Timer reach confirm count. Default to 0.
When using a structure like this, must set a count.
Otherwise it goes wrong, if screenshot time cost greater than limit.
if self.appear(MAIN_CHECK):
if confirm_timer.reached():
pass
else:
confirm_timer.reset()
"""
self.limit = limit
self.count = count
self._current = 0
self._reach_count = 0
def start(self):
if not self.started():
self._current = time.time()
def started(self):
return bool(self._current)
def current(self):
"""
Returns:
float
"""
return time.time() - self._current
def reached(self):
"""
Returns:
bool
"""
self._reach_count += 1
return time.time() - self._current > self.limit and self._reach_count > self.count
def reset(self):
self._current = time.time()
self._reach_count = 0
def wait(self):
"""
Wait until timer reached.
"""
diff = self._current + self.limit - time.time()
if diff > 0:
time.sleep(diff)
def show(self):
logger.info('%s s' % str(self.current()))