Skip to content

Commit

Permalink
chore: 优化性能
Browse files Browse the repository at this point in the history
  • Loading branch information
Night-stars-1 committed Jul 20, 2023
1 parent d845c0b commit 9113438
Show file tree
Hide file tree
Showing 11 changed files with 122 additions and 1,339 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ venv.bak/
# custom
logs/
map/
maps/
map_data/
temp/
tmp/
Expand Down
115 changes: 71 additions & 44 deletions utils/calculated.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ def __init__(self, title=_("崩坏:星穹铁道"), det_model_name="ch_PP-OCRv3

self.end_list = ["Tab", _("轮盘"), _("唤起鼠标"), _("手机"), _("退出")]

def Click(self, points = None):
def click(self, points = None):
"""
说明:
点击坐标
Expand Down Expand Up @@ -106,7 +106,7 @@ def appoint_click(self, points, appoint_points, hsv = [18, 18, 18]):
log.info(_(_("识别超时")))
break

def Relative_click(self, points, click_time=0.5):
def relative_click(self, points, click_time=0.5):
"""
说明:
点击相对坐标
Expand All @@ -130,8 +130,8 @@ def img_click(self, points):
:param points: 坐标
"""
left, top, __, __ = self.window.left, self.window.top, self.window.right, self.window.bottom
x, y = int(left + points[0]), int(top + points[1])
log.debug((x, y))
x, y = int(left + points[0] + sra_config_obj.left_border), int(top + points[1] + sra_config_obj.up_border)
log.info((x, y))
self.mouse.position = (x, y)
self.mouse.press(mouse.Button.left)
time.sleep(0.5)
Expand All @@ -153,14 +153,14 @@ def ocr_click(self, characters, overtime = 10, frequency = 1, points = (0, 0, 0,
__, pos = self.ocr_pos(characters, points)
log.debug(characters)
if pos:
self.Click(pos)
self.click(pos)
time.sleep(0.3)
return pos
if time.time() - start_time > overtime:
log.info(_("识别超时")) if overtime != 0 else None
return False

def click_hsv(self, hsv_color, points=(0,0,0,0), offset=(0,0), flag=True, tolerance = 5):
def hsv_click(self, hsv_color, points=(0,0,0,0), offset=(0,0), flag=True, tolerance = 5):
"""
说明:
点击指定hsv颜色,允许偏移
Expand All @@ -186,7 +186,7 @@ def click_hsv(self, hsv_color, points=(0,0,0,0), offset=(0,0), flag=True, tolera
break
ret = [x + pos[0] + offset[0] , y + pos[1] + offset[1] ]
log.info(_('点击坐标{ret}').format(ret=ret))
self.Click(ret)
self.click(ret)
return True

def take_screenshot(self,points=(0,0,0,0)):
Expand Down Expand Up @@ -298,6 +298,9 @@ def click_target(self, target_path: str, threshold, flag:bool=True, check:bool=F
"map_3-2": _("迥星港"),
"map_3-3": _("太卜司"),
"map_3-4": _("工造司"),
"map_3-5": _("丹鼎司"),
"map_3-6": _("鳞渊境"),
"change_team": _("更换队伍"),
}
'''
map:
Expand All @@ -318,11 +321,11 @@ def click_target(self, target_path: str, threshold, flag:bool=True, check:bool=F
log.info(_("选择传送锚点"))
elif "map" in temp_name:
log.info(_("选择地图"))
if "map" not in temp_name:
if "orientation" in temp_name or "transfer" in temp_name:
if type(temp_ocr[temp_name]) == dict:
result = self.ocr_click(temp_ocr[temp_name]["name"], points=temp_ocr[temp_name]["points"])
elif type(temp_ocr[temp_name]) == tuple:
self.Relative_click(temp_ocr[temp_name])
self.relative_click(temp_ocr[temp_name])
result = True
else:
result = self.ocr_click(temp_ocr[temp_name])
Expand All @@ -333,7 +336,9 @@ def click_target(self, target_path: str, threshold, flag:bool=True, check:bool=F
break
if not self.is_blackscreen():
break
elif "point" in temp_name:
elif "change_team" in temp_name:
self.change_team()
elif "point" in temp_name and "map" in temp_name:
target = cv.imread(target_path)
start_time = time.time()
while True:
Expand All @@ -358,7 +363,7 @@ def click_target(self, target_path: str, threshold, flag:bool=True, check:bool=F
# 右边列表太长了 尝试向下滚动5秒 再向上滚动5秒
# scroll内部sleep 0.5s 大概能10次 目前最长在雅利洛需要向下滚动7次
if first_timeout: # 点击右边的地图列表
self.Relative_click((80, 50))
self.relative_click((80, 50))
first_timeout = False
if time.time() - start_time < 10:
self.scroll(-10)
Expand All @@ -376,26 +381,31 @@ def click_target(self, target_path: str, threshold, flag:bool=True, check:bool=F
target = cv.imread(target_path)
start_time = time.time()
first_timeout = True
distance_iter = itertools.cycle([500, -500, -500])
distance_iter = itertools.cycle([300, -300, -300])
level_iter = itertools.cycle([(3, 81), (3, 89), (3, 75)])
move_num = 0
while True:
result = self.scan_screenshot(target)
log.info(result["max_val"])
if result["max_val"] > threshold:
#points = self.calculated(result, target.shape)
self.Click(result["max_loc"])
self.click(result["max_loc"])
break
if time.time() - start_time > 5 and "point" in temp_name:
start_x = (self.window.left+self.window.right) // 2
start_y = (self.window.top+self.window.bottom) // 2
import pyautogui # 写这里是为了防止缩放比获取错误
log.info(move_num%3)
if move_num%3 == 0 and move_num != 0:
self.relative_click(next(level_iter))
time.sleep(0.2)
pyautogui.moveTo(start_x, start_y)
pyautogui.mouseDown()
pyautogui.moveTo(start_x, start_y+next(distance_iter), duration=1)
pyautogui.mouseUp()
self.Relative_click(next(level_iter))
if ((time.time() - start_time > 10 and "point" not in temp_name) \
or (time.time() - start_time > 15 and "point" in temp_name)): #防止卡死.重启线程
move_num+=1
if ((time.time() - start_time > 15 and "point" not in temp_name) \
or (time.time() - start_time > 30 and "point" in temp_name)): #防止卡死.重启线程
log.info(_("传送识别超时"))
self.keyboard.press(Key.esc)
time.sleep(0.1)
Expand All @@ -407,14 +417,14 @@ def click_target(self, target_path: str, threshold, flag:bool=True, check:bool=F

def fighting(self):
start_time = time.time()
self.Click()
self.click()
time.sleep(0.1)
if self.has_red((4, 7, 10, 19)):
while True:
result = self.get_pix_rgb(pos=(1422, 59))
result = self.get_pix_rgb(pos=(1337, 62))
log.debug(f"进入战斗取色: {result}")
if self.compare_lists([0, 0, 222], result) and self.compare_lists(result, [0, 0, 255]):
self.Click()
self.click()
else:
break
time.sleep(0.1)
Expand All @@ -424,13 +434,13 @@ def fighting(self):
self.wait_fight_end()
return True
time.sleep(0.2)
result = self.get_pix_rgb(pos=(1422, 59))
result = self.get_pix_rgb(pos=(1337, 62))
log.debug(f"进入战斗取色: {result}")
if not (self.compare_lists([0, 0, 225], result) and self.compare_lists(result, [0, 0, 255])):
self.wait_fight_end() # 无论是否识别到敌人都判断是否结束战斗,反正怪物袭击
return True

def Check_fighting(self):
def check_fighting(self):
while True:
end_str = str(self.part_ocr((20,95,100,100)))
if any(substring in end_str for substring in self.end_list):
Expand All @@ -455,14 +465,14 @@ def fighting_old(self):
log.info(_("识别超时,此处可能漏怪!"))
return False
if self.scan_screenshot(self.attack,points=(3.75,5.5,11.6,23))["max_val"] > 0.97: #修改检测机制,精度更高
self.Click()
self.click()
time.sleep(0.3)
doubt_time = time.time()
log.info(_("监控疑问或警告"))
while time.time() - doubt_time < 8:
if self.scan_screenshot(self.doubt,points=(3.75,5.5,11.6,23))["max_val"] > 0.95 or self.scan_screenshot(self.warn,points=(3.75,5.5,11.6,23))["max_val"] > 0.95:
log.info(_("识别到疑问或警告,等待怪物开战或反击"))
self.Click()
self.click()
time.sleep(1.5)
log.info(_("识别反击"))
result = self.scan_screenshot(self.finish,points=(0,95,100,100))
Expand All @@ -474,14 +484,14 @@ def fighting_old(self):
if result["max_val"] < 0.95:
break
else:
self.Click()
self.click()
time.sleep(0.3)
doubt_time = time.time() + 7
log.info(_("监控疑问或警告!"))
while time.time() < doubt_time:
if self.scan_screenshot(self.doubt,pos=(3.75,5.5,11.6,23))["max_val"] > 0.95 or self.scan_screenshot(self.warn,pos=(3.75,5.5,11.6,23))["max_val"] > 0.95:
log.info(_("识别到疑问或警告,等待怪物开战或反击"))
self.Click()
self.click()
time.sleep(1.5)
log.info(_("识别反击"))
break
Expand Down Expand Up @@ -544,7 +554,7 @@ def wait_fight_end(self, type=0):
break
time.sleep(1) # 避免长时间ocr

def Mouse_move(self, x):
def mouse_move(self, x):
"""
说明:
视角转动
Expand Down Expand Up @@ -577,14 +587,14 @@ def move(self, com = ["w","a","s","d","f"], time1=1, map_name=""):
loc = self.get_loc(map_name=map_name)
log.debug(loc)
self.keyboard.press(com)
result = self.get_pix_r(pos=(1712, 958))
log.debug(result)
if sra_config_obj.sprint and (self.compare_lists(result, [130, 160, 180]) or self.compare_lists([200, 200, 200], result)):
time.sleep(0.05)
log.info("疾跑")
self.mouse.press(mouse.Button.right)
self.mouse.release(mouse.Button.right)
start_time = time.perf_counter()
if sra_config_obj.sprint:
result = self.get_pix_r(pos=(1712, 958))
if (self.compare_lists(result, [130, 160, 180]) or self.compare_lists([200, 200, 200], result)):
time.sleep(0.05)
log.info("疾跑")
self.mouse.press(mouse.Button.right)
self.mouse.release(mouse.Button.right)
while time.perf_counter() - start_time < (time1/move_division_excursion+move_excursion):
pass
self.keyboard.release(com)
Expand Down Expand Up @@ -868,7 +878,7 @@ def wait_join(self):
return endtime
'''
endtime = time.time() - start_time
result = self.get_pix_rgb(pos=(1422, 59))
result = self.get_pix_rgb(pos=(1337, 62))
log.debug(result)
if self.compare_lists([0, 0, 222], result):
log.info(_("已进入地图"))
Expand Down Expand Up @@ -937,7 +947,7 @@ def monthly_pass(self):
log.info(_("点击月卡"))
pos = self.ocr_click(_("今日补给"))
time.sleep(0.5)
self.Click(pos)
self.click(pos)

def get_loc(self, map_name: str="", map_id: int=None):
"""
Expand All @@ -951,18 +961,35 @@ def get_loc(self, map_name: str="", map_id: int=None):
"""
if self.DEBUG:
map_name2id = {
"基座舱段": 1,
"收容舱段": 2,
"支援舱段": 3
"鳞渊境-1": 1,
"丹鼎司-1": 2,
"丹鼎司-2": 3,
"丹鼎司-3": 3,
"丹鼎司-4": 3,
"丹鼎司-5": 4,
"丹鼎司-6": 4,
}
map_id = map_name2id.get(map_name, 1) if not map_id else map_id
if not map_id and map_name not in map_name2id:
return (0, 0)
map_id = map_name2id[map_name] if not map_id else map_id
img = cv.imread(f"./maps/{map_id}.png")
template = self.take_screenshot((4,8,10,20))[0]
#__, max_vl, max_loc, length, width = find_best_match(img, template,(100,120,5))
max_val, max_loc = match_scaled(img, template,2.09)
print(max_val)
__, max_val, max_loc, __, __ = find_best_match(img, template,(100,120,5))
#max_val, max_loc = match_scaled(img, template,2.09)
cv.rectangle(img, max_loc, (max_loc[0] + 100, max_loc[1] + 100), (0, 255, 0), 2)
#show_img(img)
return (max_loc[0] + 100/2, max_loc[1] + 100/2)
show_img(img)
return (max_loc[0] + 63, max_loc[1] + 67)
else:
return (0, 0)

def change_team(self):
"""
说明:
切换队伍
"""
if self.ocr_click("队伍", points = (4, 1, 9, 6), overtime=1):
team_list = [(732, 79),(854, 83),(975, 77),(1091, 79),(1214, 81),(1333, 79)] # 队伍坐标
self.img_click(team_list[sra_config_obj.team_number-1])
return True
else:
return False
4 changes: 2 additions & 2 deletions utils/commission.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,11 @@ def run(self):
points2 = get_percentile([350,280,350+480,280+600],[1920,1080])

self.calculated.take_screenshot()
result = self.calculated.click_hsv([0,201,212], points=points1, offset=[-20,20], flag=True, tolerance=3)
result = self.calculated.hsv_click([0,201,212], points=points1, offset=[-20,20], flag=True, tolerance=3)
if not result:
log.info("可能没有任务")
return False
result = self.calculated.click_hsv([0,201,212], points=points2, offset=[-20,20], flag=True, tolerance=3)
result = self.calculated.hsv_click([0,201,212], points=points2, offset=[-20,20], flag=True, tolerance=3)
if not result:
log.info("可能没有任务")
return False
Expand Down
28 changes: 18 additions & 10 deletions utils/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,12 +188,15 @@ def get_class_methods(cls):
methods.append(name)
return methods

def load_config_data(cls):
def load_config_data(cls, __name):
"""
加载配置文件
"""
methods= get_class_methods(cls)
#methods = get_class_methods(cls)
sradata = read_json_file(CONFIG_FILE_NAME)
if __name in sradata:
setattr(cls, __name, sradata[__name])
'''
lack_methods = set(methods) - set(sradata.keys()) # 获取缺少的配置
# 如果缺少配置则添加
if lack_methods:
Expand All @@ -203,13 +206,14 @@ def load_config_data(cls):
# 读取配置
for key, value in sradata.items():
setattr(cls, key, value)
'''

class SRADataMeta(type):
def __setattr__(cls, __name, __value):
type_hints = get_type_hints(cls) # 获取所有类属性的类型信息
__name_type = type_hints.get(__name)
if type(__value) != __name_type and __name_type is not None:
raise TypeError(f"类型错误, 期望类型为{__name_type.__name__}, 实际类型为{type(__value).__name__}")
if __name_type is not None and not isinstance(__value, __name_type):
raise TypeError(f"{__name}类型错误, 期望类型为{__name_type.__name__}, 实际类型为{type(__value).__name__}")
modify_json_file(CONFIG_FILE_NAME, __name, __value)
super().__setattr__(__name, __value)

Expand Down Expand Up @@ -269,6 +273,10 @@ class SRAData(metaclass=SRADataMeta):
"""战斗时间"""
fight_data: dict = {}
"""战斗数据"""
team_number: int = 1
"""切换队伍的队伍编号"""
stop: bool = False
"""是否停止"""


def __init__(self) -> None:
Expand All @@ -277,21 +285,21 @@ def __init__(self) -> None:
def __setattr__(self, __name: str, __value: Any) -> None:
type_hints = get_type_hints(self) # 获取所有类属性的类型信息
__name_type = type_hints.get(__name)
if type(__value) != __name_type:
raise TypeError(f"类型错误, 期望类型为{__name_type.__name__}, 实际类型为{type(__value).__name__}")
if not isinstance(__value, __name_type):
raise TypeError(f"{__name}类型错误, 期望类型为{__name_type.__name__}, 实际类型为{type(__value).__name__}")
modify_json_file(CONFIG_FILE_NAME, __name, __value)
super().__setattr__(__name, __value)

def __getattribute__(self, __name: str) -> Any:
if __name == "__dict__":
if "__" in __name:
return super().__getattribute__(__name)
if __name in self.__dict__:
type_hints = get_type_hints(self) # 获取所有类属性的类型信息
__name_type = type_hints.get(__name)
__value = super().__getattribute__(__name)
if type(__value) != __name_type:
raise TypeError(f"类型错误, 期望类型为{__name_type.__name__}, 实际类型为{type(__value).__name__}")
load_config_data(SRAData)
if not isinstance(__value, __name_type):
raise TypeError(f"{__name}类型错误, 期望类型为{__name_type.__name__}, 实际类型为{type(__value).__name__}")
load_config_data(SRAData, __name)
return super().__getattribute__(__name)

def set_config(self, key, value):
Expand Down
Loading

0 comments on commit 9113438

Please sign in to comment.