Skip to content

Commit

Permalink
Merge pull request #173 from Ks-luow/dev_shawn
Browse files Browse the repository at this point in the history
v3.0.1
  • Loading branch information
Ks-luow authored Apr 17, 2023
2 parents ae1b816 + 66fc96f commit 4240918
Show file tree
Hide file tree
Showing 33 changed files with 3,560 additions and 411 deletions.
11 changes: 7 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
- 自动登录
- 账户密码需要手动输入
- 自动访友收取信用点
- 自动前往信用商店,领取信用点并按指定优先级购买商品
- 自动确认任务完成
- 自动刷体力
- 默认进行上一次完成的关卡
Expand All @@ -39,8 +40,8 @@
- 自动收取邮件奖励
- 自动收取并安放线索
- 自动消耗无人机加速制造站或贸易站
- 自动更换基建排班干员(建议搭配配置文件使用, 也可命令行直接输入)
- 自动使用菲亚梅塔恢复指定房间心情最低干员的心情并重回岗位(工作位置不变以避免重新暖机) [[参考使用场景](https://www.bilibili.com/video/BV1mZ4y1z7wx)]
- 自动更换基建排班干员(需要搭配配置文件使用)
- 支持游戏任意分辨率(低于 1080p 的分辨率可能会有一些问题)

## 安装
Expand Down Expand Up @@ -101,7 +102,7 @@ usage: arknights-mower command [command args] [--config filepath] [--debug]
commands (prefix abbreviation accepted):
base [plan] [-c] [-d[F][N]] [-f[F][N]]
自动处理基建的信赖/货物/订单/线索/无人机
plan 表示选择的基建干员排班计划(需要搭配配置文件使用
plan 自动更换基建排班干员(建议搭配配置文件使用,也可命令行直接输入
-c 是否自动收集并使用线索
-d 是否自动消耗无人机,F 表示第几层(1-3),N 表示从左往右第几个房间(1-3)
-f 是否自动使用菲亚梅塔恢复指定房间心情最差干员的心情并恢复原位,F、N 含义同上
Expand Down Expand Up @@ -158,9 +159,11 @@ arknights-mower recruit 因陀罗 火神
arknights-mower shop 招聘许可 赤金 龙门币
# 在商场使用信用点消费,购买物品的优先级从高到低分别是招聘许可、赤金和龙门币,其余物品不购买
arknights-mower base -f12 plan_2
# 自动使用菲亚梅塔恢复B102房间心情最差干员的心情,并保持原位;自动进行名为`plan_2`的的基建排班(排班功能须搭配配置文件使用)
# 自动使用菲亚梅塔恢复B102房间心情最差干员的心情,并保持原位;自动进行配置文件中名为`plan_2`的的基建排班
arknights-mower base -c -d33
# 自动收取基建中的信赖/货物/订单;自动放置线索;自动前往 B303 房间(地下 3 层从左往右数第 3 间)使用无人机加速生产或贸易订单;
arknights-mower base room_1_2 柏喙 巫恋 龙舌兰 contact 絮雨 dormitory_1 杜林 Free Free Free Free
# 自动更换基建B102房间干员为 柏喙 巫恋 龙舌兰, 更换办公室干员为 絮雨, 更换1号宿舍干员为 杜林和任意4个空闲干员(房间名请参考 base.json)
```

命令可使用前缀或首字母缩写,如:
Expand Down Expand Up @@ -197,7 +200,7 @@ plan = {
# 阶段 1
'plan_1': {
# 控制中枢
'contral': ['', '', '凯尔希', '阿米娅', '玛恩纳'],
'central': ['', '', '凯尔希', '阿米娅', '玛恩纳'],
# 办公室
'contact': ['艾雅法拉'],
# 宿舍
Expand Down
265 changes: 204 additions & 61 deletions arknights_mower/__main__.py
Original file line number Diff line number Diff line change
@@ -1,72 +1,215 @@
import sys
import traceback
from pathlib import Path
import time
from datetime import datetime

from . import __pyinstall__, __rootdir__
from .command import *
from .utils import config
from .utils.device import Device
from .utils.log import logger, set_debug_mode
conf = {}
plan = {}


def main(module: bool = True) -> None:
args = sys.argv[1:]
if not args and __pyinstall__:
logger.info('参数为空,默认执行 schedule 模式,按下 Ctrl+C 以结束脚本运行')
args.append('schedule')
config_path = None
debug_mode = False
while True:
if len(args) > 1 and args[-2] == '--config':
config_path = Path(args[-1])
args = args[:-2]
continue
if len(args) > 0 and args[-1] == '--debug':
debug_mode = True
args = args[:-1]
continue
break

if config_path is None:
if __pyinstall__:
config_path = Path(sys.executable).parent.joinpath('config.yaml')
elif module:
config_path = Path.home().joinpath('.ark_mower.yaml')
# 执行自动排班
def main(c, p, child_conn):
__init_params__()
from arknights_mower.utils.log import logger, init_fhlr
from arknights_mower.utils import config
global plan
global conf
conf = c
plan = p
config.LOGFILE_PATH = './log'
config.SCREENSHOT_PATH = './screenshot'
config.SCREENSHOT_MAXNUM = 1000
config.ADB_DEVICE = [conf['adb']]
config.ADB_CONNECT = [conf['adb']]
config.ADB_CONNECT = [conf['adb']]
config.APPNAME = 'com.hypergryph.arknights' if conf[
'package_type'] == 1 else 'com.hypergryph.arknights.bilibili' # 服务器
init_fhlr(child_conn)
if conf['ling_xi'] == 1:
agent_base_config['令']['UpperLimit'] = 11
agent_base_config['夕']['UpperLimit'] = 11
agent_base_config['夕']['LowerLimit'] = 13
elif conf['ling_xi'] == 2:
agent_base_config['夕']['UpperLimit'] = 11
agent_base_config['令']['UpperLimit'] = 11
agent_base_config['令']['LowerLimit'] = 13
for key in list(filter(None, conf['rest_in_full'].replace(',', ',').split(','))):
if key in agent_base_config.keys():
agent_base_config[key]['RestInFull'] = True
else:
config_path = __rootdir__.parent.joinpath('config.yaml')
if not config_path.exists():
config.build_config(config_path, module)
else:
if not config_path.exists():
logger.error(f'The configuration file does not exist: {config_path}')
return
try:
logger.info(f'Loading the configuration file: {config_path}')
config.load_config(config_path)
except Exception as e:
logger.error('An error occurred when loading the configuration file')
raise e
agent_base_config[key] = {'RestInFull': True}
logger.info('开始运行Mower')
simulate()

if debug_mode and not config.DEBUG_MODE:
config.DEBUG_MODE = True
set_debug_mode()

def inialize(tasks, scheduler=None):
from arknights_mower.utils.log import logger
from arknights_mower.solvers.base_schedule import BaseSchedulerSolver
from arknights_mower.strategy import Solver
from arknights_mower.utils.device import Device
from arknights_mower.utils import config
device = Device()
cli = Solver(device)
if scheduler is None:
base_scheduler = BaseSchedulerSolver(cli.device, cli.recog)
base_scheduler.operators = {}
plan1 = {}
for key in plan:
plan1[key] = plan[key]['plans']
base_scheduler.package_name = config.APPNAME # 服务器
base_scheduler.global_plan = {'default': "plan_1", "plan_1": plan1}
base_scheduler.current_base = {}
base_scheduler.resting = []
base_scheduler.max_resting_count = conf['max_resting_count']
base_scheduler.drone_count_limit = conf['drone_count_limit']
base_scheduler.tasks = tasks
# 读取心情开关,有菲亚梅塔或者希望全自动换班得设置为 true
base_scheduler.read_mood = conf['run_mode'] == 1
# 干员宿舍回复阈值
# 高效组心情低于 UpperLimit * 阈值 (向下取整)的时候才会会安排休息

logger.debug(args)
if len(args) == 0:
help()
base_scheduler.scan_time = {}
base_scheduler.last_room = ''
base_scheduler.free_blacklist = list(filter(None, conf['free_blacklist'].replace(',', ',').split(',')))
logger.info('宿舍黑名单:' + str(base_scheduler.free_blacklist))
base_scheduler.resting_treshhold = 0.5
base_scheduler.MAA = None
base_scheduler.email_config = {
'mail_enable': conf['mail_enable'],
'subject': '[Mower通知]',
'account': conf['account'],
'pass_code': conf['pass_code'],
'receipts': [conf['account']],
'notify': False
}
maa_config['maa_path'] = conf['maa_path']
maa_config['maa_adb_path'] = conf['maa_adb_path']
maa_config['maa_adb'] = conf['adb']
maa_config['weekly_plan'] = conf['maa_weekly_plan']
base_scheduler.maa_config = maa_config
base_scheduler.ADB_CONNECT = config.ADB_CONNECT[0]
base_scheduler.error = False
base_scheduler.drone_room = None if conf['drone_room'] == '' else conf['drone_room']
base_scheduler.drone_execution_gap = 4
base_scheduler.run_order_delay = conf['run_order_delay']
base_scheduler.agent_base_config = agent_base_config
return base_scheduler
else:
target_cmd = match_cmd(args[0])
if target_cmd is not None:
try:
target_cmd(args[1:], device)
except ParamError:
logger.debug(traceback.format_exc())
help()
else:
help()
scheduler.device = cli.device
scheduler.recog = cli.recog
scheduler.handle_error(True)
return scheduler


def simulate():
from arknights_mower.utils.log import logger
'''
具体调用方法可见各个函数的参数说明
'''
tasks = []
reconnect_max_tries = 10
reconnect_tries = 0
base_scheduler = inialize(tasks)
while True:
try:
if len(base_scheduler.tasks) > 0:
(base_scheduler.tasks.sort(key=lambda x: x["time"], reverse=False))
sleep_time = (base_scheduler.tasks[0]["time"] - datetime.now()).total_seconds()
logger.debug(base_scheduler.tasks)
remaining_time = (base_scheduler.tasks[0]["time"] - datetime.now()).total_seconds()
if sleep_time > 540 and conf['maa_enable'] == 1:
subject = f"下次任务在{base_scheduler.tasks[0]['time'].strftime('%H:%M:%S')}"
context = f"下一次任务:{base_scheduler.tasks[0]['plan']}"
logger.info(context)
logger.info(subject)
base_scheduler.send_email(context, subject)
base_scheduler.maa_plan_solver()
elif sleep_time > 0:
subject = f"开始休息 {'%.2f' % (remaining_time / 60)} 分钟,到{base_scheduler.tasks[0]['time'].strftime('%H:%M:%S')}"
context = f"下一次任务:{base_scheduler.tasks[0]['plan']}"
logger.info(context)
logger.info(subject)
base_scheduler.send_email(context, subject)
time.sleep(sleep_time)
base_scheduler.run()
reconnect_tries = 0
except ConnectionError as e:
reconnect_tries += 1
if reconnect_tries < reconnect_max_tries:
logger.warning(f'连接端口断开....正在重连....')
connected = False
while not connected:
try:
base_scheduler = inialize([], base_scheduler)
break
except Exception as ce:
logger.error(ce)
time.sleep(5)
continue
continue
else:
raise Exception(e)
except Exception as E:
logger.exception(f"程序出错--->{E}")


agent_base_config = {}
maa_config = {}


if __name__ == '__main__':
main(module=True)
def __init_params__():
global agent_base_config
global maa_config
agent_base_config = {
"Default": {"UpperLimit": 24, "LowerLimit": 0, "ExhaustRequire": False, "ArrangeOrder": [2, "false"],
"RestInFull": False},
"令": {"ArrangeOrder": [2, "true"]},
"夕": {"ArrangeOrder": [2, "true"]},
"稀音": {"ExhaustRequire": True, "ArrangeOrder": [2, "true"], "RestInFull": True},
"巫恋": {"ArrangeOrder": [2, "true"]},
"柏喙": {"ExhaustRequire": True, "ArrangeOrder": [2, "true"]},
"龙舌兰": {"ArrangeOrder": [2, "true"]},
"空弦": {"ArrangeOrder": [2, "true"], "RestingPriority": "low"},
"伺夜": {"ArrangeOrder": [2, "true"]},
"绮良": {"ArrangeOrder": [2, "true"]},
"但书": {"ArrangeOrder": [2, "true"]},
"泡泡": {"ArrangeOrder": [2, "true"]},
"火神": {"ArrangeOrder": [2, "true"]},
"黑键": {"ArrangeOrder": [2, "true"]},
"波登可": {"ArrangeOrder": [2, "false"]},
"夜莺": {"ArrangeOrder": [2, "false"]},
"菲亚梅塔": {"ArrangeOrder": [2, "false"]},
"流明": {"ArrangeOrder": [2, "false"]},
"蜜莓": {"ArrangeOrder": [2, "false"]},
"闪灵": {"ArrangeOrder": [2, "false"]},
"杜林": {"ArrangeOrder": [2, "false"]},
"褐果": {"ArrangeOrder": [2, "false"]},
"车尔尼": {"ArrangeOrder": [2, "false"]},
"安比尔": {"ArrangeOrder": [2, "false"]},
"爱丽丝": {"ArrangeOrder": [2, "false"]},
"桃金娘": {"ArrangeOrder": [2, "false"]},
"帕拉斯": {"RestingPriority": "low"},
"红云": {"RestingPriority": "low", "ArrangeOrder": [2, "true"]},
"承曦格雷伊": {"ArrangeOrder": [2, "true"]},
"乌有": {"ArrangeOrder": [2, "true"], "RestingPriority": "low"},
"图耶": {"ArrangeOrder": [2, "true"]},
"鸿雪": {"ArrangeOrder": [2, "true"]},
"孑": {"ArrangeOrder": [2, "true"]},
"清道夫": {"ArrangeOrder": [2, "true"]},
"临光": {"ArrangeOrder": [2, "true"]},
"杜宾": {"ArrangeOrder": [2, "true"]},
"焰尾": {"RestInFull": True},
"重岳": {"ArrangeOrder": [2, "true"]},
"坚雷": {"ArrangeOrder": [2, "true"]},
"年": {"RestingPriority": "low"}
}
maa_config = {
# maa 运行的时间间隔,以小时计
"maa_execution_gap": 4,
# 以下配置,第一个设置为true的首先生效
# 是否启动肉鸽
"roguelike": False,
# 是否启动生息演算
"reclamation_algorithm": False,
# 是否启动保全派驻
"stationary_security_service": False,
"last_execution": None
}
15 changes: 14 additions & 1 deletion arknights_mower/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,19 @@ def base(args: list[str] = [], device: Device = None):
"""
base [plan] [-c] [-d[F][N]] [-f[F][N]]
自动处理基建的信赖/货物/订单/线索/无人机
plan 表示选择的基建干员排班计划(需要搭配配置文件使用
plan 表示选择的基建干员排班计划(建议搭配配置文件使用, 也可命令行直接输入
-c 是否自动收集并使用线索
-d 是否自动消耗无人机,F 表示第几层(1-3),N 表示从左往右第几个房间(1-3)
-f 是否使用菲亚梅塔恢复特定房间干员心情,恢复后恢复原位且工作位置不变,F、N 含义同上
"""
from .data import base_room_list, agent_list

arrange = None
clue_collect = False
drone_room = None
fia_room = None
any_room = []
agents = []

try:
for p in args:
Expand All @@ -45,8 +49,17 @@ def base(args: list[str] = [], device: Device = None):
fia_room = f'room_{p[2]}_{p[3]}'
elif arrange is None:
arrange = config.BASE_CONSTRUCT_PLAN.get(p)
if arrange is None:
if p in base_room_list:
any_room.append(p)
agents.append([])
elif p in agent_list or 'free' == p.lower():
agents[-1].append(p)
except Exception:
raise ParamError

if arrange is None and any_room is not None and len(agents) > 0:
arrange = dict(zip(any_room, agents))

BaseConstructSolver(device).run(arrange, clue_collect, drone_room, fia_room)

Expand Down
3 changes: 3 additions & 0 deletions arknights_mower/data/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
agent_list = json.loads(
Path(f'{__rootdir__}/data/agent.json').read_text('utf-8'))

# # agents base skills
# agent_base_config = json.loads(
# Path(f'{__rootdir__}/data/agent-base.json').read_text('utf-8'))

# name of each room in the basement
base_room_list = json.loads(
Expand Down
Loading

0 comments on commit 4240918

Please sign in to comment.