Skip to content

Commit

Permalink
#66 支持疾跑模式
Browse files Browse the repository at this point in the history
  • Loading branch information
DoctorReid committed Oct 28, 2023
1 parent 3126b56 commit dfe553b
Show file tree
Hide file tree
Showing 42 changed files with 336 additions and 195 deletions.
2 changes: 2 additions & 0 deletions config/game_sample.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ mini_map:
x: 141
y: 151
walk_speed: 20
run_speed: 25
turn_dx: 0
server_region: CN
run_mode: 0
interact: 'f'
2 changes: 1 addition & 1 deletion config/world_patrol/P01_KJZHT/R04_ZYCD_R01_DLS.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ route:
data: [322, 312]
- op: 'patrol'
- op: 'move'
data: [450, 312]
data: [448, 312]
- op: 'move'
data: [445, 231]
- op: 'move'
Expand Down
4 changes: 3 additions & 1 deletion config/world_patrol/P02_YLL6/R05_CXHL_R02_MLZX.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ level: 0
tp: '鸣雷之形'
route:
- op: 'move'
data: [484, 630]
data: [488, 630]
- op: 'move'
data: [484, 606]
- op: 'move'
data: [486, 453]
- op: 'move'
data: [507, 436]
- op: 'patrol'
10 changes: 8 additions & 2 deletions config/world_patrol/P03_XZLF/R06_TBS_R01_JHZ.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ route:
- op: 'move'
data: [390, 240]
- op: 'move'
data: [398, 208]
data: [396, 208]
- op: 'move'
data: [431, 173]
- op: 'move'
Expand All @@ -17,9 +17,13 @@ route:
- op: 'move'
data: [541, 169]
- op: 'move'
data: [593, 168]
data: [585, 170]
- op: 'interact'
data: '入画'
- op: 'wait'
data: 'in_world'
- op: 'update_pos'
data: [690, 224]
- op: 'move'
data: [706, 237]
- op: 'move'
Expand All @@ -35,6 +39,8 @@ route:
data: [835, 415]
- op: 'move'
data: [871, 394]
- op: 'move'
data: [907, 395]
- op: 'move'
data: [930, 368]
- op: 'patrol'
Expand Down
11 changes: 6 additions & 5 deletions src/basic/config_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def get_config_file_path(name: str, sub_dir: List[str] = None):
return os.path.join(dir_path, '%s.yml' % name)


def get_sample_config_file_path(name: str, sub_dir: str = None):
def get_sample_config_file_path(name: str, sub_dir: List[str] = None):
"""
获取样例配置文件的完整路径
:param name: 配置名
Expand Down Expand Up @@ -48,7 +48,7 @@ def read_config(name: str, sample: bool = True, sub_dir: List[str] = None):
return data


def read_sample_config(name: str, sub_dir: str = None):
def read_sample_config(name: str, sub_dir: List[str] = None):
"""
读取样例配置
:param name: 配置名
Expand Down Expand Up @@ -107,14 +107,15 @@ def deep_del_extra_prop(source: dict, target: dict):
del target[key]


def async_sample(name: str) -> dict:
def async_sample(name: str, sub_dir: List[str] = None) -> dict:
"""
将样例配置同步到具体配置中
:param name: 模块名称
:param sub_dir: 子目录
:return: 同步后的配置
"""
sample = read_sample_config(name)
config = read_config(name)
sample = read_sample_config(name, sub_dir)
config = read_config(name, False, sub_dir)
if config is None:
config = sample
else:
Expand Down
1 change: 0 additions & 1 deletion src/basic/img/cv2_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ def read_image(file_path: str) -> MatLike:
"""
读取图片
:param file_path: 图片路径
:param show_result: 是否显示结果
:return:
"""
if not os.path.exists(file_path):
Expand Down
4 changes: 2 additions & 2 deletions src/basic/os_utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import datetime
import os
import sys
import datetime


def join_dir_path_with_mk(path: str, *subs) -> str:
Expand Down Expand Up @@ -33,7 +33,7 @@ def get_work_dir() -> str:
返回项目根目录的路径 StarRailCopilot/
:return: 项目根目录
"""
dir_path = os.path.abspath(__file__)
dir_path: str = os.path.abspath(__file__)
# 打包后运行
up_times = 2 if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS') else 3
for _ in range(up_times):
Expand Down
15 changes: 8 additions & 7 deletions src/basic/win_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,21 +124,22 @@ def screenshot(left, top, width, height) -> MatLike:
return cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)


def click(x: int = None, y: int = None, press_time: float = 0):
def click(pos: tuple = None, press_time: float = 0, primary: bool = True):
"""
点击鼠标
:param x: 屏幕坐标
:param y: 屏幕坐标
:param pos: 屏幕坐标
:param press_time: 按住时间
:param primary: 是否点击鼠标主要按键(通常是左键)
:return:
"""
btn = pyautogui.PRIMARY if primary else pyautogui.SECONDARY
if press_time > 0:
pyautogui.moveTo(x, y)
pyautogui.mouseDown()
pyautogui.moveTo(pos)
pyautogui.mouseDown(button=btn)
time.sleep(press_time)
pyautogui.mouseUp()
pyautogui.mouseUp(button=btn)
else:
pyautogui.click(x, y)
pyautogui.click(pos, button=btn)


def drag_mouse(start: tuple, end: tuple, duration: float = 0.5):
Expand Down
2 changes: 1 addition & 1 deletion src/gui/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

def run_app(page: ft.Page):
ctx = get_context()
page.title = gt('崩坏:星穹铁道 自动代理器') + ' v0.4.0'
page.title = gt('崩坏:星穹铁道 自动代理器') + ' v0.4.1'

display_part = ft.Container(content=world_patrol_view.get(page, ctx).component)

Expand Down
30 changes: 24 additions & 6 deletions src/gui/settings_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@

from basic.i18_utils import gt
from basic.log_utils import log
from sr import constants
from sr.config import game_config
from sr.config.game_config import GameConfig
from sr.const import game_config_const
from sr.context import Context


Expand All @@ -15,18 +15,28 @@ def __init__(self, page: ft.Page, ctx: Context):
self.page = page
self.ctx = ctx

self.save_btn = ft.ElevatedButton(text=gt("保存"), on_click=self.save_config)
self.server_region = ft.Dropdown(
label=gt("区服"), width=200,
options=[
ft.dropdown.Option(text=r, key=r) for r in constants.SERVER_TIME_OFFSET.keys()
ft.dropdown.Option(text=r, key=r) for r in game_config_const.SERVER_TIME_OFFSET.keys()
],
on_change=self.on_server_region_changed
)
self.run_mode_dropdown = ft.Dropdown(
label=gt("疾跑设置"), width=200,
options=[
ft.dropdown.Option(text=k, key=v) for k, v in game_config_const.RUN_MODE.items()
],
on_change=self.on_run_mode_changed
)

self.save_btn = ft.ElevatedButton(text=gt("保存"), on_click=self.save_config)

self.component = ft.Column(
spacing=20, horizontal_alignment=CrossAxisAlignment.CENTER, expand=True,
controls=[
ft.Container(content=self.server_region, padding=5),
ft.Container(content=self.run_mode_dropdown, padding=5),
ft.Container(content=self.save_btn, padding=5),
])

Expand All @@ -39,11 +49,19 @@ def init_with_config(self):
"""
gc: GameConfig = game_config.get()
self.server_region.value = gc.server_region
self.run_mode_dropdown.value = gc.run_mode

def on_server_region_changed(self, e):
gc: GameConfig = game_config.get()
gc.set_server_region(self.server_region.value)

def on_run_mode_changed(self, e):
gc: GameConfig = game_config.get()
gc.set_run_mode(int(self.run_mode_dropdown.value))

def save_config(self, e):
config: GameConfig = game_config.get()
config.update('server_region', self.server_region.value)
config.write_config()
gc: GameConfig = game_config.get()
gc.write_config()
log.info('保存成功')


Expand Down
9 changes: 4 additions & 5 deletions src/gui/world_patrol_draft_route_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,12 @@
from cv2.typing import MatLike
from flet_core import ScrollMode

from basic import config_utils, os_utils
from basic.img import cv2_utils
from basic import os_utils
from basic.log_utils import log
from sr import constants
from sr.app.world_patrol import load_all_route_id, WorldPatrolRoute, WorldPatrol, WorldPatrolRouteId, \
WorldPatrolWhitelist
from sr.constants.map import Planet, get_planet_by_cn, PLANET_LIST, PLANET_2_REGION, get_region_by_cn, Region, \
from sr.const import map_const
from sr.const.map_const import Planet, get_planet_by_cn, PLANET_LIST, PLANET_2_REGION, get_region_by_cn, Region, \
REGION_2_SP, TransportPoint, region_with_another_floor
from sr.context import Context

Expand Down Expand Up @@ -466,7 +465,7 @@ def update_all_component_status(self):

def mock_temp_route(self, route_id: WorldPatrolRouteId=None) -> WorldPatrolRoute:
if route_id is None:
route_id = WorldPatrolRouteId(constants.map.P01, 'R02_JZCD_R01_JKS')
route_id = WorldPatrolRouteId(map_const.P01, 'R02_JZCD_R01_JKS')
route = WorldPatrolRoute(route_id)

route_id.planet = self.chosen_planet
Expand Down
80 changes: 68 additions & 12 deletions src/sr/app/calibrator.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,17 @@
import numpy as np
from cv2.typing import MatLike

from basic import cal_utils
from basic.i18_utils import gt
from basic.log_utils import log
from sr import constants
from sr import cal_pos
from sr.app import Application
from sr.config import game_config
from sr.config.game_config import GameConfig, MiniMapPos
from sr.constants.map import TransportPoint
from sr.const import map_const
from sr.const.map_const import TransportPoint
from sr.context import Context, get_context
from sr.image.sceenshot import mini_map
from sr.image.sceenshot import mini_map, large_map, LargeMapInfo, MiniMapInfo
from sr.operation.combine.transport import Transport


Expand All @@ -26,26 +28,27 @@ def __init__(self, ctx: Context):
def run(self):
self._check_mini_map_pos()
self._check_turning_rate()
# self._check_running_distance()
return True

def _check_mini_map_pos(self, screenshot: MatLike = None):
def _check_mini_map_pos(self, screenshot: MatLike = None, config=None):
log.info('[小地图定位校准] 开始')
if screenshot is None:
tp: TransportPoint = constants.map.P01_R02_SP02
tp: TransportPoint = map_const.P01_R02_SP02
op = Transport(self.ctx, tp, True)
if not op.execute():
log.error('传送到 %s %s 失败 小地图定位校准 失败', gt(tp.region.cn), gt(tp.cn))
return False

screenshot = self.screenshot()
mm_pos: MiniMapPos = mini_map.cal_little_map_pos(screenshot)
config: GameConfig = game_config.get()
config.update('mini_map', {
cfg: GameConfig = game_config.get()
cfg.update('mini_map', {
'x': mm_pos.x,
'y': mm_pos.y,
'r': mm_pos.r
})
config.write_config()
cfg.write_config()

log.info('[小地图定位校准] 完成 位置: (%d, %d) 半径: %d', mm_pos.x, mm_pos.y, mm_pos.r)
return True
Expand All @@ -60,7 +63,7 @@ def _check_turning_rate(self, tp: bool = True):
"""
log.info('[转向校准] 开始')
if tp:
p: TransportPoint = constants.map.P01_R01_SP03
p: TransportPoint = map_const.P01_R01_SP03
op = Transport(self.ctx, p, False)
if not op.execute():
log.error('传送到 %s %s 失败 转向校准 失败', gt(p.region.cn), gt(p.cn))
Expand All @@ -82,9 +85,9 @@ def _check_turning_rate(self, tp: bool = True):
log.info('平均旋转角度 %.4f', avg_turn_angle)
ans = float(turn_distance / avg_turn_angle)
log.info('每度移动距离 %.4f', ans)
config: GameConfig = game_config.get()
config.update('turn_dx', ans)
config.write_config()
gc: GameConfig = game_config.get()
gc.update('turn_dx', ans)
gc.write_config()
log.info('[转向校准] 完成')
# cv2.waitKey(0)
return ans
Expand All @@ -98,6 +101,59 @@ def _get_current_angle(self):
log.info('当前角度 %.2f', next_angle)
return next_angle

def _check_running_distance(self) -> bool:
"""
检测疾跑距离 传送到 黑塔空间站-支援舱段-月台
应该只跑一次提供一个默认值给大家用就够了 暂时不需要用户自己校准
:return:
"""
log.info('疾跑距离校准 开始')
tp: TransportPoint = map_const.P01_R04_SP02
op = Transport(self.ctx, tp, True)
if not op.execute():
log.error('传送到 %s %s 失败 疾跑距离校准 失败', gt(tp.region.cn), gt(tp.cn))
return False

lm_info: LargeMapInfo = self.ctx.ih.get_large_map(tp.region)

self.ctx.controller.start_moving_forward(run=True)

dis_arr = []
use_time_arr = []
last_pos = tp.lm_pos
last_record_time = 0

while True:
now_time = time.time()
screen = self.ctx.controller.screenshot()
mm = mini_map.cut_mini_map(screen)

lx, ly = last_pos
move_distance = self.ctx.controller.cal_move_distance_by_time(now_time - last_record_time, run=True) if last_record_time > 0 else 0
possible_pos = (lx, ly, move_distance)
lm_rect = large_map.get_large_map_rect_by_pos(lm_info.origin.shape[:2], mm.shape[:2], possible_pos)

sp_map = map_const.get_sp_type_in_rect(tp.region, lm_rect)
mm_info: MiniMapInfo = mini_map.analyse_mini_map(mm, self.ctx.im, sp_types=set(sp_map.keys()))
current_pos = cal_pos.cal_character_pos(self.ctx.im, lm_info, mm_info, lm_rect, retry_without_rect=False, running=True)

if current_pos[0] is None:
log.error('判断坐标失败')
continue

if last_record_time > 0:
dis_arr.append(cal_utils.distance_between(last_pos, current_pos))
use_time_arr.append(now_time - last_record_time)

last_pos = current_pos
last_record_time = now_time

if len(dis_arr) > 10:
break

run_speed = np.sum(dis_arr) / np.sum(use_time_arr)
log.info('疾跑平均速度 %.4f', run_speed)


if __name__ == '__main__':
ctx = get_context()
Expand Down
Loading

0 comments on commit dfe553b

Please sign in to comment.